File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1075.2.163: download - view: text, annotated - select for diffs
Wed Jan 19 00:39:01 2022 UTC (2 years, 4 months ago) by raeburn
Branches: version_2_11_X
- For 2.11
  Backport 1.1375

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1075.2.163 2022/01/19 00:39:01 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: # Makes a table out of the previous attempts
   30: # Inputs result_from_symbread, user, domain, course_id
   31: # Reads in non-network-related .tab files
   32: 
   33: # POD header:
   34: 
   35: =pod
   36: 
   37: =head1 NAME
   38: 
   39: Apache::loncommon - pile of common routines
   40: 
   41: =head1 SYNOPSIS
   42: 
   43: Common routines for manipulating connections, student answers,
   44:     domains, common Javascript fragments, etc.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: A collection of commonly used subroutines that don't have a natural
   49: home anywhere else. This collection helps remove
   50: redundancy from other modules and increase efficiency of memory usage.
   51: 
   52: =cut 
   53: 
   54: # End of POD header
   55: package Apache::loncommon;
   56: 
   57: use strict;
   58: use Apache::lonnet;
   59: use GDBM_File;
   60: use POSIX qw(strftime mktime);
   61: use Apache::lonmenu();
   62: use Apache::lonenc();
   63: use Apache::lonlocal;
   64: use Apache::lonnet();
   65: use HTML::Entities;
   66: use Apache::lonhtmlcommon();
   67: use Apache::loncoursedata();
   68: use Apache::lontexconvert();
   69: use Apache::lonclonecourse();
   70: use Apache::lonuserutils();
   71: use Apache::lonuserstate();
   72: use Apache::courseclassifier();
   73: use LONCAPA qw(:DEFAULT :match);
   74: use HTTP::Request;
   75: use DateTime::TimeZone;
   76: use DateTime::Locale;
   77: use Encode();
   78: use Authen::Captcha;
   79: use Captcha::reCAPTCHA;
   80: use JSON::DWIW;
   81: use LWP::UserAgent;
   82: use Crypt::DES;
   83: use DynaLoader; # for Crypt::DES version
   84: use File::Copy();
   85: use File::Path();
   86: 
   87: # ---------------------------------------------- Designs
   88: use vars qw(%defaultdesign);
   89: 
   90: my $readit;
   91: 
   92: 
   93: ##
   94: ## Global Variables
   95: ##
   96: 
   97: 
   98: # ----------------------------------------------- SSI with retries:
   99: #
  100: 
  101: =pod
  102: 
  103: =head1 Server Side include with retries:
  104: 
  105: =over 4
  106: 
  107: =item * &ssi_with_retries(resource,retries form)
  108: 
  109: Performs an ssi with some number of retries.  Retries continue either
  110: until the result is ok or until the retry count supplied by the
  111: caller is exhausted.  
  112: 
  113: Inputs:
  114: 
  115: =over 4
  116: 
  117: resource   - Identifies the resource to insert.
  118: 
  119: retries    - Count of the number of retries allowed.
  120: 
  121: form       - Hash that identifies the rendering options.
  122: 
  123: =back
  124: 
  125: Returns:
  126: 
  127: =over 4
  128: 
  129: content    - The content of the response.  If retries were exhausted this is empty.
  130: 
  131: response   - The response from the last attempt (which may or may not have been successful.
  132: 
  133: =back
  134: 
  135: =back
  136: 
  137: =cut
  138: 
  139: sub ssi_with_retries {
  140:     my ($resource, $retries, %form) = @_;
  141: 
  142: 
  143:     my $ok = 0;			# True if we got a good response.
  144:     my $content;
  145:     my $response;
  146: 
  147:     # Try to get the ssi done. within the retries count:
  148: 
  149:     do {
  150: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  151: 	$ok      = $response->is_success;
  152:         if (!$ok) {
  153:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  154:         }
  155: 	$retries--;
  156:     } while (!$ok && ($retries > 0));
  157: 
  158:     if (!$ok) {
  159: 	$content = '';		# On error return an empty content.
  160:     }
  161:     return ($content, $response);
  162: 
  163: }
  164: 
  165: 
  166: 
  167: # ----------------------------------------------- Filetypes/Languages/Copyright
  168: my %language;
  169: my %supported_language;
  170: my %latex_language;		# For choosing hyphenation in <transl..>
  171: my %latex_language_bykey;	# for choosing hyphenation from metadata
  172: my %cprtag;
  173: my %scprtag;
  174: my %fe; my %fd; my %fm;
  175: my %category_extensions;
  176: 
  177: # ---------------------------------------------- Thesaurus variables
  178: #
  179: # %Keywords:
  180: #      A hash used by &keyword to determine if a word is considered a keyword.
  181: # $thesaurus_db_file 
  182: #      Scalar containing the full path to the thesaurus database.
  183: 
  184: my %Keywords;
  185: my $thesaurus_db_file;
  186: 
  187: #
  188: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  189: # thesaurus.tab, and filecategories.tab.
  190: #
  191: BEGIN {
  192:     # Variable initialization
  193:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  194:     #
  195:     unless ($readit) {
  196: # ------------------------------------------------------------------- languages
  197:     {
  198:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  199:                                    '/language.tab';
  200:         if ( open(my $fh,'<',$langtabfile) ) {
  201:             while (my $line = <$fh>) {
  202:                 next if ($line=~/^\#/);
  203:                 chomp($line);
  204:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  205:                 $language{$key}=$val.' - '.$enc;
  206:                 if ($sup) {
  207:                     $supported_language{$key}=$sup;
  208:                 }
  209: 		if ($latex) {
  210: 		    $latex_language_bykey{$key} = $latex;
  211: 		    $latex_language{$two} = $latex;
  212: 		}
  213:             }
  214:             close($fh);
  215:         }
  216:     }
  217: # ------------------------------------------------------------------ copyrights
  218:     {
  219:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  220:                                   '/copyright.tab';
  221:         if ( open (my $fh,'<',$copyrightfile) ) {
  222:             while (my $line = <$fh>) {
  223:                 next if ($line=~/^\#/);
  224:                 chomp($line);
  225:                 my ($key,$val)=(split(/\s+/,$line,2));
  226:                 $cprtag{$key}=$val;
  227:             }
  228:             close($fh);
  229:         }
  230:     }
  231: # ----------------------------------------------------------- source copyrights
  232:     {
  233:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  234:                                   '/source_copyright.tab';
  235:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
  236:             while (my $line = <$fh>) {
  237:                 next if ($line =~ /^\#/);
  238:                 chomp($line);
  239:                 my ($key,$val)=(split(/\s+/,$line,2));
  240:                 $scprtag{$key}=$val;
  241:             }
  242:             close($fh);
  243:         }
  244:     }
  245: 
  246: # -------------------------------------------------------------- default domain designs
  247:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  248:     my $designfile = $designdir.'/default.tab';
  249:     if ( open (my $fh,'<',$designfile) ) {
  250:         while (my $line = <$fh>) {
  251:             next if ($line =~ /^\#/);
  252:             chomp($line);
  253:             my ($key,$val)=(split(/\=/,$line));
  254:             if ($val) { $defaultdesign{$key}=$val; }
  255:         }
  256:         close($fh);
  257:     }
  258: 
  259: # ------------------------------------------------------------- file categories
  260:     {
  261:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  262:                                   '/filecategories.tab';
  263:         if ( open (my $fh,'<',$categoryfile) ) {
  264: 	    while (my $line = <$fh>) {
  265: 		next if ($line =~ /^\#/);
  266: 		chomp($line);
  267:                 my ($extension,$category)=(split(/\s+/,$line,2));
  268:                 push(@{$category_extensions{lc($category)}},$extension);
  269:             }
  270:             close($fh);
  271:         }
  272: 
  273:     }
  274: # ------------------------------------------------------------------ file types
  275:     {
  276:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  277:                '/filetypes.tab';
  278:         if ( open (my $fh,'<',$typesfile) ) {
  279:             while (my $line = <$fh>) {
  280: 		next if ($line =~ /^\#/);
  281: 		chomp($line);
  282:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  283:                 if ($descr ne '') {
  284:                     $fe{$ending}=lc($emb);
  285:                     $fd{$ending}=$descr;
  286:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  287:                 }
  288:             }
  289:             close($fh);
  290:         }
  291:     }
  292:     &Apache::lonnet::logthis(
  293:              "<span style='color:yellow;'>INFO: Read file types</span>");
  294:     $readit=1;
  295:     }  # end of unless($readit) 
  296:     
  297: }
  298: 
  299: ###############################################################
  300: ##           HTML and Javascript Helper Functions            ##
  301: ###############################################################
  302: 
  303: =pod 
  304: 
  305: =head1 HTML and Javascript Functions
  306: 
  307: =over 4
  308: 
  309: =item * &browser_and_searcher_javascript()
  310: 
  311: X<browsing, javascript>X<searching, javascript>Returns a string
  312: containing javascript with two functions, C<openbrowser> and
  313: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  314: tags.
  315: 
  316: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  317: 
  318: inputs: formname, elementname, only, omit
  319: 
  320: formname and elementname indicate the name of the html form and name of
  321: the element that the results of the browsing selection are to be placed in. 
  322: 
  323: Specifying 'only' will restrict the browser to displaying only files
  324: with the given extension.  Can be a comma separated list.
  325: 
  326: Specifying 'omit' will restrict the browser to NOT displaying files
  327: with the given extension.  Can be a comma separated list.
  328: 
  329: =item * &opensearcher(formname,elementname) [javascript]
  330: 
  331: Inputs: formname, elementname
  332: 
  333: formname and elementname specify the name of the html form and the name
  334: of the element the selection from the search results will be placed in.
  335: 
  336: =cut
  337: 
  338: sub browser_and_searcher_javascript {
  339:     my ($mode)=@_;
  340:     if (!defined($mode)) { $mode='edit'; }
  341:     my $resurl=&escape_single(&lastresurl());
  342:     return <<END;
  343: // <!-- BEGIN LON-CAPA Internal
  344:     var editbrowser = null;
  345:     function openbrowser(formname,elementname,only,omit,titleelement) {
  346:         var url = '$resurl/?';
  347:         if (editbrowser == null) {
  348:             url += 'launch=1&';
  349:         }
  350:         url += 'catalogmode=interactive&';
  351:         url += 'mode=$mode&';
  352:         url += 'inhibitmenu=yes&';
  353:         url += 'form=' + formname + '&';
  354:         if (only != null) {
  355:             url += 'only=' + only + '&';
  356:         } else {
  357:             url += 'only=&';
  358: 	}
  359:         if (omit != null) {
  360:             url += 'omit=' + omit + '&';
  361:         } else {
  362:             url += 'omit=&';
  363: 	}
  364:         if (titleelement != null) {
  365:             url += 'titleelement=' + titleelement + '&';
  366:         } else {
  367: 	    url += 'titleelement=&';
  368: 	}
  369:         url += 'element=' + elementname + '';
  370:         var title = 'Browser';
  371:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  372:         options += ',width=700,height=600';
  373:         editbrowser = open(url,title,options,'1');
  374:         editbrowser.focus();
  375:     }
  376:     var editsearcher;
  377:     function opensearcher(formname,elementname,titleelement) {
  378:         var url = '/adm/searchcat?';
  379:         if (editsearcher == null) {
  380:             url += 'launch=1&';
  381:         }
  382:         url += 'catalogmode=interactive&';
  383:         url += 'mode=$mode&';
  384:         url += 'form=' + formname + '&';
  385:         if (titleelement != null) {
  386:             url += 'titleelement=' + titleelement + '&';
  387:         } else {
  388: 	    url += 'titleelement=&';
  389: 	}
  390:         url += 'element=' + elementname + '';
  391:         var title = 'Search';
  392:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  393:         options += ',width=700,height=600';
  394:         editsearcher = open(url,title,options,'1');
  395:         editsearcher.focus();
  396:     }
  397: // END LON-CAPA Internal -->
  398: END
  399: }
  400: 
  401: sub lastresurl {
  402:     if ($env{'environment.lastresurl'}) {
  403: 	return $env{'environment.lastresurl'}
  404:     } else {
  405: 	return '/res';
  406:     }
  407: }
  408: 
  409: sub storeresurl {
  410:     my $resurl=&Apache::lonnet::clutter(shift);
  411:     unless ($resurl=~/^\/res/) { return 0; }
  412:     $resurl=~s/\/$//;
  413:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  414:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  415:     return 1;
  416: }
  417: 
  418: sub studentbrowser_javascript {
  419:    unless (
  420:             (($env{'request.course.id'}) && 
  421:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  422: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  423: 					  '/'.$env{'request.course.sec'})
  424: 	      ))
  425:          || ($env{'request.role'}=~/^(au|dc|su)/)
  426:           ) { return ''; }  
  427:    return (<<'ENDSTDBRW');
  428: <script type="text/javascript" language="Javascript">
  429: // <![CDATA[
  430:     var stdeditbrowser;
  431:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv) {
  432:         var url = '/adm/pickstudent?';
  433:         var filter;
  434: 	if (!ignorefilter) {
  435: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  436: 	}
  437:         if (filter != null) {
  438:            if (filter != '') {
  439:                url += 'filter='+filter+'&';
  440: 	   }
  441:         }
  442:         url += 'form=' + formname + '&unameelement='+uname+
  443:                                     '&udomelement='+udom+
  444:                                     '&clicker='+clicker;
  445: 	if (roleflag) { url+="&roles=1"; }
  446:         if (courseadv == 'condition') {
  447:             if (document.getElementById('courseadv')) {
  448:                 courseadv = document.getElementById('courseadv').value;
  449:             }
  450:         }
  451:         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
  452:         var title = 'Student_Browser';
  453:         var options = 'scrollbars=1,resizable=1,menubar=0';
  454:         options += ',width=700,height=600';
  455:         stdeditbrowser = open(url,title,options,'1');
  456:         stdeditbrowser.focus();
  457:     }
  458: // ]]>
  459: </script>
  460: ENDSTDBRW
  461: }
  462: 
  463: sub resourcebrowser_javascript {
  464:    unless ($env{'request.course.id'}) { return ''; }
  465:    return (<<'ENDRESBRW');
  466: <script type="text/javascript" language="Javascript">
  467: // <![CDATA[
  468:     var reseditbrowser;
  469:     function openresbrowser(formname,reslink) {
  470:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  471:         var title = 'Resource_Browser';
  472:         var options = 'scrollbars=1,resizable=1,menubar=0';
  473:         options += ',width=700,height=500';
  474:         reseditbrowser = open(url,title,options,'1');
  475:         reseditbrowser.focus();
  476:     }
  477: // ]]>
  478: </script>
  479: ENDRESBRW
  480: }
  481: 
  482: sub selectstudent_link {
  483:    my ($form,$unameele,$udomele,$courseadv,$clickerid)=@_;
  484:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  485:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  486:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  487:    if ($env{'request.course.id'}) {  
  488:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  489: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  490: 					'/'.$env{'request.course.sec'})) {
  491: 	   return '';
  492:        }
  493:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  494:        if ($courseadv eq 'only') {
  495:            $callargs .= ",'',1,'$courseadv'";
  496:        } elsif ($courseadv eq 'none') {
  497:            $callargs .= ",'','','$courseadv'";
  498:        } elsif ($courseadv eq 'condition') {
  499:            $callargs .= ",'','','$courseadv'";
  500:        }
  501:        return '<span class="LC_nobreak">'.
  502:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  503:               &mt('Select User').'</a></span>';
  504:    }
  505:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  506:        $callargs .= ",'',1"; 
  507:        return '<span class="LC_nobreak">'.
  508:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  509:               &mt('Select User').'</a></span>';
  510:    }
  511:    return '';
  512: }
  513: 
  514: sub selectresource_link {
  515:    my ($form,$reslink,$arg)=@_;
  516:    
  517:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  518:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  519:    unless ($env{'request.course.id'}) { return $arg; }
  520:    return '<span class="LC_nobreak">'.
  521:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  522:               $arg.'</a></span>';
  523: }
  524: 
  525: 
  526: 
  527: sub authorbrowser_javascript {
  528:     return <<"ENDAUTHORBRW";
  529: <script type="text/javascript" language="JavaScript">
  530: // <![CDATA[
  531: var stdeditbrowser;
  532: 
  533: function openauthorbrowser(formname,udom) {
  534:     var url = '/adm/pickauthor?';
  535:     url += 'form='+formname+'&roledom='+udom;
  536:     var title = 'Author_Browser';
  537:     var options = 'scrollbars=1,resizable=1,menubar=0';
  538:     options += ',width=700,height=600';
  539:     stdeditbrowser = open(url,title,options,'1');
  540:     stdeditbrowser.focus();
  541: }
  542: 
  543: // ]]>
  544: </script>
  545: ENDAUTHORBRW
  546: }
  547: 
  548: sub coursebrowser_javascript {
  549:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
  550:         $credits_element,$instcode) = @_;
  551:     my $wintitle = 'Course_Browser';
  552:     if ($crstype eq 'Community') {
  553:         $wintitle = 'Community_Browser';
  554:     }
  555:     my $id_functions = &javascript_index_functions();
  556:     my $output = '
  557: <script type="text/javascript" language="JavaScript">
  558: // <![CDATA[
  559:     var stdeditbrowser;'."\n";
  560: 
  561:     $output .= <<"ENDSTDBRW";
  562:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  563:         var url = '/adm/pickcourse?';
  564:         var formid = getFormIdByName(formname);
  565:         var domainfilter = getDomainFromSelectbox(formname,udom);
  566:         if (domainfilter != null) {
  567:            if (domainfilter != '') {
  568:                url += 'domainfilter='+domainfilter+'&';
  569: 	   }
  570:         }
  571:         url += 'form=' + formname + '&cnumelement='+uname+
  572: 	                            '&cdomelement='+udom+
  573:                                     '&cnameelement='+desc;
  574:         if (extra_element !=null && extra_element != '') {
  575:             if (formname == 'rolechoice' || formname == 'studentform') {
  576:                 url += '&roleelement='+extra_element;
  577:                 if (domainfilter == null || domainfilter == '') {
  578:                     url += '&domainfilter='+extra_element;
  579:                 }
  580:             }
  581:             else {
  582:                 if (formname == 'portform') {
  583:                     url += '&setroles='+extra_element;
  584:                 } else {
  585:                     if (formname == 'rules') {
  586:                         url += '&fixeddom='+extra_element; 
  587:                     }
  588:                 }
  589:             }     
  590:         }
  591:         if (type != null && type != '') {
  592:             url += '&type='+type;
  593:         }
  594:         if (type_elem != null && type_elem != '') {
  595:             url += '&typeelement='+type_elem;
  596:         }
  597:         if (formname == 'ccrs') {
  598:             var ownername = document.forms[formid].ccuname.value;
  599:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  600:             url += '&cloner='+ownername+':'+ownerdom;
  601:             if (type == 'Course') {
  602:                 url += '&crscode='+document.forms[formid].crscode.value;
  603:             }
  604:         }
  605:         if (formname == 'requestcrs') {
  606:             url += '&crsdom=$domainfilter&crscode=$instcode';
  607:         }
  608:         if (multflag !=null && multflag != '') {
  609:             url += '&multiple='+multflag;
  610:         }
  611:         var title = '$wintitle';
  612:         var options = 'scrollbars=1,resizable=1,menubar=0';
  613:         options += ',width=700,height=600';
  614:         stdeditbrowser = open(url,title,options,'1');
  615:         stdeditbrowser.focus();
  616:     }
  617: $id_functions
  618: ENDSTDBRW
  619:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
  620:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
  621:                                       $credits_element);
  622:     }
  623:     $output .= '
  624: // ]]>
  625: </script>';
  626:     return $output;
  627: }
  628: 
  629: sub javascript_index_functions {
  630:     return <<"ENDJS";
  631: 
  632: function getFormIdByName(formname) {
  633:     for (var i=0;i<document.forms.length;i++) {
  634:         if (document.forms[i].name == formname) {
  635:             return i;
  636:         }
  637:     }
  638:     return -1;
  639: }
  640: 
  641: function getIndexByName(formid,item) {
  642:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  643:         if (document.forms[formid].elements[i].name == item) {
  644:             return i;
  645:         }
  646:     }
  647:     return -1;
  648: }
  649: 
  650: function getDomainFromSelectbox(formname,udom) {
  651:     var userdom;
  652:     var formid = getFormIdByName(formname);
  653:     if (formid > -1) {
  654:         var domid = getIndexByName(formid,udom);
  655:         if (domid > -1) {
  656:             if (document.forms[formid].elements[domid].type == 'select-one') {
  657:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  658:             }
  659:             if (document.forms[formid].elements[domid].type == 'hidden') {
  660:                 userdom=document.forms[formid].elements[domid].value;
  661:             }
  662:         }
  663:     }
  664:     return userdom;
  665: }
  666: 
  667: ENDJS
  668: 
  669: }
  670: 
  671: sub javascript_array_indexof {
  672:     return <<ENDJS;
  673: <script type="text/javascript" language="JavaScript">
  674: // <![CDATA[
  675: 
  676: if (!Array.prototype.indexOf) {
  677:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  678:         "use strict";
  679:         if (this === void 0 || this === null) {
  680:             throw new TypeError();
  681:         }
  682:         var t = Object(this);
  683:         var len = t.length >>> 0;
  684:         if (len === 0) {
  685:             return -1;
  686:         }
  687:         var n = 0;
  688:         if (arguments.length > 0) {
  689:             n = Number(arguments[1]);
  690:             if (n !== n) { // shortcut for verifying if it's NaN
  691:                 n = 0;
  692:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  693:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  694:             }
  695:         }
  696:         if (n >= len) {
  697:             return -1;
  698:         }
  699:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  700:         for (; k < len; k++) {
  701:             if (k in t && t[k] === searchElement) {
  702:                 return k;
  703:             }
  704:         }
  705:         return -1;
  706:     }
  707: }
  708: 
  709: // ]]>
  710: </script>
  711: 
  712: ENDJS
  713: 
  714: }
  715: 
  716: sub userbrowser_javascript {
  717:     my $id_functions = &javascript_index_functions();
  718:     return <<"ENDUSERBRW";
  719: 
  720: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  721:     var url = '/adm/pickuser?';
  722:     var userdom = getDomainFromSelectbox(formname,udom);
  723:     if (userdom != null) {
  724:        if (userdom != '') {
  725:            url += 'srchdom='+userdom+'&';
  726:        }
  727:     }
  728:     url += 'form=' + formname + '&unameelement='+uname+
  729:                                 '&udomelement='+udom+
  730:                                 '&ulastelement='+ulast+
  731:                                 '&ufirstelement='+ufirst+
  732:                                 '&uemailelement='+uemail+
  733:                                 '&hideudomelement='+hideudom+
  734:                                 '&coursedom='+crsdom;
  735:     if ((caller != null) && (caller != undefined)) {
  736:         url += '&caller='+caller;
  737:     }
  738:     var title = 'User_Browser';
  739:     var options = 'scrollbars=1,resizable=1,menubar=0';
  740:     options += ',width=700,height=600';
  741:     var stdeditbrowser = open(url,title,options,'1');
  742:     stdeditbrowser.focus();
  743: }
  744: 
  745: function fix_domain (formname,udom,origdom,uname) {
  746:     var formid = getFormIdByName(formname);
  747:     if (formid > -1) {
  748:         var unameid = getIndexByName(formid,uname);
  749:         var domid = getIndexByName(formid,udom);
  750:         var hidedomid = getIndexByName(formid,origdom);
  751:         if (hidedomid > -1) {
  752:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  753:             var unameval = document.forms[formid].elements[unameid].value;
  754:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  755:                 if (domid > -1) {
  756:                     var slct = document.forms[formid].elements[domid];
  757:                     if (slct.type == 'select-one') {
  758:                         var i;
  759:                         for (i=0;i<slct.length;i++) {
  760:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  761:                         }
  762:                     }
  763:                     if (slct.type == 'hidden') {
  764:                         slct.value = fixeddom;
  765:                     }
  766:                 }
  767:             }
  768:         }
  769:     }
  770:     return;
  771: }
  772: 
  773: $id_functions
  774: ENDUSERBRW
  775: }
  776: 
  777: sub setsec_javascript {
  778:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
  779:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  780:         $communityrolestr);
  781:     if ($role_element ne '') {
  782:         my @allroles = ('st','ta','ep','in','ad');
  783:         foreach my $crstype ('Course','Community') {
  784:             if ($crstype eq 'Community') {
  785:                 foreach my $role (@allroles) {
  786:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  787:                 }
  788:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  789:             } else {
  790:                 foreach my $role (@allroles) {
  791:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  792:                 }
  793:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  794:             }
  795:         }
  796:         $rolestr = '"'.join('","',@allroles).'"';
  797:         $courserolestr = '"'.join('","',@courserolenames).'"';
  798:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  799:     }
  800:     my $setsections = qq|
  801: function setSect(sectionlist) {
  802:     var sectionsArray = new Array();
  803:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  804:         sectionsArray = sectionlist.split(",");
  805:     }
  806:     var numSections = sectionsArray.length;
  807:     document.$formname.$sec_element.length = 0;
  808:     if (numSections == 0) {
  809:         document.$formname.$sec_element.multiple=false;
  810:         document.$formname.$sec_element.size=1;
  811:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  812:     } else {
  813:         if (numSections == 1) {
  814:             document.$formname.$sec_element.multiple=false;
  815:             document.$formname.$sec_element.size=1;
  816:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  817:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  818:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  819:         } else {
  820:             for (var i=0; i<numSections; i++) {
  821:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  822:             }
  823:             document.$formname.$sec_element.multiple=true
  824:             if (numSections < 3) {
  825:                 document.$formname.$sec_element.size=numSections;
  826:             } else {
  827:                 document.$formname.$sec_element.size=3;
  828:             }
  829:             document.$formname.$sec_element.options[0].selected = false
  830:         }
  831:     }
  832: }
  833: 
  834: function setRole(crstype) {
  835: |;
  836:     if ($role_element eq '') {
  837:         $setsections .= '    return;
  838: }
  839: ';
  840:     } else {
  841:         $setsections .= qq|
  842:     var elementLength = document.$formname.$role_element.length;
  843:     var allroles = Array($rolestr);
  844:     var courserolenames = Array($courserolestr);
  845:     var communityrolenames = Array($communityrolestr);
  846:     if (elementLength != undefined) {
  847:         if (document.$formname.$role_element.options[5].value == 'cc') {
  848:             if (crstype == 'Course') {
  849:                 return;
  850:             } else {
  851:                 allroles[5] = 'co';
  852:                 for (var i=0; i<6; i++) {
  853:                     document.$formname.$role_element.options[i].value = allroles[i];
  854:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  855:                 }
  856:             }
  857:         } else {
  858:             if (crstype == 'Community') {
  859:                 return;
  860:             } else {
  861:                 allroles[5] = 'cc';
  862:                 for (var i=0; i<6; i++) {
  863:                     document.$formname.$role_element.options[i].value = allroles[i];
  864:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  865:                 }
  866:             }
  867:         }
  868:     }
  869:     return;
  870: }
  871: |;
  872:     }
  873:     if ($credits_element) {
  874:         $setsections .= qq|
  875: function setCredits(defaultcredits) {
  876:     document.$formname.$credits_element.value = defaultcredits;
  877:     return;
  878: }
  879: |;
  880:     }
  881:     return $setsections;
  882: }
  883: 
  884: sub selectcourse_link {
  885:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  886:        $typeelement) = @_;
  887:    my $type = $selecttype;
  888:    my $linktext = &mt('Select Course');
  889:    if ($selecttype eq 'Community') {
  890:        $linktext = &mt('Select Community');
  891:    } elsif ($selecttype eq 'Course/Community') {
  892:        $linktext = &mt('Select Course/Community');
  893:        $type = '';
  894:    } elsif ($selecttype eq 'Select') {
  895:        $linktext = &mt('Select');
  896:        $type = '';
  897:    }
  898:    return '<span class="LC_nobreak">'
  899:          ."<a href='"
  900:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  901:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  902:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  903:          ."'>".$linktext.'</a>'
  904:          .'</span>';
  905: }
  906: 
  907: sub selectauthor_link {
  908:    my ($form,$udom)=@_;
  909:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  910:           &mt('Select Author').'</a>';
  911: }
  912: 
  913: sub selectuser_link {
  914:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  915:         $coursedom,$linktext,$caller) = @_;
  916:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  917:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  918:            ');">'.$linktext.'</a>';
  919: }
  920: 
  921: sub check_uncheck_jscript {
  922:     my $jscript = <<"ENDSCRT";
  923: function checkAll(field) {
  924:     if (field.length > 0) {
  925:         for (i = 0; i < field.length; i++) {
  926:             if (!field[i].disabled) {
  927:                 field[i].checked = true;
  928:             }
  929:         }
  930:     } else {
  931:         if (!field.disabled) {
  932:             field.checked = true;
  933:         }
  934:     }
  935: }
  936:  
  937: function uncheckAll(field) {
  938:     if (field.length > 0) {
  939:         for (i = 0; i < field.length; i++) {
  940:             field[i].checked = false ;
  941:         }
  942:     } else {
  943:         field.checked = false ;
  944:     }
  945: }
  946: ENDSCRT
  947:     return $jscript;
  948: }
  949: 
  950: sub select_timezone {
  951:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  952:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  953:    if ($includeempty) {
  954:        $output .= '<option value=""';
  955:        if (($selected eq '') || ($selected eq 'local')) {
  956:            $output .= ' selected="selected" ';
  957:        }
  958:        $output .= '> </option>';
  959:    }
  960:    my @timezones = DateTime::TimeZone->all_names;
  961:    foreach my $tzone (@timezones) {
  962:        $output.= '<option value="'.$tzone.'"';
  963:        if ($tzone eq $selected) {
  964:            $output.=' selected="selected"';
  965:        }
  966:        $output.=">$tzone</option>\n";
  967:    }
  968:    $output.="</select>";
  969:    return $output;
  970: }
  971: 
  972: sub select_datelocale {
  973:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  974:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  975:     if ($includeempty) {
  976:         $output .= '<option value=""';
  977:         if ($selected eq '') {
  978:             $output .= ' selected="selected" ';
  979:         }
  980:         $output .= '> </option>';
  981:     }
  982:     my @languages = &Apache::lonlocal::preferred_languages();
  983:     my (@possibles,%locale_names);
  984:     my @locales = DateTime::Locale->ids();
  985:     foreach my $id (@locales) {
  986:         if ($id ne '') {
  987:             my ($en_terr,$native_terr);
  988:             my $loc = DateTime::Locale->load($id);
  989:             if (ref($loc)) {
  990:                 $en_terr = $loc->name();
  991:                 $native_terr = $loc->native_name();
  992:                 if (grep(/^en$/,@languages) || !@languages) {
  993:                     if ($en_terr ne '') {
  994:                         $locale_names{$id} = '('.$en_terr.')';
  995:                     } elsif ($native_terr ne '') {
  996:                         $locale_names{$id} = $native_terr;
  997:                     }
  998:                 } else {
  999:                     if ($native_terr ne '') {
 1000:                         $locale_names{$id} = $native_terr.' ';
 1001:                     } elsif ($en_terr ne '') {
 1002:                         $locale_names{$id} = '('.$en_terr.')';
 1003:                     }
 1004:                 }
 1005:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
 1006:                 push(@possibles,$id);
 1007:             }
 1008:         }
 1009:     }
 1010:     foreach my $item (sort(@possibles)) {
 1011:         $output.= '<option value="'.$item.'"';
 1012:         if ($item eq $selected) {
 1013:             $output.=' selected="selected"';
 1014:         }
 1015:         $output.=">$item";
 1016:         if ($locale_names{$item} ne '') {
 1017:             $output.='  '.$locale_names{$item};
 1018:         }
 1019:         $output.="</option>\n";
 1020:     }
 1021:     $output.="</select>";
 1022:     return $output;
 1023: }
 1024: 
 1025: sub select_language {
 1026:     my ($name,$selected,$includeempty,$noedit) = @_;
 1027:     my %langchoices;
 1028:     if ($includeempty) {
 1029:         %langchoices = ('' => 'No language preference');
 1030:     }
 1031:     foreach my $id (&languageids()) {
 1032:         my $code = &supportedlanguagecode($id);
 1033:         if ($code) {
 1034:             $langchoices{$code} = &plainlanguagedescription($id);
 1035:         }
 1036:     }
 1037:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
 1038:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
 1039: }
 1040: 
 1041: =pod
 1042: 
 1043: =item * &linked_select_forms(...)
 1044: 
 1045: linked_select_forms returns a string containing a <script></script> block
 1046: and html for two <select> menus.  The select menus will be linked in that
 1047: changing the value of the first menu will result in new values being placed
 1048: in the second menu.  The values in the select menu will appear in alphabetical
 1049: order unless a defined order is provided.
 1050: 
 1051: linked_select_forms takes the following ordered inputs:
 1052: 
 1053: =over 4
 1054: 
 1055: =item * $formname, the name of the <form> tag
 1056: 
 1057: =item * $middletext, the text which appears between the <select> tags
 1058: 
 1059: =item * $firstdefault, the default value for the first menu
 1060: 
 1061: =item * $firstselectname, the name of the first <select> tag
 1062: 
 1063: =item * $secondselectname, the name of the second <select> tag
 1064: 
 1065: =item * $hashref, a reference to a hash containing the data for the menus.
 1066: 
 1067: =item * $menuorder, the order of values in the first menu
 1068: 
 1069: =item * $onchangefirst, additional javascript call to execute for an onchange
 1070:         event for the first <select> tag
 1071: 
 1072: =item * $onchangesecond, additional javascript call to execute for an onchange
 1073:         event for the second <select> tag
 1074: 
 1075: =back 
 1076: 
 1077: Below is an example of such a hash.  Only the 'text', 'default', and 
 1078: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1079: values for the first select menu.  The text that coincides with the 
 1080: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1081: and text for the second menu are given in the hash pointed to by 
 1082: $menu{$choice1}->{'select2'}.  
 1083: 
 1084:  my %menu = ( A1 => { text =>"Choice A1" ,
 1085:                        default => "B3",
 1086:                        select2 => { 
 1087:                            B1 => "Choice B1",
 1088:                            B2 => "Choice B2",
 1089:                            B3 => "Choice B3",
 1090:                            B4 => "Choice B4"
 1091:                            },
 1092:                        order => ['B4','B3','B1','B2'],
 1093:                    },
 1094:                A2 => { text =>"Choice A2" ,
 1095:                        default => "C2",
 1096:                        select2 => { 
 1097:                            C1 => "Choice C1",
 1098:                            C2 => "Choice C2",
 1099:                            C3 => "Choice C3"
 1100:                            },
 1101:                        order => ['C2','C1','C3'],
 1102:                    },
 1103:                A3 => { text =>"Choice A3" ,
 1104:                        default => "D6",
 1105:                        select2 => { 
 1106:                            D1 => "Choice D1",
 1107:                            D2 => "Choice D2",
 1108:                            D3 => "Choice D3",
 1109:                            D4 => "Choice D4",
 1110:                            D5 => "Choice D5",
 1111:                            D6 => "Choice D6",
 1112:                            D7 => "Choice D7"
 1113:                            },
 1114:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1115:                    }
 1116:                );
 1117: 
 1118: =cut
 1119: 
 1120: sub linked_select_forms {
 1121:     my ($formname,
 1122:         $middletext,
 1123:         $firstdefault,
 1124:         $firstselectname,
 1125:         $secondselectname, 
 1126:         $hashref,
 1127:         $menuorder,
 1128:         $onchangefirst,
 1129:         $onchangesecond
 1130:         ) = @_;
 1131:     my $second = "document.$formname.$secondselectname";
 1132:     my $first = "document.$formname.$firstselectname";
 1133:     # output the javascript to do the changing
 1134:     my $result = '';
 1135:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1136:     $result.="// <![CDATA[\n";
 1137:     $result.="var select2data = new Object();\n";
 1138:     $" = '","';
 1139:     my $debug = '';
 1140:     foreach my $s1 (sort(keys(%$hashref))) {
 1141:         $result.="select2data.d_$s1 = new Object();\n";        
 1142:         $result.="select2data.d_$s1.def = new String('".
 1143:             $hashref->{$s1}->{'default'}."');\n";
 1144:         $result.="select2data.d_$s1.values = new Array(";
 1145:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1146:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1147:             @s2values = @{$hashref->{$s1}->{'order'}};
 1148:         }
 1149:         $result.="\"@s2values\");\n";
 1150:         $result.="select2data.d_$s1.texts = new Array(";        
 1151:         my @s2texts;
 1152:         foreach my $value (@s2values) {
 1153:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
 1154:         }
 1155:         $result.="\"@s2texts\");\n";
 1156:     }
 1157:     $"=' ';
 1158:     $result.= <<"END";
 1159: 
 1160: function select1_changed() {
 1161:     // Determine new choice
 1162:     var newvalue = "d_" + $first.value;
 1163:     // update select2
 1164:     var values     = select2data[newvalue].values;
 1165:     var texts      = select2data[newvalue].texts;
 1166:     var select2def = select2data[newvalue].def;
 1167:     var i;
 1168:     // out with the old
 1169:     for (i = 0; i < $second.options.length; i++) {
 1170:         $second.options[i] = null;
 1171:     }
 1172:     // in with the nuclear
 1173:     for (i=0;i<values.length; i++) {
 1174:         $second.options[i] = new Option(values[i]);
 1175:         $second.options[i].value = values[i];
 1176:         $second.options[i].text = texts[i];
 1177:         if (values[i] == select2def) {
 1178:             $second.options[i].selected = true;
 1179:         }
 1180:     }
 1181: }
 1182: // ]]>
 1183: </script>
 1184: END
 1185:     # output the initial values for the selection lists
 1186:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
 1187:     my @order = sort(keys(%{$hashref}));
 1188:     if (ref($menuorder) eq 'ARRAY') {
 1189:         @order = @{$menuorder};
 1190:     }
 1191:     foreach my $value (@order) {
 1192:         $result.="    <option value=\"$value\" ";
 1193:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1194:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1195:     }
 1196:     $result .= "</select>\n";
 1197:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1198:     $result .= $middletext;
 1199:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
 1200:     if ($onchangesecond) {
 1201:         $result .= ' onchange="'.$onchangesecond.'"';
 1202:     }
 1203:     $result .= ">\n";
 1204:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1205:     
 1206:     my @secondorder = sort(keys(%select2));
 1207:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1208:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1209:     }
 1210:     foreach my $value (@secondorder) {
 1211:         $result.="    <option value=\"$value\" ";        
 1212:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1213:         $result.=">".&mt($select2{$value})."</option>\n";
 1214:     }
 1215:     $result .= "</select>\n";
 1216:     #    return $debug;
 1217:     return $result;
 1218: }   #  end of sub linked_select_forms {
 1219: 
 1220: =pod
 1221: 
 1222: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1223: 
 1224: Returns a string corresponding to an HTML link to the given help
 1225: $topic, where $topic corresponds to the name of a .tex file in
 1226: /home/httpd/html/adm/help/tex, with underscores replaced by
 1227: spaces. 
 1228: 
 1229: $text will optionally be linked to the same topic, allowing you to
 1230: link text in addition to the graphic. If you do not want to link
 1231: text, but wish to specify one of the later parameters, pass an
 1232: empty string. 
 1233: 
 1234: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1235: the link will not open a new window. If false, the link will open
 1236: a new window using Javascript. (Default is false.) 
 1237: 
 1238: $width and $height are optional numerical parameters that will
 1239: override the width and height of the popped up window, which may
 1240: be useful for certain help topics with big pictures included.
 1241: 
 1242: $imgid is the id of the img tag used for the help icon. This may be
 1243: used in a javascript call to switch the image src.  See 
 1244: lonhtmlcommon::htmlareaselectactive() for an example.
 1245: 
 1246: =cut
 1247: 
 1248: sub help_open_topic {
 1249:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1250:     $text = "" if (not defined $text);
 1251:     $stayOnPage = 0 if (not defined $stayOnPage);
 1252:     $width = 500 if (not defined $width);
 1253:     $height = 400 if (not defined $height);
 1254:     my $filename = $topic;
 1255:     $filename =~ s/ /_/g;
 1256: 
 1257:     my $template = "";
 1258:     my $link;
 1259:     
 1260:     $topic=~s/\W/\_/g;
 1261: 
 1262:     if (!$stayOnPage) {
 1263:         if ($env{'browser.mobile'}) {
 1264: 	    $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1265:         } else {
 1266:             $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1267:         }
 1268:     } elsif ($stayOnPage eq 'popup') {
 1269:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1270:     } else {
 1271: 	$link = "/adm/help/${filename}.hlp";
 1272:     }
 1273: 
 1274:     # Add the text
 1275:     if ($text ne "") {	
 1276: 	$template.='<span class="LC_help_open_topic">'
 1277:                   .'<a target="_top" href="'.$link.'">'
 1278:                   .$text.'</a>';
 1279:     }
 1280: 
 1281:     # (Always) Add the graphic
 1282:     my $title = &mt('Online Help');
 1283:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1284:     if ($imgid ne '') {
 1285:         $imgid = ' id="'.$imgid.'"';
 1286:     }
 1287:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
 1288:               .'<img src="'.$helpicon.'" border="0"'
 1289:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1290:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1291:               .' /></a>';
 1292:     if ($text ne "") {	
 1293:         $template.='</span>';
 1294:     }
 1295:     return $template;
 1296: 
 1297: }
 1298: 
 1299: # This is a quicky function for Latex cheatsheet editing, since it 
 1300: # appears in at least four places
 1301: sub helpLatexCheatsheet {
 1302:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1303:     my $out;
 1304:     my $addOther = '';
 1305:     if ($topic) {
 1306: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1307:     }
 1308:     $out = '<span>' # Start cheatsheet
 1309: 	  .$addOther
 1310:           .'<span>'
 1311: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1312: 	  .'</span> <span>'
 1313: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1314: 	  .'</span>';
 1315:     unless ($not_author) {
 1316:         $out .= ' <span>'
 1317: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1318: 	       .'</span> <span>'
 1319:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
 1320:                .'</span>';
 1321:     }
 1322:     $out .= '</span>'; # End cheatsheet
 1323:     return $out;
 1324: }
 1325: 
 1326: sub general_help {
 1327:     my $helptopic='Student_Intro';
 1328:     if ($env{'request.role'}=~/^(ca|au)/) {
 1329: 	$helptopic='Authoring_Intro';
 1330:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1331: 	$helptopic='Course_Coordination_Intro';
 1332:     } elsif ($env{'request.role'}=~/^dc/) {
 1333:         $helptopic='Domain_Coordination_Intro';
 1334:     }
 1335:     return $helptopic;
 1336: }
 1337: 
 1338: sub update_help_link {
 1339:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1340:     my $origurl = $ENV{'REQUEST_URI'};
 1341:     $origurl=~s|^/~|/priv/|;
 1342:     my $timestamp = time;
 1343:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1344:         $$datum = &escape($$datum);
 1345:     }
 1346: 
 1347:     my $banner_link = "/adm/helpmenu?page=banner&amp;topic=$topic&amp;component_help=$component_help&amp;faq=$faq&amp;bug=$bug&amp;origurl=$origurl&amp;stamp=$timestamp&amp;stayonpage=$stayOnPage";
 1348:     my $output .= <<"ENDOUTPUT";
 1349: <script type="text/javascript">
 1350: // <![CDATA[
 1351: banner_link = '$banner_link';
 1352: // ]]>
 1353: </script>
 1354: ENDOUTPUT
 1355:     return $output;
 1356: }
 1357: 
 1358: # now just updates the help link and generates a blue icon
 1359: sub help_open_menu {
 1360:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1361: 	= @_;    
 1362:     $stayOnPage = 1;
 1363:     my $output;
 1364:     if ($component_help) {
 1365: 	if (!$text) {
 1366: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1367: 				       $width,$height);
 1368: 	} else {
 1369: 	    my $help_text;
 1370: 	    $help_text=&unescape($topic);
 1371: 	    $output='<table><tr><td>'.
 1372: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1373: 				 $width,$height).'</td></tr></table>';
 1374: 	}
 1375:     }
 1376:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1377:     return $output.$banner_link;
 1378: }
 1379: 
 1380: sub top_nav_help {
 1381:     my ($text,$linkattr) = @_;
 1382:     $text = &mt($text);
 1383:     my $stay_on_page;
 1384:     unless ($env{'environment.remote'} eq 'on') {
 1385:         $stay_on_page = 1;
 1386:     }
 1387:     my ($link,$banner_link);
 1388:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
 1389:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1390: 	                         : "javascript:helpMenu('open')";
 1391:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1392:     }
 1393:     my $title = &mt('Get help');
 1394:     if ($link) {
 1395:         return <<"END";
 1396: $banner_link
 1397: <a href="$link" title="$title" $linkattr>$text</a>
 1398: END
 1399:     } else {
 1400:         return '&nbsp;'.$text.'&nbsp;';
 1401:     }
 1402: }
 1403: 
 1404: sub help_menu_js {
 1405:     my ($httphost) = @_;
 1406:     my $stayOnPage = 1;
 1407:     my $width = 620;
 1408:     my $height = 600;
 1409:     my $helptopic=&general_help();
 1410:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
 1411:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1412:     my $start_page =
 1413:         &Apache::loncommon::start_page('Help Menu', undef,
 1414: 				       {'frameset'    => 1,
 1415: 					'js_ready'    => 1,
 1416:                                         'use_absolute' => $httphost,
 1417: 					'add_entries' => {
 1418: 					    'border' => '0',
 1419: 					    'rows'   => "110,*",},});
 1420:     my $end_page =
 1421:         &Apache::loncommon::end_page({'frameset' => 1,
 1422: 				      'js_ready' => 1,});
 1423: 
 1424:     my $template .= <<"ENDTEMPLATE";
 1425: <script type="text/javascript">
 1426: // <![CDATA[
 1427: // <!-- BEGIN LON-CAPA Internal
 1428: var banner_link = '';
 1429: function helpMenu(target) {
 1430:     var caller = this;
 1431:     if (target == 'open') {
 1432:         var newWindow = null;
 1433:         try {
 1434:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1435:         }
 1436:         catch(error) {
 1437:             writeHelp(caller);
 1438:             return;
 1439:         }
 1440:         if (newWindow) {
 1441:             caller = newWindow;
 1442:         }
 1443:     }
 1444:     writeHelp(caller);
 1445:     return;
 1446: }
 1447: function writeHelp(caller) {
 1448:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
 1449:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
 1450:     caller.document.close();
 1451:     caller.focus();
 1452: }
 1453: // END LON-CAPA Internal -->
 1454: // ]]>
 1455: </script>
 1456: ENDTEMPLATE
 1457:     return $template;
 1458: }
 1459: 
 1460: sub help_open_bug {
 1461:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1462:     unless ($env{'user.adv'}) { return ''; }
 1463:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1464:     $text = "" if (not defined $text);
 1465: 	$stayOnPage=1;
 1466:     $width = 600 if (not defined $width);
 1467:     $height = 600 if (not defined $height);
 1468: 
 1469:     $topic=~s/\W+/\+/g;
 1470:     my $link='';
 1471:     my $template='';
 1472:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1473: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1474:     if (!$stayOnPage)
 1475:     {
 1476: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1477:     }
 1478:     else
 1479:     {
 1480: 	$link = $url;
 1481:     }
 1482:     # Add the text
 1483:     if ($text ne "")
 1484:     {
 1485: 	$template .= 
 1486:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1487:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1488:     }
 1489: 
 1490:     # Add the graphic
 1491:     my $title = &mt('Report a Bug');
 1492:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1493:     $template .= <<"ENDTEMPLATE";
 1494:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1495: ENDTEMPLATE
 1496:     if ($text ne '') { $template.='</td></tr></table>' };
 1497:     return $template;
 1498: 
 1499: }
 1500: 
 1501: sub help_open_faq {
 1502:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1503:     unless ($env{'user.adv'}) { return ''; }
 1504:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1505:     $text = "" if (not defined $text);
 1506: 	$stayOnPage=1;
 1507:     $width = 350 if (not defined $width);
 1508:     $height = 400 if (not defined $height);
 1509: 
 1510:     $topic=~s/\W+/\+/g;
 1511:     my $link='';
 1512:     my $template='';
 1513:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1514:     if (!$stayOnPage)
 1515:     {
 1516: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1517:     }
 1518:     else
 1519:     {
 1520: 	$link = $url;
 1521:     }
 1522: 
 1523:     # Add the text
 1524:     if ($text ne "")
 1525:     {
 1526: 	$template .= 
 1527:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1528:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1529:     }
 1530: 
 1531:     # Add the graphic
 1532:     my $title = &mt('View the FAQ');
 1533:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1534:     $template .= <<"ENDTEMPLATE";
 1535:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1536: ENDTEMPLATE
 1537:     if ($text ne '') { $template.='</td></tr></table>' };
 1538:     return $template;
 1539: 
 1540: }
 1541: 
 1542: ###############################################################
 1543: ###############################################################
 1544: 
 1545: =pod
 1546: 
 1547: =item * &change_content_javascript():
 1548: 
 1549: This and the next function allow you to create small sections of an
 1550: otherwise static HTML page that you can update on the fly with
 1551: Javascript, even in Netscape 4.
 1552: 
 1553: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1554: must be written to the HTML page once. It will prove the Javascript
 1555: function "change(name, content)". Calling the change function with the
 1556: name of the section 
 1557: you want to update, matching the name passed to C<changable_area>, and
 1558: the new content you want to put in there, will put the content into
 1559: that area.
 1560: 
 1561: B<Note>: Netscape 4 only reserves enough space for the changable area
 1562: to contain room for the original contents. You need to "make space"
 1563: for whatever changes you wish to make, and be B<sure> to check your
 1564: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1565: it's adequate for updating a one-line status display, but little more.
 1566: This script will set the space to 100% width, so you only need to
 1567: worry about height in Netscape 4.
 1568: 
 1569: Modern browsers are much less limiting, and if you can commit to the
 1570: user not using Netscape 4, this feature may be used freely with
 1571: pretty much any HTML.
 1572: 
 1573: =cut
 1574: 
 1575: sub change_content_javascript {
 1576:     # If we're on Netscape 4, we need to use Layer-based code
 1577:     if ($env{'browser.type'} eq 'netscape' &&
 1578: 	$env{'browser.version'} =~ /^4\./) {
 1579: 	return (<<NETSCAPE4);
 1580: 	function change(name, content) {
 1581: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1582: 	    doc.open();
 1583: 	    doc.write(content);
 1584: 	    doc.close();
 1585: 	}
 1586: NETSCAPE4
 1587:     } else {
 1588: 	# Otherwise, we need to use semi-standards-compliant code
 1589: 	# (technically, "innerHTML" isn't standard but the equivalent
 1590: 	# is really scary, and every useful browser supports it
 1591: 	return (<<DOMBASED);
 1592: 	function change(name, content) {
 1593: 	    element = document.getElementById(name);
 1594: 	    element.innerHTML = content;
 1595: 	}
 1596: DOMBASED
 1597:     }
 1598: }
 1599: 
 1600: =pod
 1601: 
 1602: =item * &changable_area($name,$origContent):
 1603: 
 1604: This provides a "changable area" that can be modified on the fly via
 1605: the Javascript code provided in C<change_content_javascript>. $name is
 1606: the name you will use to reference the area later; do not repeat the
 1607: same name on a given HTML page more then once. $origContent is what
 1608: the area will originally contain, which can be left blank.
 1609: 
 1610: =cut
 1611: 
 1612: sub changable_area {
 1613:     my ($name, $origContent) = @_;
 1614: 
 1615:     if ($env{'browser.type'} eq 'netscape' &&
 1616: 	$env{'browser.version'} =~ /^4\./) {
 1617: 	# If this is netscape 4, we need to use the Layer tag
 1618: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1619:     } else {
 1620: 	return "<span id='$name'>$origContent</span>";
 1621:     }
 1622: }
 1623: 
 1624: =pod
 1625: 
 1626: =item * &viewport_geometry_js 
 1627: 
 1628: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1629: 
 1630: =cut
 1631: 
 1632: 
 1633: sub viewport_geometry_js { 
 1634:     return <<"GEOMETRY";
 1635: var Geometry = {};
 1636: function init_geometry() {
 1637:     if (Geometry.init) { return };
 1638:     Geometry.init=1;
 1639:     if (window.innerHeight) {
 1640:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1641:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1642:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1643:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1644:     }
 1645:     else if (document.documentElement && document.documentElement.clientHeight) {
 1646:         Geometry.getViewportHeight =
 1647:             function() { return document.documentElement.clientHeight; };
 1648:         Geometry.getViewportWidth =
 1649:             function() { return document.documentElement.clientWidth; };
 1650: 
 1651:         Geometry.getHorizontalScroll =
 1652:             function() { return document.documentElement.scrollLeft; };
 1653:         Geometry.getVerticalScroll =
 1654:             function() { return document.documentElement.scrollTop; };
 1655:     }
 1656:     else if (document.body.clientHeight) {
 1657:         Geometry.getViewportHeight =
 1658:             function() { return document.body.clientHeight; };
 1659:         Geometry.getViewportWidth =
 1660:             function() { return document.body.clientWidth; };
 1661:         Geometry.getHorizontalScroll =
 1662:             function() { return document.body.scrollLeft; };
 1663:         Geometry.getVerticalScroll =
 1664:             function() { return document.body.scrollTop; };
 1665:     }
 1666: }
 1667: 
 1668: GEOMETRY
 1669: }
 1670: 
 1671: =pod
 1672: 
 1673: =item * &viewport_size_js()
 1674: 
 1675: Provides a javascript function to set values of two form elements - width and height (elements are passed in as arguments to the javascript function) to the dimensions of the user's browser window. 
 1676: 
 1677: =cut
 1678: 
 1679: sub viewport_size_js {
 1680:     my $geometry = &viewport_geometry_js();
 1681:     return <<"DIMS";
 1682: 
 1683: $geometry
 1684: 
 1685: function getViewportDims(width,height) {
 1686:     init_geometry();
 1687:     width.value = Geometry.getViewportWidth();
 1688:     height.value = Geometry.getViewportHeight();
 1689:     return;
 1690: }
 1691: 
 1692: DIMS
 1693: }
 1694: 
 1695: =pod
 1696: 
 1697: =item * &resize_textarea_js()
 1698: 
 1699: emits the needed javascript to resize a textarea to be as big as possible
 1700: 
 1701: creates a function resize_textrea that takes two IDs first should be
 1702: the id of the element to resize, second should be the id of a div that
 1703: surrounds everything that comes after the textarea, this routine needs
 1704: to be attached to the <body> for the onload and onresize events.
 1705: 
 1706: =back
 1707: 
 1708: =cut
 1709: 
 1710: sub resize_textarea_js {
 1711:     my $geometry = &viewport_geometry_js();
 1712:     return <<"RESIZE";
 1713:     <script type="text/javascript">
 1714: // <![CDATA[
 1715: $geometry
 1716: 
 1717: function getX(element) {
 1718:     var x = 0;
 1719:     while (element) {
 1720: 	x += element.offsetLeft;
 1721: 	element = element.offsetParent;
 1722:     }
 1723:     return x;
 1724: }
 1725: function getY(element) {
 1726:     var y = 0;
 1727:     while (element) {
 1728: 	y += element.offsetTop;
 1729: 	element = element.offsetParent;
 1730:     }
 1731:     return y;
 1732: }
 1733: 
 1734: 
 1735: function resize_textarea(textarea_id,bottom_id) {
 1736:     init_geometry();
 1737:     var textarea        = document.getElementById(textarea_id);
 1738:     //alert(textarea);
 1739: 
 1740:     var textarea_top    = getY(textarea);
 1741:     var textarea_height = textarea.offsetHeight;
 1742:     var bottom          = document.getElementById(bottom_id);
 1743:     var bottom_top      = getY(bottom);
 1744:     var bottom_height   = bottom.offsetHeight;
 1745:     var window_height   = Geometry.getViewportHeight();
 1746:     var fudge           = 23;
 1747:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1748:     if (new_height < 300) {
 1749: 	new_height = 300;
 1750:     }
 1751:     textarea.style.height=new_height+'px';
 1752: }
 1753: // ]]>
 1754: </script>
 1755: RESIZE
 1756: 
 1757: }
 1758: 
 1759: sub colorfuleditor_js {
 1760:     return <<"COLORFULEDIT"
 1761: <script type="text/javascript">
 1762: // <![CDATA[>
 1763:     function fold_box(curDepth, lastresource){
 1764: 
 1765:     // we need a list because there can be several blocks you need to fold in one tag
 1766:         var block = document.getElementsByName('foldblock_'+curDepth);
 1767:     // but there is only one folding button per tag
 1768:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
 1769: 
 1770:         if(block.item(0).style.display == 'none'){
 1771: 
 1772:             foldbutton.value = '@{[&mt("Hide")]}';
 1773:             for (i = 0; i < block.length; i++){
 1774:                 block.item(i).style.display = '';
 1775:             }
 1776:         }else{
 1777: 
 1778:             foldbutton.value = '@{[&mt("Show")]}';
 1779:             for (i = 0; i < block.length; i++){
 1780:                 // block.item(i).style.visibility = 'collapse';
 1781:                 block.item(i).style.display = 'none';
 1782:             }
 1783:         };
 1784:         saveState(lastresource);
 1785:     }
 1786: 
 1787:     function saveState (lastresource) {
 1788: 
 1789:         var tag_list = getTagList();
 1790:         if(tag_list != null){
 1791:             var timestamp = new Date().getTime();
 1792:             var key = lastresource;
 1793: 
 1794:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
 1795:             // starting with timestamp
 1796:             var value = timestamp+';';
 1797: 
 1798:             // building the list of key-value pairs
 1799:             for(var i = 0; i < tag_list.length; i++){
 1800:                 value += tag_list[i]+',';
 1801:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
 1802:             }
 1803: 
 1804:             // only iterate whole storage if nothing to override
 1805:             if(localStorage.getItem(key) == null){
 1806: 
 1807:                 // prevent storage from growing large
 1808:                 if(localStorage.length > 50){
 1809:                     var regex_getTimestamp = /^(?:\d)+;/;
 1810:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
 1811:                     var oldest_key;
 1812: 
 1813:                     for(var i = 1; i < localStorage.length; i++){
 1814:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
 1815:                             oldest_key = localStorage.key(i);
 1816:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
 1817:                         }
 1818:                     }
 1819:                     localStorage.removeItem(oldest_key);
 1820:                 }
 1821:             }
 1822:             localStorage.setItem(key,value);
 1823:         }
 1824:     }
 1825: 
 1826:     // restore folding status of blocks (on page load)
 1827:     function restoreState (lastresource) {
 1828:         if(localStorage.getItem(lastresource) != null){
 1829:             var key = lastresource;
 1830:             var value = localStorage.getItem(key);
 1831:             var regex_delTimestamp = /^\d+;/;
 1832: 
 1833:             value.replace(regex_delTimestamp, '');
 1834: 
 1835:             var valueArr = value.split(';');
 1836:             var pairs;
 1837:             var elements;
 1838:             for (var i = 0; i < valueArr.length; i++){
 1839:                 pairs = valueArr[i].split(',');
 1840:                 elements = document.getElementsByName(pairs[0]);
 1841: 
 1842:                 for (var j = 0; j < elements.length; j++){
 1843:                     elements[j].style.display = pairs[1];
 1844:                     if (pairs[1] == "none"){
 1845:                         var regex_id = /([_\\d]+)\$/;
 1846:                         regex_id.exec(pairs[0]);
 1847:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
 1848:                     }
 1849:                 }
 1850:             }
 1851:         }
 1852:     }
 1853: 
 1854:     function getTagList () {
 1855: 
 1856:         var stringToSearch = document.lonhomework.innerHTML;
 1857: 
 1858:         var ret = new Array();
 1859:         var regex_findBlock = /(foldblock_.*?)"/g;
 1860:         var tag_list = stringToSearch.match(regex_findBlock);
 1861: 
 1862:         if(tag_list != null){
 1863:             for(var i = 0; i < tag_list.length; i++){
 1864:                 ret.push(tag_list[i].replace(/"/, ''));
 1865:             }
 1866:         }
 1867:         return ret;
 1868:     }
 1869: 
 1870:     function saveScrollPosition (resource) {
 1871:         var tag_list = getTagList();
 1872: 
 1873:         // we dont always want to jump to the first block
 1874:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
 1875:         if(\$(window).scrollTop() > 170){
 1876:             if(tag_list != null){
 1877:                 var result;
 1878:                 for(var i = 0; i < tag_list.length; i++){
 1879:                     if(isElementInViewport(tag_list[i])){
 1880:                         result += tag_list[i]+';';
 1881:                     }
 1882:                 }
 1883:                 sessionStorage.setItem('anchor_'+resource, result);
 1884:             }
 1885:         } else {
 1886:             // we dont need to save zero, just delete the item to leave everything tidy
 1887:             sessionStorage.removeItem('anchor_'+resource);
 1888:         }
 1889:     }
 1890: 
 1891:     function restoreScrollPosition(resource){
 1892: 
 1893:         var elem = sessionStorage.getItem('anchor_'+resource);
 1894:         if(elem != null){
 1895:             var tag_list = elem.split(';');
 1896:             var elem_list;
 1897: 
 1898:             for(var i = 0; i < tag_list.length; i++){
 1899:                 elem_list = document.getElementsByName(tag_list[i]);
 1900: 
 1901:                 if(elem_list.length > 0){
 1902:                     elem = elem_list[0];
 1903:                     break;
 1904:                 }
 1905:             }
 1906:             elem.scrollIntoView();
 1907:         }
 1908:     }
 1909: 
 1910:     function isElementInViewport(el) {
 1911: 
 1912:         // change to last element instead of first
 1913:         var elem = document.getElementsByName(el);
 1914:         var rect = elem[0].getBoundingClientRect();
 1915: 
 1916:         return (
 1917:             rect.top >= 0 &&
 1918:             rect.left >= 0 &&
 1919:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
 1920:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
 1921:         );
 1922:     }
 1923: 
 1924:     function autosize(depth){
 1925:         var cmInst = window['cm'+depth];
 1926:         var fitsizeButton = document.getElementById('fitsize'+depth);
 1927: 
 1928:         // is fixed size, switching to dynamic
 1929:         if (sessionStorage.getItem("autosized_"+depth) == null) {
 1930:             cmInst.setSize("","auto");
 1931:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
 1932:             sessionStorage.setItem("autosized_"+depth, "yes");
 1933: 
 1934:         // is dynamic size, switching to fixed
 1935:         } else {
 1936:             cmInst.setSize("","300px");
 1937:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
 1938:             sessionStorage.removeItem("autosized_"+depth);
 1939:         }
 1940:     }
 1941: 
 1942: 
 1943: 
 1944: // ]]>
 1945: </script>
 1946: COLORFULEDIT
 1947: }
 1948: 
 1949: sub xmleditor_js {
 1950:     return <<XMLEDIT
 1951: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
 1952: <script type="text/javascript">
 1953: // <![CDATA[>
 1954: 
 1955:     function saveScrollPosition (resource) {
 1956: 
 1957:         var scrollPos = \$(window).scrollTop();
 1958:         sessionStorage.setItem(resource,scrollPos);
 1959:     }
 1960: 
 1961:     function restoreScrollPosition(resource){
 1962: 
 1963:         var scrollPos = sessionStorage.getItem(resource);
 1964:         \$(window).scrollTop(scrollPos);
 1965:     }
 1966: 
 1967:     // unless internet explorer
 1968:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
 1969: 
 1970:         \$(document).ready(function() {
 1971:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
 1972:         });
 1973:     }
 1974: 
 1975:     // inserts text at cursor position into codemirror (xml editor only)
 1976:     function insertText(text){
 1977:         cm.focus();
 1978:         var curPos = cm.getCursor();
 1979:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
 1980:     }
 1981: // ]]>
 1982: </script>
 1983: XMLEDIT
 1984: }
 1985: 
 1986: sub insert_folding_button {
 1987:     my $curDepth = $Apache::lonxml::curdepth;
 1988:     my $lastresource = $env{'request.ambiguous'};
 1989: 
 1990:     return "<input type=\"button\" id=\"folding_btn_$curDepth\"
 1991:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
 1992: }
 1993: 
 1994: 
 1995: =pod
 1996: 
 1997: =head1 Excel and CSV file utility routines
 1998: 
 1999: =cut
 2000: 
 2001: ###############################################################
 2002: ###############################################################
 2003: 
 2004: =pod
 2005: 
 2006: =over 4
 2007: 
 2008: =item * &csv_translate($text) 
 2009: 
 2010: Translate $text to allow it to be output as a 'comma separated values' 
 2011: format.
 2012: 
 2013: =cut
 2014: 
 2015: ###############################################################
 2016: ###############################################################
 2017: sub csv_translate {
 2018:     my $text = shift;
 2019:     $text =~ s/\"/\"\"/g;
 2020:     $text =~ s/\n/ /g;
 2021:     return $text;
 2022: }
 2023: 
 2024: ###############################################################
 2025: ###############################################################
 2026: 
 2027: =pod
 2028: 
 2029: =item * &define_excel_formats()
 2030: 
 2031: Define some commonly used Excel cell formats.
 2032: 
 2033: Currently supported formats:
 2034: 
 2035: =over 4
 2036: 
 2037: =item header
 2038: 
 2039: =item bold
 2040: 
 2041: =item h1
 2042: 
 2043: =item h2
 2044: 
 2045: =item h3
 2046: 
 2047: =item h4
 2048: 
 2049: =item i
 2050: 
 2051: =item date
 2052: 
 2053: =back
 2054: 
 2055: Inputs: $workbook
 2056: 
 2057: Returns: $format, a hash reference.
 2058: 
 2059: 
 2060: =cut
 2061: 
 2062: ###############################################################
 2063: ###############################################################
 2064: sub define_excel_formats {
 2065:     my ($workbook) = @_;
 2066:     my $format;
 2067:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 2068:                                                 bottom    => 1,
 2069:                                                 align     => 'center');
 2070:     $format->{'bold'} = $workbook->add_format(bold=>1);
 2071:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 2072:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 2073:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 2074:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 2075:     $format->{'i'}    = $workbook->add_format(italic=>1);
 2076:     $format->{'date'} = $workbook->add_format(num_format=>
 2077:                                             'mm/dd/yyyy hh:mm:ss');
 2078:     return $format;
 2079: }
 2080: 
 2081: ###############################################################
 2082: ###############################################################
 2083: 
 2084: =pod
 2085: 
 2086: =item * &create_workbook()
 2087: 
 2088: Create an Excel worksheet.  If it fails, output message on the
 2089: request object and return undefs.
 2090: 
 2091: Inputs: Apache request object
 2092: 
 2093: Returns (undef) on failure, 
 2094:     Excel worksheet object, scalar with filename, and formats 
 2095:     from &Apache::loncommon::define_excel_formats on success
 2096: 
 2097: =cut
 2098: 
 2099: ###############################################################
 2100: ###############################################################
 2101: sub create_workbook {
 2102:     my ($r) = @_;
 2103:         #
 2104:     # Create the excel spreadsheet
 2105:     my $filename = '/prtspool/'.
 2106:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2107:         time.'_'.rand(1000000000).'.xls';
 2108:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 2109:     if (! defined($workbook)) {
 2110:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 2111:         $r->print(
 2112:             '<p class="LC_error">'
 2113:            .&mt('Problems occurred in creating the new Excel file.')
 2114:            .' '.&mt('This error has been logged.')
 2115:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2116:            .'</p>'
 2117:         );
 2118:         return (undef);
 2119:     }
 2120:     #
 2121:     $workbook->set_tempdir(LONCAPA::tempdir());
 2122:     #
 2123:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 2124:     return ($workbook,$filename,$format);
 2125: }
 2126: 
 2127: ###############################################################
 2128: ###############################################################
 2129: 
 2130: =pod
 2131: 
 2132: =item * &create_text_file()
 2133: 
 2134: Create a file to write to and eventually make available to the user.
 2135: If file creation fails, outputs an error message on the request object and 
 2136: return undefs.
 2137: 
 2138: Inputs: Apache request object, and file suffix
 2139: 
 2140: Returns (undef) on failure, 
 2141:     Filehandle and filename on success.
 2142: 
 2143: =cut
 2144: 
 2145: ###############################################################
 2146: ###############################################################
 2147: sub create_text_file {
 2148:     my ($r,$suffix) = @_;
 2149:     if (! defined($suffix)) { $suffix = 'txt'; };
 2150:     my $fh;
 2151:     my $filename = '/prtspool/'.
 2152:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2153:         time.'_'.rand(1000000000).'.'.$suffix;
 2154:     $fh = Apache::File->new('>/home/httpd'.$filename);
 2155:     if (! defined($fh)) {
 2156:         $r->log_error("Couldn't open $filename for output $!");
 2157:         $r->print(
 2158:             '<p class="LC_error">'
 2159:            .&mt('Problems occurred in creating the output file.')
 2160:            .' '.&mt('This error has been logged.')
 2161:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2162:            .'</p>'
 2163:         );
 2164:     }
 2165:     return ($fh,$filename)
 2166: }
 2167: 
 2168: 
 2169: =pod 
 2170: 
 2171: =back
 2172: 
 2173: =cut
 2174: 
 2175: ###############################################################
 2176: ##        Home server <option> list generating code          ##
 2177: ###############################################################
 2178: 
 2179: # ------------------------------------------
 2180: 
 2181: sub domain_select {
 2182:     my ($name,$value,$multiple)=@_;
 2183:     my %domains=map { 
 2184: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 2185:     } &Apache::lonnet::all_domains();
 2186:     if ($multiple) {
 2187: 	$domains{''}=&mt('Any domain');
 2188: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2189: 	return &multiple_select_form($name,$value,4,\%domains);
 2190:     } else {
 2191: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2192: 	return &select_form($name,$value,\%domains);
 2193:     }
 2194: }
 2195: 
 2196: #-------------------------------------------
 2197: 
 2198: =pod
 2199: 
 2200: =head1 Routines for form select boxes
 2201: 
 2202: =over 4
 2203: 
 2204: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 2205: 
 2206: Returns a string containing a <select> element int multiple mode
 2207: 
 2208: 
 2209: Args:
 2210:   $name - name of the <select> element
 2211:   $value - scalar or array ref of values that should already be selected
 2212:   $size - number of rows long the select element is
 2213:   $hash - the elements should be 'option' => 'shown text'
 2214:           (shown text should already have been &mt())
 2215:   $order - (optional) array ref of the order to show the elements in
 2216: 
 2217: =cut
 2218: 
 2219: #-------------------------------------------
 2220: sub multiple_select_form {
 2221:     my ($name,$value,$size,$hash,$order)=@_;
 2222:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 2223:     my $output='';
 2224:     if (! defined($size)) {
 2225:         $size = 4;
 2226:         if (scalar(keys(%$hash))<4) {
 2227:             $size = scalar(keys(%$hash));
 2228:         }
 2229:     }
 2230:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 2231:     my @order;
 2232:     if (ref($order) eq 'ARRAY')  {
 2233:         @order = @{$order};
 2234:     } else {
 2235:         @order = sort(keys(%$hash));
 2236:     }
 2237:     if (exists($$hash{'select_form_order'})) {
 2238:         @order = @{$$hash{'select_form_order'}};
 2239:     }
 2240:         
 2241:     foreach my $key (@order) {
 2242:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 2243:         $output.='selected="selected" ' if ($selected{$key});
 2244:         $output.='>'.$hash->{$key}."</option>\n";
 2245:     }
 2246:     $output.="</select>\n";
 2247:     return $output;
 2248: }
 2249: 
 2250: #-------------------------------------------
 2251: 
 2252: =pod
 2253: 
 2254: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
 2255: 
 2256: Returns a string containing a <select name='$name' size='1'> form to 
 2257: allow a user to select options from a ref to a hash containing:
 2258: option_name => displayed text. An optional $onchange can include
 2259: a javascript onchange item, e.g., onchange="this.form.submit();".
 2260: An optional arg -- $readonly -- if true will cause the select form
 2261: to be disabled, e.g., for the case where an instructor has a section-
 2262: specific role, and is viewing/modifying parameters.  
 2263: 
 2264: See lonrights.pm for an example invocation and use.
 2265: 
 2266: =cut
 2267: 
 2268: #-------------------------------------------
 2269: sub select_form {
 2270:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
 2271:     return unless (ref($hashref) eq 'HASH');
 2272:     if ($onchange) {
 2273:         $onchange = ' onchange="'.$onchange.'"';
 2274:     }
 2275:     my $disabled;
 2276:     if ($readonly) {
 2277:         $disabled = ' disabled="disabled"';
 2278:     }
 2279:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2280:     my @keys;
 2281:     if (exists($hashref->{'select_form_order'})) {
 2282: 	@keys=@{$hashref->{'select_form_order'}};
 2283:     } else {
 2284: 	@keys=sort(keys(%{$hashref}));
 2285:     }
 2286:     foreach my $key (@keys) {
 2287:         $selectform.=
 2288: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2289:             ($key eq $def ? 'selected="selected" ' : '').
 2290:                 ">".$hashref->{$key}."</option>\n";
 2291:     }
 2292:     $selectform.="</select>";
 2293:     return $selectform;
 2294: }
 2295: 
 2296: # For display filters
 2297: 
 2298: sub display_filter {
 2299:     my ($context) = @_;
 2300:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2301:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2302:     my $phraseinput = 'hidden';
 2303:     my $includeinput = 'hidden';
 2304:     my ($checked,$includetypestext);
 2305:     if ($env{'form.displayfilter'} eq 'containing') {
 2306:         $phraseinput = 'text'; 
 2307:         if ($context eq 'parmslog') {
 2308:             $includeinput = 'checkbox';
 2309:             if ($env{'form.includetypes'}) {
 2310:                 $checked = ' checked="checked"';
 2311:             }
 2312:             $includetypestext = &mt('Include parameter types');
 2313:         }
 2314:     } else {
 2315:         $includetypestext = '&nbsp;';
 2316:     }
 2317:     my ($additional,$secondid,$thirdid);
 2318:     if ($context eq 'parmslog') {
 2319:         $additional = 
 2320:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2321:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2322:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2323:             '</label>';
 2324:         $secondid = 'includetypes';
 2325:         $thirdid = 'includetypestext';
 2326:     }
 2327:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2328:                                                     '$secondid','$thirdid')";
 2329:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2330: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 2331: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2332: 	   '</label></span> <span class="LC_nobreak">'.
 2333:            &mt('Filter: [_1]',
 2334: 	   &select_form($env{'form.displayfilter'},
 2335: 			'displayfilter',
 2336: 			{'currentfolder' => 'Current folder/page',
 2337: 			 'containing' => 'Containing phrase',
 2338: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2339: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2340:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2341:                          '" />'.$additional;
 2342: }
 2343: 
 2344: sub display_filter_js {
 2345:     my $includetext = &mt('Include parameter types');
 2346:     return <<"ENDJS";
 2347:   
 2348: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2349:     var firstType = 'hidden';
 2350:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2351:         firstType = 'text';
 2352:     }
 2353:     firstObject = document.getElementById(firstid);
 2354:     if (typeof(firstObject) == 'object') {
 2355:         if (firstObject.type != firstType) {
 2356:             changeInputType(firstObject,firstType);
 2357:         }
 2358:     }
 2359:     if (context == 'parmslog') {
 2360:         var secondType = 'hidden';
 2361:         if (firstType == 'text') {
 2362:             secondType = 'checkbox';
 2363:         }
 2364:         secondObject = document.getElementById(secondid);  
 2365:         if (typeof(secondObject) == 'object') {
 2366:             if (secondObject.type != secondType) {
 2367:                 changeInputType(secondObject,secondType);
 2368:             }
 2369:         }
 2370:         var textItem = document.getElementById(thirdid);
 2371:         var currtext = textItem.innerHTML;
 2372:         var newtext;
 2373:         if (firstType == 'text') {
 2374:             newtext = '$includetext';
 2375:         } else {
 2376:             newtext = '&nbsp;';
 2377:         }
 2378:         if (currtext != newtext) {
 2379:             textItem.innerHTML = newtext;
 2380:         }
 2381:     }
 2382:     return;
 2383: }
 2384: 
 2385: function changeInputType(oldObject,newType) {
 2386:     var newObject = document.createElement('input');
 2387:     newObject.type = newType;
 2388:     if (oldObject.size) {
 2389:         newObject.size = oldObject.size;
 2390:     }
 2391:     if (oldObject.value) {
 2392:         newObject.value = oldObject.value;
 2393:     }
 2394:     if (oldObject.name) {
 2395:         newObject.name = oldObject.name;
 2396:     }
 2397:     if (oldObject.id) {
 2398:         newObject.id = oldObject.id;
 2399:     }
 2400:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2401:     return;
 2402: }
 2403: 
 2404: ENDJS
 2405: }
 2406: 
 2407: sub gradeleveldescription {
 2408:     my $gradelevel=shift;
 2409:     my %gradelevels=(0 => 'Not specified',
 2410: 		     1 => 'Grade 1',
 2411: 		     2 => 'Grade 2',
 2412: 		     3 => 'Grade 3',
 2413: 		     4 => 'Grade 4',
 2414: 		     5 => 'Grade 5',
 2415: 		     6 => 'Grade 6',
 2416: 		     7 => 'Grade 7',
 2417: 		     8 => 'Grade 8',
 2418: 		     9 => 'Grade 9',
 2419: 		     10 => 'Grade 10',
 2420: 		     11 => 'Grade 11',
 2421: 		     12 => 'Grade 12',
 2422: 		     13 => 'Grade 13',
 2423: 		     14 => '100 Level',
 2424: 		     15 => '200 Level',
 2425: 		     16 => '300 Level',
 2426: 		     17 => '400 Level',
 2427: 		     18 => 'Graduate Level');
 2428:     return &mt($gradelevels{$gradelevel});
 2429: }
 2430: 
 2431: sub select_level_form {
 2432:     my ($deflevel,$name)=@_;
 2433:     unless ($deflevel) { $deflevel=0; }
 2434:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2435:     for (my $i=0; $i<=18; $i++) {
 2436:         $selectform.="<option value=\"$i\" ".
 2437:             ($i==$deflevel ? 'selected="selected" ' : '').
 2438:                 ">".&gradeleveldescription($i)."</option>\n";
 2439:     }
 2440:     $selectform.="</select>";
 2441:     return $selectform;
 2442: }
 2443: 
 2444: #-------------------------------------------
 2445: 
 2446: =pod
 2447: 
 2448: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
 2449: 
 2450: Returns a string containing a <select name='$name' size='1'> form to 
 2451: allow a user to select the domain to preform an operation in.  
 2452: See loncreateuser.pm for an example invocation and use.
 2453: 
 2454: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2455: selected");
 2456: 
 2457: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2458: 
 2459: The optional $onchange argument specifies what should occur if the domain selector is changed, e.g., 'this.form.submit()' if the form is to be automatically submitted.
 2460: 
 2461: The optional $incdoms is a reference to an array of domains which will be the only available options.
 2462: 
 2463: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
 2464: 
 2465: The optional $disabled argument, if true, adds the disabled attribute to the select tag. 
 2466: 
 2467: =cut
 2468: 
 2469: #-------------------------------------------
 2470: sub select_dom_form {
 2471:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
 2472:     if ($onchange) {
 2473:         $onchange = ' onchange="'.$onchange.'"';
 2474:     }
 2475:     if ($disabled) {
 2476:         $disabled = ' disabled="disabled"';
 2477:     }
 2478:     my (@domains,%exclude);
 2479:     if (ref($incdoms) eq 'ARRAY') {
 2480:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2481:     } else {
 2482:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2483:     }
 2484:     if ($includeempty) { @domains=('',@domains); }
 2485:     if (ref($excdoms) eq 'ARRAY') {
 2486:         map { $exclude{$_} = 1; } @{$excdoms};
 2487:     }
 2488:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2489:     foreach my $dom (@domains) {
 2490:         next if ($exclude{$dom});
 2491:         $selectdomain.="<option value=\"$dom\" ".
 2492:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2493:         if ($showdomdesc) {
 2494:             if ($dom ne '') {
 2495:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2496:                 if ($domdesc ne '') {
 2497:                     $selectdomain .= ' ('.$domdesc.')';
 2498:                 }
 2499:             } 
 2500:         }
 2501:         $selectdomain .= "</option>\n";
 2502:     }
 2503:     $selectdomain.="</select>";
 2504:     return $selectdomain;
 2505: }
 2506: 
 2507: #-------------------------------------------
 2508: 
 2509: =pod
 2510: 
 2511: =item * &home_server_form_item($domain,$name,$defaultflag)
 2512: 
 2513: input: 4 arguments (two required, two optional) - 
 2514:     $domain - domain of new user
 2515:     $name - name of form element
 2516:     $default - Value of 'default' causes a default item to be first 
 2517:                             option, and selected by default. 
 2518:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2519:                             if 1 server found, or default, if 0 found.
 2520: output: returns 2 items: 
 2521: (a) form element which contains either:
 2522:    (i) <select name="$name">
 2523:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2524:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2525:        </select>
 2526:        form item if there are multiple library servers in $domain, or
 2527:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2528:        if there is only one library server in $domain.
 2529: 
 2530: (b) number of library servers found.
 2531: 
 2532: See loncreateuser.pm for example of use.
 2533: 
 2534: =cut
 2535: 
 2536: #-------------------------------------------
 2537: sub home_server_form_item {
 2538:     my ($domain,$name,$default,$hide) = @_;
 2539:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2540:     my $result;
 2541:     my $numlib = keys(%servers);
 2542:     if ($numlib > 1) {
 2543:         $result .= '<select name="'.$name.'" />'."\n";
 2544:         if ($default) {
 2545:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2546:                        '</option>'."\n";
 2547:         }
 2548:         foreach my $hostid (sort(keys(%servers))) {
 2549:             $result.= '<option value="'.$hostid.'">'.
 2550: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2551:         }
 2552:         $result .= '</select>'."\n";
 2553:     } elsif ($numlib == 1) {
 2554:         my $hostid;
 2555:         foreach my $item (keys(%servers)) {
 2556:             $hostid = $item;
 2557:         }
 2558:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2559:                    $hostid.'" />';
 2560:                    if (!$hide) {
 2561:                        $result .= $hostid.' '.$servers{$hostid};
 2562:                    }
 2563:                    $result .= "\n";
 2564:     } elsif ($default) {
 2565:         $result .= '<input type="hidden" name="'.$name.
 2566:                    '" value="default" />';
 2567:                    if (!$hide) {
 2568:                        $result .= &mt('default');
 2569:                    }
 2570:                    $result .= "\n";
 2571:     }
 2572:     return ($result,$numlib);
 2573: }
 2574: 
 2575: =pod
 2576: 
 2577: =back 
 2578: 
 2579: =cut
 2580: 
 2581: ###############################################################
 2582: ##                  Decoding User Agent                      ##
 2583: ###############################################################
 2584: 
 2585: =pod
 2586: 
 2587: =head1 Decoding the User Agent
 2588: 
 2589: =over 4
 2590: 
 2591: =item * &decode_user_agent()
 2592: 
 2593: Inputs: $r
 2594: 
 2595: Outputs:
 2596: 
 2597: =over 4
 2598: 
 2599: =item * $httpbrowser
 2600: 
 2601: =item * $clientbrowser
 2602: 
 2603: =item * $clientversion
 2604: 
 2605: =item * $clientmathml
 2606: 
 2607: =item * $clientunicode
 2608: 
 2609: =item * $clientos
 2610: 
 2611: =item * $clientmobile
 2612: 
 2613: =item * $clientinfo
 2614: 
 2615: =item * $clientosversion
 2616: 
 2617: =back
 2618: 
 2619: =back 
 2620: 
 2621: =cut
 2622: 
 2623: ###############################################################
 2624: ###############################################################
 2625: sub decode_user_agent {
 2626:     my ($r)=@_;
 2627:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2628:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2629:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2630:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2631:     my $clientbrowser='unknown';
 2632:     my $clientversion='0';
 2633:     my $clientmathml='';
 2634:     my $clientunicode='0';
 2635:     my $clientmobile=0;
 2636:     my $clientosversion='';
 2637:     for (my $i=0;$i<=$#browsertype;$i++) {
 2638:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
 2639: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2640: 	    $clientbrowser=$bname;
 2641:             $httpbrowser=~/$vreg/i;
 2642: 	    $clientversion=$1;
 2643:             $clientmathml=($clientversion>=$minv);
 2644:             $clientunicode=($clientversion>=$univ);
 2645: 	}
 2646:     }
 2647:     my $clientos='unknown';
 2648:     my $clientinfo;
 2649:     if (($httpbrowser=~/linux/i) ||
 2650:         ($httpbrowser=~/unix/i) ||
 2651:         ($httpbrowser=~/ux/i) ||
 2652:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2653:     if (($httpbrowser=~/vax/i) ||
 2654:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2655:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2656:     if (($httpbrowser=~/mac/i) ||
 2657:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2658:     if ($httpbrowser=~/win/i) {
 2659:         $clientos='win';
 2660:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
 2661:             $clientosversion = $1;
 2662:         }
 2663:     }
 2664:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2665:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 2666:         $clientmobile=lc($1);
 2667:     }
 2668:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 2669:         $clientinfo = 'firefox-'.$1;
 2670:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 2671:         $clientinfo = 'chromeframe-'.$1;
 2672:     }
 2673:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2674:             $clientunicode,$clientos,$clientmobile,$clientinfo,
 2675:             $clientosversion);
 2676: }
 2677: 
 2678: ###############################################################
 2679: ##    Authentication changing form generation subroutines    ##
 2680: ###############################################################
 2681: ##
 2682: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2683: ## hash, and have reasonable default values.
 2684: ##
 2685: ##    formname = the name given in the <form> tag.
 2686: #-------------------------------------------
 2687: 
 2688: =pod
 2689: 
 2690: =head1 Authentication Routines
 2691: 
 2692: =over 4
 2693: 
 2694: =item * &authform_xxxxxx()
 2695: 
 2696: The authform_xxxxxx subroutines provide javascript and html forms which 
 2697: handle some of the conveniences required for authentication forms.  
 2698: This is not an optimal method, but it works.  
 2699: 
 2700: =over 4
 2701: 
 2702: =item * authform_header
 2703: 
 2704: =item * authform_authorwarning
 2705: 
 2706: =item * authform_nochange
 2707: 
 2708: =item * authform_kerberos
 2709: 
 2710: =item * authform_internal
 2711: 
 2712: =item * authform_filesystem
 2713: 
 2714: =back
 2715: 
 2716: See loncreateuser.pm for invocation and use examples.
 2717: 
 2718: =cut
 2719: 
 2720: #-------------------------------------------
 2721: sub authform_header{  
 2722:     my %in = (
 2723:         formname => 'cu',
 2724:         kerb_def_dom => '',
 2725:         @_,
 2726:     );
 2727:     $in{'formname'} = 'document.' . $in{'formname'};
 2728:     my $result='';
 2729: 
 2730: #---------------------------------------------- Code for upper case translation
 2731:     my $Javascript_toUpperCase;
 2732:     unless ($in{kerb_def_dom}) {
 2733:         $Javascript_toUpperCase =<<"END";
 2734:         switch (choice) {
 2735:            case 'krb': currentform.elements[choicearg].value =
 2736:                currentform.elements[choicearg].value.toUpperCase();
 2737:                break;
 2738:            default:
 2739:         }
 2740: END
 2741:     } else {
 2742:         $Javascript_toUpperCase = "";
 2743:     }
 2744: 
 2745:     my $radioval = "'nochange'";
 2746:     if (defined($in{'curr_authtype'})) {
 2747:         if ($in{'curr_authtype'} ne '') {
 2748:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2749:         }
 2750:     }
 2751:     my $argfield = 'null';
 2752:     if (defined($in{'mode'})) {
 2753:         if ($in{'mode'} eq 'modifycourse')  {
 2754:             if (defined($in{'curr_autharg'})) {
 2755:                 if ($in{'curr_autharg'} ne '') {
 2756:                     $argfield = "'$in{'curr_autharg'}'";
 2757:                 }
 2758:             }
 2759:         }
 2760:     }
 2761: 
 2762:     $result.=<<"END";
 2763: var current = new Object();
 2764: current.radiovalue = $radioval;
 2765: current.argfield = $argfield;
 2766: 
 2767: function changed_radio(choice,currentform) {
 2768:     var choicearg = choice + 'arg';
 2769:     // If a radio button in changed, we need to change the argfield
 2770:     if (current.radiovalue != choice) {
 2771:         current.radiovalue = choice;
 2772:         if (current.argfield != null) {
 2773:             currentform.elements[current.argfield].value = '';
 2774:         }
 2775:         if (choice == 'nochange') {
 2776:             current.argfield = null;
 2777:         } else {
 2778:             current.argfield = choicearg;
 2779:             switch(choice) {
 2780:                 case 'krb': 
 2781:                     currentform.elements[current.argfield].value = 
 2782:                         "$in{'kerb_def_dom'}";
 2783:                 break;
 2784:               default:
 2785:                 break;
 2786:             }
 2787:         }
 2788:     }
 2789:     return;
 2790: }
 2791: 
 2792: function changed_text(choice,currentform) {
 2793:     var choicearg = choice + 'arg';
 2794:     if (currentform.elements[choicearg].value !='') {
 2795:         $Javascript_toUpperCase
 2796:         // clear old field
 2797:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2798:             currentform.elements[current.argfield].value = '';
 2799:         }
 2800:         current.argfield = choicearg;
 2801:     }
 2802:     set_auth_radio_buttons(choice,currentform);
 2803:     return;
 2804: }
 2805: 
 2806: function set_auth_radio_buttons(newvalue,currentform) {
 2807:     var numauthchoices = currentform.login.length;
 2808:     if (typeof numauthchoices  == "undefined") {
 2809:         return;
 2810:     } 
 2811:     var i=0;
 2812:     while (i < numauthchoices) {
 2813:         if (currentform.login[i].value == newvalue) { break; }
 2814:         i++;
 2815:     }
 2816:     if (i == numauthchoices) {
 2817:         return;
 2818:     }
 2819:     current.radiovalue = newvalue;
 2820:     currentform.login[i].checked = true;
 2821:     return;
 2822: }
 2823: END
 2824:     return $result;
 2825: }
 2826: 
 2827: sub authform_authorwarning {
 2828:     my $result='';
 2829:     $result='<i>'.
 2830:         &mt('As a general rule, only authors or co-authors should be '.
 2831:             'filesystem authenticated '.
 2832:             '(which allows access to the server filesystem).')."</i>\n";
 2833:     return $result;
 2834: }
 2835: 
 2836: sub authform_nochange {
 2837:     my %in = (
 2838:               formname => 'document.cu',
 2839:               kerb_def_dom => 'MSU.EDU',
 2840:               @_,
 2841:           );
 2842:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
 2843:     my $result;
 2844:     if (!$authnum) {
 2845:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 2846:     } else {
 2847:         $result = '<label>'.&mt('[_1] Do not change login data',
 2848:                   '<input type="radio" name="login" value="nochange" '.
 2849:                   'checked="checked" onclick="'.
 2850:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2851: 	    '</label>';
 2852:     }
 2853:     return $result;
 2854: }
 2855: 
 2856: sub authform_kerberos {
 2857:     my %in = (
 2858:               formname => 'document.cu',
 2859:               kerb_def_dom => 'MSU.EDU',
 2860:               kerb_def_auth => 'krb4',
 2861:               @_,
 2862:               );
 2863:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2864:         $autharg,$jscall,$disabled);
 2865:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2866:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2867:        $check5 = ' checked="checked"';
 2868:     } else {
 2869:        $check4 = ' checked="checked"';
 2870:     }
 2871:     if ($in{'readonly'}) {
 2872:         $disabled = ' disabled="disabled"';
 2873:     }
 2874:     $krbarg = $in{'kerb_def_dom'};
 2875:     if (defined($in{'curr_authtype'})) {
 2876:         if ($in{'curr_authtype'} eq 'krb') {
 2877:             $krbcheck = ' checked="checked"';
 2878:             if (defined($in{'mode'})) {
 2879:                 if ($in{'mode'} eq 'modifyuser') {
 2880:                     $krbcheck = '';
 2881:                 }
 2882:             }
 2883:             if (defined($in{'curr_kerb_ver'})) {
 2884:                 if ($in{'curr_krb_ver'} eq '5') {
 2885:                     $check5 = ' checked="checked"';
 2886:                     $check4 = '';
 2887:                 } else {
 2888:                     $check4 = ' checked="checked"';
 2889:                     $check5 = '';
 2890:                 }
 2891:             }
 2892:             if (defined($in{'curr_autharg'})) {
 2893:                 $krbarg = $in{'curr_autharg'};
 2894:             }
 2895:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2896:                 if (defined($in{'curr_autharg'})) {
 2897:                     $result = 
 2898:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2899:         $in{'curr_autharg'},$krbver);
 2900:                 } else {
 2901:                     $result =
 2902:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2903:                 }
 2904:                 return $result; 
 2905:             }
 2906:         }
 2907:     } else {
 2908:         if ($authnum == 1) {
 2909:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2910:         }
 2911:     }
 2912:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2913:         return;
 2914:     } elsif ($authtype eq '') {
 2915:         if (defined($in{'mode'})) {
 2916:             if ($in{'mode'} eq 'modifycourse') {
 2917:                 if ($authnum == 1) {
 2918:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
 2919:                 }
 2920:             }
 2921:         }
 2922:     }
 2923:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2924:     if ($authtype eq '') {
 2925:         $authtype = '<input type="radio" name="login" value="krb" '.
 2926:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2927:                     $krbcheck.$disabled.' />';
 2928:     }
 2929:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2930:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 2931:          $in{'curr_authtype'} eq 'krb5') ||
 2932:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 2933:          $in{'curr_authtype'} eq 'krb4')) {
 2934:         $result .= &mt
 2935:         ('[_1] Kerberos authenticated with domain [_2] '.
 2936:          '[_3] Version 4 [_4] Version 5 [_5]',
 2937:          '<label>'.$authtype,
 2938:          '</label><input type="text" size="10" name="krbarg" '.
 2939:              'value="'.$krbarg.'" '.
 2940:              'onchange="'.$jscall.'"'.$disabled.' />',
 2941:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
 2942:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
 2943: 	 '</label>');
 2944:     } elsif ($can_assign{'krb4'}) {
 2945:         $result .= &mt
 2946:         ('[_1] Kerberos authenticated with domain [_2] '.
 2947:          '[_3] Version 4 [_4]',
 2948:          '<label>'.$authtype,
 2949:          '</label><input type="text" size="10" name="krbarg" '.
 2950:              'value="'.$krbarg.'" '.
 2951:              'onchange="'.$jscall.'"'.$disabled.' />',
 2952:          '<label><input type="hidden" name="krbver" value="4" />',
 2953:          '</label>');
 2954:     } elsif ($can_assign{'krb5'}) {
 2955:         $result .= &mt
 2956:         ('[_1] Kerberos authenticated with domain [_2] '.
 2957:          '[_3] Version 5 [_4]',
 2958:          '<label>'.$authtype,
 2959:          '</label><input type="text" size="10" name="krbarg" '.
 2960:              'value="'.$krbarg.'" '.
 2961:              'onchange="'.$jscall.'"'.$disabled.' />',
 2962:          '<label><input type="hidden" name="krbver" value="5" />',
 2963:          '</label>');
 2964:     }
 2965:     return $result;
 2966: }
 2967: 
 2968: sub authform_internal {
 2969:     my %in = (
 2970:                 formname => 'document.cu',
 2971:                 kerb_def_dom => 'MSU.EDU',
 2972:                 @_,
 2973:                 );
 2974:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
 2975:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2976:     if ($in{'readonly'}) {
 2977:         $disabled = ' disabled="disabled"';
 2978:     }
 2979:     if (defined($in{'curr_authtype'})) {
 2980:         if ($in{'curr_authtype'} eq 'int') {
 2981:             if ($can_assign{'int'}) {
 2982:                 $intcheck = 'checked="checked" ';
 2983:                 if (defined($in{'mode'})) {
 2984:                     if ($in{'mode'} eq 'modifyuser') {
 2985:                         $intcheck = '';
 2986:                     }
 2987:                 }
 2988:                 if (defined($in{'curr_autharg'})) {
 2989:                     $intarg = $in{'curr_autharg'};
 2990:                 }
 2991:             } else {
 2992:                 $result = &mt('Currently internally authenticated.');
 2993:                 return $result;
 2994:             }
 2995:         }
 2996:     } else {
 2997:         if ($authnum == 1) {
 2998:             $authtype = '<input type="hidden" name="login" value="int" />';
 2999:         }
 3000:     }
 3001:     if (!$can_assign{'int'}) {
 3002:         return;
 3003:     } elsif ($authtype eq '') {
 3004:         if (defined($in{'mode'})) {
 3005:             if ($in{'mode'} eq 'modifycourse') {
 3006:                 if ($authnum == 1) {
 3007:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
 3008:                 }
 3009:             }
 3010:         }
 3011:     }
 3012:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 3013:     if ($authtype eq '') {
 3014:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 3015:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
 3016:     }
 3017:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 3018:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3019:     $result = &mt
 3020:         ('[_1] Internally authenticated (with initial password [_2])',
 3021:          '<label>'.$authtype,'</label>'.$autharg);
 3022:     $result.='<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.intarg.type='."'text'".' } else { this.form.intarg.type='."'password'".' }"'.$disabled.' />'.&mt('Visible input').'</label>';
 3023:     return $result;
 3024: }
 3025: 
 3026: sub authform_local {
 3027:     my %in = (
 3028:               formname => 'document.cu',
 3029:               kerb_def_dom => 'MSU.EDU',
 3030:               @_,
 3031:               );
 3032:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
 3033:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3034:     if ($in{'readonly'}) {
 3035:         $disabled = ' disabled="disabled"';
 3036:     }
 3037:     if (defined($in{'curr_authtype'})) {
 3038:         if ($in{'curr_authtype'} eq 'loc') {
 3039:             if ($can_assign{'loc'}) {
 3040:                 $loccheck = 'checked="checked" ';
 3041:                 if (defined($in{'mode'})) {
 3042:                     if ($in{'mode'} eq 'modifyuser') {
 3043:                         $loccheck = '';
 3044:                     }
 3045:                 }
 3046:                 if (defined($in{'curr_autharg'})) {
 3047:                     $locarg = $in{'curr_autharg'};
 3048:                 }
 3049:             } else {
 3050:                 $result = &mt('Currently using local (institutional) authentication.');
 3051:                 return $result;
 3052:             }
 3053:         }
 3054:     } else {
 3055:         if ($authnum == 1) {
 3056:             $authtype = '<input type="hidden" name="login" value="loc" />';
 3057:         }
 3058:     }
 3059:     if (!$can_assign{'loc'}) {
 3060:         return;
 3061:     } elsif ($authtype eq '') {
 3062:         if (defined($in{'mode'})) {
 3063:             if ($in{'mode'} eq 'modifycourse') {
 3064:                 if ($authnum == 1) {
 3065:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
 3066:                 }
 3067:             }
 3068:         }
 3069:     }
 3070:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 3071:     if ($authtype eq '') {
 3072:         $authtype = '<input type="radio" name="login" value="loc" '.
 3073:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 3074:                     $jscall.'"'.$disabled.' />';
 3075:     }
 3076:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 3077:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3078:     $result = &mt('[_1] Local Authentication with argument [_2]',
 3079:                   '<label>'.$authtype,'</label>'.$autharg);
 3080:     return $result;
 3081: }
 3082: 
 3083: sub authform_filesystem {
 3084:     my %in = (
 3085:               formname => 'document.cu',
 3086:               kerb_def_dom => 'MSU.EDU',
 3087:               @_,
 3088:               );
 3089:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
 3090:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3091:     if ($in{'readonly'}) {
 3092:         $disabled = ' disabled="disabled"';
 3093:     }
 3094:     if (defined($in{'curr_authtype'})) {
 3095:         if ($in{'curr_authtype'} eq 'fsys') {
 3096:             if ($can_assign{'fsys'}) {
 3097:                 $fsyscheck = 'checked="checked" ';
 3098:                 if (defined($in{'mode'})) {
 3099:                     if ($in{'mode'} eq 'modifyuser') {
 3100:                         $fsyscheck = '';
 3101:                     }
 3102:                 }
 3103:             } else {
 3104:                 $result = &mt('Currently Filesystem Authenticated.');
 3105:                 return $result;
 3106:             }           
 3107:         }
 3108:     } else {
 3109:         if ($authnum == 1) {
 3110:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 3111:         }
 3112:     }
 3113:     if (!$can_assign{'fsys'}) {
 3114:         return;
 3115:     } elsif ($authtype eq '') {
 3116:         if (defined($in{'mode'})) {
 3117:             if ($in{'mode'} eq 'modifycourse') {
 3118:                 if ($authnum == 1) {
 3119:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
 3120:                 }
 3121:             }
 3122:         }
 3123:     }
 3124:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 3125:     if ($authtype eq '') {
 3126:         $authtype = '<input type="radio" name="login" value="fsys" '.
 3127:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 3128:                     $jscall.'"'.$disabled.' />';
 3129:     }
 3130:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
 3131:                ' onchange="'.$jscall.'"'.$disabled.' />';
 3132:     $result = &mt
 3133:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 3134:          '<label>'.$authtype,'</label>'.$autharg);
 3135:     return $result;
 3136: }
 3137: 
 3138: sub get_assignable_auth {
 3139:     my ($dom) = @_;
 3140:     if ($dom eq '') {
 3141:         $dom = $env{'request.role.domain'};
 3142:     }
 3143:     my %can_assign = (
 3144:                           krb4 => 1,
 3145:                           krb5 => 1,
 3146:                           int  => 1,
 3147:                           loc  => 1,
 3148:                      );
 3149:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 3150:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 3151:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 3152:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 3153:             my $context;
 3154:             if ($env{'request.role'} =~ /^au/) {
 3155:                 $context = 'author';
 3156:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
 3157:                 $context = 'domain';
 3158:             } elsif ($env{'request.course.id'}) {
 3159:                 $context = 'course';
 3160:             }
 3161:             if ($context) {
 3162:                 if (ref($authhash->{$context}) eq 'HASH') {
 3163:                    %can_assign = %{$authhash->{$context}}; 
 3164:                 }
 3165:             }
 3166:         }
 3167:     }
 3168:     my $authnum = 0;
 3169:     foreach my $key (keys(%can_assign)) {
 3170:         if ($can_assign{$key}) {
 3171:             $authnum ++;
 3172:         }
 3173:     }
 3174:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 3175:         $authnum --;
 3176:     }
 3177:     return ($authnum,%can_assign);
 3178: }
 3179: 
 3180: sub check_passwd_rules {
 3181:     my ($domain,$plainpass) = @_;
 3182:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
 3183:     my ($min,$max,@chars,@brokerule,$warning);
 3184:     $min = $Apache::lonnet::passwdmin;
 3185:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
 3186:         if ($passwdconf{'min'} =~ /^\d+$/) {
 3187:             if ($passwdconf{'min'} > $min) {
 3188:                 $min = $passwdconf{'min'};
 3189:             }
 3190:         }
 3191:         if ($passwdconf{'max'} =~ /^\d+$/) {
 3192:             $max = $passwdconf{'max'};
 3193:         }
 3194:         @chars = @{$passwdconf{'chars'}};
 3195:     }
 3196:     if (($min) && (length($plainpass) < $min)) {
 3197:         push(@brokerule,'min');
 3198:     }
 3199:     if (($max) && (length($plainpass) > $max)) {
 3200:         push(@brokerule,'max');
 3201:     }
 3202:     if (@chars) {
 3203:         my %rules;
 3204:         map { $rules{$_} = 1; } @chars;
 3205:         if ($rules{'uc'}) {
 3206:             unless ($plainpass =~ /[A-Z]/) {
 3207:                 push(@brokerule,'uc');
 3208:             }
 3209:         }
 3210:         if ($rules{'lc'}) {
 3211:             unless ($plainpass =~ /[a-z]/) {
 3212:                 push(@brokerule,'lc');
 3213:             }
 3214:         }
 3215:         if ($rules{'num'}) {
 3216:             unless ($plainpass =~ /\d/) {
 3217:                 push(@brokerule,'num');
 3218:             }
 3219:         }
 3220:         if ($rules{'spec'}) {
 3221:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
 3222:                 push(@brokerule,'spec');
 3223:             }
 3224:         }
 3225:     }
 3226:     if (@brokerule) {
 3227:         my %rulenames = &Apache::lonlocal::texthash(
 3228:             uc   => 'At least one upper case letter',
 3229:             lc   => 'At least one lower case letter',
 3230:             num  => 'At least one number',
 3231:             spec => 'At least one non-alphanumeric',
 3232:         );
 3233:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
 3234:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
 3235:         $rulenames{'num'} .= ': 0123456789';
 3236:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
 3237:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
 3238:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
 3239:         $warning = &mt('Password did not satisfy the following:').'<ul>';
 3240:         foreach my $rule ('min','max','uc','lc','num','spec') {
 3241:             if (grep(/^$rule$/,@brokerule)) {
 3242:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
 3243:             }
 3244:         }
 3245:         $warning .= '</ul>';
 3246:     }
 3247:     if (wantarray) {
 3248:         return @brokerule;
 3249:     }
 3250:     return $warning;
 3251: }
 3252: 
 3253: ###############################################################
 3254: ##    Get Kerberos Defaults for Domain                 ##
 3255: ###############################################################
 3256: ##
 3257: ## Returns default kerberos version and an associated argument
 3258: ## as listed in file domain.tab. If not listed, provides
 3259: ## appropriate default domain and kerberos version.
 3260: ##
 3261: #-------------------------------------------
 3262: 
 3263: =pod
 3264: 
 3265: =item * &get_kerberos_defaults()
 3266: 
 3267: get_kerberos_defaults($target_domain) returns the default kerberos
 3268: version and domain. If not found, it defaults to version 4 and the 
 3269: domain of the server.
 3270: 
 3271: =over 4
 3272: 
 3273: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 3274: 
 3275: =back
 3276: 
 3277: =back
 3278: 
 3279: =cut
 3280: 
 3281: #-------------------------------------------
 3282: sub get_kerberos_defaults {
 3283:     my $domain=shift;
 3284:     my ($krbdef,$krbdefdom);
 3285:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 3286:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 3287:         $krbdef = $domdefaults{'auth_def'};
 3288:         $krbdefdom = $domdefaults{'auth_arg_def'};
 3289:     } else {
 3290:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 3291:         my $krbdefdom=$1;
 3292:         $krbdefdom=~tr/a-z/A-Z/;
 3293:         $krbdef = "krb4";
 3294:     }
 3295:     return ($krbdef,$krbdefdom);
 3296: }
 3297: 
 3298: 
 3299: ###############################################################
 3300: ##                Thesaurus Functions                        ##
 3301: ###############################################################
 3302: 
 3303: =pod
 3304: 
 3305: =head1 Thesaurus Functions
 3306: 
 3307: =over 4
 3308: 
 3309: =item * &initialize_keywords()
 3310: 
 3311: Initializes the package variable %Keywords if it is empty.  Uses the
 3312: package variable $thesaurus_db_file.
 3313: 
 3314: =cut
 3315: 
 3316: ###################################################
 3317: 
 3318: sub initialize_keywords {
 3319:     return 1 if (scalar keys(%Keywords));
 3320:     # If we are here, %Keywords is empty, so fill it up
 3321:     #   Make sure the file we need exists...
 3322:     if (! -e $thesaurus_db_file) {
 3323:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 3324:                                  " failed because it does not exist");
 3325:         return 0;
 3326:     }
 3327:     #   Set up the hash as a database
 3328:     my %thesaurus_db;
 3329:     if (! tie(%thesaurus_db,'GDBM_File',
 3330:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3331:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 3332:                                  $thesaurus_db_file);
 3333:         return 0;
 3334:     } 
 3335:     #  Get the average number of appearances of a word.
 3336:     my $avecount = $thesaurus_db{'average.count'};
 3337:     #  Put keywords (those that appear > average) into %Keywords
 3338:     while (my ($word,$data)=each (%thesaurus_db)) {
 3339:         my ($count,undef) = split /:/,$data;
 3340:         $Keywords{$word}++ if ($count > $avecount);
 3341:     }
 3342:     untie %thesaurus_db;
 3343:     # Remove special values from %Keywords.
 3344:     foreach my $value ('total.count','average.count') {
 3345:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 3346:   }
 3347:     return 1;
 3348: }
 3349: 
 3350: ###################################################
 3351: 
 3352: =pod
 3353: 
 3354: =item * &keyword($word)
 3355: 
 3356: Returns true if $word is a keyword.  A keyword is a word that appears more 
 3357: than the average number of times in the thesaurus database.  Calls 
 3358: &initialize_keywords
 3359: 
 3360: =cut
 3361: 
 3362: ###################################################
 3363: 
 3364: sub keyword {
 3365:     return if (!&initialize_keywords());
 3366:     my $word=lc(shift());
 3367:     $word=~s/\W//g;
 3368:     return exists($Keywords{$word});
 3369: }
 3370: 
 3371: ###############################################################
 3372: 
 3373: =pod 
 3374: 
 3375: =item * &get_related_words()
 3376: 
 3377: Look up a word in the thesaurus.  Takes a scalar argument and returns
 3378: an array of words.  If the keyword is not in the thesaurus, an empty array
 3379: will be returned.  The order of the words returned is determined by the
 3380: database which holds them.
 3381: 
 3382: Uses global $thesaurus_db_file.
 3383: 
 3384: 
 3385: =cut
 3386: 
 3387: ###############################################################
 3388: sub get_related_words {
 3389:     my $keyword = shift;
 3390:     my %thesaurus_db;
 3391:     if (! -e $thesaurus_db_file) {
 3392:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 3393:                                  "failed because the file does not exist");
 3394:         return ();
 3395:     }
 3396:     if (! tie(%thesaurus_db,'GDBM_File',
 3397:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3398:         return ();
 3399:     } 
 3400:     my @Words=();
 3401:     my $count=0;
 3402:     if (exists($thesaurus_db{$keyword})) {
 3403: 	# The first element is the number of times
 3404: 	# the word appears.  We do not need it now.
 3405: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 3406: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 3407: 	my $threshold=$mostfrequentcount/10;
 3408:         foreach my $possibleword (@RelatedWords) {
 3409:             my ($word,$wordcount)=split(/\,/,$possibleword);
 3410:             if ($wordcount>$threshold) {
 3411: 		push(@Words,$word);
 3412:                 $count++;
 3413:                 if ($count>10) { last; }
 3414: 	    }
 3415:         }
 3416:     }
 3417:     untie %thesaurus_db;
 3418:     return @Words;
 3419: }
 3420: 
 3421: =pod
 3422: 
 3423: =back
 3424: 
 3425: =cut
 3426: 
 3427: # -------------------------------------------------------------- Plaintext name
 3428: =pod
 3429: 
 3430: =head1 User Name Functions
 3431: 
 3432: =over 4
 3433: 
 3434: =item * &plainname($uname,$udom,$first)
 3435: 
 3436: Takes a users logon name and returns it as a string in
 3437: "first middle last generation" form 
 3438: if $first is set to 'lastname' then it returns it as
 3439: 'lastname generation, firstname middlename' if their is a lastname
 3440: 
 3441: =cut
 3442: 
 3443: 
 3444: ###############################################################
 3445: sub plainname {
 3446:     my ($uname,$udom,$first)=@_;
 3447:     return if (!defined($uname) || !defined($udom));
 3448:     my %names=&getnames($uname,$udom);
 3449:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 3450: 					  $names{'middlename'},
 3451: 					  $names{'lastname'},
 3452: 					  $names{'generation'},$first);
 3453:     $name=~s/^\s+//;
 3454:     $name=~s/\s+$//;
 3455:     $name=~s/\s+/ /g;
 3456:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 3457:     return $name;
 3458: }
 3459: 
 3460: # -------------------------------------------------------------------- Nickname
 3461: =pod
 3462: 
 3463: =item * &nickname($uname,$udom)
 3464: 
 3465: Gets a users name and returns it as a string as
 3466: 
 3467: "&quot;nickname&quot;"
 3468: 
 3469: if the user has a nickname or
 3470: 
 3471: "first middle last generation"
 3472: 
 3473: if the user does not
 3474: 
 3475: =cut
 3476: 
 3477: sub nickname {
 3478:     my ($uname,$udom)=@_;
 3479:     return if (!defined($uname) || !defined($udom));
 3480:     my %names=&getnames($uname,$udom);
 3481:     my $name=$names{'nickname'};
 3482:     if ($name) {
 3483:        $name='&quot;'.$name.'&quot;'; 
 3484:     } else {
 3485:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 3486: 	     $names{'lastname'}.' '.$names{'generation'};
 3487:        $name=~s/\s+$//;
 3488:        $name=~s/\s+/ /g;
 3489:     }
 3490:     return $name;
 3491: }
 3492: 
 3493: sub getnames {
 3494:     my ($uname,$udom)=@_;
 3495:     return if (!defined($uname) || !defined($udom));
 3496:     if ($udom eq 'public' && $uname eq 'public') {
 3497: 	return ('lastname' => &mt('Public'));
 3498:     }
 3499:     my $id=$uname.':'.$udom;
 3500:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 3501:     if ($cached) {
 3502: 	return %{$names};
 3503:     } else {
 3504: 	my %loadnames=&Apache::lonnet::get('environment',
 3505:                     ['firstname','middlename','lastname','generation','nickname'],
 3506: 					 $udom,$uname);
 3507: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 3508: 	return %loadnames;
 3509:     }
 3510: }
 3511: 
 3512: # -------------------------------------------------------------------- getemails
 3513: 
 3514: =pod
 3515: 
 3516: =item * &getemails($uname,$udom)
 3517: 
 3518: Gets a user's email information and returns it as a hash with keys:
 3519: notification, critnotification, permanentemail
 3520: 
 3521: For notification and critnotification, values are comma-separated lists 
 3522: of e-mail addresses; for permanentemail, value is a single e-mail address.
 3523:  
 3524: 
 3525: =cut
 3526: 
 3527: 
 3528: sub getemails {
 3529:     my ($uname,$udom)=@_;
 3530:     if ($udom eq 'public' && $uname eq 'public') {
 3531: 	return;
 3532:     }
 3533:     if (!$udom) { $udom=$env{'user.domain'}; }
 3534:     if (!$uname) { $uname=$env{'user.name'}; }
 3535:     my $id=$uname.':'.$udom;
 3536:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 3537:     if ($cached) {
 3538: 	return %{$names};
 3539:     } else {
 3540: 	my %loadnames=&Apache::lonnet::get('environment',
 3541:                     			   ['notification','critnotification',
 3542: 					    'permanentemail'],
 3543: 					   $udom,$uname);
 3544: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 3545: 	return %loadnames;
 3546:     }
 3547: }
 3548: 
 3549: sub flush_email_cache {
 3550:     my ($uname,$udom)=@_;
 3551:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3552:     if (!$uname) { $uname=$env{'user.name'};   }
 3553:     return if ($udom eq 'public' && $uname eq 'public');
 3554:     my $id=$uname.':'.$udom;
 3555:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 3556: }
 3557: 
 3558: # -------------------------------------------------------------------- getlangs
 3559: 
 3560: =pod
 3561: 
 3562: =item * &getlangs($uname,$udom)
 3563: 
 3564: Gets a user's language preference and returns it as a hash with key:
 3565: language.
 3566: 
 3567: =cut
 3568: 
 3569: 
 3570: sub getlangs {
 3571:     my ($uname,$udom) = @_;
 3572:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3573:     if (!$uname) { $uname=$env{'user.name'};   }
 3574:     my $id=$uname.':'.$udom;
 3575:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 3576:     if ($cached) {
 3577:         return %{$langs};
 3578:     } else {
 3579:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 3580:                                            $udom,$uname);
 3581:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 3582:         return %loadlangs;
 3583:     }
 3584: }
 3585: 
 3586: sub flush_langs_cache {
 3587:     my ($uname,$udom)=@_;
 3588:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3589:     if (!$uname) { $uname=$env{'user.name'};   }
 3590:     return if ($udom eq 'public' && $uname eq 'public');
 3591:     my $id=$uname.':'.$udom;
 3592:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 3593: }
 3594: 
 3595: # ------------------------------------------------------------------ Screenname
 3596: 
 3597: =pod
 3598: 
 3599: =item * &screenname($uname,$udom)
 3600: 
 3601: Gets a users screenname and returns it as a string
 3602: 
 3603: =cut
 3604: 
 3605: sub screenname {
 3606:     my ($uname,$udom)=@_;
 3607:     if ($uname eq $env{'user.name'} &&
 3608: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 3609:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 3610:     return $names{'screenname'};
 3611: }
 3612: 
 3613: 
 3614: # ------------------------------------------------------------- Confirm Wrapper
 3615: =pod
 3616: 
 3617: =item * &confirmwrapper($message)
 3618: 
 3619: Wrap messages about completion of operation in box
 3620: 
 3621: =cut
 3622: 
 3623: sub confirmwrapper {
 3624:     my ($message)=@_;
 3625:     if ($message) {
 3626:         return "\n".'<div class="LC_confirm_box">'."\n"
 3627:                .$message."\n"
 3628:                .'</div>'."\n";
 3629:     } else {
 3630:         return $message;
 3631:     }
 3632: }
 3633: 
 3634: # ------------------------------------------------------------- Message Wrapper
 3635: 
 3636: sub messagewrapper {
 3637:     my ($link,$username,$domain,$subject,$text)=@_;
 3638:     return 
 3639:         '<a href="/adm/email?compose=individual&amp;'.
 3640:         'recname='.$username.'&amp;recdom='.$domain.
 3641: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3642:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3643: }
 3644: 
 3645: # --------------------------------------------------------------- Notes Wrapper
 3646: 
 3647: sub noteswrapper {
 3648:     my ($link,$un,$do)=@_;
 3649:     return 
 3650: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3651: }
 3652: 
 3653: # ------------------------------------------------------------- Aboutme Wrapper
 3654: 
 3655: sub aboutmewrapper {
 3656:     my ($link,$username,$domain,$target,$class)=@_;
 3657:     if (!defined($username)  && !defined($domain)) {
 3658:         return;
 3659:     }
 3660:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 3661: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3662: }
 3663: 
 3664: # ------------------------------------------------------------ Syllabus Wrapper
 3665: 
 3666: sub syllabuswrapper {
 3667:     my ($linktext,$coursedir,$domain)=@_;
 3668:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3669: }
 3670: 
 3671: # -----------------------------------------------------------------------------
 3672: 
 3673: sub track_student_link {
 3674:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3675:     my $link ="/adm/trackstudent?";
 3676:     my $title = 'View recent activity';
 3677:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3678:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3679:         $link .= "selected_student=$sname:$sdom";
 3680:         $title .= ' of this student';
 3681:     } 
 3682:     if (defined($target) && $target !~ /^\s*$/) {
 3683:         $target = qq{target="$target"};
 3684:     } else {
 3685:         $target = '';
 3686:     }
 3687:     if ($start) { $link.='&amp;start='.$start; }
 3688:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3689:     $title = &mt($title);
 3690:     $linktext = &mt($linktext);
 3691:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3692: 	&help_open_topic('View_recent_activity');
 3693: }
 3694: 
 3695: sub slot_reservations_link {
 3696:     my ($linktext,$sname,$sdom,$target) = @_;
 3697:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3698:     my $title = 'View slot reservation history';
 3699:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3700:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3701:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3702:         $title .= ' of this student';
 3703:     }
 3704:     if (defined($target) && $target !~ /^\s*$/) {
 3705:         $target = qq{target="$target"};
 3706:     } else {
 3707:         $target = '';
 3708:     }
 3709:     $title = &mt($title);
 3710:     $linktext = &mt($linktext);
 3711:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3712: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3713: 
 3714: }
 3715: 
 3716: # ===================================================== Display a student photo
 3717: 
 3718: 
 3719: sub student_image_tag {
 3720:     my ($domain,$user)=@_;
 3721:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3722:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3723: 	return '<img src="'.$imgsrc.'" align="right" />';
 3724:     } else {
 3725: 	return '';
 3726:     }
 3727: }
 3728: 
 3729: =pod
 3730: 
 3731: =back
 3732: 
 3733: =head1 Access .tab File Data
 3734: 
 3735: =over 4
 3736: 
 3737: =item * &languageids() 
 3738: 
 3739: returns list of all language ids
 3740: 
 3741: =cut
 3742: 
 3743: sub languageids {
 3744:     return sort(keys(%language));
 3745: }
 3746: 
 3747: =pod
 3748: 
 3749: =item * &languagedescription() 
 3750: 
 3751: returns description of a specified language id
 3752: 
 3753: =cut
 3754: 
 3755: sub languagedescription {
 3756:     my $code=shift;
 3757:     return  ($supported_language{$code}?'* ':'').
 3758:             $language{$code}.
 3759: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 3760: }
 3761: 
 3762: =pod
 3763: 
 3764: =item * &plainlanguagedescription
 3765: 
 3766: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 3767: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 3768: 
 3769: =cut
 3770: 
 3771: sub plainlanguagedescription {
 3772:     my $code=shift;
 3773:     return $language{$code};
 3774: }
 3775: 
 3776: =pod
 3777: 
 3778: =item * &supportedlanguagecode
 3779: 
 3780: Returns the supported language code (e.g. sptutf maps to pt) given a language
 3781: code.
 3782: 
 3783: =cut
 3784: 
 3785: sub supportedlanguagecode {
 3786:     my $code=shift;
 3787:     return $supported_language{$code};
 3788: }
 3789: 
 3790: =pod
 3791: 
 3792: =item * &latexlanguage()
 3793: 
 3794: Given a language key code returns the correspondnig language to use
 3795: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 3796: is no supported hyphenation for the language code.
 3797: 
 3798: =cut
 3799: 
 3800: sub latexlanguage {
 3801:     my $code = shift;
 3802:     return $latex_language{$code};
 3803: }
 3804: 
 3805: =pod
 3806: 
 3807: =item * &latexhyphenation()
 3808: 
 3809: Same as above but what's supplied is the language as it might be stored
 3810: in the metadata.
 3811: 
 3812: =cut
 3813: 
 3814: sub latexhyphenation {
 3815:     my $key = shift;
 3816:     return $latex_language_bykey{$key};
 3817: }
 3818: 
 3819: =pod
 3820: 
 3821: =item * &copyrightids() 
 3822: 
 3823: returns list of all copyrights
 3824: 
 3825: =cut
 3826: 
 3827: sub copyrightids {
 3828:     return sort(keys(%cprtag));
 3829: }
 3830: 
 3831: =pod
 3832: 
 3833: =item * &copyrightdescription() 
 3834: 
 3835: returns description of a specified copyright id
 3836: 
 3837: =cut
 3838: 
 3839: sub copyrightdescription {
 3840:     return &mt($cprtag{shift(@_)});
 3841: }
 3842: 
 3843: =pod
 3844: 
 3845: =item * &source_copyrightids() 
 3846: 
 3847: returns list of all source copyrights
 3848: 
 3849: =cut
 3850: 
 3851: sub source_copyrightids {
 3852:     return sort(keys(%scprtag));
 3853: }
 3854: 
 3855: =pod
 3856: 
 3857: =item * &source_copyrightdescription() 
 3858: 
 3859: returns description of a specified source copyright id
 3860: 
 3861: =cut
 3862: 
 3863: sub source_copyrightdescription {
 3864:     return &mt($scprtag{shift(@_)});
 3865: }
 3866: 
 3867: =pod
 3868: 
 3869: =item * &filecategories() 
 3870: 
 3871: returns list of all file categories
 3872: 
 3873: =cut
 3874: 
 3875: sub filecategories {
 3876:     return sort(keys(%category_extensions));
 3877: }
 3878: 
 3879: =pod
 3880: 
 3881: =item * &filecategorytypes() 
 3882: 
 3883: returns list of file types belonging to a given file
 3884: category
 3885: 
 3886: =cut
 3887: 
 3888: sub filecategorytypes {
 3889:     my ($cat) = @_;
 3890:     return @{$category_extensions{lc($cat)}};
 3891: }
 3892: 
 3893: =pod
 3894: 
 3895: =item * &fileembstyle() 
 3896: 
 3897: returns embedding style for a specified file type
 3898: 
 3899: =cut
 3900: 
 3901: sub fileembstyle {
 3902:     return $fe{lc(shift(@_))};
 3903: }
 3904: 
 3905: sub filemimetype {
 3906:     return $fm{lc(shift(@_))};
 3907: }
 3908: 
 3909: 
 3910: sub filecategoryselect {
 3911:     my ($name,$value)=@_;
 3912:     return &select_form($value,$name,
 3913:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 3914: }
 3915: 
 3916: =pod
 3917: 
 3918: =item * &filedescription() 
 3919: 
 3920: returns description for a specified file type
 3921: 
 3922: =cut
 3923: 
 3924: sub filedescription {
 3925:     my $file_description = $fd{lc(shift())};
 3926:     $file_description =~ s:([\[\]]):~$1:g;
 3927:     return &mt($file_description);
 3928: }
 3929: 
 3930: =pod
 3931: 
 3932: =item * &filedescriptionex() 
 3933: 
 3934: returns description for a specified file type with
 3935: extra formatting
 3936: 
 3937: =cut
 3938: 
 3939: sub filedescriptionex {
 3940:     my $ex=shift;
 3941:     my $file_description = $fd{lc($ex)};
 3942:     $file_description =~ s:([\[\]]):~$1:g;
 3943:     return '.'.$ex.' '.&mt($file_description);
 3944: }
 3945: 
 3946: # End of .tab access
 3947: =pod
 3948: 
 3949: =back
 3950: 
 3951: =cut
 3952: 
 3953: # ------------------------------------------------------------------ File Types
 3954: sub fileextensions {
 3955:     return sort(keys(%fe));
 3956: }
 3957: 
 3958: # ----------------------------------------------------------- Display Languages
 3959: # returns a hash with all desired display languages
 3960: #
 3961: 
 3962: sub display_languages {
 3963:     my %languages=();
 3964:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3965: 	$languages{$lang}=1;
 3966:     }
 3967:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3968:     if ($env{'form.displaylanguage'}) {
 3969: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3970: 	    $languages{$lang}=1;
 3971:         }
 3972:     }
 3973:     return %languages;
 3974: }
 3975: 
 3976: sub languages {
 3977:     my ($possible_langs) = @_;
 3978:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3979:     if (!ref($possible_langs)) {
 3980: 	if( wantarray ) {
 3981: 	    return @preferred_langs;
 3982: 	} else {
 3983: 	    return $preferred_langs[0];
 3984: 	}
 3985:     }
 3986:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3987:     my @preferred_possibilities;
 3988:     foreach my $preferred_lang (@preferred_langs) {
 3989: 	if (exists($possibilities{$preferred_lang})) {
 3990: 	    push(@preferred_possibilities, $preferred_lang);
 3991: 	}
 3992:     }
 3993:     if( wantarray ) {
 3994: 	return @preferred_possibilities;
 3995:     }
 3996:     return $preferred_possibilities[0];
 3997: }
 3998: 
 3999: sub user_lang {
 4000:     my ($touname,$toudom,$fromcid) = @_;
 4001:     my @userlangs;
 4002:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 4003:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 4004:                     $env{'course.'.$fromcid.'.languages'}));
 4005:     } else {
 4006:         my %langhash = &getlangs($touname,$toudom);
 4007:         if ($langhash{'languages'} ne '') {
 4008:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 4009:         } else {
 4010:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 4011:             if ($domdefs{'lang_def'} ne '') {
 4012:                 @userlangs = ($domdefs{'lang_def'});
 4013:             }
 4014:         }
 4015:     }
 4016:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 4017:     my $user_lh = Apache::localize->get_handle(@languages);
 4018:     return $user_lh;
 4019: }
 4020: 
 4021: 
 4022: ###############################################################
 4023: ##               Student Answer Attempts                     ##
 4024: ###############################################################
 4025: 
 4026: =pod
 4027: 
 4028: =head1 Alternate Problem Views
 4029: 
 4030: =over 4
 4031: 
 4032: =item * &get_previous_attempt($symb, $username, $domain, $course,
 4033:     $getattempt, $regexp, $gradesub, $usec, $identifier)
 4034: 
 4035: Return string with previous attempt on problem. Arguments:
 4036: 
 4037: =over 4
 4038: 
 4039: =item * $symb: Problem, including path
 4040: 
 4041: =item * $username: username of the desired student
 4042: 
 4043: =item * $domain: domain of the desired student
 4044: 
 4045: =item * $course: Course ID
 4046: 
 4047: =item * $getattempt: Leave blank for all attempts, otherwise put
 4048:     something
 4049: 
 4050: =item * $regexp: if string matches this regexp, the string will be
 4051:     sent to $gradesub
 4052: 
 4053: =item * $gradesub: routine that processes the string if it matches $regexp
 4054: 
 4055: =item * $usec: section of the desired student
 4056: 
 4057: =item * $identifier: counter for student (multiple students one problem) or
 4058:     problem (one student; whole sequence).
 4059: 
 4060: =back
 4061: 
 4062: The output string is a table containing all desired attempts, if any.
 4063: 
 4064: =cut
 4065: 
 4066: sub get_previous_attempt {
 4067:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
 4068:   my $prevattempts='';
 4069:   no strict 'refs';
 4070:   if ($symb) {
 4071:     my (%returnhash)=
 4072:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 4073:     if ($returnhash{'version'}) {
 4074:       my %lasthash=();
 4075:       my $version;
 4076:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 4077:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
 4078:             if ($key =~ /\.rawrndseed$/) {
 4079:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
 4080:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
 4081:             } else {
 4082:                 $lasthash{$key}=$returnhash{$version.':'.$key};
 4083:             }
 4084:         }
 4085:       }
 4086:       $prevattempts=&start_data_table().&start_data_table_header_row();
 4087:       $prevattempts.='<th>'.&mt('History').'</th>';
 4088:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
 4089:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 4090:       foreach my $key (sort(keys(%lasthash))) {
 4091: 	my ($ign,@parts) = split(/\./,$key);
 4092: 	if ($#parts > 0) {
 4093: 	  my $data=$parts[-1];
 4094:           next if ($data eq 'foilorder');
 4095: 	  pop(@parts);
 4096:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 4097:           if ($data eq 'type') {
 4098:               unless ($showsurv) {
 4099:                   my $id = join(',',@parts);
 4100:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 4101:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 4102:                       $lasthidden{$ign.'.'.$id} = 1;
 4103:                   }
 4104:               }
 4105:               if ($identifier ne '') {
 4106:                   my $id = join(',',@parts);
 4107:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
 4108:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
 4109:                       $hidestatus{$ign.'.'.$id} = 1;
 4110:                   }
 4111:               }
 4112:           } elsif ($data eq 'regrader') {
 4113:               if (($identifier ne '') && (@parts)) {
 4114:                   my $id = join(',',@parts);
 4115:                   $regraded{$ign.'.'.$id} = 1;
 4116:               }
 4117:           } 
 4118: 	} else {
 4119: 	  if ($#parts == 0) {
 4120: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 4121: 	  } else {
 4122: 	    $prevattempts.='<th>'.$ign.'</th>';
 4123: 	  }
 4124: 	}
 4125:       }
 4126:       $prevattempts.=&end_data_table_header_row();
 4127:       if ($getattempt eq '') {
 4128:         my (%solved,%resets,%probstatus);
 4129:         if (($identifier ne '') && (keys(%regraded) > 0)) {
 4130:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 4131:                 foreach my $id (keys(%regraded)) {
 4132:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
 4133:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
 4134:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
 4135:                         push(@{$resets{$id}},$version);
 4136:                     }
 4137:                 }
 4138:             }
 4139:         }
 4140: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 4141:             my (@hidden,@unsolved);
 4142:             if (%typeparts) {
 4143:                 foreach my $id (keys(%typeparts)) {
 4144:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
 4145:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 4146:                         push(@hidden,$id);
 4147:                     } elsif ($identifier ne '') {
 4148:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
 4149:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
 4150:                                 ($hidestatus{$id})) {
 4151:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
 4152:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
 4153:                                 push(@{$solved{$id}},$version);
 4154:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
 4155:                                      (ref($solved{$id}) eq 'ARRAY')) {
 4156:                                 my $skip;
 4157:                                 if (ref($resets{$id}) eq 'ARRAY') {
 4158:                                     foreach my $reset (@{$resets{$id}}) {
 4159:                                         if ($reset > $solved{$id}[-1]) {
 4160:                                             $skip=1;
 4161:                                             last;
 4162:                                         }
 4163:                                     }
 4164:                                 }
 4165:                                 unless ($skip) {
 4166:                                     my ($ign,$partslist) = split(/\./,$id,2);
 4167:                                     push(@unsolved,$partslist);
 4168:                                 }
 4169:                             }
 4170:                         }
 4171:                     }
 4172:                 }
 4173:             }
 4174:             $prevattempts.=&start_data_table_row().
 4175:                            '<td>'.&mt('Transaction [_1]',$version);
 4176:             if (@unsolved) {
 4177:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
 4178:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
 4179:                                  &mt('Hide').'</label></span>';
 4180:             }
 4181:             $prevattempts .= '</td>';
 4182:             if (@hidden) {
 4183:                 foreach my $key (sort(keys(%lasthash))) {
 4184:                     next if ($key =~ /\.foilorder$/);
 4185:                     my $hide;
 4186:                     foreach my $id (@hidden) {
 4187:                         if ($key =~ /^\Q$id\E/) {
 4188:                             $hide = 1;
 4189:                             last;
 4190:                         }
 4191:                     }
 4192:                     if ($hide) {
 4193:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4194:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 4195:                             my $value = &format_previous_attempt_value($key,
 4196:                                              $returnhash{$version.':'.$key});
 4197:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4198:                         } else {
 4199:                             $prevattempts.='<td>&nbsp;</td>';
 4200:                         }
 4201:                     } else {
 4202:                         if ($key =~ /\./) {
 4203:                             my $value = $returnhash{$version.':'.$key};
 4204:                             if ($key =~ /\.rndseed$/) {
 4205:                                 my ($id) = ($key =~ /^(.+)\.rndseed$/);
 4206:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4207:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4208:                                 }
 4209:                             }
 4210:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4211:                                            '&nbsp;</td>';
 4212:                         } else {
 4213:                             $prevattempts.='<td>&nbsp;</td>';
 4214:                         }
 4215:                     }
 4216:                 }
 4217:             } else {
 4218: 	        foreach my $key (sort(keys(%lasthash))) {
 4219:                     next if ($key =~ /\.foilorder$/);
 4220:                     my $value = $returnhash{$version.':'.$key};
 4221:                     if ($key =~ /\.rndseed$/) {
 4222:                         my ($id) = ($key =~ /^(.+)\.rndseed$/);
 4223:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4224:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4225:                         }
 4226:                     }
 4227:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4228:                                    '&nbsp;</td>';
 4229: 	        }
 4230:             }
 4231: 	    $prevattempts.=&end_data_table_row();
 4232: 	 }
 4233:       }
 4234:       my @currhidden = keys(%lasthidden);
 4235:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 4236:       foreach my $key (sort(keys(%lasthash))) {
 4237:           next if ($key =~ /\.foilorder$/);
 4238:           if (%typeparts) {
 4239:               my $hidden;
 4240:               foreach my $id (@currhidden) {
 4241:                   if ($key =~ /^\Q$id\E/) {
 4242:                       $hidden = 1;
 4243:                       last;
 4244:                   }
 4245:               }
 4246:               if ($hidden) {
 4247:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4248:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 4249:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4250:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4251:                           $value = &$gradesub($value);
 4252:                       }
 4253:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4254:                   } else {
 4255:                       $prevattempts.='<td>&nbsp;</td>';
 4256:                   }
 4257:               } else {
 4258:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4259:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4260:                       $value = &$gradesub($value);
 4261:                   }
 4262:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4263:               }
 4264:           } else {
 4265: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4266: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4267:                   $value = &$gradesub($value);
 4268:               }
 4269: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4270:           }
 4271:       }
 4272:       $prevattempts.= &end_data_table_row().&end_data_table();
 4273:     } else {
 4274:       $prevattempts=
 4275: 	  &start_data_table().&start_data_table_row().
 4276: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 4277: 	  &end_data_table_row().&end_data_table();
 4278:     }
 4279:   } else {
 4280:     $prevattempts=
 4281: 	  &start_data_table().&start_data_table_row().
 4282: 	  '<td>'.&mt('No data.').'</td>'.
 4283: 	  &end_data_table_row().&end_data_table();
 4284:   }
 4285: }
 4286: 
 4287: sub format_previous_attempt_value {
 4288:     my ($key,$value) = @_;
 4289:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 4290: 	$value = &Apache::lonlocal::locallocaltime($value);
 4291:     } elsif (ref($value) eq 'ARRAY') {
 4292: 	$value = '('.join(', ', @{ $value }).')';
 4293:     } elsif ($key =~ /answerstring$/) {
 4294:         my %answers = &Apache::lonnet::str2hash($value);
 4295:         my @anskeys = sort(keys(%answers));
 4296:         if (@anskeys == 1) {
 4297:             my $answer = $answers{$anskeys[0]};
 4298:             if ($answer =~ m{\0}) {
 4299:                 $answer =~ s{\0}{,}g;
 4300:             }
 4301:             my $tag_internal_answer_name = 'INTERNAL';
 4302:             if ($anskeys[0] eq $tag_internal_answer_name) {
 4303:                 $value = $answer; 
 4304:             } else {
 4305:                 $value = $anskeys[0].'='.$answer;
 4306:             }
 4307:         } else {
 4308:             foreach my $ans (@anskeys) {
 4309:                 my $answer = $answers{$ans};
 4310:                 if ($answer =~ m{\0}) {
 4311:                     $answer =~ s{\0}{,}g;
 4312:                 }
 4313:                 $value .=  $ans.'='.$answer.'<br />';;
 4314:             } 
 4315:         }
 4316:     } else {
 4317: 	$value = &unescape($value);
 4318:     }
 4319:     return $value;
 4320: }
 4321: 
 4322: 
 4323: sub relative_to_absolute {
 4324:     my ($url,$output)=@_;
 4325:     my $parser=HTML::TokeParser->new(\$output);
 4326:     my $token;
 4327:     my $thisdir=$url;
 4328:     my @rlinks=();
 4329:     while ($token=$parser->get_token) {
 4330: 	if ($token->[0] eq 'S') {
 4331: 	    if ($token->[1] eq 'a') {
 4332: 		if ($token->[2]->{'href'}) {
 4333: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 4334: 		}
 4335: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 4336: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 4337: 	    } elsif ($token->[1] eq 'base') {
 4338: 		$thisdir=$token->[2]->{'href'};
 4339: 	    }
 4340: 	}
 4341:     }
 4342:     $thisdir=~s-/[^/]*$--;
 4343:     foreach my $link (@rlinks) {
 4344: 	unless (($link=~/^https?\:\/\//i) ||
 4345: 		($link=~/^\//) ||
 4346: 		($link=~/^javascript:/i) ||
 4347: 		($link=~/^mailto:/i) ||
 4348: 		($link=~/^\#/)) {
 4349: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 4350: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 4351: 	}
 4352:     }
 4353: # -------------------------------------------------- Deal with Applet codebases
 4354:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 4355:     return $output;
 4356: }
 4357: 
 4358: =pod
 4359: 
 4360: =item * &get_student_view()
 4361: 
 4362: show a snapshot of what student was looking at
 4363: 
 4364: =cut
 4365: 
 4366: sub get_student_view {
 4367:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 4368:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4369:   my (%form);
 4370:   my @elements=('symb','courseid','domain','username');
 4371:   foreach my $element (@elements) {
 4372:       $form{'grade_'.$element}=eval '$'.$element #'
 4373:   }
 4374:   if (defined($moreenv)) {
 4375:       %form=(%form,%{$moreenv});
 4376:   }
 4377:   if (defined($target)) { $form{'grade_target'} = $target; }
 4378:   $feedurl=&Apache::lonnet::clutter($feedurl);
 4379:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 4380:   $userview=~s/\<body[^\>]*\>//gi;
 4381:   $userview=~s/\<\/body\>//gi;
 4382:   $userview=~s/\<html\>//gi;
 4383:   $userview=~s/\<\/html\>//gi;
 4384:   $userview=~s/\<head\>//gi;
 4385:   $userview=~s/\<\/head\>//gi;
 4386:   $userview=~s/action\s*\=/would_be_action\=/gi;
 4387:   $userview=&relative_to_absolute($feedurl,$userview);
 4388:   if (wantarray) {
 4389:      return ($userview,$response);
 4390:   } else {
 4391:      return $userview;
 4392:   }
 4393: }
 4394: 
 4395: sub get_student_view_with_retries {
 4396:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 4397: 
 4398:     my $ok = 0;                 # True if we got a good response.
 4399:     my $content;
 4400:     my $response;
 4401: 
 4402:     # Try to get the student_view done. within the retries count:
 4403:     
 4404:     do {
 4405:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 4406:          $ok      = $response->is_success;
 4407:          if (!$ok) {
 4408:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 4409:          }
 4410:          $retries--;
 4411:     } while (!$ok && ($retries > 0));
 4412:     
 4413:     if (!$ok) {
 4414:        $content = '';          # On error return an empty content.
 4415:     }
 4416:     if (wantarray) {
 4417:        return ($content, $response);
 4418:     } else {
 4419:        return $content;
 4420:     }
 4421: }
 4422: 
 4423: sub css_links {
 4424:     my ($currsymb,$level) = @_;
 4425:     my ($links,@symbs,%cssrefs,%httpref);
 4426:     if ($level eq 'map') {
 4427:         my $navmap = Apache::lonnavmaps::navmap->new();
 4428:         if (ref($navmap)) {
 4429:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
 4430:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
 4431:             foreach my $res (@resources) {
 4432:                 if (ref($res) && $res->symb()) {
 4433:                     push(@symbs,$res->symb());
 4434:                 }
 4435:             }
 4436:         }
 4437:     } else {
 4438:         @symbs = ($currsymb);
 4439:     }
 4440:     foreach my $symb (@symbs) {
 4441:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
 4442:         if ($css_href =~ /\S/) {
 4443:             unless ($css_href =~ m{https?://}) {
 4444:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
 4445:                 my $proburl =  &Apache::lonnet::clutter($url);
 4446:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
 4447:                 unless ($css_href =~ m{^/}) {
 4448:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
 4449:                 }
 4450:                 if ($css_href =~ m{^/(res|uploaded)/}) {
 4451:                     unless (($httpref{'httpref.'.$css_href}) ||
 4452:                             (&Apache::lonnet::is_on_map($css_href))) {
 4453:                         my $thisurl = $proburl;
 4454:                         if ($env{'httpref.'.$proburl}) {
 4455:                             $thisurl = $env{'httpref.'.$proburl};
 4456:                         }
 4457:                         $httpref{'httpref.'.$css_href} = $thisurl;
 4458:                     }
 4459:                 }
 4460:             }
 4461:             $cssrefs{$css_href} = 1;
 4462:         }
 4463:     }
 4464:     if (keys(%httpref)) {
 4465:         &Apache::lonnet::appenv(\%httpref);
 4466:     }
 4467:     if (keys(%cssrefs)) {
 4468:         foreach my $css_href (keys(%cssrefs)) {
 4469:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
 4470:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
 4471:         }
 4472:     }
 4473:     return $links;
 4474: }
 4475: 
 4476: =pod
 4477: 
 4478: =item * &get_student_answers() 
 4479: 
 4480: show a snapshot of how student was answering problem
 4481: 
 4482: =cut
 4483: 
 4484: sub get_student_answers {
 4485:   my ($symb,$username,$domain,$courseid,%form) = @_;
 4486:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4487:   my (%moreenv);
 4488:   my @elements=('symb','courseid','domain','username');
 4489:   foreach my $element (@elements) {
 4490:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 4491:   }
 4492:   $moreenv{'grade_target'}='answer';
 4493:   %moreenv=(%form,%moreenv);
 4494:   $feedurl = &Apache::lonnet::clutter($feedurl);
 4495:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 4496:   return $userview;
 4497: }
 4498: 
 4499: =pod
 4500: 
 4501: =item * &submlink()
 4502: 
 4503: Inputs: $text $uname $udom $symb $target
 4504: 
 4505: Returns: A link to grades.pm such as to see the SUBM view of a student
 4506: 
 4507: =cut
 4508: 
 4509: ###############################################
 4510: sub submlink {
 4511:     my ($text,$uname,$udom,$symb,$target)=@_;
 4512:     if (!($uname && $udom)) {
 4513: 	(my $cursymb, my $courseid,$udom,$uname)=
 4514: 	    &Apache::lonnet::whichuser($symb);
 4515: 	if (!$symb) { $symb=$cursymb; }
 4516:     }
 4517:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4518:     $symb=&escape($symb);
 4519:     if ($target) { $target=" target=\"$target\""; }
 4520:     return
 4521:         '<a href="/adm/grades?command=submission'.
 4522:         '&amp;symb='.$symb.
 4523:         '&amp;student='.$uname.
 4524:         '&amp;userdom='.$udom.'"'.
 4525:         $target.'>'.$text.'</a>';
 4526: }
 4527: ##############################################
 4528: 
 4529: =pod
 4530: 
 4531: =item * &pgrdlink()
 4532: 
 4533: Inputs: $text $uname $udom $symb $target
 4534: 
 4535: Returns: A link to grades.pm such as to see the PGRD view of a student
 4536: 
 4537: =cut
 4538: 
 4539: ###############################################
 4540: sub pgrdlink {
 4541:     my $link=&submlink(@_);
 4542:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 4543:     return $link;
 4544: }
 4545: ##############################################
 4546: 
 4547: =pod
 4548: 
 4549: =item * &pprmlink()
 4550: 
 4551: Inputs: $text $uname $udom $symb $target
 4552: 
 4553: Returns: A link to parmset.pm such as to see the PPRM view of a
 4554: student and a specific resource
 4555: 
 4556: =cut
 4557: 
 4558: ###############################################
 4559: sub pprmlink {
 4560:     my ($text,$uname,$udom,$symb,$target)=@_;
 4561:     if (!($uname && $udom)) {
 4562: 	(my $cursymb, my $courseid,$udom,$uname)=
 4563: 	    &Apache::lonnet::whichuser($symb);
 4564: 	if (!$symb) { $symb=$cursymb; }
 4565:     }
 4566:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4567:     $symb=&escape($symb);
 4568:     if ($target) { $target="target=\"$target\""; }
 4569:     return '<a href="/adm/parmset?command=set&amp;'.
 4570: 	'symb='.$symb.'&amp;uname='.$uname.
 4571: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 4572: }
 4573: ##############################################
 4574: 
 4575: =pod
 4576: 
 4577: =back
 4578: 
 4579: =cut
 4580: 
 4581: ###############################################
 4582: 
 4583: 
 4584: sub timehash {
 4585:     my ($thistime) = @_;
 4586:     my $timezone = &Apache::lonlocal::gettimezone();
 4587:     my $dt = DateTime->from_epoch(epoch => $thistime)
 4588:                      ->set_time_zone($timezone);
 4589:     my $wday = $dt->day_of_week();
 4590:     if ($wday == 7) { $wday = 0; }
 4591:     return ( 'second' => $dt->second(),
 4592:              'minute' => $dt->minute(),
 4593:              'hour'   => $dt->hour(),
 4594:              'day'     => $dt->day_of_month(),
 4595:              'month'   => $dt->month(),
 4596:              'year'    => $dt->year(),
 4597:              'weekday' => $wday,
 4598:              'dayyear' => $dt->day_of_year(),
 4599:              'dlsav'   => $dt->is_dst() );
 4600: }
 4601: 
 4602: sub utc_string {
 4603:     my ($date)=@_;
 4604:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 4605: }
 4606: 
 4607: sub maketime {
 4608:     my %th=@_;
 4609:     my ($epoch_time,$timezone,$dt);
 4610:     $timezone = &Apache::lonlocal::gettimezone();
 4611:     eval {
 4612:         $dt = DateTime->new( year   => $th{'year'},
 4613:                              month  => $th{'month'},
 4614:                              day    => $th{'day'},
 4615:                              hour   => $th{'hour'},
 4616:                              minute => $th{'minute'},
 4617:                              second => $th{'second'},
 4618:                              time_zone => $timezone,
 4619:                          );
 4620:     };
 4621:     if (!$@) {
 4622:         $epoch_time = $dt->epoch;
 4623:         if ($epoch_time) {
 4624:             return $epoch_time;
 4625:         }
 4626:     }
 4627:     return POSIX::mktime(
 4628:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 4629:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 4630: }
 4631: 
 4632: #########################################
 4633: 
 4634: sub findallcourses {
 4635:     my ($roles,$uname,$udom) = @_;
 4636:     my %roles;
 4637:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 4638:     my %courses;
 4639:     my $now=time;
 4640:     if (!defined($uname)) {
 4641:         $uname = $env{'user.name'};
 4642:     }
 4643:     if (!defined($udom)) {
 4644:         $udom = $env{'user.domain'};
 4645:     }
 4646:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 4647:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 4648:         if (!%roles) {
 4649:             %roles = (
 4650:                        cc => 1,
 4651:                        co => 1,
 4652:                        in => 1,
 4653:                        ep => 1,
 4654:                        ta => 1,
 4655:                        cr => 1,
 4656:                        st => 1,
 4657:              );
 4658:         }
 4659:         foreach my $entry (keys(%roleshash)) {
 4660:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 4661:             if ($trole =~ /^cr/) { 
 4662:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 4663:             } else {
 4664:                 next if (!exists($roles{$trole}));
 4665:             }
 4666:             if ($tend) {
 4667:                 next if ($tend < $now);
 4668:             }
 4669:             if ($tstart) {
 4670:                 next if ($tstart > $now);
 4671:             }
 4672:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 4673:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 4674:             my $value = $trole.'/'.$cdom.'/';
 4675:             if ($secpart eq '') {
 4676:                 ($cnum,$role) = split(/_/,$cnumpart); 
 4677:                 $sec = 'none';
 4678:                 $value .= $cnum.'/';
 4679:             } else {
 4680:                 $cnum = $cnumpart;
 4681:                 ($sec,$role) = split(/_/,$secpart);
 4682:                 $value .= $cnum.'/'.$sec;
 4683:             }
 4684:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4685:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4686:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4687:                 }
 4688:             } else {
 4689:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4690:             }
 4691:         }
 4692:     } else {
 4693:         foreach my $key (keys(%env)) {
 4694: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 4695:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 4696: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 4697: 	        next if ($role eq 'ca' || $role eq 'aa');
 4698: 	        next if (%roles && !exists($roles{$role}));
 4699: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 4700:                 my $active=1;
 4701:                 if ($starttime) {
 4702: 		    if ($now<$starttime) { $active=0; }
 4703:                 }
 4704:                 if ($endtime) {
 4705:                     if ($now>$endtime) { $active=0; }
 4706:                 }
 4707:                 if ($active) {
 4708:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 4709:                     if ($sec eq '') {
 4710:                         $sec = 'none';
 4711:                     } else {
 4712:                         $value .= $sec;
 4713:                     }
 4714:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4715:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4716:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4717:                         }
 4718:                     } else {
 4719:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4720:                     }
 4721:                 }
 4722:             }
 4723:         }
 4724:     }
 4725:     return %courses;
 4726: }
 4727: 
 4728: ###############################################
 4729: 
 4730: sub blockcheck {
 4731:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
 4732: 
 4733:     unless ($activity eq 'docs') {
 4734:         my ($has_evb,$check_ipaccess);
 4735:         my $dom = $env{'user.domain'};
 4736:         if ($env{'request.course.id'}) {
 4737:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4738:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4739:             my $checkrole = "cm./$cdom/$cnum";
 4740:             my $sec = $env{'request.course.sec'};
 4741:             if ($sec ne '') {
 4742:                 $checkrole .= "/$sec";
 4743:             }
 4744:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 4745:                 ($env{'request.role'} !~ /^st/)) {
 4746:                 $has_evb = 1;
 4747:             }
 4748:             unless ($has_evb) {
 4749:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
 4750:                     ($activity eq 'boards') || ($activity eq 'groups') || ($activity eq 'chat')) {
 4751:                     if ($udom eq $cdom) {
 4752:                         $check_ipaccess = 1;
 4753:                     }
 4754:                 }
 4755:             }
 4756:         } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
 4757:                 ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
 4758:             my $checkrole;
 4759:             if ($env{'request.role.domain'} eq '') {
 4760:                 $checkrole = "cm./$env{'user.domain'}/";
 4761:             } else {
 4762:                 $checkrole = "cm./$env{'request.role.domain'}/";
 4763:             }
 4764:             if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
 4765:                 $has_evb = 1;
 4766:             }
 4767:         }
 4768:         unless ($has_evb || $check_ipaccess) {
 4769:             my @machinedoms = &Apache::lonnet::current_machine_domains();
 4770:             if (($dom eq 'public') && ($activity eq 'port')) {
 4771:                 $dom = $udom;
 4772:             }
 4773:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
 4774:                 $check_ipaccess = 1;
 4775:             } else {
 4776:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 4777:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
 4778:                 my $prim = &Apache::lonnet::domain($dom,'primary');
 4779:                 my $intdom = &Apache::lonnet::internet_dom($prim);
 4780:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
 4781:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
 4782:                         $check_ipaccess = 1;
 4783:                     }
 4784:                 }
 4785:             }
 4786:         }
 4787:         if ($check_ipaccess) {
 4788:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
 4789:             unless (defined($cached)) {
 4790:                 my %domconfig =
 4791:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
 4792:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
 4793:             }
 4794:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
 4795:                 foreach my $id (keys(%{$ipaccessref})) {
 4796:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
 4797:                         my $range = $ipaccessref->{$id}->{'ip'};
 4798:                         if ($range) {
 4799:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
 4800:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
 4801:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
 4802:                                         return ('','','',$id,$dom);
 4803:                                         last;
 4804:                                     }
 4805:                                 }
 4806:                             }
 4807:                         }
 4808:                     }
 4809:                 }
 4810:             }
 4811:         }
 4812:     }
 4813:     if (defined($udom) && defined($uname)) {
 4814:         # If uname and udom are for a course, check for blocks in the course.
 4815:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
 4816:             my ($startblock,$endblock,$triggerblock) =
 4817:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
 4818:             return ($startblock,$endblock,$triggerblock);
 4819:         }
 4820:     } else {
 4821:         $udom = $env{'user.domain'};
 4822:         $uname = $env{'user.name'};
 4823:     }
 4824: 
 4825:     my $startblock = 0;
 4826:     my $endblock = 0;
 4827:     my $triggerblock = '';
 4828:     my %live_courses;
 4829:     unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
 4830:         %live_courses = &findallcourses(undef,$uname,$udom);
 4831:     }
 4832: 
 4833:     # If uname is for a user, and activity is course-specific, i.e.,
 4834:     # boards, chat or groups, check for blocking in current course only.
 4835: 
 4836:     if (($activity eq 'boards' || $activity eq 'chat' ||
 4837:          $activity eq 'groups' || $activity eq 'printout') &&
 4838:         ($env{'request.course.id'})) {
 4839:         foreach my $key (keys(%live_courses)) {
 4840:             if ($key ne $env{'request.course.id'}) {
 4841:                 delete($live_courses{$key});
 4842:             }
 4843:         }
 4844:     }
 4845: 
 4846:     my $otheruser = 0;
 4847:     my %own_courses;
 4848:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 4849:         # Resource belongs to user other than current user.
 4850:         $otheruser = 1;
 4851:         # Gather courses for current user
 4852:         %own_courses = 
 4853:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 4854:     }
 4855: 
 4856:     # Gather active course roles - course coordinator, instructor, 
 4857:     # exam proctor, ta, student, or custom role.
 4858: 
 4859:     foreach my $course (keys(%live_courses)) {
 4860:         my ($cdom,$cnum);
 4861:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 4862:             $cdom = $env{'course.'.$course.'.domain'};
 4863:             $cnum = $env{'course.'.$course.'.num'};
 4864:         } else {
 4865:             ($cdom,$cnum) = split(/_/,$course); 
 4866:         }
 4867:         my $no_ownblock = 0;
 4868:         my $no_userblock = 0;
 4869:         if ($otheruser && $activity ne 'com') {
 4870:             # Check if current user has 'evb' priv for this
 4871:             if (defined($own_courses{$course})) {
 4872:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 4873:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4874:                     if ($sec ne 'none') {
 4875:                         $checkrole .= '/'.$sec;
 4876:                     }
 4877:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4878:                         $no_ownblock = 1;
 4879:                         last;
 4880:                     }
 4881:                 }
 4882:             }
 4883:             # if they have 'evb' priv and are currently not playing student
 4884:             next if (($no_ownblock) &&
 4885:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 4886:         }
 4887:         foreach my $sec (keys(%{$live_courses{$course}})) {
 4888:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4889:             if ($sec ne 'none') {
 4890:                 $checkrole .= '/'.$sec;
 4891:             }
 4892:             if ($otheruser) {
 4893:                 # Resource belongs to user other than current user.
 4894:                 # Assemble privs for that user, and check for 'evb' priv.
 4895:                 my (%allroles,%userroles);
 4896:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 4897:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 4898:                         my ($trole,$tdom,$tnum,$tsec);
 4899:                         if ($entry =~ /^cr/) {
 4900:                             ($trole,$tdom,$tnum,$tsec) = 
 4901:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 4902:                         } else {
 4903:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 4904:                         }
 4905:                         my ($spec,$area,$trest);
 4906:                         $area = '/'.$tdom.'/'.$tnum;
 4907:                         $trest = $tnum;
 4908:                         if ($tsec ne '') {
 4909:                             $area .= '/'.$tsec;
 4910:                             $trest .= '/'.$tsec;
 4911:                         }
 4912:                         $spec = $trole.'.'.$area;
 4913:                         if ($trole =~ /^cr/) {
 4914:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 4915:                                                               $tdom,$spec,$trest,$area);
 4916:                         } else {
 4917:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 4918:                                                                 $tdom,$spec,$trest,$area);
 4919:                         }
 4920:                     }
 4921:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 4922:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 4923:                         if ($1) {
 4924:                             $no_userblock = 1;
 4925:                             last;
 4926:                         }
 4927:                     }
 4928:                 }
 4929:             } else {
 4930:                 # Resource belongs to current user
 4931:                 # Check for 'evb' priv via lonnet::allowed().
 4932:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4933:                     $no_ownblock = 1;
 4934:                     last;
 4935:                 }
 4936:             }
 4937:         }
 4938:         # if they have the evb priv and are currently not playing student
 4939:         next if (($no_ownblock) &&
 4940:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 4941:         next if ($no_userblock);
 4942: 
 4943:         # Retrieve blocking times and identity of blocker for course
 4944:         # of specified user, unless user has 'evb' privilege.
 4945:         
 4946:         my ($start,$end,$trigger) = 
 4947:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
 4948:         if (($start != 0) && 
 4949:             (($startblock == 0) || ($startblock > $start))) {
 4950:             $startblock = $start;
 4951:             if ($trigger ne '') {
 4952:                 $triggerblock = $trigger;
 4953:             }
 4954:         }
 4955:         if (($end != 0)  &&
 4956:             (($endblock == 0) || ($endblock < $end))) {
 4957:             $endblock = $end;
 4958:             if ($trigger ne '') {
 4959:                 $triggerblock = $trigger;
 4960:             }
 4961:         }
 4962:     }
 4963:     return ($startblock,$endblock,$triggerblock);
 4964: }
 4965: 
 4966: sub get_blocks {
 4967:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
 4968:     my $startblock = 0;
 4969:     my $endblock = 0;
 4970:     my $triggerblock = '';
 4971:     my $course = $cdom.'_'.$cnum;
 4972:     $setters->{$course} = {};
 4973:     $setters->{$course}{'staff'} = [];
 4974:     $setters->{$course}{'times'} = [];
 4975:     $setters->{$course}{'triggers'} = [];
 4976:     my (@blockers,%triggered);
 4977:     my $now = time;
 4978:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 4979:     if ($activity eq 'docs') {
 4980:         my ($blocked,$nosymbcache,$noenccheck);
 4981:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
 4982:             $blocked = 1;
 4983:             $nosymbcache = 1;
 4984:             $noenccheck = 1;
 4985:         }
 4986:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
 4987:         foreach my $block (@blockers) {
 4988:             if ($block =~ /^firstaccess____(.+)$/) {
 4989:                 my $item = $1;
 4990:                 my $type = 'map';
 4991:                 my $timersymb = $item;
 4992:                 if ($item eq 'course') {
 4993:                     $type = 'course';
 4994:                 } elsif ($item =~ /___\d+___/) {
 4995:                     $type = 'resource';
 4996:                 } else {
 4997:                     $timersymb = &Apache::lonnet::symbread($item);
 4998:                 }
 4999:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5000:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 5001:                 $triggered{$block} = {
 5002:                                        start => $start,
 5003:                                        end   => $end,
 5004:                                        type  => $type,
 5005:                                      };
 5006:             }
 5007:         }
 5008:     } else {
 5009:         foreach my $block (keys(%commblocks)) {
 5010:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 5011:                 my ($start,$end) = ($1,$2);
 5012:                 if ($start <= time && $end >= time) {
 5013:                     if (ref($commblocks{$block}) eq 'HASH') {
 5014:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5015:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5016:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 5017:                                     push(@blockers,$block);
 5018:                                 }
 5019:                             }
 5020:                         }
 5021:                     }
 5022:                 }
 5023:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 5024:                 my $item = $1;
 5025:                 my $timersymb = $item; 
 5026:                 my $type = 'map';
 5027:                 if ($item eq 'course') {
 5028:                     $type = 'course';
 5029:                 } elsif ($item =~ /___\d+___/) {
 5030:                     $type = 'resource';
 5031:                 } else {
 5032:                     $timersymb = &Apache::lonnet::symbread($item);
 5033:                 }
 5034:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5035:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 5036:                 if ($start && $end) {
 5037:                     if (($start <= time) && ($end >= time)) {
 5038:                         if (ref($commblocks{$block}) eq 'HASH') {
 5039:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5040:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5041:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
 5042:                                         push(@blockers,$block);
 5043:                                         $triggered{$block} = {
 5044:                                                                start => $start,
 5045:                                                                end   => $end,
 5046:                                                                type  => $type,
 5047:                                                              };
 5048:                                     }
 5049:                                 }
 5050:                             }
 5051:                         }
 5052:                     }
 5053:                 }
 5054:             }
 5055:         }
 5056:     }
 5057:     foreach my $blocker (@blockers) {
 5058:         my ($staff_name,$staff_dom,$title,$blocks) =
 5059:             &parse_block_record($commblocks{$blocker});
 5060:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 5061:         my ($start,$end,$triggertype);
 5062:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 5063:             ($start,$end) = ($1,$2);
 5064:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 5065:             $start = $triggered{$blocker}{'start'};
 5066:             $end = $triggered{$blocker}{'end'};
 5067:             $triggertype = $triggered{$blocker}{'type'};
 5068:         }
 5069:         if ($start) {
 5070:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 5071:             if ($triggertype) {
 5072:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 5073:             } else {
 5074:                 push(@{$$setters{$course}{'triggers'}},0);
 5075:             }
 5076:             if ( ($startblock == 0) || ($startblock > $start) ) {
 5077:                 $startblock = $start;
 5078:                 if ($triggertype) {
 5079:                     $triggerblock = $blocker;
 5080:                 }
 5081:             }
 5082:             if ( ($endblock == 0) || ($endblock < $end) ) {
 5083:                $endblock = $end;
 5084:                if ($triggertype) {
 5085:                    $triggerblock = $blocker;
 5086:                }
 5087:             }
 5088:         }
 5089:     }
 5090:     return ($startblock,$endblock,$triggerblock);
 5091: }
 5092: 
 5093: sub parse_block_record {
 5094:     my ($record) = @_;
 5095:     my ($setuname,$setudom,$title,$blocks);
 5096:     if (ref($record) eq 'HASH') {
 5097:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 5098:         $title = &unescape($record->{'event'});
 5099:         $blocks = $record->{'blocks'};
 5100:     } else {
 5101:         my @data = split(/:/,$record,3);
 5102:         if (scalar(@data) eq 2) {
 5103:             $title = $data[1];
 5104:             ($setuname,$setudom) = split(/@/,$data[0]);
 5105:         } else {
 5106:             ($setuname,$setudom,$title) = @data;
 5107:         }
 5108:         $blocks = { 'com' => 'on' };
 5109:     }
 5110:     return ($setuname,$setudom,$title,$blocks);
 5111: }
 5112: 
 5113: sub blocking_status {
 5114:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
 5115:     my %setters;
 5116: 
 5117: # check for active blocking
 5118:     if ($clientip eq '') {
 5119:         $clientip = &Apache::lonnet::get_requestor_ip();
 5120:     }
 5121:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
 5122:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
 5123:     my $blocked = 0;
 5124:     if (($startblock && $endblock) || ($by_ip)) {
 5125:         $blocked = 1;
 5126:     }
 5127: 
 5128: # caller just wants to know whether a block is active
 5129:     if (!wantarray) { return $blocked; }
 5130: 
 5131: # build a link to a popup window containing the details
 5132:     my $querystring  = "?activity=$activity";
 5133: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
 5134:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
 5135:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/);
 5136:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
 5137:     } elsif ($activity eq 'docs') {
 5138:         my $showurl = &Apache::lonenc::check_encrypt($url);
 5139:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
 5140:         if ($symb) {
 5141:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
 5142:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
 5143:         }
 5144:     }
 5145: 
 5146:     my $output .= <<'END_MYBLOCK';
 5147: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 5148:     var options = "width=" + w + ",height=" + h + ",";
 5149:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 5150:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 5151:     var newWin = window.open(url, wdwName, options);
 5152:     newWin.focus();
 5153: }
 5154: END_MYBLOCK
 5155: 
 5156:     $output = Apache::lonhtmlcommon::scripttag($output);
 5157:   
 5158:     my $popupUrl = "/adm/blockingstatus/$querystring";
 5159:     my $text = &mt('Communication Blocked');
 5160:     my $class = 'LC_comblock';
 5161:     if ($activity eq 'docs') {
 5162:         $text = &mt('Content Access Blocked');
 5163:         $class = '';
 5164:     } elsif ($activity eq 'printout') {
 5165:         $text = &mt('Printing Blocked');
 5166:     } elsif ($activity eq 'passwd') {
 5167:         $text = &mt('Password Changing Blocked');
 5168:     } elsif ($activity eq 'grades') {
 5169:         $text = &mt('Gradebook Blocked');
 5170:     } elsif ($activity eq 'search') {
 5171:         $text = &mt('Search Blocked');
 5172:     } elsif ($activity eq 'about') {
 5173:         $text = &mt('Access to User Information Pages Blocked');
 5174:     } elsif ($activity eq 'wishlist') {
 5175:         $text = &mt('Access to Stored Links Blocked');
 5176:     } elsif ($activity eq 'annotate') {
 5177:         $text = &mt('Access to Annotations Blocked');
 5178:     }
 5179:     $output .= <<"END_BLOCK";
 5180: <div class='$class'>
 5181:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 5182:   title='$text'>
 5183:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 5184:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 5185:   title='$text'>$text</a>
 5186: </div>
 5187: 
 5188: END_BLOCK
 5189: 
 5190:     return ($blocked, $output);
 5191: }
 5192: 
 5193: ###############################################
 5194: 
 5195: sub check_ip_acc {
 5196:     my ($acc,$clientip)=@_;
 5197:     &Apache::lonxml::debug("acc is $acc");
 5198:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 5199:         return 1;
 5200:     }
 5201:     my $allowed=0;
 5202:     my $ip;
 5203:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
 5204:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
 5205:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
 5206:     } else {
 5207:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
 5208:         $ip = $remote_ip || $env{'request.host'} || $clientip;
 5209:     }
 5210: 
 5211:     my $name;
 5212:     foreach my $pattern (split(',',$acc)) {
 5213:         $pattern =~ s/^\s*//;
 5214:         $pattern =~ s/\s*$//;
 5215:         if ($pattern =~ /\*$/) {
 5216:             #35.8.*
 5217:             $pattern=~s/\*//;
 5218:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 5219:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 5220:             #35.8.3.[34-56]
 5221:             my $low=$2;
 5222:             my $high=$3;
 5223:             $pattern=$1;
 5224:             if ($ip =~ /^\Q$pattern\E/) {
 5225:                 my $last=(split(/\./,$ip))[3];
 5226:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 5227:             }
 5228:         } elsif ($pattern =~ /^\*/) {
 5229:             #*.msu.edu
 5230:             $pattern=~s/\*//;
 5231:             if (!defined($name)) {
 5232:                 use Socket;
 5233:                 my $netaddr=inet_aton($ip);
 5234:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5235:             }
 5236:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 5237:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 5238:             #127.0.0.1
 5239:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 5240:         } else {
 5241:             #some.name.com
 5242:             if (!defined($name)) {
 5243:                 use Socket;
 5244:                 my $netaddr=inet_aton($ip);
 5245:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5246:             }
 5247:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 5248:         }
 5249:         if ($allowed) { last; }
 5250:     }
 5251:     return $allowed;
 5252: }
 5253: 
 5254: ###############################################
 5255: 
 5256: =pod
 5257: 
 5258: =head1 Domain Template Functions
 5259: 
 5260: =over 4
 5261: 
 5262: =item * &determinedomain()
 5263: 
 5264: Inputs: $domain (usually will be undef)
 5265: 
 5266: Returns: Determines which domain should be used for designs
 5267: 
 5268: =cut
 5269: 
 5270: ###############################################
 5271: sub determinedomain {
 5272:     my $domain=shift;
 5273:     if (! $domain) {
 5274:         # Determine domain if we have not been given one
 5275:         $domain = &Apache::lonnet::default_login_domain();
 5276:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 5277:         if ($env{'request.role.domain'}) { 
 5278:             $domain=$env{'request.role.domain'}; 
 5279:         }
 5280:     }
 5281:     return $domain;
 5282: }
 5283: ###############################################
 5284: 
 5285: sub devalidate_domconfig_cache {
 5286:     my ($udom)=@_;
 5287:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 5288: }
 5289: 
 5290: # ---------------------- Get domain configuration for a domain
 5291: sub get_domainconf {
 5292:     my ($udom) = @_;
 5293:     my $cachetime=1800;
 5294:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 5295:     if (defined($cached)) { return %{$result}; }
 5296: 
 5297:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 5298: 					     ['login','rolecolors','autoenroll'],$udom);
 5299:     my (%designhash,%legacy);
 5300:     if (keys(%domconfig) > 0) {
 5301:         if (ref($domconfig{'login'}) eq 'HASH') {
 5302:             if (keys(%{$domconfig{'login'}})) {
 5303:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 5304:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5305:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
 5306:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5307:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
 5308:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
 5309:                                         if ($key eq 'loginvia') {
 5310:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 5311:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 5312:                                                 $designhash{$udom.'.login.loginvia'} = $server;
 5313:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 5314:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 5315:                                                 } else {
 5316:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 5317:                                                 }
 5318:                                             }
 5319:                                         } elsif ($key eq 'headtag') {
 5320:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
 5321:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
 5322:                                             }
 5323:                                         }
 5324:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
 5325:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
 5326:                                         }
 5327:                                     }
 5328:                                 }
 5329:                             }
 5330:                         } elsif ($key eq 'saml') {
 5331:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5332:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
 5333:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
 5334:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
 5335:                                         foreach my $item ('text','img','alt','url','title','notsso') {
 5336:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
 5337:                                         }
 5338:                                     }
 5339:                                 }
 5340:                             }
 5341:                         } else {
 5342:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 5343:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 5344:                                     $domconfig{'login'}{$key}{$img};
 5345:                             }
 5346:                         }
 5347:                     } else {
 5348:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 5349:                     }
 5350:                 }
 5351:             } else {
 5352:                 $legacy{'login'} = 1;
 5353:             }
 5354:         } else {
 5355:             $legacy{'login'} = 1;
 5356:         }
 5357:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 5358:             if (keys(%{$domconfig{'rolecolors'}})) {
 5359:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 5360:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 5361:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 5362:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 5363:                         }
 5364:                     }
 5365:                 }
 5366:             } else {
 5367:                 $legacy{'rolecolors'} = 1;
 5368:             }
 5369:         } else {
 5370:             $legacy{'rolecolors'} = 1;
 5371:         }
 5372:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5373:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 5374:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 5375:             }
 5376:         }
 5377:         if (keys(%legacy) > 0) {
 5378:             my %legacyhash = &get_legacy_domconf($udom);
 5379:             foreach my $item (keys(%legacyhash)) {
 5380:                 if ($item =~ /^\Q$udom\E\.login/) {
 5381:                     if ($legacy{'login'}) { 
 5382:                         $designhash{$item} = $legacyhash{$item};
 5383:                     }
 5384:                 } else {
 5385:                     if ($legacy{'rolecolors'}) {
 5386:                         $designhash{$item} = $legacyhash{$item};
 5387:                     }
 5388:                 }
 5389:             }
 5390:         }
 5391:     } else {
 5392:         %designhash = &get_legacy_domconf($udom); 
 5393:     }
 5394:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 5395: 				  $cachetime);
 5396:     return %designhash;
 5397: }
 5398: 
 5399: sub get_legacy_domconf {
 5400:     my ($udom) = @_;
 5401:     my %legacyhash;
 5402:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 5403:     my $designfile =  $designdir.'/'.$udom.'.tab';
 5404:     if (-e $designfile) {
 5405:         if ( open (my $fh,'<',$designfile) ) {
 5406:             while (my $line = <$fh>) {
 5407:                 next if ($line =~ /^\#/);
 5408:                 chomp($line);
 5409:                 my ($key,$val)=(split(/\=/,$line));
 5410:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 5411:             }
 5412:             close($fh);
 5413:         }
 5414:     }
 5415:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 5416:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 5417:     }
 5418:     return %legacyhash;
 5419: }
 5420: 
 5421: =pod
 5422: 
 5423: =item * &domainlogo()
 5424: 
 5425: Inputs: $domain (usually will be undef)
 5426: 
 5427: Returns: A link to a domain logo, if the domain logo exists.
 5428: If the domain logo does not exist, a description of the domain.
 5429: 
 5430: =cut
 5431: 
 5432: ###############################################
 5433: sub domainlogo {
 5434:     my $domain = &determinedomain(shift);
 5435:     my %designhash = &get_domainconf($domain);    
 5436:     # See if there is a logo
 5437:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 5438:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 5439:         if ($imgsrc =~ m{^/(adm|res)/}) {
 5440: 	    if ($imgsrc =~ m{^/res/}) {
 5441: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 5442: 		&Apache::lonnet::repcopy($local_name);
 5443: 	    }
 5444: 	   $imgsrc = &lonhttpdurl($imgsrc);
 5445:         }
 5446:         my $alttext = $domain;
 5447:         if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
 5448:             $alttext = $designhash{$domain.'.login.alttext_domlogo'};
 5449:         }
 5450:         return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
 5451:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 5452:         return &Apache::lonnet::domain($domain,'description');
 5453:     } else {
 5454:         return '';
 5455:     }
 5456: }
 5457: ##############################################
 5458: 
 5459: =pod
 5460: 
 5461: =item * &designparm()
 5462: 
 5463: Inputs: $which parameter; $domain (usually will be undef)
 5464: 
 5465: Returns: value of designparamter $which
 5466: 
 5467: =cut
 5468: 
 5469: 
 5470: ##############################################
 5471: sub designparm {
 5472:     my ($which,$domain)=@_;
 5473:     if (exists($env{'environment.color.'.$which})) {
 5474:         return $env{'environment.color.'.$which};
 5475:     }
 5476:     $domain=&determinedomain($domain);
 5477:     my %domdesign;
 5478:     unless ($domain eq 'public') {
 5479:         %domdesign = &get_domainconf($domain);
 5480:     }
 5481:     my $output;
 5482:     if ($domdesign{$domain.'.'.$which} ne '') {
 5483:         $output = $domdesign{$domain.'.'.$which};
 5484:     } else {
 5485:         $output = $defaultdesign{$which};
 5486:     }
 5487:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 5488:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 5489:         if ($output =~ m{^/(adm|res)/}) {
 5490:             if ($output =~ m{^/res/}) {
 5491:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 5492:                 &Apache::lonnet::repcopy($local_name);
 5493:             }
 5494:             $output = &lonhttpdurl($output);
 5495:         }
 5496:     }
 5497:     return $output;
 5498: }
 5499: 
 5500: ##############################################
 5501: =pod
 5502: 
 5503: =item * &authorspace()
 5504: 
 5505: Inputs: $url (usually will be undef).
 5506: 
 5507: Returns: Path to Authoring Space containing the resource or 
 5508:          directory being viewed (or for which action is being taken). 
 5509:          If $url is provided, and begins /priv/<domain>/<uname>
 5510:          the path will be that portion of the $context argument.
 5511:          Otherwise the path will be for the author space of the current
 5512:          user when the current role is author, or for that of the 
 5513:          co-author/assistant co-author space when the current role 
 5514:          is co-author or assistant co-author.
 5515: 
 5516: =cut
 5517: 
 5518: sub authorspace {
 5519:     my ($url) = @_;
 5520:     if ($url ne '') {
 5521:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 5522:            return $1;
 5523:         }
 5524:     }
 5525:     my $caname = '';
 5526:     my $cadom = '';
 5527:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 5528:         ($cadom,$caname) =
 5529:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 5530:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 5531:         $caname = $env{'user.name'};
 5532:         $cadom = $env{'user.domain'};
 5533:     }
 5534:     if (($caname ne '') && ($cadom ne '')) {
 5535:         return "/priv/$cadom/$caname/";
 5536:     }
 5537:     return;
 5538: }
 5539: 
 5540: ##############################################
 5541: =pod
 5542: 
 5543: =item * &head_subbox()
 5544: 
 5545: Inputs: $content (contains HTML code with page functions, etc.)
 5546: 
 5547: Returns: HTML div with $content
 5548:          To be included in page header
 5549: 
 5550: =cut
 5551: 
 5552: sub head_subbox {
 5553:     my ($content)=@_;
 5554:     my $output =
 5555:         '<div class="LC_head_subbox">'
 5556:        .$content
 5557:        .'</div>'
 5558: }
 5559: 
 5560: ##############################################
 5561: =pod
 5562: 
 5563: =item * &CSTR_pageheader()
 5564: 
 5565: Input: (optional) filename from which breadcrumb trail is built.
 5566:        In most cases no input as needed, as $env{'request.filename'}
 5567:        is appropriate for use in building the breadcrumb trail.
 5568: 
 5569: Returns: HTML div with CSTR path and recent box
 5570:          To be included on Authoring Space pages
 5571: 
 5572: =cut
 5573: 
 5574: sub CSTR_pageheader {
 5575:     my ($trailfile) = @_;
 5576:     if ($trailfile eq '') {
 5577:         $trailfile = $env{'request.filename'};
 5578:     }
 5579: 
 5580: # this is for resources; directories have customtitle, and crumbs
 5581: # and select recent are created in lonpubdir.pm
 5582: 
 5583:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 5584:     my ($udom,$uname,$thisdisfn)=
 5585:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 5586:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 5587:     $formaction =~ s{/+}{/}g;
 5588: 
 5589:     my $parentpath = '';
 5590:     my $lastitem = '';
 5591:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 5592:         $parentpath = $1;
 5593:         $lastitem = $2;
 5594:     } else {
 5595:         $lastitem = $thisdisfn;
 5596:     }
 5597: 
 5598:     my $output =
 5599:          '<div>'
 5600:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 5601:         .'<b>'.&mt('Authoring Space:').'</b> '
 5602:         .'<form name="dirs" method="post" action="'.$formaction
 5603:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
 5604:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
 5605: 
 5606:     if ($lastitem) {
 5607:         $output .=
 5608:              '<span class="LC_filename">'
 5609:             .$lastitem
 5610:             .'</span>';
 5611:     }
 5612:     $output .=
 5613:          '<br />'
 5614:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 5615:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 5616:         .'</form>'
 5617:         .&Apache::lonmenu::constspaceform()
 5618:         .'</div>';
 5619: 
 5620:     return $output;
 5621: }
 5622: 
 5623: ###############################################
 5624: ###############################################
 5625: 
 5626: =pod
 5627: 
 5628: =back
 5629: 
 5630: =head1 HTML Helpers
 5631: 
 5632: =over 4
 5633: 
 5634: =item * &bodytag()
 5635: 
 5636: Returns a uniform header for LON-CAPA web pages.
 5637: 
 5638: Inputs: 
 5639: 
 5640: =over 4
 5641: 
 5642: =item * $title, A title to be displayed on the page.
 5643: 
 5644: =item * $function, the current role (can be undef).
 5645: 
 5646: =item * $addentries, extra parameters for the <body> tag.
 5647: 
 5648: =item * $bodyonly, if defined, only return the <body> tag.
 5649: 
 5650: =item * $domain, if defined, force a given domain.
 5651: 
 5652: =item * $forcereg, if page should register as content page (relevant for 
 5653:             text interface only)
 5654: 
 5655: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 5656:                      navigational links
 5657: 
 5658: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 5659: 
 5660: =item * $no_inline_link, if true and in remote mode, don't show the
 5661:          'Switch To Inline Menu' link
 5662: 
 5663: =item * $args, optional argument valid values are
 5664:             no_auto_mt_title -> prevents &mt()ing the title arg
 5665:             use_absolute     -> for external resource or syllabus, this will
 5666:                                 contain https://<hostname> if server uses
 5667:                                 https (as per hosts.tab), but request is for http
 5668:             hostname         -> hostname, from $r->hostname().
 5669: 
 5670: =item * $advtoolsref, optional argument, ref to an array containing
 5671:             inlineremote items to be added in "Functions" menu below
 5672:             breadcrumbs.
 5673: 
 5674: =back
 5675: 
 5676: Returns: A uniform header for LON-CAPA web pages.  
 5677: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 5678: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 5679: other decorations will be returned.
 5680: 
 5681: =cut
 5682: 
 5683: sub bodytag {
 5684:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 5685:         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_;
 5686: 
 5687:     my $public;
 5688:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 5689:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 5690:         $public = 1;
 5691:     }
 5692:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5693:     my $httphost = $args->{'use_absolute'};
 5694:     my $hostname = $args->{'hostname'};
 5695: 
 5696:     $function = &get_users_function() if (!$function);
 5697:     my $img =    &designparm($function.'.img',$domain);
 5698:     my $font =   &designparm($function.'.font',$domain);
 5699:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 5700: 
 5701:     my %design = ( 'style'   => 'margin-top: 0',
 5702: 		   'bgcolor' => $pgbg,
 5703: 		   'text'    => $font,
 5704:                    'alink'   => &designparm($function.'.alink',$domain),
 5705: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 5706: 		   'link'    => &designparm($function.'.link',$domain),);
 5707:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 5708: 
 5709:  # role and realm
 5710:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
 5711:     if ($realm) {
 5712:         $realm = '/'.$realm;
 5713:     }
 5714:     if ($role eq 'ca') {
 5715:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 5716:         $realm = &plainname($rname,$rdom);
 5717:     } 
 5718: # realm
 5719:     my ($cid,$sec);
 5720:     if ($env{'request.course.id'}) {
 5721:         $cid = $env{'request.course.id'};
 5722:         if ($env{'request.course.sec'}) {
 5723:             $sec = $env{'request.course.sec'};
 5724:         }
 5725:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
 5726:         if (&Apache::lonnet::is_course($1,$2)) {
 5727:             $cid = $1.'_'.$2;
 5728:             $sec = $3;
 5729:         }
 5730:     }
 5731:     if ($cid) {
 5732:         if ($env{'request.role'} !~ /^cr/) {
 5733:             $role = &Apache::lonnet::plaintext($role,&course_type());
 5734:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
 5735:             if ($env{'request.role.desc'}) {
 5736:                 $role = $env{'request.role.desc'};
 5737:             } else {
 5738:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
 5739:             }
 5740:         } else {
 5741:             $role = (split(/\//,$role,4))[-1];
 5742:         }
 5743:         if ($sec) {
 5744:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
 5745:         }   
 5746: 	$realm = $env{'course.'.$cid.'.description'};
 5747:     } else {
 5748:         $role = &Apache::lonnet::plaintext($role);
 5749:     }
 5750: 
 5751:     if (!$realm) { $realm='&nbsp;'; }
 5752: 
 5753:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 5754: 
 5755: # construct main body tag
 5756:     my $bodytag = "<body $extra_body_attr>".
 5757: 	&Apache::lontexconvert::init_math_support();
 5758: 
 5759:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 5760: 
 5761:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 5762:         return $bodytag;
 5763:     }
 5764: 
 5765:     if ($public) {
 5766: 	undef($role);
 5767:     }
 5768: 
 5769:     my $titleinfo = '<h1>'.$title.'</h1>';
 5770:     #
 5771:     # Extra info if you are the DC
 5772:     my $dc_info = '';
 5773:     if (($env{'user.adv'}) && ($env{'request.course.id'}) &&
 5774:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
 5775:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 5776:         $dc_info =~ s/\s+$//;
 5777:     }
 5778: 
 5779:     $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
 5780: 
 5781:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 5782: 
 5783: 
 5784: 
 5785:     my $funclist;
 5786:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
 5787:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
 5788:                     Apache::lonmenu::serverform();
 5789:         my $forbodytag;
 5790:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5791:                                             $forcereg,$args->{'group'},
 5792:                                             $args->{'bread_crumbs'},
 5793:                                             $advtoolsref,'','',\$forbodytag);
 5794:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 5795:             $funclist = $forbodytag;
 5796:         }
 5797:     } else {
 5798: 
 5799:         #    if ($env{'request.state'} eq 'construct') {
 5800:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 5801:         #    }
 5802: 
 5803:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 5804:             Apache::lonmenu::utilityfunctions($httphost), 'start');
 5805: 
 5806:         my ($left,$right) = Apache::lonmenu::primary_menu($args->{'links_disabled'});
 5807: 
 5808:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 5809:             if ($dc_info) {
 5810:                 $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 5811:             }
 5812:             $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 5813:                            <em>$realm</em> $dc_info</div>|;
 5814:             return $bodytag;
 5815:         }
 5816: 
 5817:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 5818:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 5819:         }
 5820: 
 5821:         $bodytag .= $right;
 5822: 
 5823:         if ($dc_info) {
 5824:             $dc_info = &dc_courseid_toggle($dc_info);
 5825:         }
 5826:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 5827: 
 5828:         #if directed to not display the secondary menu, don't.
 5829:         if ($args->{'no_secondary_menu'}) {
 5830:             return $bodytag;
 5831:         }
 5832:         #don't show menus for public users
 5833:         if (!$public){
 5834:             $bodytag .= Apache::lonmenu::secondary_menu($httphost,$args->{'links_disabled'});
 5835:             $bodytag .= Apache::lonmenu::serverform();
 5836:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 5837:             if ($env{'request.state'} eq 'construct') {
 5838:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 5839:                                 $args->{'bread_crumbs'},'','',$hostname);
 5840:             } elsif ($forcereg) {
 5841:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 5842:                                                             $args->{'group'},
 5843:                                                             $args->{'hide_buttons'},
 5844:                                                             $hostname);
 5845:             } else {
 5846:                 my $forbodytag;
 5847:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5848:                                                     $forcereg,$args->{'group'},
 5849:                                                     $args->{'bread_crumbs'},
 5850:                                                     $advtoolsref,'',$hostname,
 5851:                                                     \$forbodytag);
 5852:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 5853:                     $bodytag .= $forbodytag;
 5854:                 }
 5855:             }
 5856:         }else{
 5857:             # this is to seperate menu from content when there's no secondary
 5858:             # menu. Especially needed for public accessible ressources.
 5859:             $bodytag .= '<hr style="clear:both" />';
 5860:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 5861:         }
 5862: 
 5863:         return $bodytag;
 5864:     }
 5865: 
 5866: #
 5867: # Top frame rendering, Remote is up
 5868: #
 5869: 
 5870:     my $imgsrc = $img;
 5871:     if ($img =~ /^\/adm/) {
 5872:         $imgsrc = &lonhttpdurl($img);
 5873:     }
 5874:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 5875: 
 5876:     my $help=($no_inline_link?''
 5877:               :&Apache::loncommon::top_nav_help('Help'));
 5878: 
 5879:     # Explicit link to get inline menu
 5880:     my $menu= ($no_inline_link?''
 5881:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
 5882: 
 5883:     if ($dc_info) {
 5884:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
 5885:     }
 5886: 
 5887:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 5888:     unless ($public) {
 5889:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
 5890:                                 undef,'LC_menubuttons_link');
 5891:     }
 5892: 
 5893:     unless ($env{'form.inhibitmenu'}) {
 5894:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
 5895:                        <ol class="LC_primary_menu LC_floatright LC_right">
 5896:                        <li>$help</li>
 5897:                        <li>$menu</li>
 5898:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
 5899:     }
 5900:     if ($env{'request.state'} eq 'construct') {
 5901:         if (!$public){
 5902:             if ($env{'request.state'} eq 'construct') {
 5903:                 $funclist = &Apache::lonhtmlcommon::scripttag(
 5904:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
 5905:                             &Apache::lonhtmlcommon::scripttag('','end').
 5906:                             &Apache::lonmenu::innerregister($forcereg,
 5907:                                                             $args->{'bread_crumbs'});
 5908:             }
 5909:         }
 5910:     }
 5911:     return $bodytag."\n".$funclist;
 5912: }
 5913: 
 5914: sub dc_courseid_toggle {
 5915:     my ($dc_info) = @_;
 5916:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 5917:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 5918:            &mt('(More ...)').'</a></span>'.
 5919:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 5920: }
 5921: 
 5922: sub make_attr_string {
 5923:     my ($register,$attr_ref) = @_;
 5924: 
 5925:     if ($attr_ref && !ref($attr_ref)) {
 5926: 	die("addentries Must be a hash ref ".
 5927: 	    join(':',caller(1))." ".
 5928: 	    join(':',caller(0))." ");
 5929:     }
 5930: 
 5931:     if ($register) {
 5932: 	my ($on_load,$on_unload);
 5933: 	foreach my $key (keys(%{$attr_ref})) {
 5934: 	    if      (lc($key) eq 'onload') {
 5935: 		$on_load.=$attr_ref->{$key}.';';
 5936: 		delete($attr_ref->{$key});
 5937: 
 5938: 	    } elsif (lc($key) eq 'onunload') {
 5939: 		$on_unload.=$attr_ref->{$key}.';';
 5940: 		delete($attr_ref->{$key});
 5941: 	    }
 5942: 	}
 5943:         if ($env{'environment.remote'} eq 'on') {
 5944:             $attr_ref->{'onload'}  =
 5945:                 &Apache::lonmenu::loadevents().  $on_load;
 5946:             $attr_ref->{'onunload'}=
 5947:                 &Apache::lonmenu::unloadevents().$on_unload;
 5948:         } else {  
 5949: 	    $attr_ref->{'onload'}  = $on_load;
 5950: 	    $attr_ref->{'onunload'}= $on_unload;
 5951:         }
 5952:     }
 5953: 
 5954:     my $attr_string;
 5955:     foreach my $attr (sort(keys(%$attr_ref))) {
 5956: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 5957:     }
 5958:     return $attr_string;
 5959: }
 5960: 
 5961: 
 5962: ###############################################
 5963: ###############################################
 5964: 
 5965: =pod
 5966: 
 5967: =item * &endbodytag()
 5968: 
 5969: Returns a uniform footer for LON-CAPA web pages.
 5970: 
 5971: Inputs: 1 - optional reference to an args hash
 5972: If in the hash, key for noredirectlink has a value which evaluates to true,
 5973: a 'Continue' link is not displayed if the page contains an
 5974: internal redirect in the <head></head> section,
 5975: i.e., $env{'internal.head.redirect'} exists   
 5976: 
 5977: =cut
 5978: 
 5979: sub endbodytag {
 5980:     my ($args) = @_;
 5981:     my $endbodytag;
 5982:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 5983:         $endbodytag='</body>';
 5984:     }
 5985:     if ( exists( $env{'internal.head.redirect'} ) ) {
 5986:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 5987: 	    $endbodytag=
 5988: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 5989: 	        &mt('Continue').'</a>'.
 5990: 	        $endbodytag;
 5991:         }
 5992:     }
 5993:     return $endbodytag;
 5994: }
 5995: 
 5996: =pod
 5997: 
 5998: =item * &standard_css()
 5999: 
 6000: Returns a style sheet
 6001: 
 6002: Inputs: (all optional)
 6003:             domain         -> force to color decorate a page for a specific
 6004:                                domain
 6005:             function       -> force usage of a specific rolish color scheme
 6006:             bgcolor        -> override the default page bgcolor
 6007: 
 6008: =cut
 6009: 
 6010: sub standard_css {
 6011:     my ($function,$domain,$bgcolor) = @_;
 6012:     $function  = &get_users_function() if (!$function);
 6013:     my $img    = &designparm($function.'.img',   $domain);
 6014:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 6015:     my $font   = &designparm($function.'.font',  $domain);
 6016:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 6017: #second colour for later usage
 6018:     my $sidebg = &designparm($function.'.sidebg',$domain);
 6019:     my $pgbg_or_bgcolor =
 6020: 	         $bgcolor ||
 6021: 	         &designparm($function.'.pgbg',  $domain);
 6022:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 6023:     my $alink  = &designparm($function.'.alink', $domain);
 6024:     my $vlink  = &designparm($function.'.vlink', $domain);
 6025:     my $link   = &designparm($function.'.link',  $domain);
 6026: 
 6027:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 6028:     my $mono                 = 'monospace';
 6029:     my $data_table_head      = $sidebg;
 6030:     my $data_table_light     = '#FAFAFA';
 6031:     my $data_table_dark      = '#E0E0E0';
 6032:     my $data_table_darker    = '#CCCCCC';
 6033:     my $data_table_highlight = '#FFFF00';
 6034:     my $mail_new             = '#FFBB77';
 6035:     my $mail_new_hover       = '#DD9955';
 6036:     my $mail_read            = '#BBBB77';
 6037:     my $mail_read_hover      = '#999944';
 6038:     my $mail_replied         = '#AAAA88';
 6039:     my $mail_replied_hover   = '#888855';
 6040:     my $mail_other           = '#99BBBB';
 6041:     my $mail_other_hover     = '#669999';
 6042:     my $table_header         = '#DDDDDD';
 6043:     my $feedback_link_bg     = '#BBBBBB';
 6044:     my $lg_border_color      = '#C8C8C8';
 6045:     my $button_hover         = '#BF2317';
 6046: 
 6047:     my $border = ($env{'browser.type'} eq 'explorer' ||
 6048:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 6049:                                              : '0 3px 0 4px';
 6050: 
 6051: 
 6052:     return <<END;
 6053: 
 6054: /* needed for iframe to allow 100% height in FF */
 6055: body, html { 
 6056:     margin: 0;
 6057:     padding: 0 0.5%;
 6058:     height: 99%; /* to avoid scrollbars */
 6059: }
 6060: 
 6061: body {
 6062:   font-family: $sans;
 6063:   line-height:130%;
 6064:   font-size:0.83em;
 6065:   color:$font;
 6066: }
 6067: 
 6068: a:focus,
 6069: a:focus img {
 6070:   color: red;
 6071: }
 6072: 
 6073: form, .inline {
 6074:   display: inline;
 6075: }
 6076: 
 6077: .LC_right {
 6078:   text-align:right;
 6079: }
 6080: 
 6081: .LC_middle {
 6082:   vertical-align:middle;
 6083: }
 6084: 
 6085: .LC_floatleft {
 6086:   float: left;
 6087: }
 6088: 
 6089: .LC_floatright {
 6090:   float: right;
 6091: }
 6092: 
 6093: .LC_400Box {
 6094:   width:400px;
 6095: }
 6096: 
 6097: .LC_iframecontainer {
 6098:     width: 98%;
 6099:     margin: 0;
 6100:     position: fixed;
 6101:     top: 8.5em;
 6102:     bottom: 0;
 6103: }
 6104: 
 6105: .LC_iframecontainer iframe{
 6106:     border: none;
 6107:     width: 100%;
 6108:     height: 100%;
 6109: }
 6110: 
 6111: .LC_filename {
 6112:   font-family: $mono;
 6113:   white-space:pre;
 6114:   font-size: 120%;
 6115: }
 6116: 
 6117: .LC_fileicon {
 6118:   border: none;
 6119:   height: 1.3em;
 6120:   vertical-align: text-bottom;
 6121:   margin-right: 0.3em;
 6122:   text-decoration:none;
 6123: }
 6124: 
 6125: .LC_setting {
 6126:   text-decoration:underline;
 6127: }
 6128: 
 6129: .LC_error {
 6130:   color: red;
 6131: }
 6132: 
 6133: .LC_warning {
 6134:   color: darkorange;
 6135: }
 6136: 
 6137: .LC_diff_removed {
 6138:   color: red;
 6139: }
 6140: 
 6141: .LC_info,
 6142: .LC_success,
 6143: .LC_diff_added {
 6144:   color: green;
 6145: }
 6146: 
 6147: div.LC_confirm_box {
 6148:   background-color: #FAFAFA;
 6149:   border: 1px solid $lg_border_color;
 6150:   margin-right: 0;
 6151:   padding: 5px;
 6152: }
 6153: 
 6154: div.LC_confirm_box .LC_error img,
 6155: div.LC_confirm_box .LC_success img {
 6156:   vertical-align: middle;
 6157: }
 6158: 
 6159: .LC_maxwidth {
 6160:   max-width: 100%;
 6161:   height: auto;
 6162: }
 6163: 
 6164: .LC_textsize_mobile {
 6165:   \@media only screen and (max-device-width: 480px) {
 6166:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
 6167:   }
 6168: }
 6169: 
 6170: .LC_icon {
 6171:   border: none;
 6172:   vertical-align: middle;
 6173: }
 6174: 
 6175: .LC_docs_spacer {
 6176:   width: 25px;
 6177:   height: 1px;
 6178:   border: none;
 6179: }
 6180: 
 6181: .LC_internal_info {
 6182:   color: #999999;
 6183: }
 6184: 
 6185: .LC_discussion {
 6186:   background: $data_table_dark;
 6187:   border: 1px solid black;
 6188:   margin: 2px;
 6189: }
 6190: 
 6191: .LC_disc_action_left {
 6192:   background: $sidebg;
 6193:   text-align: left;
 6194:   padding: 4px;
 6195:   margin: 2px;
 6196: }
 6197: 
 6198: .LC_disc_action_right {
 6199:   background: $sidebg;
 6200:   text-align: right;
 6201:   padding: 4px;
 6202:   margin: 2px;
 6203: }
 6204: 
 6205: .LC_disc_new_item {
 6206:   background: white;
 6207:   border: 2px solid red;
 6208:   margin: 4px;
 6209:   padding: 4px;
 6210: }
 6211: 
 6212: .LC_disc_old_item {
 6213:   background: white;
 6214:   margin: 4px;
 6215:   padding: 4px;
 6216: }
 6217: 
 6218: table.LC_pastsubmission {
 6219:   border: 1px solid black;
 6220:   margin: 2px;
 6221: }
 6222: 
 6223: table#LC_menubuttons {
 6224:   width: 100%;
 6225:   background: $pgbg;
 6226:   border: 2px;
 6227:   border-collapse: separate;
 6228:   padding: 0;
 6229: }
 6230: 
 6231: table#LC_title_bar a {
 6232:   color: $fontmenu;
 6233: }
 6234: 
 6235: table#LC_title_bar {
 6236:   clear: both;
 6237:   display: none;
 6238: }
 6239: 
 6240: table#LC_title_bar,
 6241: table.LC_breadcrumbs, /* obsolete? */
 6242: table#LC_title_bar.LC_with_remote {
 6243:   width: 100%;
 6244:   border-color: $pgbg;
 6245:   border-style: solid;
 6246:   border-width: $border;
 6247:   background: $pgbg;
 6248:   color: $fontmenu;
 6249:   border-collapse: collapse;
 6250:   padding: 0;
 6251:   margin: 0;
 6252: }
 6253: 
 6254: ul.LC_breadcrumb_tools_outerlist {
 6255:     margin: 0;
 6256:     padding: 0;
 6257:     position: relative;
 6258:     list-style: none;
 6259: }
 6260: ul.LC_breadcrumb_tools_outerlist li {
 6261:     display: inline;
 6262: }
 6263: 
 6264: .LC_breadcrumb_tools_navigation {
 6265:     padding: 0;
 6266:     margin: 0;
 6267:     float: left;
 6268: }
 6269: .LC_breadcrumb_tools_tools {
 6270:     padding: 0;
 6271:     margin: 0;
 6272:     float: right;
 6273: }
 6274: 
 6275: table#LC_title_bar td {
 6276:   background: $tabbg;
 6277: }
 6278: 
 6279: table#LC_menubuttons img {
 6280:   border: none;
 6281: }
 6282: 
 6283: .LC_breadcrumbs_component {
 6284:   float: right;
 6285:   margin: 0 1em;
 6286: }
 6287: .LC_breadcrumbs_component img {
 6288:   vertical-align: middle;
 6289: }
 6290: 
 6291: .LC_breadcrumbs_hoverable {
 6292:   background: $sidebg;
 6293: }
 6294: 
 6295: td.LC_table_cell_checkbox {
 6296:   text-align: center;
 6297: }
 6298: 
 6299: .LC_fontsize_small {
 6300:   font-size: 70%;
 6301: }
 6302: 
 6303: #LC_breadcrumbs {
 6304:   clear:both;
 6305:   background: $sidebg;
 6306:   border-bottom: 1px solid $lg_border_color;
 6307:   line-height: 2.5em;
 6308:   overflow: hidden;
 6309:   margin: 0;
 6310:   padding: 0;
 6311:   text-align: left;
 6312: }
 6313: 
 6314: .LC_head_subbox, .LC_actionbox {
 6315:   clear:both;
 6316:   background: #F8F8F8; /* $sidebg; */
 6317:   border: 1px solid $sidebg;
 6318:   margin: 0 0 10px 0;
 6319:   padding: 3px;
 6320:   text-align: left;
 6321: }
 6322: 
 6323: .LC_fontsize_medium {
 6324:   font-size: 85%;
 6325: }
 6326: 
 6327: .LC_fontsize_large {
 6328:   font-size: 120%;
 6329: }
 6330: 
 6331: .LC_menubuttons_inline_text {
 6332:   color: $font;
 6333:   font-size: 90%;
 6334:   padding-left:3px;
 6335: }
 6336: 
 6337: .LC_menubuttons_inline_text img{
 6338:   vertical-align: middle;
 6339: }
 6340: 
 6341: li.LC_menubuttons_inline_text img {
 6342:   cursor:pointer;
 6343:   text-decoration: none;
 6344: }
 6345: 
 6346: .LC_menubuttons_link {
 6347:   text-decoration: none;
 6348: }
 6349: 
 6350: .LC_menubuttons_category {
 6351:   color: $font;
 6352:   background: $pgbg;
 6353:   font-size: larger;
 6354:   font-weight: bold;
 6355: }
 6356: 
 6357: td.LC_menubuttons_text {
 6358:   color: $font;
 6359: }
 6360: 
 6361: .LC_current_location {
 6362:   background: $tabbg;
 6363: }
 6364: 
 6365: td.LC_zero_height {
 6366:   line-height: 0;
 6367:   cellpadding: 0;
 6368: }
 6369: 
 6370: table.LC_data_table {
 6371:   border: 1px solid #000000;
 6372:   border-collapse: separate;
 6373:   border-spacing: 1px;
 6374:   background: $pgbg;
 6375: }
 6376: 
 6377: .LC_data_table_dense {
 6378:   font-size: small;
 6379: }
 6380: 
 6381: table.LC_nested_outer {
 6382:   border: 1px solid #000000;
 6383:   border-collapse: collapse;
 6384:   border-spacing: 0;
 6385:   width: 100%;
 6386: }
 6387: 
 6388: table.LC_innerpickbox,
 6389: table.LC_nested {
 6390:   border: none;
 6391:   border-collapse: collapse;
 6392:   border-spacing: 0;
 6393:   width: 100%;
 6394: }
 6395: 
 6396: table.LC_data_table tr th,
 6397: table.LC_calendar tr th,
 6398: table.LC_prior_tries tr th,
 6399: table.LC_innerpickbox tr th {
 6400:   font-weight: bold;
 6401:   background-color: $data_table_head;
 6402:   color:$fontmenu;
 6403:   font-size:90%;
 6404: }
 6405: 
 6406: table.LC_innerpickbox tr th,
 6407: table.LC_innerpickbox tr td {
 6408:   vertical-align: top;
 6409: }
 6410: 
 6411: table.LC_data_table tr.LC_info_row > td {
 6412:   background-color: #CCCCCC;
 6413:   font-weight: bold;
 6414:   text-align: left;
 6415: }
 6416: 
 6417: table.LC_data_table tr.LC_odd_row > td {
 6418:   background-color: $data_table_light;
 6419:   padding: 2px;
 6420:   vertical-align: top;
 6421: }
 6422: 
 6423: table.LC_pick_box tr > td.LC_odd_row {
 6424:   background-color: $data_table_light;
 6425:   vertical-align: top;
 6426: }
 6427: 
 6428: table.LC_data_table tr.LC_even_row > td {
 6429:   background-color: $data_table_dark;
 6430:   padding: 2px;
 6431:   vertical-align: top;
 6432: }
 6433: 
 6434: table.LC_pick_box tr > td.LC_even_row {
 6435:   background-color: $data_table_dark;
 6436:   vertical-align: top;
 6437: }
 6438: 
 6439: table.LC_data_table tr.LC_data_table_highlight td {
 6440:   background-color: $data_table_darker;
 6441: }
 6442: 
 6443: table.LC_data_table tr td.LC_leftcol_header {
 6444:   background-color: $data_table_head;
 6445:   font-weight: bold;
 6446: }
 6447: 
 6448: table.LC_data_table tr.LC_empty_row td,
 6449: table.LC_nested tr.LC_empty_row td {
 6450:   font-weight: bold;
 6451:   font-style: italic;
 6452:   text-align: center;
 6453:   padding: 8px;
 6454: }
 6455: 
 6456: table.LC_data_table tr.LC_empty_row td,
 6457: table.LC_data_table tr.LC_footer_row td {
 6458:   background-color: $sidebg;
 6459: }
 6460: 
 6461: table.LC_nested tr.LC_empty_row td {
 6462:   background-color: #FFFFFF;
 6463: }
 6464: 
 6465: table.LC_caption {
 6466: }
 6467: 
 6468: table.LC_nested tr.LC_empty_row td {
 6469:   padding: 4ex
 6470: }
 6471: 
 6472: table.LC_nested_outer tr th {
 6473:   font-weight: bold;
 6474:   color:$fontmenu;
 6475:   background-color: $data_table_head;
 6476:   font-size: small;
 6477:   border-bottom: 1px solid #000000;
 6478: }
 6479: 
 6480: table.LC_nested_outer tr td.LC_subheader {
 6481:   background-color: $data_table_head;
 6482:   font-weight: bold;
 6483:   font-size: small;
 6484:   border-bottom: 1px solid #000000;
 6485:   text-align: right;
 6486: }
 6487: 
 6488: table.LC_nested tr.LC_info_row td {
 6489:   background-color: #CCCCCC;
 6490:   font-weight: bold;
 6491:   font-size: small;
 6492:   text-align: center;
 6493: }
 6494: 
 6495: table.LC_nested tr.LC_info_row td.LC_left_item,
 6496: table.LC_nested_outer tr th.LC_left_item {
 6497:   text-align: left;
 6498: }
 6499: 
 6500: table.LC_nested td {
 6501:   background-color: #FFFFFF;
 6502:   font-size: small;
 6503: }
 6504: 
 6505: table.LC_nested_outer tr th.LC_right_item,
 6506: table.LC_nested tr.LC_info_row td.LC_right_item,
 6507: table.LC_nested tr.LC_odd_row td.LC_right_item,
 6508: table.LC_nested tr td.LC_right_item {
 6509:   text-align: right;
 6510: }
 6511: 
 6512: table.LC_nested tr.LC_odd_row td {
 6513:   background-color: #EEEEEE;
 6514: }
 6515: 
 6516: table.LC_createuser {
 6517: }
 6518: 
 6519: table.LC_createuser tr.LC_section_row td {
 6520:   font-size: small;
 6521: }
 6522: 
 6523: table.LC_createuser tr.LC_info_row td  {
 6524:   background-color: #CCCCCC;
 6525:   font-weight: bold;
 6526:   text-align: center;
 6527: }
 6528: 
 6529: table.LC_calendar {
 6530:   border: 1px solid #000000;
 6531:   border-collapse: collapse;
 6532:   width: 98%;
 6533: }
 6534: 
 6535: table.LC_calendar_pickdate {
 6536:   font-size: xx-small;
 6537: }
 6538: 
 6539: table.LC_calendar tr td {
 6540:   border: 1px solid #000000;
 6541:   vertical-align: top;
 6542:   width: 14%;
 6543: }
 6544: 
 6545: table.LC_calendar tr td.LC_calendar_day_empty {
 6546:   background-color: $data_table_dark;
 6547: }
 6548: 
 6549: table.LC_calendar tr td.LC_calendar_day_current {
 6550:   background-color: $data_table_highlight;
 6551: }
 6552: 
 6553: table.LC_data_table tr td.LC_mail_new {
 6554:   background-color: $mail_new;
 6555: }
 6556: 
 6557: table.LC_data_table tr.LC_mail_new:hover {
 6558:   background-color: $mail_new_hover;
 6559: }
 6560: 
 6561: table.LC_data_table tr td.LC_mail_read {
 6562:   background-color: $mail_read;
 6563: }
 6564: 
 6565: /*
 6566: table.LC_data_table tr.LC_mail_read:hover {
 6567:   background-color: $mail_read_hover;
 6568: }
 6569: */
 6570: 
 6571: table.LC_data_table tr td.LC_mail_replied {
 6572:   background-color: $mail_replied;
 6573: }
 6574: 
 6575: /*
 6576: table.LC_data_table tr.LC_mail_replied:hover {
 6577:   background-color: $mail_replied_hover;
 6578: }
 6579: */
 6580: 
 6581: table.LC_data_table tr td.LC_mail_other {
 6582:   background-color: $mail_other;
 6583: }
 6584: 
 6585: /*
 6586: table.LC_data_table tr.LC_mail_other:hover {
 6587:   background-color: $mail_other_hover;
 6588: }
 6589: */
 6590: 
 6591: table.LC_data_table tr > td.LC_browser_file,
 6592: table.LC_data_table tr > td.LC_browser_file_published {
 6593:   background: #AAEE77;
 6594: }
 6595: 
 6596: table.LC_data_table tr > td.LC_browser_file_locked,
 6597: table.LC_data_table tr > td.LC_browser_file_unpublished {
 6598:   background: #FFAA99;
 6599: }
 6600: 
 6601: table.LC_data_table tr > td.LC_browser_file_obsolete {
 6602:   background: #888888;
 6603: }
 6604: 
 6605: table.LC_data_table tr > td.LC_browser_file_modified,
 6606: table.LC_data_table tr > td.LC_browser_file_metamodified {
 6607:   background: #F8F866;
 6608: }
 6609: 
 6610: table.LC_data_table tr.LC_browser_folder > td {
 6611:   background: #E0E8FF;
 6612: }
 6613: 
 6614: table.LC_data_table tr > td.LC_roles_is {
 6615:   /* background: #77FF77; */
 6616: }
 6617: 
 6618: table.LC_data_table tr > td.LC_roles_future {
 6619:   border-right: 8px solid #FFFF77;
 6620: }
 6621: 
 6622: table.LC_data_table tr > td.LC_roles_will {
 6623:   border-right: 8px solid #FFAA77;
 6624: }
 6625: 
 6626: table.LC_data_table tr > td.LC_roles_expired {
 6627:   border-right: 8px solid #FF7777;
 6628: }
 6629: 
 6630: table.LC_data_table tr > td.LC_roles_will_not {
 6631:   border-right: 8px solid #AAFF77;
 6632: }
 6633: 
 6634: table.LC_data_table tr > td.LC_roles_selected {
 6635:   border-right: 8px solid #11CC55;
 6636: }
 6637: 
 6638: span.LC_current_location {
 6639:   font-size:larger;
 6640:   background: $pgbg;
 6641: }
 6642: 
 6643: span.LC_current_nav_location {
 6644:   font-weight:bold;
 6645:   background: $sidebg;
 6646: }
 6647: 
 6648: span.LC_parm_menu_item {
 6649:   font-size: larger;
 6650: }
 6651: 
 6652: span.LC_parm_scope_all {
 6653:   color: red;
 6654: }
 6655: 
 6656: span.LC_parm_scope_folder {
 6657:   color: green;
 6658: }
 6659: 
 6660: span.LC_parm_scope_resource {
 6661:   color: orange;
 6662: }
 6663: 
 6664: span.LC_parm_part {
 6665:   color: blue;
 6666: }
 6667: 
 6668: span.LC_parm_folder,
 6669: span.LC_parm_symb {
 6670:   font-size: x-small;
 6671:   font-family: $mono;
 6672:   color: #AAAAAA;
 6673: }
 6674: 
 6675: ul.LC_parm_parmlist li {
 6676:   display: inline-block;
 6677:   padding: 0.3em 0.8em;
 6678:   vertical-align: top;
 6679:   width: 150px;
 6680:   border-top:1px solid $lg_border_color;
 6681: }
 6682: 
 6683: td.LC_parm_overview_level_menu,
 6684: td.LC_parm_overview_map_menu,
 6685: td.LC_parm_overview_parm_selectors,
 6686: td.LC_parm_overview_restrictions  {
 6687:   border: 1px solid black;
 6688:   border-collapse: collapse;
 6689: }
 6690: 
 6691: table.LC_parm_overview_restrictions td {
 6692:   border-width: 1px 4px 1px 4px;
 6693:   border-style: solid;
 6694:   border-color: $pgbg;
 6695:   text-align: center;
 6696: }
 6697: 
 6698: table.LC_parm_overview_restrictions th {
 6699:   background: $tabbg;
 6700:   border-width: 1px 4px 1px 4px;
 6701:   border-style: solid;
 6702:   border-color: $pgbg;
 6703: }
 6704: 
 6705: table#LC_helpmenu {
 6706:   border: none;
 6707:   height: 55px;
 6708:   border-spacing: 0;
 6709: }
 6710: 
 6711: table#LC_helpmenu fieldset legend {
 6712:   font-size: larger;
 6713: }
 6714: 
 6715: table#LC_helpmenu_links {
 6716:   width: 100%;
 6717:   border: 1px solid black;
 6718:   background: $pgbg;
 6719:   padding: 0;
 6720:   border-spacing: 1px;
 6721: }
 6722: 
 6723: table#LC_helpmenu_links tr td {
 6724:   padding: 1px;
 6725:   background: $tabbg;
 6726:   text-align: center;
 6727:   font-weight: bold;
 6728: }
 6729: 
 6730: table#LC_helpmenu_links a:link,
 6731: table#LC_helpmenu_links a:visited,
 6732: table#LC_helpmenu_links a:active {
 6733:   text-decoration: none;
 6734:   color: $font;
 6735: }
 6736: 
 6737: table#LC_helpmenu_links a:hover {
 6738:   text-decoration: underline;
 6739:   color: $vlink;
 6740: }
 6741: 
 6742: .LC_chrt_popup_exists {
 6743:   border: 1px solid #339933;
 6744:   margin: -1px;
 6745: }
 6746: 
 6747: .LC_chrt_popup_up {
 6748:   border: 1px solid yellow;
 6749:   margin: -1px;
 6750: }
 6751: 
 6752: .LC_chrt_popup {
 6753:   border: 1px solid #8888FF;
 6754:   background: #CCCCFF;
 6755: }
 6756: 
 6757: table.LC_pick_box {
 6758:   border-collapse: separate;
 6759:   background: white;
 6760:   border: 1px solid black;
 6761:   border-spacing: 1px;
 6762: }
 6763: 
 6764: table.LC_pick_box td.LC_pick_box_title {
 6765:   background: $sidebg;
 6766:   font-weight: bold;
 6767:   text-align: left;
 6768:   vertical-align: top;
 6769:   width: 184px;
 6770:   padding: 8px;
 6771: }
 6772: 
 6773: table.LC_pick_box td.LC_pick_box_value {
 6774:   text-align: left;
 6775:   padding: 8px;
 6776: }
 6777: 
 6778: table.LC_pick_box td.LC_pick_box_select {
 6779:   text-align: left;
 6780:   padding: 8px;
 6781: }
 6782: 
 6783: table.LC_pick_box td.LC_pick_box_separator {
 6784:   padding: 0;
 6785:   height: 1px;
 6786:   background: black;
 6787: }
 6788: 
 6789: table.LC_pick_box td.LC_pick_box_submit {
 6790:   text-align: right;
 6791: }
 6792: 
 6793: table.LC_pick_box td.LC_evenrow_value {
 6794:   text-align: left;
 6795:   padding: 8px;
 6796:   background-color: $data_table_light;
 6797: }
 6798: 
 6799: table.LC_pick_box td.LC_oddrow_value {
 6800:   text-align: left;
 6801:   padding: 8px;
 6802:   background-color: $data_table_light;
 6803: }
 6804: 
 6805: span.LC_helpform_receipt_cat {
 6806:   font-weight: bold;
 6807: }
 6808: 
 6809: table.LC_group_priv_box {
 6810:   background: white;
 6811:   border: 1px solid black;
 6812:   border-spacing: 1px;
 6813: }
 6814: 
 6815: table.LC_group_priv_box td.LC_pick_box_title {
 6816:   background: $tabbg;
 6817:   font-weight: bold;
 6818:   text-align: right;
 6819:   width: 184px;
 6820: }
 6821: 
 6822: table.LC_group_priv_box td.LC_groups_fixed {
 6823:   background: $data_table_light;
 6824:   text-align: center;
 6825: }
 6826: 
 6827: table.LC_group_priv_box td.LC_groups_optional {
 6828:   background: $data_table_dark;
 6829:   text-align: center;
 6830: }
 6831: 
 6832: table.LC_group_priv_box td.LC_groups_functionality {
 6833:   background: $data_table_darker;
 6834:   text-align: center;
 6835:   font-weight: bold;
 6836: }
 6837: 
 6838: table.LC_group_priv td {
 6839:   text-align: left;
 6840:   padding: 0;
 6841: }
 6842: 
 6843: .LC_navbuttons {
 6844:   margin: 2ex 0ex 2ex 0ex;
 6845: }
 6846: 
 6847: .LC_topic_bar {
 6848:   font-weight: bold;
 6849:   background: $tabbg;
 6850:   margin: 1em 0em 1em 2em;
 6851:   padding: 3px;
 6852:   font-size: 1.2em;
 6853: }
 6854: 
 6855: .LC_topic_bar span {
 6856:   left: 0.5em;
 6857:   position: absolute;
 6858:   vertical-align: middle;
 6859:   font-size: 1.2em;
 6860: }
 6861: 
 6862: table.LC_course_group_status {
 6863:   margin: 20px;
 6864: }
 6865: 
 6866: table.LC_status_selector td {
 6867:   vertical-align: top;
 6868:   text-align: center;
 6869:   padding: 4px;
 6870: }
 6871: 
 6872: div.LC_feedback_link {
 6873:   clear: both;
 6874:   background: $sidebg;
 6875:   width: 100%;
 6876:   padding-bottom: 10px;
 6877:   border: 1px $tabbg solid;
 6878:   height: 22px;
 6879:   line-height: 22px;
 6880:   padding-top: 5px;
 6881: }
 6882: 
 6883: div.LC_feedback_link img {
 6884:   height: 22px;
 6885:   vertical-align:middle;
 6886: }
 6887: 
 6888: div.LC_feedback_link a {
 6889:   text-decoration: none;
 6890: }
 6891: 
 6892: div.LC_comblock {
 6893:   display:inline;
 6894:   color:$font;
 6895:   font-size:90%;
 6896: }
 6897: 
 6898: div.LC_feedback_link div.LC_comblock {
 6899:   padding-left:5px;
 6900: }
 6901: 
 6902: div.LC_feedback_link div.LC_comblock a {
 6903:   color:$font;
 6904: }
 6905: 
 6906: span.LC_feedback_link {
 6907:   /* background: $feedback_link_bg; */
 6908:   font-size: larger;
 6909: }
 6910: 
 6911: span.LC_message_link {
 6912:   /* background: $feedback_link_bg; */
 6913:   font-size: larger;
 6914:   position: absolute;
 6915:   right: 1em;
 6916: }
 6917: 
 6918: table.LC_prior_tries {
 6919:   border: 1px solid #000000;
 6920:   border-collapse: separate;
 6921:   border-spacing: 1px;
 6922: }
 6923: 
 6924: table.LC_prior_tries td {
 6925:   padding: 2px;
 6926: }
 6927: 
 6928: .LC_answer_correct {
 6929:   background: lightgreen;
 6930:   color: darkgreen;
 6931:   padding: 6px;
 6932: }
 6933: 
 6934: .LC_answer_charged_try {
 6935:   background: #FFAAAA;
 6936:   color: darkred;
 6937:   padding: 6px;
 6938: }
 6939: 
 6940: .LC_answer_not_charged_try,
 6941: .LC_answer_no_grade,
 6942: .LC_answer_late {
 6943:   background: lightyellow;
 6944:   color: black;
 6945:   padding: 6px;
 6946: }
 6947: 
 6948: .LC_answer_previous {
 6949:   background: lightblue;
 6950:   color: darkblue;
 6951:   padding: 6px;
 6952: }
 6953: 
 6954: .LC_answer_no_message {
 6955:   background: #FFFFFF;
 6956:   color: black;
 6957:   padding: 6px;
 6958: }
 6959: 
 6960: .LC_answer_unknown,
 6961: .LC_answer_warning {
 6962:   background: orange;
 6963:   color: black;
 6964:   padding: 6px;
 6965: }
 6966: 
 6967: span.LC_prior_numerical,
 6968: span.LC_prior_string,
 6969: span.LC_prior_custom,
 6970: span.LC_prior_reaction,
 6971: span.LC_prior_math {
 6972:   font-family: $mono;
 6973:   white-space: pre;
 6974: }
 6975: 
 6976: span.LC_prior_string {
 6977:   font-family: $mono;
 6978:   white-space: pre;
 6979: }
 6980: 
 6981: table.LC_prior_option {
 6982:   width: 100%;
 6983:   border-collapse: collapse;
 6984: }
 6985: 
 6986: table.LC_prior_rank,
 6987: table.LC_prior_match {
 6988:   border-collapse: collapse;
 6989: }
 6990: 
 6991: table.LC_prior_option tr td,
 6992: table.LC_prior_rank tr td,
 6993: table.LC_prior_match tr td {
 6994:   border: 1px solid #000000;
 6995: }
 6996: 
 6997: .LC_nobreak {
 6998:   white-space: nowrap;
 6999: }
 7000: 
 7001: span.LC_cusr_emph {
 7002:   font-style: italic;
 7003: }
 7004: 
 7005: span.LC_cusr_subheading {
 7006:   font-weight: normal;
 7007:   font-size: 85%;
 7008: }
 7009: 
 7010: div.LC_docs_entry_move {
 7011:   border: 1px solid #BBBBBB;
 7012:   background: #DDDDDD;
 7013:   width: 22px;
 7014:   padding: 1px;
 7015:   margin: 0;
 7016: }
 7017: 
 7018: table.LC_data_table tr > td.LC_docs_entry_commands,
 7019: table.LC_data_table tr > td.LC_docs_entry_parameter {
 7020:   font-size: x-small;
 7021: }
 7022: 
 7023: .LC_docs_entry_parameter {
 7024:   white-space: nowrap;
 7025: }
 7026: 
 7027: .LC_docs_copy {
 7028:   color: #000099;
 7029: }
 7030: 
 7031: .LC_docs_cut {
 7032:   color: #550044;
 7033: }
 7034: 
 7035: .LC_docs_rename {
 7036:   color: #009900;
 7037: }
 7038: 
 7039: .LC_docs_remove {
 7040:   color: #990000;
 7041: }
 7042: 
 7043: .LC_domprefs_email,
 7044: .LC_docs_reinit_warn,
 7045: .LC_docs_ext_edit {
 7046:   font-size: x-small;
 7047: }
 7048: 
 7049: table.LC_docs_adddocs td,
 7050: table.LC_docs_adddocs th {
 7051:   border: 1px solid #BBBBBB;
 7052:   padding: 4px;
 7053:   background: #DDDDDD;
 7054: }
 7055: 
 7056: table.LC_sty_begin {
 7057:   background: #BBFFBB;
 7058: }
 7059: 
 7060: table.LC_sty_end {
 7061:   background: #FFBBBB;
 7062: }
 7063: 
 7064: table.LC_double_column {
 7065:   border-width: 0;
 7066:   border-collapse: collapse;
 7067:   width: 100%;
 7068:   padding: 2px;
 7069: }
 7070: 
 7071: table.LC_double_column tr td.LC_left_col {
 7072:   top: 2px;
 7073:   left: 2px;
 7074:   width: 47%;
 7075:   vertical-align: top;
 7076: }
 7077: 
 7078: table.LC_double_column tr td.LC_right_col {
 7079:   top: 2px;
 7080:   right: 2px;
 7081:   width: 47%;
 7082:   vertical-align: top;
 7083: }
 7084: 
 7085: div.LC_left_float {
 7086:   float: left;
 7087:   padding-right: 5%;
 7088:   padding-bottom: 4px;
 7089: }
 7090: 
 7091: div.LC_clear_float_header {
 7092:   padding-bottom: 2px;
 7093: }
 7094: 
 7095: div.LC_clear_float_footer {
 7096:   padding-top: 10px;
 7097:   clear: both;
 7098: }
 7099: 
 7100: div.LC_grade_show_user {
 7101: /*  border-left: 5px solid $sidebg; */
 7102:   border-top: 5px solid #000000;
 7103:   margin: 50px 0 0 0;
 7104:   padding: 15px 0 5px 10px;
 7105: }
 7106: 
 7107: div.LC_grade_show_user_odd_row {
 7108: /*  border-left: 5px solid #000000; */
 7109: }
 7110: 
 7111: div.LC_grade_show_user div.LC_Box {
 7112:   margin-right: 50px;
 7113: }
 7114: 
 7115: div.LC_grade_submissions,
 7116: div.LC_grade_message_center,
 7117: div.LC_grade_info_links {
 7118:   margin: 5px;
 7119:   width: 99%;
 7120:   background: #FFFFFF;
 7121: }
 7122: 
 7123: div.LC_grade_submissions_header,
 7124: div.LC_grade_message_center_header {
 7125:   font-weight: bold;
 7126:   font-size: large;
 7127: }
 7128: 
 7129: div.LC_grade_submissions_body,
 7130: div.LC_grade_message_center_body {
 7131:   border: 1px solid black;
 7132:   width: 99%;
 7133:   background: #FFFFFF;
 7134: }
 7135: 
 7136: table.LC_scantron_action {
 7137:   width: 100%;
 7138: }
 7139: 
 7140: table.LC_scantron_action tr th {
 7141:   font-weight:bold;
 7142:   font-style:normal;
 7143: }
 7144: 
 7145: .LC_edit_problem_header,
 7146: div.LC_edit_problem_footer {
 7147:   font-weight: normal;
 7148:   font-size:  medium;
 7149:   margin: 2px;
 7150:   background-color: $sidebg;
 7151: }
 7152: 
 7153: div.LC_edit_problem_header,
 7154: div.LC_edit_problem_header div,
 7155: div.LC_edit_problem_footer,
 7156: div.LC_edit_problem_footer div,
 7157: div.LC_edit_problem_editxml_header,
 7158: div.LC_edit_problem_editxml_header div {
 7159:   z-index: 100;
 7160: }
 7161: 
 7162: div.LC_edit_problem_header_title {
 7163:   font-weight: bold;
 7164:   font-size: larger;
 7165:   background: $tabbg;
 7166:   padding: 3px;
 7167:   margin: 0 0 5px 0;
 7168: }
 7169: 
 7170: table.LC_edit_problem_header_title {
 7171:   width: 100%;
 7172:   background: $tabbg;
 7173: }
 7174: 
 7175: div.LC_edit_actionbar {
 7176:     background-color: $sidebg;
 7177:     margin: 0;
 7178:     padding: 0;
 7179:     line-height: 200%;
 7180: }
 7181: 
 7182: div.LC_edit_actionbar div{
 7183:     padding: 0;
 7184:     margin: 0;
 7185:     display: inline-block;
 7186: }
 7187: 
 7188: .LC_edit_opt {
 7189:   padding-left: 1em;
 7190:   white-space: nowrap;
 7191: }
 7192: 
 7193: .LC_edit_problem_latexhelper{
 7194:     text-align: right;
 7195: }
 7196: 
 7197: #LC_edit_problem_colorful div{
 7198:     margin-left: 40px;
 7199: }
 7200: 
 7201: #LC_edit_problem_codemirror div{
 7202:     margin-left: 0px;
 7203: }
 7204: 
 7205: img.stift {
 7206:   border-width: 0;
 7207:   vertical-align: middle;
 7208: }
 7209: 
 7210: table td.LC_mainmenu_col_fieldset {
 7211:   vertical-align: top;
 7212: }
 7213: 
 7214: div.LC_createcourse {
 7215:   margin: 10px 10px 10px 10px;
 7216: }
 7217: 
 7218: .LC_dccid {
 7219:   float: right;
 7220:   margin: 0.2em 0 0 0;
 7221:   padding: 0;
 7222:   font-size: 90%;
 7223:   display:none;
 7224: }
 7225: 
 7226: ol.LC_primary_menu a:hover,
 7227: ol#LC_MenuBreadcrumbs a:hover,
 7228: ol#LC_PathBreadcrumbs a:hover,
 7229: ul#LC_secondary_menu a:hover,
 7230: .LC_FormSectionClearButton input:hover
 7231: ul.LC_TabContent   li:hover a {
 7232:   color:$button_hover;
 7233:   text-decoration:none;
 7234: }
 7235: 
 7236: h1 {
 7237:   padding: 0;
 7238:   line-height:130%;
 7239: }
 7240: 
 7241: h2,
 7242: h3,
 7243: h4,
 7244: h5,
 7245: h6 {
 7246:   margin: 5px 0 5px 0;
 7247:   padding: 0;
 7248:   line-height:130%;
 7249: }
 7250: 
 7251: .LC_hcell {
 7252:   padding:3px 15px 3px 15px;
 7253:   margin: 0;
 7254:   background-color:$tabbg;
 7255:   color:$fontmenu;
 7256:   border-bottom:solid 1px $lg_border_color;
 7257: }
 7258: 
 7259: .LC_Box > .LC_hcell {
 7260:   margin: 0 -10px 10px -10px;
 7261: }
 7262: 
 7263: .LC_noBorder {
 7264:   border: 0;
 7265: }
 7266: 
 7267: .LC_FormSectionClearButton input {
 7268:   background-color:transparent;
 7269:   border: none;
 7270:   cursor:pointer;
 7271:   text-decoration:underline;
 7272: }
 7273: 
 7274: .LC_help_open_topic {
 7275:   color: #FFFFFF;
 7276:   background-color: #EEEEFF;
 7277:   margin: 1px;
 7278:   padding: 4px;
 7279:   border: 1px solid #000033;
 7280:   white-space: nowrap;
 7281:   /* vertical-align: middle; */
 7282: }
 7283: 
 7284: dl,
 7285: ul,
 7286: div,
 7287: fieldset {
 7288:   margin: 10px 10px 10px 0;
 7289:   /* overflow: hidden; */
 7290: }
 7291: 
 7292: article.geogebraweb div {
 7293:     margin: 0;
 7294: }
 7295: 
 7296: fieldset > legend {
 7297:   font-weight: bold;
 7298:   padding: 0 5px 0 5px;
 7299: }
 7300: 
 7301: #LC_nav_bar {
 7302:   float: left;
 7303:   background-color: $pgbg_or_bgcolor;
 7304:   margin: 0 0 2px 0;
 7305: }
 7306: 
 7307: #LC_realm {
 7308:   margin: 0.2em 0 0 0;
 7309:   padding: 0;
 7310:   font-weight: bold;
 7311:   text-align: center;
 7312:   background-color: $pgbg_or_bgcolor;
 7313: }
 7314: 
 7315: #LC_nav_bar em {
 7316:   font-weight: bold;
 7317:   font-style: normal;
 7318: }
 7319: 
 7320: ol.LC_primary_menu {
 7321:   margin: 0;
 7322:   padding: 0;
 7323: }
 7324: 
 7325: ol#LC_PathBreadcrumbs {
 7326:   margin: 0;
 7327: }
 7328: 
 7329: ol.LC_primary_menu li {
 7330:   color: RGB(80, 80, 80);
 7331:   vertical-align: middle;
 7332:   text-align: left;
 7333:   list-style: none;
 7334:   position: relative;
 7335:   float: left;
 7336:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
 7337:   line-height: 1.5em;
 7338: }
 7339: 
 7340: ol.LC_primary_menu li a, 
 7341: ol.LC_primary_menu li p {
 7342:   display: block;
 7343:   margin: 0;
 7344:   padding: 0 5px 0 10px;
 7345:   text-decoration: none;
 7346: }
 7347: 
 7348: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
 7349:   display: inline-block;
 7350:   width: 95%;
 7351:   text-align: left;
 7352: }
 7353: 
 7354: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
 7355:   display: inline-block;
 7356:   width: 5%;
 7357:   float: right;
 7358:   text-align: right;
 7359:   font-size: 70%;
 7360: }
 7361: 
 7362: ol.LC_primary_menu ul {
 7363:   display: none;
 7364:   width: 15em;
 7365:   background-color: $data_table_light;
 7366:   position: absolute;
 7367:   top: 100%;
 7368: }
 7369: 
 7370: ol.LC_primary_menu ul ul {
 7371:   left: 100%;
 7372:   top: 0;
 7373: }
 7374: 
 7375: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
 7376:   display: block;
 7377:   position: absolute;
 7378:   margin: 0;
 7379:   padding: 0;
 7380:   z-index: 2;
 7381: }
 7382: 
 7383: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 7384: /* First Submenu -> size should be smaller than the menu title of the whole menu */
 7385:   font-size: 90%;
 7386:   vertical-align: top;
 7387:   float: none;
 7388:   border-left: 1px solid black;
 7389:   border-right: 1px solid black;
 7390: /* A dark bottom border to visualize different menu options;
 7391: overwritten in the create_submenu routine for the last border-bottom of the menu */
 7392:   border-bottom: 1px solid $data_table_dark;
 7393: }
 7394: 
 7395: ol.LC_primary_menu li li p:hover {
 7396:   color:$button_hover;
 7397:   text-decoration:none;
 7398:   background-color:$data_table_dark;
 7399: }
 7400: 
 7401: ol.LC_primary_menu li li a:hover {
 7402:    color:$button_hover;
 7403:    background-color:$data_table_dark;
 7404: }
 7405: 
 7406: /* Font-size equal to the size of the predecessors*/
 7407: ol.LC_primary_menu li:hover li li {
 7408:   font-size: 100%;
 7409: }
 7410: 
 7411: ol.LC_primary_menu li img {
 7412:   vertical-align: bottom;
 7413:   height: 1.1em;
 7414:   margin: 0.2em 0 0 0;
 7415: }
 7416: 
 7417: ol.LC_primary_menu a {
 7418:   color: RGB(80, 80, 80);
 7419:   text-decoration: none;
 7420: }
 7421: 
 7422: ol.LC_primary_menu a.LC_new_message {
 7423:   font-weight:bold;
 7424:   color: darkred;
 7425: }
 7426: 
 7427: ol.LC_docs_parameters {
 7428:   margin-left: 0;
 7429:   padding: 0;
 7430:   list-style: none;
 7431: }
 7432: 
 7433: ol.LC_docs_parameters li {
 7434:   margin: 0;
 7435:   padding-right: 20px;
 7436:   display: inline;
 7437: }
 7438: 
 7439: ol.LC_docs_parameters li:before {
 7440:   content: "\\002022 \\0020";
 7441: }
 7442: 
 7443: li.LC_docs_parameters_title {
 7444:   font-weight: bold;
 7445: }
 7446: 
 7447: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 7448:   content: "";
 7449: }
 7450: 
 7451: ul#LC_secondary_menu {
 7452:   clear: right;
 7453:   color: $fontmenu;
 7454:   background: $tabbg;
 7455:   list-style: none;
 7456:   padding: 0;
 7457:   margin: 0;
 7458:   width: 100%;
 7459:   text-align: left;
 7460:   float: left;
 7461: }
 7462: 
 7463: ul#LC_secondary_menu li {
 7464:   font-weight: bold;
 7465:   line-height: 1.8em;
 7466:   border-right: 1px solid black;
 7467:   float: left;
 7468: }
 7469: 
 7470: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 7471:   background-color: $data_table_light;
 7472: }
 7473: 
 7474: ul#LC_secondary_menu li a {
 7475:   padding: 0 0.8em;
 7476: }
 7477: 
 7478: ul#LC_secondary_menu li ul {
 7479:   display: none;
 7480: }
 7481: 
 7482: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 7483:   display: block;
 7484:   position: absolute;
 7485:   margin: 0;
 7486:   padding: 0;
 7487:   list-style:none;
 7488:   float: none;
 7489:   background-color: $data_table_light;
 7490:   z-index: 2;
 7491:   margin-left: -1px;
 7492: }
 7493: 
 7494: ul#LC_secondary_menu li ul li {
 7495:   font-size: 90%;
 7496:   vertical-align: top;
 7497:   border-left: 1px solid black;
 7498:   border-right: 1px solid black;
 7499:   background-color: $data_table_light;
 7500:   list-style:none;
 7501:   float: none;
 7502: }
 7503: 
 7504: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 7505:   background-color: $data_table_dark;
 7506: }
 7507: 
 7508: ul.LC_TabContent {
 7509:   display:block;
 7510:   background: $sidebg;
 7511:   border-bottom: solid 1px $lg_border_color;
 7512:   list-style:none;
 7513:   margin: -1px -10px 0 -10px;
 7514:   padding: 0;
 7515: }
 7516: 
 7517: ul.LC_TabContent li,
 7518: ul.LC_TabContentBigger li {
 7519:   float:left;
 7520: }
 7521: 
 7522: ul#LC_secondary_menu li a {
 7523:   color: $fontmenu;
 7524:   text-decoration: none;
 7525: }
 7526: 
 7527: ul.LC_TabContent {
 7528:   min-height:20px;
 7529: }
 7530: 
 7531: ul.LC_TabContent li {
 7532:   vertical-align:middle;
 7533:   padding: 0 16px 0 10px;
 7534:   background-color:$tabbg;
 7535:   border-bottom:solid 1px $lg_border_color;
 7536:   border-left: solid 1px $font;
 7537: }
 7538: 
 7539: ul.LC_TabContent .right {
 7540:   float:right;
 7541: }
 7542: 
 7543: ul.LC_TabContent li a,
 7544: ul.LC_TabContent li {
 7545:   color:rgb(47,47,47);
 7546:   text-decoration:none;
 7547:   font-size:95%;
 7548:   font-weight:bold;
 7549:   min-height:20px;
 7550: }
 7551: 
 7552: ul.LC_TabContent li a:hover,
 7553: ul.LC_TabContent li a:focus {
 7554:   color: $button_hover;
 7555:   background:none;
 7556:   outline:none;
 7557: }
 7558: 
 7559: ul.LC_TabContent li:hover {
 7560:   color: $button_hover;
 7561:   cursor:pointer;
 7562: }
 7563: 
 7564: ul.LC_TabContent li.active {
 7565:   color: $font;
 7566:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 7567:   border-bottom:solid 1px #FFFFFF;
 7568:   cursor: default;
 7569: }
 7570: 
 7571: ul.LC_TabContent li.active a {
 7572:   color:$font;
 7573:   background:#FFFFFF;
 7574:   outline: none;
 7575: }
 7576: 
 7577: ul.LC_TabContent li.goback {
 7578:   float: left;
 7579:   border-left: none;
 7580: }
 7581: 
 7582: #maincoursedoc {
 7583:   clear:both;
 7584: }
 7585: 
 7586: ul.LC_TabContentBigger {
 7587:   display:block;
 7588:   list-style:none;
 7589:   padding: 0;
 7590: }
 7591: 
 7592: ul.LC_TabContentBigger li {
 7593:   vertical-align:bottom;
 7594:   height: 30px;
 7595:   font-size:110%;
 7596:   font-weight:bold;
 7597:   color: #737373;
 7598: }
 7599: 
 7600: ul.LC_TabContentBigger li.active {
 7601:   position: relative;
 7602:   top: 1px;
 7603: }
 7604: 
 7605: ul.LC_TabContentBigger li a {
 7606:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 7607:   height: 30px;
 7608:   line-height: 30px;
 7609:   text-align: center;
 7610:   display: block;
 7611:   text-decoration: none;
 7612:   outline: none;  
 7613: }
 7614: 
 7615: ul.LC_TabContentBigger li.active a {
 7616:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 7617:   color:$font;
 7618: }
 7619: 
 7620: ul.LC_TabContentBigger li b {
 7621:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 7622:   display: block;
 7623:   float: left;
 7624:   padding: 0 30px;
 7625:   border-bottom: 1px solid $lg_border_color;
 7626: }
 7627: 
 7628: ul.LC_TabContentBigger li:hover b {
 7629:   color:$button_hover;
 7630: }
 7631: 
 7632: ul.LC_TabContentBigger li.active b {
 7633:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 7634:   color:$font;
 7635:   border: 0;
 7636: }
 7637: 
 7638: 
 7639: ul.LC_CourseBreadcrumbs {
 7640:   background: $sidebg;
 7641:   height: 2em;
 7642:   padding-left: 10px;
 7643:   margin: 0;
 7644:   list-style-position: inside;
 7645: }
 7646: 
 7647: ol#LC_MenuBreadcrumbs,
 7648: ol#LC_PathBreadcrumbs {
 7649:   padding-left: 10px;
 7650:   margin: 0;
 7651:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 7652: }
 7653: 
 7654: ol#LC_MenuBreadcrumbs li,
 7655: ol#LC_PathBreadcrumbs li,
 7656: ul.LC_CourseBreadcrumbs li {
 7657:   display: inline;
 7658:   white-space: normal;  
 7659: }
 7660: 
 7661: ol#LC_MenuBreadcrumbs li a,
 7662: ul.LC_CourseBreadcrumbs li a {
 7663:   text-decoration: none;
 7664:   font-size:90%;
 7665: }
 7666: 
 7667: ol#LC_MenuBreadcrumbs h1 {
 7668:   display: inline;
 7669:   font-size: 90%;
 7670:   line-height: 2.5em;
 7671:   margin: 0;
 7672:   padding: 0;
 7673: }
 7674: 
 7675: ol#LC_PathBreadcrumbs li a {
 7676:   text-decoration:none;
 7677:   font-size:100%;
 7678:   font-weight:bold;
 7679: }
 7680: 
 7681: .LC_Box {
 7682:   border: solid 1px $lg_border_color;
 7683:   padding: 0 10px 10px 10px;
 7684: }
 7685: 
 7686: .LC_DocsBox {
 7687:   border: solid 1px $lg_border_color;
 7688:   padding: 0 0 10px 10px;
 7689: }
 7690: 
 7691: .LC_AboutMe_Image {
 7692:   float:left;
 7693:   margin-right:10px;
 7694: }
 7695: 
 7696: .LC_Clear_AboutMe_Image {
 7697:   clear:left;
 7698: }
 7699: 
 7700: dl.LC_ListStyleClean dt {
 7701:   padding-right: 5px;
 7702:   display: table-header-group;
 7703: }
 7704: 
 7705: dl.LC_ListStyleClean dd {
 7706:   display: table-row;
 7707: }
 7708: 
 7709: .LC_ListStyleClean,
 7710: .LC_ListStyleSimple,
 7711: .LC_ListStyleNormal,
 7712: .LC_ListStyleSpecial {
 7713:   /* display:block; */
 7714:   list-style-position: inside;
 7715:   list-style-type: none;
 7716:   overflow: hidden;
 7717:   padding: 0;
 7718: }
 7719: 
 7720: .LC_ListStyleSimple li,
 7721: .LC_ListStyleSimple dd,
 7722: .LC_ListStyleNormal li,
 7723: .LC_ListStyleNormal dd,
 7724: .LC_ListStyleSpecial li,
 7725: .LC_ListStyleSpecial dd {
 7726:   margin: 0;
 7727:   padding: 5px 5px 5px 10px;
 7728:   clear: both;
 7729: }
 7730: 
 7731: .LC_ListStyleClean li,
 7732: .LC_ListStyleClean dd {
 7733:   padding-top: 0;
 7734:   padding-bottom: 0;
 7735: }
 7736: 
 7737: .LC_ListStyleSimple dd,
 7738: .LC_ListStyleSimple li {
 7739:   border-bottom: solid 1px $lg_border_color;
 7740: }
 7741: 
 7742: .LC_ListStyleSpecial li,
 7743: .LC_ListStyleSpecial dd {
 7744:   list-style-type: none;
 7745:   background-color: RGB(220, 220, 220);
 7746:   margin-bottom: 4px;
 7747: }
 7748: 
 7749: table.LC_SimpleTable {
 7750:   margin:5px;
 7751:   border:solid 1px $lg_border_color;
 7752: }
 7753: 
 7754: table.LC_SimpleTable tr {
 7755:   padding: 0;
 7756:   border:solid 1px $lg_border_color;
 7757: }
 7758: 
 7759: table.LC_SimpleTable thead {
 7760:   background:rgb(220,220,220);
 7761: }
 7762: 
 7763: div.LC_columnSection {
 7764:   display: block;
 7765:   clear: both;
 7766:   overflow: hidden;
 7767:   margin: 0;
 7768: }
 7769: 
 7770: div.LC_columnSection>* {
 7771:   float: left;
 7772:   margin: 10px 20px 10px 0;
 7773:   overflow:hidden;
 7774: }
 7775: 
 7776: table em {
 7777:   font-weight: bold;
 7778:   font-style: normal;
 7779: }
 7780: 
 7781: table.LC_tableBrowseRes,
 7782: table.LC_tableOfContent {
 7783:   border:none;
 7784:   border-spacing: 1px;
 7785:   padding: 3px;
 7786:   background-color: #FFFFFF;
 7787:   font-size: 90%;
 7788: }
 7789: 
 7790: table.LC_tableOfContent {
 7791:   border-collapse: collapse;
 7792: }
 7793: 
 7794: table.LC_tableBrowseRes a,
 7795: table.LC_tableOfContent a {
 7796:   background-color: transparent;
 7797:   text-decoration: none;
 7798: }
 7799: 
 7800: table.LC_tableOfContent img {
 7801:   border: none;
 7802:   height: 1.3em;
 7803:   vertical-align: text-bottom;
 7804:   margin-right: 0.3em;
 7805: }
 7806: 
 7807: a#LC_content_toolbar_firsthomework {
 7808:   background-image:url(/res/adm/pages/open-first-problem.gif);
 7809: }
 7810: 
 7811: a#LC_content_toolbar_everything {
 7812:   background-image:url(/res/adm/pages/show-all.gif);
 7813: }
 7814: 
 7815: a#LC_content_toolbar_uncompleted {
 7816:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 7817: }
 7818: 
 7819: #LC_content_toolbar_clearbubbles {
 7820:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 7821: }
 7822: 
 7823: a#LC_content_toolbar_changefolder {
 7824:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 7825: }
 7826: 
 7827: a#LC_content_toolbar_changefolder_toggled {
 7828:   background-image:url(/res/adm/pages/open-all-folders.gif);
 7829: }
 7830: 
 7831: a#LC_content_toolbar_edittoplevel {
 7832:   background-image:url(/res/adm/pages/edittoplevel.gif);
 7833: }
 7834: 
 7835: ul#LC_toolbar li a:hover {
 7836:   background-position: bottom center;
 7837: }
 7838: 
 7839: ul#LC_toolbar {
 7840:   padding: 0;
 7841:   margin: 2px;
 7842:   list-style:none;
 7843:   position:relative;
 7844:   background-color:white;
 7845:   overflow: auto;
 7846: }
 7847: 
 7848: ul#LC_toolbar li {
 7849:   border:1px solid white;
 7850:   padding: 0;
 7851:   margin: 0;
 7852:   float: left;
 7853:   display:inline;
 7854:   vertical-align:middle;
 7855:   white-space: nowrap;
 7856: }
 7857: 
 7858: 
 7859: a.LC_toolbarItem {
 7860:   display:block;
 7861:   padding: 0;
 7862:   margin: 0;
 7863:   height: 32px;
 7864:   width: 32px;
 7865:   color:white;
 7866:   border: none;
 7867:   background-repeat:no-repeat;
 7868:   background-color:transparent;
 7869: }
 7870: 
 7871: ul.LC_funclist {
 7872:     margin: 0;
 7873:     padding: 0.5em 1em 0.5em 0;
 7874: }
 7875: 
 7876: ul.LC_funclist > li:first-child {
 7877:     font-weight:bold; 
 7878:     margin-left:0.8em;
 7879: }
 7880: 
 7881: ul.LC_funclist + ul.LC_funclist {
 7882:     /* 
 7883:        left border as a seperator if we have more than
 7884:        one list 
 7885:     */
 7886:     border-left: 1px solid $sidebg;
 7887:     /* 
 7888:        this hides the left border behind the border of the 
 7889:        outer box if element is wrapped to the next 'line' 
 7890:     */
 7891:     margin-left: -1px;
 7892: }
 7893: 
 7894: ul.LC_funclist li {
 7895:   display: inline;
 7896:   white-space: nowrap;
 7897:   margin: 0 0 0 25px;
 7898:   line-height: 150%;
 7899: }
 7900: 
 7901: .LC_hidden {
 7902:   display: none;
 7903: }
 7904: 
 7905: .LCmodal-overlay {
 7906: 		position:fixed;
 7907: 		top:0;
 7908: 		right:0;
 7909: 		bottom:0;
 7910: 		left:0;
 7911: 		height:100%;
 7912: 		width:100%;
 7913: 		margin:0;
 7914: 		padding:0;
 7915: 		background:#999;
 7916: 		opacity:.75;
 7917: 		filter: alpha(opacity=75);
 7918: 		-moz-opacity: 0.75;
 7919: 		z-index:101;
 7920: }
 7921: 
 7922: * html .LCmodal-overlay {   
 7923: 		position: absolute;
 7924: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 7925: }
 7926: 
 7927: .LCmodal-window {
 7928: 		position:fixed;
 7929: 		top:50%;
 7930: 		left:50%;
 7931: 		margin:0;
 7932: 		padding:0;
 7933: 		z-index:102;
 7934: 	}
 7935: 
 7936: * html .LCmodal-window {
 7937: 		position:absolute;
 7938: }
 7939: 
 7940: .LCclose-window {
 7941: 		position:absolute;
 7942: 		width:32px;
 7943: 		height:32px;
 7944: 		right:8px;
 7945: 		top:8px;
 7946: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 7947: 		text-indent:-99999px;
 7948: 		overflow:hidden;
 7949: 		cursor:pointer;
 7950: }
 7951: 
 7952: .LCisDisabled {
 7953:   cursor: not-allowed;
 7954:   opacity: 0.5;
 7955: }
 7956: 
 7957: a[aria-disabled="true"] {
 7958:   color: currentColor;
 7959:   display: inline-block;  /* For IE11/ MS Edge bug */
 7960:   pointer-events: none;
 7961:   text-decoration: none;
 7962: }
 7963: 
 7964: pre.LC_wordwrap {
 7965:   white-space: pre-wrap;
 7966:   white-space: -moz-pre-wrap;
 7967:   white-space: -pre-wrap;
 7968:   white-space: -o-pre-wrap;
 7969:   word-wrap: break-word;
 7970: }
 7971: 
 7972: /*
 7973:   styles used by TTH when "Default set of options to pass to tth/m
 7974:   when converting TeX" in course settings has been set
 7975: 
 7976:   option passed: -t
 7977: 
 7978: */
 7979: 
 7980: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 7981: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 7982: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 7983: td div.norm {line-height:normal;}
 7984: 
 7985: /*
 7986:   option passed -y3
 7987: */
 7988: 
 7989: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 7990: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 7991: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 7992: 
 7993: #LC_minitab_header {
 7994:   float:left;
 7995:   width:100%;
 7996:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
 7997:   font-size:93%;
 7998:   line-height:normal;
 7999:   margin: 0.5em 0 0.5em 0;
 8000: }
 8001: #LC_minitab_header ul {
 8002:   margin:0;
 8003:   padding:10px 10px 0;
 8004:   list-style:none;
 8005: }
 8006: #LC_minitab_header li {
 8007:   float:left;
 8008:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
 8009:   margin:0;
 8010:   padding:0 0 0 9px;
 8011: }
 8012: #LC_minitab_header a {
 8013:   display:block;
 8014:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
 8015:   padding:5px 15px 4px 6px;
 8016: }
 8017: #LC_minitab_header #LC_current_minitab {
 8018:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
 8019: }
 8020: #LC_minitab_header #LC_current_minitab a {
 8021:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
 8022:   padding-bottom:5px;
 8023: }
 8024: 
 8025: 
 8026: END
 8027: }
 8028: 
 8029: =pod
 8030: 
 8031: =item * &headtag()
 8032: 
 8033: Returns a uniform footer for LON-CAPA web pages.
 8034: 
 8035: Inputs: $title - optional title for the head
 8036:         $head_extra - optional extra HTML to put inside the <head>
 8037:         $args - optional arguments
 8038:             force_register - if is true call registerurl so the remote is 
 8039:                              informed
 8040:             redirect       -> array ref of
 8041:                                    1- seconds before redirect occurs
 8042:                                    2- url to redirect to
 8043:                                    3- whether the side effect should occur
 8044:                            (side effect of setting 
 8045:                                $env{'internal.head.redirect'} to the url 
 8046:                                redirected too)
 8047:             domain         -> force to color decorate a page for a specific
 8048:                                domain
 8049:             function       -> force usage of a specific rolish color scheme
 8050:             bgcolor        -> override the default page bgcolor
 8051:             no_auto_mt_title
 8052:                            -> prevent &mt()ing the title arg
 8053: 
 8054: =cut
 8055: 
 8056: sub headtag {
 8057:     my ($title,$head_extra,$args) = @_;
 8058:     
 8059:     my $function = $args->{'function'} || &get_users_function();
 8060:     my $domain   = $args->{'domain'}   || &determinedomain();
 8061:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 8062:     my $httphost = $args->{'use_absolute'};
 8063:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 8064: 		   $Apache::lonnet::perlvar{'lonVersion'},
 8065: 		   #time(),
 8066: 		   $env{'environment.color.timestamp'},
 8067: 		   $function,$domain,$bgcolor);
 8068: 
 8069:     $url = '/adm/css/'.&escape($url).'.css';
 8070: 
 8071:     my $result =
 8072: 	'<head>'.
 8073: 	&font_settings($args);
 8074: 
 8075:     my $inhibitprint;
 8076:     if ($args->{'print_suppress'}) {
 8077:         $inhibitprint = &print_suppression();
 8078:     }
 8079: 
 8080:     if (!$args->{'frameset'}) {
 8081: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 8082:     }
 8083:     if ($args->{'force_register'}) {
 8084:         $result .= &Apache::lonmenu::registerurl(1);
 8085:     }
 8086:     if (!$args->{'no_nav_bar'} 
 8087: 	&& !$args->{'only_body'}
 8088: 	&& !$args->{'frameset'}) {
 8089: 	$result .= &help_menu_js($httphost);
 8090:         $result.=&modal_window();
 8091:         $result.=&togglebox_script();
 8092:         $result.=&wishlist_window();
 8093:         $result.=&LCprogressbarUpdate_script();
 8094:     } else {
 8095:         if ($args->{'add_modal'}) {
 8096:            $result.=&modal_window();
 8097:         }
 8098:         if ($args->{'add_wishlist'}) {
 8099:            $result.=&wishlist_window();
 8100:         }
 8101:         if ($args->{'add_togglebox'}) {
 8102:            $result.=&togglebox_script();
 8103:         }
 8104:         if ($args->{'add_progressbar'}) {
 8105:            $result.=&LCprogressbarUpdate_script();
 8106:         }
 8107:     }
 8108:     if (ref($args->{'redirect'})) {
 8109: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 8110: 	$url = &Apache::lonenc::check_encrypt($url);
 8111: 	if (!$inhibit_continue) {
 8112: 	    $env{'internal.head.redirect'} = $url;
 8113: 	}
 8114: 	$result.=<<ADDMETA
 8115: <meta http-equiv="pragma" content="no-cache" />
 8116: <meta http-equiv="Refresh" content="$time; url=$url" />
 8117: ADDMETA
 8118:     } else {
 8119:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
 8120:             my $requrl = $env{'request.uri'};
 8121:             if ($requrl eq '') {
 8122:                 $requrl = $ENV{'REQUEST_URI'};
 8123:                 $requrl =~ s/\?.+$//;
 8124:             }
 8125:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
 8126:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
 8127:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
 8128:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
 8129:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
 8130:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
 8131:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 8132:                     my ($offload,$offloadoth);
 8133:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
 8134:                         if ($domdefs{'offloadnow'}{$lonhost}) {
 8135:                             $offload = 1;
 8136:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
 8137:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
 8138:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
 8139:                                     $offloadoth = 1;
 8140:                                     $dom_in_use = $env{'user.domain'};
 8141:                                 }
 8142:                             }
 8143:                         }
 8144:                     }
 8145:                     unless ($offload) {
 8146:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
 8147:                             if ($domdefs{'offloadoth'}{$lonhost}) {
 8148:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
 8149:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
 8150:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
 8151:                                         $offload = 1;
 8152:                                         $offloadoth = 1;
 8153:                                         $dom_in_use = $env{'user.domain'};
 8154:                                     }
 8155:                                 }
 8156:                             }
 8157:                         }
 8158:                     }
 8159:                     if ($offload) {
 8160:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
 8161:                         if (($newserver eq '') && ($offloadoth)) {
 8162:                             my @domains = &Apache::lonnet::current_machine_domains();
 8163:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) { 
 8164:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
 8165:                             }
 8166:                         }
 8167:                         if (($newserver) && ($newserver ne $lonhost)) {
 8168:                             my $numsec = 5;
 8169:                             my $timeout = $numsec * 1000;
 8170:                             my ($newurl,$locknum,%locks,$msg);
 8171:                             if ($env{'request.role.adv'}) {
 8172:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
 8173:                             }
 8174:                             my $disable_submit = 0;
 8175:                             if ($requrl =~ /$LONCAPA::assess_re/) {
 8176:                                 $disable_submit = 1;
 8177:                             }
 8178:                             if ($locknum) {
 8179:                                 my @lockinfo = sort(values(%locks));
 8180:                                 $msg = &mt('Once the following tasks are complete:')." \n".
 8181:                                        join(", ",sort(values(%locks)))."\n";
 8182:                                 if (&show_course()) {
 8183:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
 8184:                                 } else {
 8185:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
 8186:                                 }
 8187:                             } else {
 8188:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
 8189:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
 8190:                                 }
 8191:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
 8192:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
 8193:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
 8194:                                     $newurl .= '&role='.$env{'request.role'};
 8195:                                 }
 8196:                                 if ($env{'request.symb'}) {
 8197:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
 8198:                                     if ($shownsymb =~ m{^/enc/}) {
 8199:                                         my $reqdmajor = 2;
 8200:                                         my $reqdminor = 11;
 8201:                                         my $reqdsubminor = 3;
 8202:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
 8203:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
 8204:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
 8205:                                         if (($major eq '' && $minor eq '') ||
 8206:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
 8207:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
 8208:                                              ($reqdsubminor > $subminor))))) {
 8209:                                             undef($shownsymb);
 8210:                                         }
 8211:                                     }
 8212:                                     if ($shownsymb) {
 8213:                                         &js_escape(\$shownsymb);
 8214:                                         $newurl .= '&symb='.$shownsymb;
 8215:                                     }
 8216:                                 } else {
 8217:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
 8218:                                     &js_escape(\$shownurl);
 8219:                                     $newurl .= '&origurl='.$shownurl;
 8220:                                 }
 8221:                             }
 8222:                             &js_escape(\$msg);
 8223:                             $result.=<<OFFLOAD
 8224: <meta http-equiv="pragma" content="no-cache" />
 8225: <script type="text/javascript">
 8226: // <![CDATA[
 8227: function LC_Offload_Now() {
 8228:     var dest = "$newurl";
 8229:     if (dest != '') {
 8230:         window.location.href="$newurl";
 8231:     }
 8232: }
 8233: \$(document).ready(function () {
 8234:     window.alert('$msg');
 8235:     if ($disable_submit) {
 8236:         \$(".LC_hwk_submit").prop("disabled", true);
 8237:         \$( ".LC_textline" ).prop( "readonly", "readonly");
 8238:     }
 8239:     setTimeout('LC_Offload_Now()', $timeout);
 8240: });
 8241: // ]]>
 8242: </script>
 8243: OFFLOAD
 8244:                         }
 8245:                     }
 8246:                 }
 8247:             }
 8248:         }
 8249:     }
 8250:     if (!defined($title)) {
 8251: 	$title = 'The LearningOnline Network with CAPA';
 8252:     }
 8253:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 8254:     $result .= '<title> LON-CAPA '.$title.'</title>'
 8255: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
 8256:     if (!$args->{'frameset'}) {
 8257:         $result .= ' /';
 8258:     }
 8259:     $result .= '>'
 8260:         .$inhibitprint
 8261: 	.$head_extra;
 8262:     my $clientmobile;
 8263:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 8264:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
 8265:     } else {
 8266:         $clientmobile = $env{'browser.mobile'};
 8267:     }
 8268:     if ($clientmobile) {
 8269:         $result .= '
 8270: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 8271: <meta name="apple-mobile-web-app-capable" content="yes" />';
 8272:     }
 8273:     $result .= '<meta name="google" content="notranslate" />'."\n";
 8274:     return $result.'</head>';
 8275: }
 8276: 
 8277: =pod
 8278: 
 8279: =item * &font_settings()
 8280: 
 8281: Returns neccessary <meta> to set the proper encoding
 8282: 
 8283: Inputs: optional reference to HASH -- $args passed to &headtag()
 8284: 
 8285: =cut
 8286: 
 8287: sub font_settings {
 8288:     my ($args) = @_;
 8289:     my $headerstring='';
 8290:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
 8291:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
 8292: 	$headerstring.=
 8293: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
 8294:         if (!$args->{'frameset'}) {
 8295:             $headerstring.= ' /';
 8296:         }
 8297:         $headerstring .= '>'."\n";
 8298:     }
 8299:     return $headerstring;
 8300: }
 8301: 
 8302: =pod
 8303: 
 8304: =item * &print_suppression()
 8305: 
 8306: In course context returns css which causes the body to be blank when media="print",
 8307: if printout generation is unavailable for the current resource.
 8308: 
 8309: This could be because:
 8310: 
 8311: (a) printstartdate is in the future
 8312: 
 8313: (b) printenddate is in the past
 8314: 
 8315: (c) there is an active exam block with "printout"
 8316: functionality blocked
 8317: 
 8318: Users with pav, pfo or evb privileges are exempt.
 8319: 
 8320: Inputs: none
 8321: 
 8322: =cut
 8323: 
 8324: 
 8325: sub print_suppression {
 8326:     my $noprint;
 8327:     if ($env{'request.course.id'}) {
 8328:         my $scope = $env{'request.course.id'};
 8329:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8330:             (&Apache::lonnet::allowed('pfo',$scope))) {
 8331:             return;
 8332:         }
 8333:         if ($env{'request.course.sec'} ne '') {
 8334:             $scope .= "/$env{'request.course.sec'}";
 8335:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8336:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 8337:                 return;
 8338:             }
 8339:         }
 8340:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8341:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8342:         my $clientip = &Apache::lonnet::get_requestor_ip();
 8343:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
 8344:         if ($blocked) {
 8345:             my $checkrole = "cm./$cdom/$cnum";
 8346:             if ($env{'request.course.sec'} ne '') {
 8347:                 $checkrole .= "/$env{'request.course.sec'}";
 8348:             }
 8349:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 8350:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 8351:                 $noprint = 1;
 8352:             }
 8353:         }
 8354:         unless ($noprint) {
 8355:             my $symb = &Apache::lonnet::symbread();
 8356:             if ($symb ne '') {
 8357:                 my $navmap = Apache::lonnavmaps::navmap->new();
 8358:                 if (ref($navmap)) {
 8359:                     my $res = $navmap->getBySymb($symb);
 8360:                     if (ref($res)) {
 8361:                         if (!$res->resprintable()) {
 8362:                             $noprint = 1;
 8363:                         }
 8364:                     }
 8365:                 }
 8366:             }
 8367:         }
 8368:         if ($noprint) {
 8369:             return <<"ENDSTYLE";
 8370: <style type="text/css" media="print">
 8371:     body { display:none }
 8372: </style>
 8373: ENDSTYLE
 8374:         }
 8375:     }
 8376:     return;
 8377: }
 8378: 
 8379: =pod
 8380: 
 8381: =item * &xml_begin()
 8382: 
 8383: Returns the needed doctype and <html>
 8384: 
 8385: Inputs: none
 8386: 
 8387: =cut
 8388: 
 8389: sub xml_begin {
 8390:     my ($is_frameset) = @_;
 8391:     my $output='';
 8392: 
 8393:     if ($env{'browser.mathml'}) {
 8394: 	$output='<?xml version="1.0"?>'
 8395:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 8396: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 8397:             
 8398: #	    .'<!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">] >'
 8399: 	    .'<!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">'
 8400:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 8401: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 8402:     } elsif ($is_frameset) {
 8403:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
 8404:                 '<html>'."\n";
 8405:     } else {
 8406: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
 8407:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
 8408:     }
 8409:     return $output;
 8410: }
 8411: 
 8412: =pod
 8413: 
 8414: =item * &start_page()
 8415: 
 8416: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 8417: 
 8418: Inputs:
 8419: 
 8420: =over 4
 8421: 
 8422: $title - optional title for the page
 8423: 
 8424: $head_extra - optional extra HTML to incude inside the <head>
 8425: 
 8426: $args - additional optional args supported are:
 8427: 
 8428: =over 8
 8429: 
 8430:              only_body      -> is true will set &bodytag() onlybodytag
 8431:                                     arg on
 8432:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 8433:              add_entries    -> additional attributes to add to the  <body>
 8434:              domain         -> force to color decorate a page for a 
 8435:                                     specific domain
 8436:              function       -> force usage of a specific rolish color
 8437:                                     scheme
 8438:              redirect       -> see &headtag()
 8439:              bgcolor        -> override the default page bg color
 8440:              js_ready       -> return a string ready for being used in 
 8441:                                     a javascript writeln
 8442:              html_encode    -> return a string ready for being used in 
 8443:                                     a html attribute
 8444:              force_register -> if is true will turn on the &bodytag()
 8445:                                     $forcereg arg
 8446:              frameset       -> if true will start with a <frameset>
 8447:                                     rather than <body>
 8448:              skip_phases    -> hash ref of 
 8449:                                     head -> skip the <html><head> generation
 8450:                                     body -> skip all <body> generation
 8451:              no_inline_link -> if true and in remote mode, don't show the
 8452:                                     'Switch To Inline Menu' link
 8453:              no_auto_mt_title -> prevent &mt()ing the title arg
 8454:              bread_crumbs ->             Array containing breadcrumbs
 8455:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 8456:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
 8457:                                     to lonhtmlcommon::breadcrumbs
 8458:              group          -> includes the current group, if page is for a
 8459:                                specific group
 8460:              use_absolute   -> for request for external resource or syllabus, this
 8461:                                will contain https://<hostname> if server uses
 8462:                                https (as per hosts.tab), but request is for http
 8463:              hostname       -> hostname, originally from $r->hostname(), (optional).
 8464:              links_disabled -> Links in primary and secondary menus are disabled
 8465:                                (Can enable them once page has loaded - see lonroles.pm
 8466:                                for an example).
 8467: 
 8468: =back
 8469: 
 8470: =back
 8471: 
 8472: =cut
 8473: 
 8474: sub start_page {
 8475:     my ($title,$head_extra,$args) = @_;
 8476:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 8477: 
 8478:     $env{'internal.start_page'}++;
 8479:     my ($result,@advtools);
 8480: 
 8481:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 8482:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
 8483:     }
 8484:     
 8485:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 8486: 	if ($args->{'frameset'}) {
 8487: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 8488: 						$args->{'add_entries'});
 8489: 	    $result .= "\n<frameset $attr_string>\n";
 8490:         } else {
 8491:             $result .=
 8492:                 &bodytag($title, 
 8493:                          $args->{'function'},       $args->{'add_entries'},
 8494:                          $args->{'only_body'},      $args->{'domain'},
 8495:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 8496:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
 8497:                          $args,                     \@advtools);
 8498:         }
 8499:     }
 8500: 
 8501:     if ($args->{'js_ready'}) {
 8502: 		$result = &js_ready($result);
 8503:     }
 8504:     if ($args->{'html_encode'}) {
 8505: 		$result = &html_encode($result);
 8506:     }
 8507: 
 8508:     # Preparation for new and consistent functionlist at top of screen
 8509:     # if ($args->{'functionlist'}) {
 8510:     #            $result .= &build_functionlist();
 8511:     #}
 8512: 
 8513:     # Don't add anything more if only_body wanted or in const space
 8514:     return $result if    $args->{'only_body'} 
 8515:                       || $env{'request.state'} eq 'construct';
 8516: 
 8517:     #Breadcrumbs
 8518:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 8519: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 8520: 		#if any br links exists, add them to the breadcrumbs
 8521: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 8522: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 8523: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 8524: 			}
 8525: 		}
 8526:                 # if @advtools array contains items add then to the breadcrumbs
 8527:                 if (@advtools > 0) {
 8528:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 8529:                 }
 8530:                 my $menulink;
 8531:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
 8532:                 if (exists($args->{'bread_crumbs_nomenu'})) {
 8533:                     $menulink = 0;
 8534:                 } else {
 8535:                     undef($menulink);
 8536:                 }
 8537: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 8538: 		if(exists($args->{'bread_crumbs_component'})){
 8539: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
 8540: 		}else{
 8541: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
 8542: 		}
 8543:     } elsif (($env{'environment.remote'} eq 'on') &&
 8544:              ($env{'form.inhibitmenu'} ne 'yes') &&
 8545:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
 8546:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
 8547:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
 8548:     }
 8549:     return $result;
 8550: }
 8551: 
 8552: sub end_page {
 8553:     my ($args) = @_;
 8554:     $env{'internal.end_page'}++;
 8555:     my $result;
 8556:     if ($args->{'discussion'}) {
 8557: 	my ($target,$parser);
 8558: 	if (ref($args->{'discussion'})) {
 8559: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 8560: 				$args->{'discussion'}{'parser'});
 8561: 	}
 8562: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 8563:     }
 8564:     if ($args->{'frameset'}) {
 8565: 	$result .= '</frameset>';
 8566:     } else {
 8567: 	$result .= &endbodytag($args);
 8568:     }
 8569:     unless ($args->{'notbody'}) {
 8570:         $result .= "\n</html>";
 8571:     }
 8572: 
 8573:     if ($args->{'js_ready'}) {
 8574: 	$result = &js_ready($result);
 8575:     }
 8576: 
 8577:     if ($args->{'html_encode'}) {
 8578: 	$result = &html_encode($result);
 8579:     }
 8580: 
 8581:     return $result;
 8582: }
 8583: 
 8584: sub wishlist_window {
 8585:     return(<<'ENDWISHLIST');
 8586: <script type="text/javascript">
 8587: // <![CDATA[
 8588: // <!-- BEGIN LON-CAPA Internal
 8589: function set_wishlistlink(title, path) {
 8590:     if (!title) {
 8591:         title = document.title;
 8592:         title = title.replace(/^LON-CAPA /,'');
 8593:     }
 8594:     title = encodeURIComponent(title);
 8595:     title = title.replace("'","\\\'");
 8596:     if (!path) {
 8597:         path = location.pathname;
 8598:     }
 8599:     path = encodeURIComponent(path);
 8600:     path = path.replace("'","\\\'");
 8601:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 8602:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 8603: }
 8604: // END LON-CAPA Internal -->
 8605: // ]]>
 8606: </script>
 8607: ENDWISHLIST
 8608: }
 8609: 
 8610: sub modal_window {
 8611:     return(<<'ENDMODAL');
 8612: <script type="text/javascript">
 8613: // <![CDATA[
 8614: // <!-- BEGIN LON-CAPA Internal
 8615: var modalWindow = {
 8616: 	parent:"body",
 8617: 	windowId:null,
 8618: 	content:null,
 8619: 	width:null,
 8620: 	height:null,
 8621: 	close:function()
 8622: 	{
 8623: 	        $(".LCmodal-window").remove();
 8624: 	        $(".LCmodal-overlay").remove();
 8625: 	},
 8626: 	open:function()
 8627: 	{
 8628: 		var modal = "";
 8629: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 8630: 		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;\">";
 8631: 		modal += this.content;
 8632: 		modal += "</div>";	
 8633: 
 8634: 		$(this.parent).append(modal);
 8635: 
 8636: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 8637: 		$(".LCclose-window").click(function(){modalWindow.close();});
 8638: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 8639: 	}
 8640: };
 8641: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
 8642: 	{
 8643:                 source = source.replace(/'/g,"&#39;");
 8644: 		modalWindow.windowId = "myModal";
 8645: 		modalWindow.width = width;
 8646: 		modalWindow.height = height;
 8647: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
 8648: 		modalWindow.open();
 8649: 	};
 8650: // END LON-CAPA Internal -->
 8651: // ]]>
 8652: </script>
 8653: ENDMODAL
 8654: }
 8655: 
 8656: sub modal_link {
 8657:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
 8658:     unless ($width) { $width=480; }
 8659:     unless ($height) { $height=400; }
 8660:     unless ($scrolling) { $scrolling='yes'; }
 8661:     unless ($transparency) { $transparency='true'; }
 8662: 
 8663:     my $target_attr;
 8664:     if (defined($target)) {
 8665:         $target_attr = 'target="'.$target.'"';
 8666:     }
 8667:     return <<"ENDLINK";
 8668: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
 8669: ENDLINK
 8670: }
 8671: 
 8672: sub modal_adhoc_script {
 8673:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
 8674:     my $mathjax;
 8675:     if ($possmathjax) {
 8676:         $mathjax = <<'ENDJAX';
 8677:                if (typeof MathJax == 'object') {
 8678:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
 8679:                }
 8680: ENDJAX
 8681:     }
 8682:     return (<<ENDADHOC);
 8683: <script type="text/javascript">
 8684: // <![CDATA[
 8685:         var $funcname = function()
 8686:         {
 8687:                 modalWindow.windowId = "myModal";
 8688:                 modalWindow.width = $width;
 8689:                 modalWindow.height = $height;
 8690:                 modalWindow.content = '$content';
 8691:                 modalWindow.open();
 8692:                 $mathjax
 8693:         };  
 8694: // ]]>
 8695: </script>
 8696: ENDADHOC
 8697: }
 8698: 
 8699: sub modal_adhoc_inner {
 8700:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
 8701:     my $innerwidth=$width-20;
 8702:     $content=&js_ready(
 8703:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 8704:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
 8705:                  $content.
 8706:                  &end_scrollbox().
 8707:                  &end_page()
 8708:              );
 8709:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
 8710: }
 8711: 
 8712: sub modal_adhoc_window {
 8713:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
 8714:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
 8715:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 8716: }
 8717: 
 8718: sub modal_adhoc_launch {
 8719:     my ($funcname,$width,$height,$content)=@_;
 8720:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 8721: <script type="text/javascript">
 8722: // <![CDATA[
 8723: $funcname();
 8724: // ]]>
 8725: </script>
 8726: ENDLAUNCH
 8727: }
 8728: 
 8729: sub modal_adhoc_close {
 8730:     return (<<ENDCLOSE);
 8731: <script type="text/javascript">
 8732: // <![CDATA[
 8733: modalWindow.close();
 8734: // ]]>
 8735: </script>
 8736: ENDCLOSE
 8737: }
 8738: 
 8739: sub togglebox_script {
 8740:    return(<<ENDTOGGLE);
 8741: <script type="text/javascript"> 
 8742: // <![CDATA[
 8743: function LCtoggleDisplay(id,hidetext,showtext) {
 8744:    link = document.getElementById(id + "link").childNodes[0];
 8745:    with (document.getElementById(id).style) {
 8746:       if (display == "none" ) {
 8747:           display = "inline";
 8748:           link.nodeValue = hidetext;
 8749:         } else {
 8750:           display = "none";
 8751:           link.nodeValue = showtext;
 8752:        }
 8753:    }
 8754: }
 8755: // ]]>
 8756: </script>
 8757: ENDTOGGLE
 8758: }
 8759: 
 8760: sub start_togglebox {
 8761:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 8762:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 8763:     unless ($showtext) { $showtext=&mt('show'); }
 8764:     unless ($hidetext) { $hidetext=&mt('hide'); }
 8765:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 8766:     return &start_data_table().
 8767:            &start_data_table_header_row().
 8768:            '<td bgcolor="'.$headerbg.'">'.$heading.
 8769:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 8770:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 8771:            &end_data_table_header_row().
 8772:            '<tr id="'.$id.'" style="display:none""><td>';
 8773: }
 8774: 
 8775: sub end_togglebox {
 8776:     return '</td></tr>'.&end_data_table();
 8777: }
 8778: 
 8779: sub LCprogressbar_script {
 8780:    my ($id,$number_to_do)=@_;
 8781:    if ($number_to_do) {
 8782:        return(<<ENDPROGRESS);
 8783: <script type="text/javascript">
 8784: // <![CDATA[
 8785: \$('#progressbar$id').progressbar({
 8786:   value: 0,
 8787:   change: function(event, ui) {
 8788:     var newVal = \$(this).progressbar('option', 'value');
 8789:     \$('.pblabel', this).text(LCprogressTxt);
 8790:   }
 8791: });
 8792: // ]]>
 8793: </script>
 8794: ENDPROGRESS
 8795:    } else {
 8796:        return(<<ENDPROGRESS);
 8797: <script type="text/javascript">
 8798: // <![CDATA[
 8799: \$('#progressbar$id').progressbar({
 8800:   value: false,
 8801:   create: function(event, ui) {
 8802:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
 8803:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
 8804:   }
 8805: });
 8806: // ]]>
 8807: </script>
 8808: ENDPROGRESS
 8809:    }
 8810: }
 8811: 
 8812: sub LCprogressbarUpdate_script {
 8813:    return(<<ENDPROGRESSUPDATE);
 8814: <style type="text/css">
 8815: .ui-progressbar { position:relative; }
 8816: .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%; }
 8817: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 8818: </style>
 8819: <script type="text/javascript">
 8820: // <![CDATA[
 8821: var LCprogressTxt='---';
 8822: 
 8823: function LCupdateProgress(percent,progresstext,id,maxnum) {
 8824:    LCprogressTxt=progresstext;
 8825:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
 8826:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
 8827:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
 8828:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
 8829:    } else {
 8830:        \$('#progressbar'+id).progressbar('value',percent);
 8831:    }
 8832: }
 8833: // ]]>
 8834: </script>
 8835: ENDPROGRESSUPDATE
 8836: }
 8837: 
 8838: my $LClastpercent;
 8839: my $LCidcnt;
 8840: my $LCcurrentid;
 8841: 
 8842: sub LCprogressbar {
 8843:     my ($r,$number_to_do,$preamble)=@_;
 8844:     $LClastpercent=0;
 8845:     $LCidcnt++;
 8846:     $LCcurrentid=$$.'_'.$LCidcnt;
 8847:     my ($starting,$content);
 8848:     if ($number_to_do) {
 8849:         $starting=&mt('Starting');
 8850:         $content=(<<ENDPROGBAR);
 8851: $preamble
 8852:   <div id="progressbar$LCcurrentid">
 8853:     <span class="pblabel">$starting</span>
 8854:   </div>
 8855: ENDPROGBAR
 8856:     } else {
 8857:         $starting=&mt('Loading...');
 8858:         $LClastpercent='false';
 8859:         $content=(<<ENDPROGBAR);
 8860: $preamble
 8861:   <div id="progressbar$LCcurrentid">
 8862:       <div class="progress-label">$starting</div>
 8863:   </div>
 8864: ENDPROGBAR
 8865:     }
 8866:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
 8867: }
 8868: 
 8869: sub LCprogressbarUpdate {
 8870:     my ($r,$val,$text,$number_to_do)=@_;
 8871:     if ($number_to_do) {
 8872:         unless ($val) { 
 8873:             if ($LClastpercent) {
 8874:                 $val=$LClastpercent;
 8875:             } else {
 8876:                 $val=0;
 8877:             }
 8878:         }
 8879:         if ($val<0) { $val=0; }
 8880:         if ($val>100) { $val=0; }
 8881:         $LClastpercent=$val;
 8882:         unless ($text) { $text=$val.'%'; }
 8883:     } else {
 8884:         $val = 'false';
 8885:     }
 8886:     $text=&js_ready($text);
 8887:     &r_print($r,<<ENDUPDATE);
 8888: <script type="text/javascript">
 8889: // <![CDATA[
 8890: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
 8891: // ]]>
 8892: </script>
 8893: ENDUPDATE
 8894: }
 8895: 
 8896: sub LCprogressbarClose {
 8897:     my ($r)=@_;
 8898:     $LClastpercent=0;
 8899:     &r_print($r,<<ENDCLOSE);
 8900: <script type="text/javascript">
 8901: // <![CDATA[
 8902: \$("#progressbar$LCcurrentid").hide('slow'); 
 8903: // ]]>
 8904: </script>
 8905: ENDCLOSE
 8906: }
 8907: 
 8908: sub r_print {
 8909:     my ($r,$to_print)=@_;
 8910:     if ($r) {
 8911:       $r->print($to_print);
 8912:       $r->rflush();
 8913:     } else {
 8914:       print($to_print);
 8915:     }
 8916: }
 8917: 
 8918: sub html_encode {
 8919:     my ($result) = @_;
 8920: 
 8921:     $result = &HTML::Entities::encode($result,'<>&"');
 8922:     
 8923:     return $result;
 8924: }
 8925: 
 8926: sub js_ready {
 8927:     my ($result) = @_;
 8928: 
 8929:     $result =~ s/[\n\r]/ /xmsg;
 8930:     $result =~ s/\\/\\\\/xmsg;
 8931:     $result =~ s/'/\\'/xmsg;
 8932:     $result =~ s{</}{<\\/}xmsg;
 8933:     
 8934:     return $result;
 8935: }
 8936: 
 8937: sub validate_page {
 8938:     if (  exists($env{'internal.start_page'})
 8939: 	  &&     $env{'internal.start_page'} > 1) {
 8940: 	&Apache::lonnet::logthis('start_page called multiple times '.
 8941: 				 $env{'internal.start_page'}.' '.
 8942: 				 $ENV{'request.filename'});
 8943:     }
 8944:     if (  exists($env{'internal.end_page'})
 8945: 	  &&     $env{'internal.end_page'} > 1) {
 8946: 	&Apache::lonnet::logthis('end_page called multiple times '.
 8947: 				 $env{'internal.end_page'}.' '.
 8948: 				 $env{'request.filename'});
 8949:     }
 8950:     if (     exists($env{'internal.start_page'})
 8951: 	&& ! exists($env{'internal.end_page'})) {
 8952: 	&Apache::lonnet::logthis('start_page called without end_page '.
 8953: 				 $env{'request.filename'});
 8954:     }
 8955:     if (   ! exists($env{'internal.start_page'})
 8956: 	&&   exists($env{'internal.end_page'})) {
 8957: 	&Apache::lonnet::logthis('end_page called without start_page'.
 8958: 				 $env{'request.filename'});
 8959:     }
 8960: }
 8961: 
 8962: 
 8963: sub start_scrollbox {
 8964:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
 8965:     unless ($outerwidth) { $outerwidth='520px'; }
 8966:     unless ($width) { $width='500px'; }
 8967:     unless ($height) { $height='200px'; }
 8968:     my ($table_id,$div_id,$tdcol);
 8969:     if ($id ne '') {
 8970:         $table_id = ' id="table_'.$id.'"';
 8971:         $div_id = ' id="div_'.$id.'"';
 8972:     }
 8973:     if ($bgcolor ne '') {
 8974:         $tdcol = "background-color: $bgcolor;";
 8975:     }
 8976:     my $nicescroll_js;
 8977:     if ($env{'browser.mobile'}) {
 8978:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
 8979:     }
 8980:     return <<"END";
 8981: $nicescroll_js
 8982: 
 8983: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
 8984: <div style="overflow:auto; width:$width; height:$height;"$div_id>
 8985: END
 8986: }
 8987: 
 8988: sub end_scrollbox {
 8989:     return '</div></td></tr></table>';
 8990: }
 8991: 
 8992: sub nicescroll_javascript {
 8993:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
 8994:     my %options;
 8995:     if (ref($cursor) eq 'HASH') {
 8996:         %options = %{$cursor};
 8997:     }
 8998:     unless ($options{'railalign'} =~ /^left|right$/) {
 8999:         $options{'railalign'} = 'left';
 9000:     }
 9001:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 9002:         my $function  = &get_users_function();
 9003:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
 9004:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 9005:             $options{'cursorcolor'} = '#00F';
 9006:         }
 9007:     }
 9008:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
 9009:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
 9010:             $options{'cursoropacity'}='1.0';
 9011:         }
 9012:     } else {
 9013:         $options{'cursoropacity'}='1.0';
 9014:     }
 9015:     if ($options{'cursorfixedheight'} eq 'none') {
 9016:         delete($options{'cursorfixedheight'});
 9017:     } else {
 9018:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
 9019:     }
 9020:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
 9021:         delete($options{'railoffset'});
 9022:     }
 9023:     my @niceoptions;
 9024:     while (my($key,$value) = each(%options)) {
 9025:         if ($value =~ /^\{.+\}$/) {
 9026:             push(@niceoptions,$key.':'.$value);
 9027:         } else {
 9028:             push(@niceoptions,$key.':"'.$value.'"');
 9029:         }
 9030:     }
 9031:     my $nicescroll_js = '
 9032: $(document).ready(
 9033:       function() {
 9034:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
 9035:       }
 9036: );
 9037: ';
 9038:     if ($framecheck) {
 9039:         $nicescroll_js .= '
 9040: function expand_div(caller) {
 9041:     if (top === self) {
 9042:         document.getElementById("'.$id.'").style.width = "auto";
 9043:         document.getElementById("'.$id.'").style.height = "auto";
 9044:     } else {
 9045:         try {
 9046:             if (parent.frames) {
 9047:                 if (parent.frames.length > 1) {
 9048:                     var framesrc = parent.frames[1].location.href;
 9049:                     var currsrc = framesrc.replace(/\#.*$/,"");
 9050:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
 9051:                         document.getElementById("'.$id.'").style.width = "auto";
 9052:                         document.getElementById("'.$id.'").style.height = "auto";
 9053:                     }
 9054:                 }
 9055:             }
 9056:         } catch (e) {
 9057:             return;
 9058:         }
 9059:     }
 9060:     return;
 9061: }
 9062: ';
 9063:     }
 9064:     if ($needjsready) {
 9065:         $nicescroll_js = '
 9066: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
 9067:     } else {
 9068:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
 9069:     }
 9070:     return $nicescroll_js;
 9071: }
 9072: 
 9073: sub simple_error_page {
 9074:     my ($r,$title,$msg,$args) = @_;
 9075:     if (ref($args) eq 'HASH') {
 9076:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
 9077:     } else {
 9078:         $msg = &mt($msg);
 9079:     }
 9080: 
 9081:     my $page =
 9082: 	&Apache::loncommon::start_page($title).
 9083: 	'<p class="LC_error">'.$msg.'</p>'.
 9084: 	&Apache::loncommon::end_page();
 9085:     if (ref($r)) {
 9086: 	$r->print($page);
 9087: 	return;
 9088:     }
 9089:     return $page;
 9090: }
 9091: 
 9092: {
 9093:     my @row_count;
 9094: 
 9095:     sub start_data_table_count {
 9096:         unshift(@row_count, 0);
 9097:         return;
 9098:     }
 9099: 
 9100:     sub end_data_table_count {
 9101:         shift(@row_count);
 9102:         return;
 9103:     }
 9104: 
 9105:     sub start_data_table {
 9106: 	my ($add_class,$id) = @_;
 9107: 	my $css_class = (join(' ','LC_data_table',$add_class));
 9108:         my $table_id;
 9109:         if (defined($id)) {
 9110:             $table_id = ' id="'.$id.'"';
 9111:         }
 9112: 	&start_data_table_count();
 9113: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 9114:     }
 9115: 
 9116:     sub end_data_table {
 9117: 	&end_data_table_count();
 9118: 	return '</table>'."\n";;
 9119:     }
 9120: 
 9121:     sub start_data_table_row {
 9122: 	my ($add_class, $id) = @_;
 9123: 	$row_count[0]++;
 9124: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 9125: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 9126:         $id = (' id="'.$id.'"') unless ($id eq '');
 9127:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 9128:     }
 9129:     
 9130:     sub continue_data_table_row {
 9131: 	my ($add_class, $id) = @_;
 9132: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 9133: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 9134:         $id = (' id="'.$id.'"') unless ($id eq '');
 9135:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 9136:     }
 9137: 
 9138:     sub end_data_table_row {
 9139: 	return '</tr>'."\n";;
 9140:     }
 9141: 
 9142:     sub start_data_table_empty_row {
 9143: #	$row_count[0]++;
 9144: 	return  '<tr class="LC_empty_row" >'."\n";;
 9145:     }
 9146: 
 9147:     sub end_data_table_empty_row {
 9148: 	return '</tr>'."\n";;
 9149:     }
 9150: 
 9151:     sub start_data_table_header_row {
 9152: 	return  '<tr class="LC_header_row">'."\n";;
 9153:     }
 9154: 
 9155:     sub end_data_table_header_row {
 9156: 	return '</tr>'."\n";;
 9157:     }
 9158: 
 9159:     sub data_table_caption {
 9160:         my $caption = shift;
 9161:         return "<caption class=\"LC_caption\">$caption</caption>";
 9162:     }
 9163: }
 9164: 
 9165: =pod
 9166: 
 9167: =item * &inhibit_menu_check($arg)
 9168: 
 9169: Checks for a inhibitmenu state and generates output to preserve it
 9170: 
 9171: Inputs:         $arg - can be any of
 9172:                      - undef - in which case the return value is a string 
 9173:                                to add  into arguments list of a uri
 9174:                      - 'input' - in which case the return value is a HTML
 9175:                                  <form> <input> field of type hidden to
 9176:                                  preserve the value
 9177:                      - a url - in which case the return value is the url with
 9178:                                the neccesary cgi args added to preserve the
 9179:                                inhibitmenu state
 9180:                      - a ref to a url - no return value, but the string is
 9181:                                         updated to include the neccessary cgi
 9182:                                         args to preserve the inhibitmenu state
 9183: 
 9184: =cut
 9185: 
 9186: sub inhibit_menu_check {
 9187:     my ($arg) = @_;
 9188:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 9189:     if ($arg eq 'input') {
 9190: 	if ($env{'form.inhibitmenu'}) {
 9191: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 9192: 	} else {
 9193: 	    return
 9194: 	}
 9195:     }
 9196:     if ($env{'form.inhibitmenu'}) {
 9197: 	if (ref($arg)) {
 9198: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 9199: 	} elsif ($arg eq '') {
 9200: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 9201: 	} else {
 9202: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 9203: 	}
 9204:     }
 9205:     if (!ref($arg)) {
 9206: 	return $arg;
 9207:     }
 9208: }
 9209: 
 9210: ###############################################
 9211: 
 9212: =pod
 9213: 
 9214: =back
 9215: 
 9216: =head1 User Information Routines
 9217: 
 9218: =over 4
 9219: 
 9220: =item * &get_users_function()
 9221: 
 9222: Used by &bodytag to determine the current users primary role.
 9223: Returns either 'student','coordinator','admin', or 'author'.
 9224: 
 9225: =cut
 9226: 
 9227: ###############################################
 9228: sub get_users_function {
 9229:     my $function = 'norole';
 9230:     if ($env{'request.role'}=~/^(st)/) {
 9231:         $function='student';
 9232:     }
 9233:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 9234:         $function='coordinator';
 9235:     }
 9236:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 9237:         $function='admin';
 9238:     }
 9239:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 9240:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 9241:         $function='author';
 9242:     }
 9243:     return $function;
 9244: }
 9245: 
 9246: ###############################################
 9247: 
 9248: =pod
 9249: 
 9250: =item * &show_course()
 9251: 
 9252: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 9253: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 9254: 
 9255: Inputs:
 9256: None
 9257: 
 9258: Outputs:
 9259: Scalar: 1 if 'Course' to be used, 0 otherwise.
 9260: 
 9261: =cut
 9262: 
 9263: ###############################################
 9264: sub show_course {
 9265:     my $course = !$env{'user.adv'};
 9266:     if (!$env{'user.adv'}) {
 9267:         foreach my $env (keys(%env)) {
 9268:             next if ($env !~ m/^user\.priv\./);
 9269:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 9270:                 $course = 0;
 9271:                 last;
 9272:             }
 9273:         }
 9274:     }
 9275:     return $course;
 9276: }
 9277: 
 9278: ###############################################
 9279: 
 9280: =pod
 9281: 
 9282: =item * &check_user_status()
 9283: 
 9284: Determines current status of supplied role for a
 9285: specific user. Roles can be active, previous or future.
 9286: 
 9287: Inputs: 
 9288: user's domain, user's username, course's domain,
 9289: course's number, optional section ID.
 9290: 
 9291: Outputs:
 9292: role status: active, previous or future. 
 9293: 
 9294: =cut
 9295: 
 9296: sub check_user_status {
 9297:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 9298:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 9299:     my @uroles = keys(%userinfo);
 9300:     my $srchstr;
 9301:     my $active_chk = 'none';
 9302:     my $now = time;
 9303:     if (@uroles > 0) {
 9304:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 9305:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 9306:         } else {
 9307:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 9308:         }
 9309:         if (grep/^\Q$srchstr\E$/,@uroles) {
 9310:             my $role_end = 0;
 9311:             my $role_start = 0;
 9312:             $active_chk = 'active';
 9313:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 9314:                 $role_end = $1;
 9315:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 9316:                     $role_start = $1;
 9317:                 }
 9318:             }
 9319:             if ($role_start > 0) {
 9320:                 if ($now < $role_start) {
 9321:                     $active_chk = 'future';
 9322:                 }
 9323:             }
 9324:             if ($role_end > 0) {
 9325:                 if ($now > $role_end) {
 9326:                     $active_chk = 'previous';
 9327:                 }
 9328:             }
 9329:         }
 9330:     }
 9331:     return $active_chk;
 9332: }
 9333: 
 9334: ###############################################
 9335: 
 9336: =pod
 9337: 
 9338: =item * &get_sections()
 9339: 
 9340: Determines all the sections for a course including
 9341: sections with students and sections containing other roles.
 9342: Incoming parameters: 
 9343: 
 9344: 1. domain
 9345: 2. course number 
 9346: 3. reference to array containing roles for which sections should 
 9347: be gathered (optional).
 9348: 4. reference to array containing status types for which sections 
 9349: should be gathered (optional).
 9350: 
 9351: If the third argument is undefined, sections are gathered for any role. 
 9352: If the fourth argument is undefined, sections are gathered for any status.
 9353: Permissible values are 'active' or 'future' or 'previous'.
 9354:  
 9355: Returns section hash (keys are section IDs, values are
 9356: number of users in each section), subject to the
 9357: optional roles filter, optional status filter 
 9358: 
 9359: =cut
 9360: 
 9361: ###############################################
 9362: sub get_sections {
 9363:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 9364:     if (!defined($cdom) || !defined($cnum)) {
 9365:         my $cid =  $env{'request.course.id'};
 9366: 
 9367: 	return if (!defined($cid));
 9368: 
 9369:         $cdom = $env{'course.'.$cid.'.domain'};
 9370:         $cnum = $env{'course.'.$cid.'.num'};
 9371:     }
 9372: 
 9373:     my %sectioncount;
 9374:     my $now = time;
 9375: 
 9376:     my $check_students = 1;
 9377:     my $only_students = 0;
 9378:     if (ref($possible_roles) eq 'ARRAY') {
 9379:         if (grep(/^st$/,@{$possible_roles})) {
 9380:             if (@{$possible_roles} == 1) {
 9381:                 $only_students = 1;
 9382:             }
 9383:         } else {
 9384:             $check_students = 0;
 9385:         }
 9386:     }
 9387: 
 9388:     if ($check_students) {
 9389: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 9390: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 9391: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 9392:         my $start_index = &Apache::loncoursedata::CL_START();
 9393:         my $end_index = &Apache::loncoursedata::CL_END();
 9394:         my $status;
 9395: 	while (my ($student,$data) = each(%$classlist)) {
 9396: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 9397: 				                     $data->[$status_index],
 9398:                                                      $data->[$start_index],
 9399:                                                      $data->[$end_index]);
 9400:             if ($stu_status eq 'Active') {
 9401:                 $status = 'active';
 9402:             } elsif ($end < $now) {
 9403:                 $status = 'previous';
 9404:             } elsif ($start > $now) {
 9405:                 $status = 'future';
 9406:             } 
 9407: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 9408:                 if ((!defined($possible_status)) || (($status ne '') && 
 9409:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 9410: 		    $sectioncount{$section}++;
 9411:                 }
 9412: 	    }
 9413: 	}
 9414:     }
 9415:     if ($only_students) {
 9416:         return %sectioncount;
 9417:     }
 9418:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9419:     foreach my $user (sort(keys(%courseroles))) {
 9420: 	if ($user !~ /^(\w{2})/) { next; }
 9421: 	my ($role) = ($user =~ /^(\w{2})/);
 9422: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 9423: 	my ($section,$status);
 9424: 	if ($role eq 'cr' &&
 9425: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 9426: 	    $section=$1;
 9427: 	}
 9428: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 9429: 	if (!defined($section) || $section eq '-1') { next; }
 9430:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 9431:         if ($end == -1 && $start == -1) {
 9432:             next; #deleted role
 9433:         }
 9434:         if (!defined($possible_status)) { 
 9435:             $sectioncount{$section}++;
 9436:         } else {
 9437:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 9438:                 $status = 'active';
 9439:             } elsif ($end < $now) {
 9440:                 $status = 'future';
 9441:             } elsif ($start > $now) {
 9442:                 $status = 'previous';
 9443:             }
 9444:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 9445:                 $sectioncount{$section}++;
 9446:             }
 9447:         }
 9448:     }
 9449:     return %sectioncount;
 9450: }
 9451: 
 9452: ###############################################
 9453: 
 9454: =pod
 9455: 
 9456: =item * &get_course_users()
 9457: 
 9458: Retrieves usernames:domains for users in the specified course
 9459: with specific role(s), and access status. 
 9460: 
 9461: Incoming parameters:
 9462: 1. course domain
 9463: 2. course number
 9464: 3. access status: users must have - either active, 
 9465: previous, future, or all.
 9466: 4. reference to array of permissible roles
 9467: 5. reference to array of section restrictions (optional)
 9468: 6. reference to results object (hash of hashes).
 9469: 7. reference to optional userdata hash
 9470: 8. reference to optional statushash
 9471: 9. flag if privileged users (except those set to unhide in
 9472:    course settings) should be excluded    
 9473: Keys of top level results hash are roles.
 9474: Keys of inner hashes are username:domain, with 
 9475: values set to access type.
 9476: Optional userdata hash returns an array with arguments in the 
 9477: same order as loncoursedata::get_classlist() for student data.
 9478: 
 9479: Optional statushash returns
 9480: 
 9481: Entries for end, start, section and status are blank because
 9482: of the possibility of multiple values for non-student roles.
 9483: 
 9484: =cut
 9485: 
 9486: ###############################################
 9487: 
 9488: sub get_course_users {
 9489:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 9490:     my %idx = ();
 9491:     my %seclists;
 9492: 
 9493:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 9494:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 9495:     $idx{end} = &Apache::loncoursedata::CL_END();
 9496:     $idx{start} = &Apache::loncoursedata::CL_START();
 9497:     $idx{id} = &Apache::loncoursedata::CL_ID();
 9498:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 9499:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 9500:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 9501: 
 9502:     if (grep(/^st$/,@{$roles})) {
 9503:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 9504:         my $now = time;
 9505:         foreach my $student (keys(%{$classlist})) {
 9506:             my $match = 0;
 9507:             my $secmatch = 0;
 9508:             my $section = $$classlist{$student}[$idx{section}];
 9509:             my $status = $$classlist{$student}[$idx{status}];
 9510:             if ($section eq '') {
 9511:                 $section = 'none';
 9512:             }
 9513:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 9514:                 if (grep(/^all$/,@{$sections})) {
 9515:                     $secmatch = 1;
 9516:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 9517:                     if (grep(/^none$/,@{$sections})) {
 9518:                         $secmatch = 1;
 9519:                     }
 9520:                 } else {  
 9521: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 9522: 		        $secmatch = 1;
 9523:                     }
 9524: 		}
 9525:                 if (!$secmatch) {
 9526:                     next;
 9527:                 }
 9528:             }
 9529:             if (defined($$types{'active'})) {
 9530:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 9531:                     push(@{$$users{st}{$student}},'active');
 9532:                     $match = 1;
 9533:                 }
 9534:             }
 9535:             if (defined($$types{'previous'})) {
 9536:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 9537:                     push(@{$$users{st}{$student}},'previous');
 9538:                     $match = 1;
 9539:                 }
 9540:             }
 9541:             if (defined($$types{'future'})) {
 9542:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 9543:                     push(@{$$users{st}{$student}},'future');
 9544:                     $match = 1;
 9545:                 }
 9546:             }
 9547:             if ($match) {
 9548:                 push(@{$seclists{$student}},$section);
 9549:                 if (ref($userdata) eq 'HASH') {
 9550:                     $$userdata{$student} = $$classlist{$student};
 9551:                 }
 9552:                 if (ref($statushash) eq 'HASH') {
 9553:                     $statushash->{$student}{'st'}{$section} = $status;
 9554:                 }
 9555:             }
 9556:         }
 9557:     }
 9558:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 9559:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9560:         my $now = time;
 9561:         my %displaystatus = ( previous => 'Expired',
 9562:                               active   => 'Active',
 9563:                               future   => 'Future',
 9564:                             );
 9565:         my (%nothide,@possdoms);
 9566:         if ($hidepriv) {
 9567:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 9568:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 9569:                 if ($user !~ /:/) {
 9570:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 9571:                 } else {
 9572:                     $nothide{$user} = 1;
 9573:                 }
 9574:             }
 9575:             my @possdoms = ($cdom);
 9576:             if ($coursehash{'checkforpriv'}) {
 9577:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 9578:             }
 9579:         }
 9580:         foreach my $person (sort(keys(%coursepersonnel))) {
 9581:             my $match = 0;
 9582:             my $secmatch = 0;
 9583:             my $status;
 9584:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 9585:             $user =~ s/:$//;
 9586:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 9587:             if ($end == -1 || $start == -1) {
 9588:                 next;
 9589:             }
 9590:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 9591:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 9592:                 my ($uname,$udom) = split(/:/,$user);
 9593:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 9594:                     if (grep(/^all$/,@{$sections})) {
 9595:                         $secmatch = 1;
 9596:                     } elsif ($usec eq '') {
 9597:                         if (grep(/^none$/,@{$sections})) {
 9598:                             $secmatch = 1;
 9599:                         }
 9600:                     } else {
 9601:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 9602:                             $secmatch = 1;
 9603:                         }
 9604:                     }
 9605:                     if (!$secmatch) {
 9606:                         next;
 9607:                     }
 9608:                 }
 9609:                 if ($usec eq '') {
 9610:                     $usec = 'none';
 9611:                 }
 9612:                 if ($uname ne '' && $udom ne '') {
 9613:                     if ($hidepriv) {
 9614:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
 9615:                             (!$nothide{$uname.':'.$udom})) {
 9616:                             next;
 9617:                         }
 9618:                     }
 9619:                     if ($end > 0 && $end < $now) {
 9620:                         $status = 'previous';
 9621:                     } elsif ($start > $now) {
 9622:                         $status = 'future';
 9623:                     } else {
 9624:                         $status = 'active';
 9625:                     }
 9626:                     foreach my $type (keys(%{$types})) { 
 9627:                         if ($status eq $type) {
 9628:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 9629:                                 push(@{$$users{$role}{$user}},$type);
 9630:                             }
 9631:                             $match = 1;
 9632:                         }
 9633:                     }
 9634:                     if (($match) && (ref($userdata) eq 'HASH')) {
 9635:                         if (!exists($$userdata{$uname.':'.$udom})) {
 9636: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 9637:                         }
 9638:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 9639:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 9640:                         }
 9641:                         if (ref($statushash) eq 'HASH') {
 9642:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 9643:                         }
 9644:                     }
 9645:                 }
 9646:             }
 9647:         }
 9648:         if (grep(/^ow$/,@{$roles})) {
 9649:             if ((defined($cdom)) && (defined($cnum))) {
 9650:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 9651:                 if ( defined($csettings{'internal.courseowner'}) ) {
 9652:                     my $owner = $csettings{'internal.courseowner'};
 9653:                     next if ($owner eq '');
 9654:                     my ($ownername,$ownerdom);
 9655:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 9656:                         $ownername = $1;
 9657:                         $ownerdom = $2;
 9658:                     } else {
 9659:                         $ownername = $owner;
 9660:                         $ownerdom = $cdom;
 9661:                         $owner = $ownername.':'.$ownerdom;
 9662:                     }
 9663:                     @{$$users{'ow'}{$owner}} = 'any';
 9664:                     if (defined($userdata) && 
 9665: 			!exists($$userdata{$owner})) {
 9666: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 9667:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 9668:                             push(@{$seclists{$owner}},'none');
 9669:                         }
 9670:                         if (ref($statushash) eq 'HASH') {
 9671:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 9672:                         }
 9673: 		    }
 9674:                 }
 9675:             }
 9676:         }
 9677:         foreach my $user (keys(%seclists)) {
 9678:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 9679:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 9680:         }
 9681:     }
 9682:     return;
 9683: }
 9684: 
 9685: sub get_user_info {
 9686:     my ($udom,$uname,$idx,$userdata) = @_;
 9687:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 9688: 	&plainname($uname,$udom,'lastname');
 9689:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 9690:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 9691:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 9692:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 9693:     return;
 9694: }
 9695: 
 9696: ###############################################
 9697: 
 9698: =pod
 9699: 
 9700: =item * &get_user_quota()
 9701: 
 9702: Retrieves quota assigned for storage of user files.
 9703: Default is to report quota for portfolio files.
 9704: 
 9705: Incoming parameters:
 9706: 1. user's username
 9707: 2. user's domain
 9708: 3. quota name - portfolio, author, or course
 9709:    (if no quota name provided, defaults to portfolio).
 9710: 4. crstype - official, unofficial, textbook or community, if quota name is
 9711:    course
 9712: 
 9713: Returns:
 9714: 1. Disk quota (in MB) assigned to student.
 9715: 2. (Optional) Type of setting: custom or default
 9716:    (individually assigned or default for user's 
 9717:    institutional status).
 9718: 3. (Optional) - User's institutional status (e.g., faculty, staff
 9719:    or student - types as defined in localenroll::inst_usertypes 
 9720:    for user's domain, which determines default quota for user.
 9721: 4. (Optional) - Default quota which would apply to the user.
 9722: 
 9723: If a value has been stored in the user's environment, 
 9724: it will return that, otherwise it returns the maximal default
 9725: defined for the user's institutional status(es) in the domain.
 9726: 
 9727: =cut
 9728: 
 9729: ###############################################
 9730: 
 9731: 
 9732: sub get_user_quota {
 9733:     my ($uname,$udom,$quotaname,$crstype) = @_;
 9734:     my ($quota,$quotatype,$settingstatus,$defquota);
 9735:     if (!defined($udom)) {
 9736:         $udom = $env{'user.domain'};
 9737:     }
 9738:     if (!defined($uname)) {
 9739:         $uname = $env{'user.name'};
 9740:     }
 9741:     if (($udom eq '' || $uname eq '') ||
 9742:         ($udom eq 'public') && ($uname eq 'public')) {
 9743:         $quota = 0;
 9744:         $quotatype = 'default';
 9745:         $defquota = 0; 
 9746:     } else {
 9747:         my $inststatus;
 9748:         if ($quotaname eq 'course') {
 9749:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
 9750:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
 9751:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
 9752:             } else {
 9753:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
 9754:                 $quota = $cenv{'internal.uploadquota'};
 9755:             }
 9756:         } else {
 9757:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 9758:                 if ($quotaname eq 'author') {
 9759:                     $quota = $env{'environment.authorquota'};
 9760:                 } else {
 9761:                     $quota = $env{'environment.portfolioquota'};
 9762:                 }
 9763:                 $inststatus = $env{'environment.inststatus'};
 9764:             } else {
 9765:                 my %userenv = 
 9766:                     &Apache::lonnet::get('environment',['portfolioquota',
 9767:                                          'authorquota','inststatus'],$udom,$uname);
 9768:                 my ($tmp) = keys(%userenv);
 9769:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9770:                     if ($quotaname eq 'author') {
 9771:                         $quota = $userenv{'authorquota'};
 9772:                     } else {
 9773:                         $quota = $userenv{'portfolioquota'};
 9774:                     }
 9775:                     $inststatus = $userenv{'inststatus'};
 9776:                 } else {
 9777:                     undef(%userenv);
 9778:                 }
 9779:             }
 9780:         }
 9781:         if ($quota eq '' || wantarray) {
 9782:             if ($quotaname eq 'course') {
 9783:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 9784:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
 9785:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
 9786:                     $defquota = $domdefs{$crstype.'quota'};
 9787:                 }
 9788:                 if ($defquota eq '') {
 9789:                     $defquota = 500;
 9790:                 }
 9791:             } else {
 9792:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
 9793:             }
 9794:             if ($quota eq '') {
 9795:                 $quota = $defquota;
 9796:                 $quotatype = 'default';
 9797:             } else {
 9798:                 $quotatype = 'custom';
 9799:             }
 9800:         }
 9801:     }
 9802:     if (wantarray) {
 9803:         return ($quota,$quotatype,$settingstatus,$defquota);
 9804:     } else {
 9805:         return $quota;
 9806:     }
 9807: }
 9808: 
 9809: ###############################################
 9810: 
 9811: =pod
 9812: 
 9813: =item * &default_quota()
 9814: 
 9815: Retrieves default quota assigned for storage of user portfolio files,
 9816: given an (optional) user's institutional status.
 9817: 
 9818: Incoming parameters:
 9819: 
 9820: 1. domain
 9821: 2. (Optional) institutional status(es).  This is a : separated list of 
 9822:    status types (e.g., faculty, staff, student etc.)
 9823:    which apply to the user for whom the default is being retrieved.
 9824:    If the institutional status string in undefined, the domain
 9825:    default quota will be returned.
 9826: 3.  quota name - portfolio, author, or course
 9827:    (if no quota name provided, defaults to portfolio).
 9828: 
 9829: Returns:
 9830: 
 9831: 1. Default disk quota (in MB) for user portfolios in the domain.
 9832: 2. (Optional) institutional type which determined the value of the
 9833:    default quota.
 9834: 
 9835: If a value has been stored in the domain's configuration db,
 9836: it will return that, otherwise it returns 20 (for backwards 
 9837: compatibility with domains which have not set up a configuration
 9838: db file; the original statically defined portfolio quota was 20 MB). 
 9839: 
 9840: If the user's status includes multiple types (e.g., staff and student),
 9841: the largest default quota which applies to the user determines the
 9842: default quota returned.
 9843: 
 9844: =cut
 9845: 
 9846: ###############################################
 9847: 
 9848: 
 9849: sub default_quota {
 9850:     my ($udom,$inststatus,$quotaname) = @_;
 9851:     my ($defquota,$settingstatus);
 9852:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 9853:                                             ['quotas'],$udom);
 9854:     my $key = 'defaultquota';
 9855:     if ($quotaname eq 'author') {
 9856:         $key = 'authorquota';
 9857:     }
 9858:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 9859:         if ($inststatus ne '') {
 9860:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 9861:             foreach my $item (@statuses) {
 9862:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 9863:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
 9864:                         if ($defquota eq '') {
 9865:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 9866:                             $settingstatus = $item;
 9867:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
 9868:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 9869:                             $settingstatus = $item;
 9870:                         }
 9871:                     }
 9872:                 } elsif ($key eq 'defaultquota') {
 9873:                     if ($quotahash{'quotas'}{$item} ne '') {
 9874:                         if ($defquota eq '') {
 9875:                             $defquota = $quotahash{'quotas'}{$item};
 9876:                             $settingstatus = $item;
 9877:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 9878:                             $defquota = $quotahash{'quotas'}{$item};
 9879:                             $settingstatus = $item;
 9880:                         }
 9881:                     }
 9882:                 }
 9883:             }
 9884:         }
 9885:         if ($defquota eq '') {
 9886:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 9887:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
 9888:             } elsif ($key eq 'defaultquota') {
 9889:                 $defquota = $quotahash{'quotas'}{'default'};
 9890:             }
 9891:             $settingstatus = 'default';
 9892:             if ($defquota eq '') {
 9893:                 if ($quotaname eq 'author') {
 9894:                     $defquota = 500;
 9895:                 }
 9896:             }
 9897:         }
 9898:     } else {
 9899:         $settingstatus = 'default';
 9900:         if ($quotaname eq 'author') {
 9901:             $defquota = 500;
 9902:         } else {
 9903:             $defquota = 20;
 9904:         }
 9905:     }
 9906:     if (wantarray) {
 9907:         return ($defquota,$settingstatus);
 9908:     } else {
 9909:         return $defquota;
 9910:     }
 9911: }
 9912: 
 9913: ###############################################
 9914: 
 9915: =pod
 9916: 
 9917: =item * &excess_filesize_warning()
 9918: 
 9919: Returns warning message if upload of file to authoring space, or copying
 9920: of existing file within authoring space will cause quota for the authoring
 9921: space to be exceeded.
 9922: 
 9923: Same, if upload of a file directly to a course/community via Course Editor
 9924: will cause quota for uploaded content for the course to be exceeded.
 9925: 
 9926: Inputs: 7 
 9927: 1. username or coursenum
 9928: 2. domain
 9929: 3. context ('author' or 'course')
 9930: 4. filename of file for which action is being requested
 9931: 5. filesize (kB) of file
 9932: 6. action being taken: copy or upload.
 9933: 7. quotatype (in course context -- official, unofficial, community or textbook).
 9934: 
 9935: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
 9936:          otherwise return null.
 9937: 
 9938: =back
 9939: 
 9940: =cut
 9941: 
 9942: sub excess_filesize_warning {
 9943:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
 9944:     my $current_disk_usage = 0;
 9945:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
 9946:     if ($context eq 'author') {
 9947:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
 9948:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
 9949:     } else {
 9950:         foreach my $subdir ('docs','supplemental') {
 9951:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
 9952:         }
 9953:     }
 9954:     $disk_quota = int($disk_quota * 1000);
 9955:     if (($current_disk_usage + $filesize) > $disk_quota) {
 9956:         return '<p class="LC_warning">'.
 9957:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
 9958:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
 9959:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
 9960:                             $disk_quota,$current_disk_usage).
 9961:                '</p>';
 9962:     }
 9963:     return;
 9964: }
 9965: 
 9966: ###############################################
 9967: 
 9968: 
 9969: sub get_secgrprole_info {
 9970:     my ($cdom,$cnum,$needroles,$type)  = @_;
 9971:     my %sections_count = &get_sections($cdom,$cnum);
 9972:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 9973:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 9974:     my @groups = sort(keys(%curr_groups));
 9975:     my $allroles = [];
 9976:     my $rolehash;
 9977:     my $accesshash = {
 9978:                      active => 'Currently has access',
 9979:                      future => 'Will have future access',
 9980:                      previous => 'Previously had access',
 9981:                   };
 9982:     if ($needroles) {
 9983:         $rolehash = {'all' => 'all'};
 9984:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9985: 	if (&Apache::lonnet::error(%user_roles)) {
 9986: 	    undef(%user_roles);
 9987: 	}
 9988:         foreach my $item (keys(%user_roles)) {
 9989:             my ($role)=split(/\:/,$item,2);
 9990:             if ($role eq 'cr') { next; }
 9991:             if ($role =~ /^cr/) {
 9992:                 $$rolehash{$role} = (split('/',$role))[3];
 9993:             } else {
 9994:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 9995:             }
 9996:         }
 9997:         foreach my $key (sort(keys(%{$rolehash}))) {
 9998:             push(@{$allroles},$key);
 9999:         }
10000:         push (@{$allroles},'st');
10001:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
10002:     }
10003:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
10004: }
10005: 
10006: sub user_picker {
10007:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
10008:     my $currdom = $dom;
10009:     my @alldoms = &Apache::lonnet::all_domains();
10010:     if (@alldoms == 1) {
10011:         my %domsrch = &Apache::lonnet::get_dom('configuration',
10012:                                                ['directorysrch'],$alldoms[0]);
10013:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
10014:         my $showdom = $domdesc;
10015:         if ($showdom eq '') {
10016:             $showdom = $dom;
10017:         }
10018:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
10019:             if ((!$domsrch{'directorysrch'}{'available'}) &&
10020:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
10021:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
10022:             }
10023:         }
10024:     }
10025:     my %curr_selected = (
10026:                         srchin => 'dom',
10027:                         srchby => 'lastname',
10028:                       );
10029:     my $srchterm;
10030:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
10031:         if ($srch->{'srchby'} ne '') {
10032:             $curr_selected{'srchby'} = $srch->{'srchby'};
10033:         }
10034:         if ($srch->{'srchin'} ne '') {
10035:             $curr_selected{'srchin'} = $srch->{'srchin'};
10036:         }
10037:         if ($srch->{'srchtype'} ne '') {
10038:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
10039:         }
10040:         if ($srch->{'srchdomain'} ne '') {
10041:             $currdom = $srch->{'srchdomain'};
10042:         }
10043:         $srchterm = $srch->{'srchterm'};
10044:     }
10045:     my %html_lt=&Apache::lonlocal::texthash(
10046:                     'usr'       => 'Search criteria',
10047:                     'doma'      => 'Domain/institution to search',
10048:                     'uname'     => 'username',
10049:                     'lastname'  => 'last name',
10050:                     'lastfirst' => 'last name, first name',
10051:                     'crs'       => 'in this course',
10052:                     'dom'       => 'in selected LON-CAPA domain', 
10053:                     'alc'       => 'all LON-CAPA',
10054:                     'instd'     => 'in institutional directory for selected domain',
10055:                     'exact'     => 'is',
10056:                     'contains'  => 'contains',
10057:                     'begins'    => 'begins with',
10058:                                        );
10059:     my %js_lt=&Apache::lonlocal::texthash(
10060:                     'youm'      => "You must include some text to search for.",
10061:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
10062:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
10063:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
10064:                     'ymcd'      => "You must choose a domain when using a domain search.",
10065:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
10066:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
10067:                      'thfo'     => "The following need to be corrected before the search can be run:",
10068:                                        );
10069:     &html_escape(\%html_lt);
10070:     &js_escape(\%js_lt);
10071:     my $domform;
10072:     my $allow_blank = 1;
10073:     if ($fixeddom) {
10074:         $allow_blank = 0;
10075:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
10076:     } else {
10077:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1);
10078:     }
10079:     my $srchinsel = ' <select name="srchin">';
10080: 
10081:     my @srchins = ('crs','dom','alc','instd');
10082: 
10083:     foreach my $option (@srchins) {
10084:         # FIXME 'alc' option unavailable until 
10085:         #       loncreateuser::print_user_query_page()
10086:         #       has been completed.
10087:         next if ($option eq 'alc');
10088:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
10089:         next if ($option eq 'crs' && !$env{'request.course.id'});
10090:         next if (($option eq 'instd') && ($noinstd));
10091:         if ($curr_selected{'srchin'} eq $option) {
10092:             $srchinsel .= ' 
10093:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10094:         } else {
10095:             $srchinsel .= '
10096:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10097:         }
10098:     }
10099:     $srchinsel .= "\n  </select>\n";
10100: 
10101:     my $srchbysel =  ' <select name="srchby">';
10102:     foreach my $option ('lastname','lastfirst','uname') {
10103:         if ($curr_selected{'srchby'} eq $option) {
10104:             $srchbysel .= '
10105:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10106:         } else {
10107:             $srchbysel .= '
10108:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10109:          }
10110:     }
10111:     $srchbysel .= "\n  </select>\n";
10112: 
10113:     my $srchtypesel = ' <select name="srchtype">';
10114:     foreach my $option ('begins','contains','exact') {
10115:         if ($curr_selected{'srchtype'} eq $option) {
10116:             $srchtypesel .= '
10117:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10118:         } else {
10119:             $srchtypesel .= '
10120:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10121:         }
10122:     }
10123:     $srchtypesel .= "\n  </select>\n";
10124: 
10125:     my ($newuserscript,$new_user_create);
10126:     my $context_dom = $env{'request.role.domain'};
10127:     if ($context eq 'requestcrs') {
10128:         if ($env{'form.coursedom'} ne '') { 
10129:             $context_dom = $env{'form.coursedom'};
10130:         }
10131:     }
10132:     if ($forcenewuser) {
10133:         if (ref($srch) eq 'HASH') {
10134:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
10135:                 if ($cancreate) {
10136:                     $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>';
10137:                 } else {
10138:                     my $helplink = 'javascript:helpMenu('."'display'".')';
10139:                     my %usertypetext = (
10140:                         official   => 'institutional',
10141:                         unofficial => 'non-institutional',
10142:                     );
10143:                     $new_user_create = '<p class="LC_warning">'
10144:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
10145:                                       .' '
10146:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
10147:                                           ,'<a href="'.$helplink.'">','</a>')
10148:                                       .'</p><br />';
10149:                 }
10150:             }
10151:         }
10152: 
10153:         $newuserscript = <<"ENDSCRIPT";
10154: 
10155: function setSearch(createnew,callingForm) {
10156:     if (createnew == 1) {
10157:         for (var i=0; i<callingForm.srchby.length; i++) {
10158:             if (callingForm.srchby.options[i].value == 'uname') {
10159:                 callingForm.srchby.selectedIndex = i;
10160:             }
10161:         }
10162:         for (var i=0; i<callingForm.srchin.length; i++) {
10163:             if ( callingForm.srchin.options[i].value == 'dom') {
10164: 		callingForm.srchin.selectedIndex = i;
10165:             }
10166:         }
10167:         for (var i=0; i<callingForm.srchtype.length; i++) {
10168:             if (callingForm.srchtype.options[i].value == 'exact') {
10169:                 callingForm.srchtype.selectedIndex = i;
10170:             }
10171:         }
10172:         for (var i=0; i<callingForm.srchdomain.length; i++) {
10173:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
10174:                 callingForm.srchdomain.selectedIndex = i;
10175:             }
10176:         }
10177:     }
10178: }
10179: ENDSCRIPT
10180: 
10181:     }
10182: 
10183:     my $output = <<"END_BLOCK";
10184: <script type="text/javascript">
10185: // <![CDATA[
10186: function validateEntry(callingForm) {
10187: 
10188:     var checkok = 1;
10189:     var srchin;
10190:     for (var i=0; i<callingForm.srchin.length; i++) {
10191: 	if ( callingForm.srchin[i].checked ) {
10192: 	    srchin = callingForm.srchin[i].value;
10193: 	}
10194:     }
10195: 
10196:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
10197:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
10198:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
10199:     var srchterm =  callingForm.srchterm.value;
10200:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
10201:     var msg = "";
10202: 
10203:     if (srchterm == "") {
10204:         checkok = 0;
10205:         msg += "$js_lt{'youm'}\\n";
10206:     }
10207: 
10208:     if (srchtype== 'begins') {
10209:         if (srchterm.length < 2) {
10210:             checkok = 0;
10211:             msg += "$js_lt{'thte'}\\n";
10212:         }
10213:     }
10214: 
10215:     if (srchtype== 'contains') {
10216:         if (srchterm.length < 3) {
10217:             checkok = 0;
10218:             msg += "$js_lt{'thet'}\\n";
10219:         }
10220:     }
10221:     if (srchin == 'instd') {
10222:         if (srchdomain == '') {
10223:             checkok = 0;
10224:             msg += "$js_lt{'yomc'}\\n";
10225:         }
10226:     }
10227:     if (srchin == 'dom') {
10228:         if (srchdomain == '') {
10229:             checkok = 0;
10230:             msg += "$js_lt{'ymcd'}\\n";
10231:         }
10232:     }
10233:     if (srchby == 'lastfirst') {
10234:         if (srchterm.indexOf(",") == -1) {
10235:             checkok = 0;
10236:             msg += "$js_lt{'whus'}\\n";
10237:         }
10238:         if (srchterm.indexOf(",") == srchterm.length -1) {
10239:             checkok = 0;
10240:             msg += "$js_lt{'whse'}\\n";
10241:         }
10242:     }
10243:     if (checkok == 0) {
10244:         alert("$js_lt{'thfo'}\\n"+msg);
10245:         return;
10246:     }
10247:     if (checkok == 1) {
10248:         callingForm.submit();
10249:     }
10250: }
10251: 
10252: $newuserscript
10253: 
10254: // ]]>
10255: </script>
10256: 
10257: $new_user_create
10258: 
10259: END_BLOCK
10260: 
10261:     $output .= &Apache::lonhtmlcommon::start_pick_box().
10262:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
10263:                $domform.
10264:                &Apache::lonhtmlcommon::row_closure().
10265:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
10266:                $srchbysel.
10267:                $srchtypesel. 
10268:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
10269:                $srchinsel.
10270:                &Apache::lonhtmlcommon::row_closure(1). 
10271:                &Apache::lonhtmlcommon::end_pick_box().
10272:                '<br />';
10273:     return ($output,1);
10274: }
10275: 
10276: sub user_rule_check {
10277:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
10278:     my ($response,%inst_response);
10279:     if (ref($usershash) eq 'HASH') {
10280:         if (keys(%{$usershash}) > 1) {
10281:             my (%by_username,%by_id,%userdoms);
10282:             my $checkid;
10283:             if (ref($checks) eq 'HASH') {
10284:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
10285:                     $checkid = 1;
10286:                 }
10287:             }
10288:             foreach my $user (keys(%{$usershash})) {
10289:                 my ($uname,$udom) = split(/:/,$user);
10290:                 if ($checkid) {
10291:                     if (ref($usershash->{$user}) eq 'HASH') {
10292:                         if ($usershash->{$user}->{'id'} ne '') {
10293:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
10294:                             $userdoms{$udom} = 1;
10295:                             if (ref($inst_results) eq 'HASH') {
10296:                                 $inst_results->{$uname.':'.$udom} = {};
10297:                             }
10298:                         }
10299:                     }
10300:                 } else {
10301:                     $by_username{$udom}{$uname} = 1;
10302:                     $userdoms{$udom} = 1;
10303:                     if (ref($inst_results) eq 'HASH') {
10304:                         $inst_results->{$uname.':'.$udom} = {};
10305:                     }
10306:                 }
10307:             }
10308:             foreach my $udom (keys(%userdoms)) {
10309:                 if (!$got_rules->{$udom}) {
10310:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
10311:                                                              ['usercreation'],$udom);
10312:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
10313:                         foreach my $item ('username','id') {
10314:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10315:                                 $$curr_rules{$udom}{$item} =
10316:                                     $domconfig{'usercreation'}{$item.'_rule'};
10317:                             }
10318:                         }
10319:                     }
10320:                     $got_rules->{$udom} = 1;
10321:                 }
10322:             }
10323:             if ($checkid) {
10324:                 foreach my $udom (keys(%by_id)) {
10325:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
10326:                     if ($outcome eq 'ok') {
10327:                         foreach my $id (keys(%{$by_id{$udom}})) {
10328:                             my $uname = $by_id{$udom}{$id};
10329:                             $inst_response{$uname.':'.$udom} = $outcome;
10330:                         }
10331:                         if (ref($results) eq 'HASH') {
10332:                             foreach my $uname (keys(%{$results})) {
10333:                                 if (exists($inst_response{$uname.':'.$udom})) {
10334:                                     $inst_response{$uname.':'.$udom} = $outcome;
10335:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
10336:                                 }
10337:                             }
10338:                         }
10339:                     }
10340:                 }
10341:             } else {
10342:                 foreach my $udom (keys(%by_username)) {
10343:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
10344:                     if ($outcome eq 'ok') {
10345:                         foreach my $uname (keys(%{$by_username{$udom}})) {
10346:                             $inst_response{$uname.':'.$udom} = $outcome;
10347:                         }
10348:                         if (ref($results) eq 'HASH') {
10349:                             foreach my $uname (keys(%{$results})) {
10350:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
10351:                             }
10352:                         }
10353:                     }
10354:                 }
10355:             }
10356:         } elsif (keys(%{$usershash}) == 1) {
10357:             my $user = (keys(%{$usershash}))[0];
10358:             my ($uname,$udom) = split(/:/,$user);
10359:             if (($udom ne '') && ($uname ne '')) {
10360:                 if (ref($usershash->{$user}) eq 'HASH') {
10361:                     if (ref($checks) eq 'HASH') {
10362:                         if (defined($checks->{'username'})) {
10363:                             ($inst_response{$user},%{$inst_results->{$user}}) =
10364:                                 &Apache::lonnet::get_instuser($udom,$uname);
10365:                         } elsif (defined($checks->{'id'})) {
10366:                             if ($usershash->{$user}->{'id'} ne '') {
10367:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
10368:                                     &Apache::lonnet::get_instuser($udom,undef,
10369:                                                                   $usershash->{$user}->{'id'});
10370:                             } else {
10371:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
10372:                                     &Apache::lonnet::get_instuser($udom,$uname);
10373:                             }
10374:                         }
10375:                     } else {
10376:                        ($inst_response{$user},%{$inst_results->{$user}}) =
10377:                             &Apache::lonnet::get_instuser($udom,$uname);
10378:                        return;
10379:                     }
10380:                     if (!$got_rules->{$udom}) {
10381:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
10382:                                                                  ['usercreation'],$udom);
10383:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
10384:                             foreach my $item ('username','id') {
10385:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10386:                                    $$curr_rules{$udom}{$item} =
10387:                                        $domconfig{'usercreation'}{$item.'_rule'};
10388:                                 }
10389:                             }
10390:                         }
10391:                         $got_rules->{$udom} = 1;
10392:                     }
10393:                 }
10394:             } else {
10395:                 return;
10396:             }
10397:         } else {
10398:             return;
10399:         }
10400:         foreach my $user (keys(%{$usershash})) {
10401:             my ($uname,$udom) = split(/:/,$user);
10402:             next if (($udom eq '') || ($uname eq ''));
10403:             my $id;
10404:             if (ref($inst_results) eq 'HASH') {
10405:                 if (ref($inst_results->{$user}) eq 'HASH') {
10406:                     $id = $inst_results->{$user}->{'id'};
10407:                 }
10408:             }
10409:             if ($id eq '') {
10410:                 if (ref($usershash->{$user})) {
10411:                     $id = $usershash->{$user}->{'id'};
10412:                 }
10413:             }
10414:             foreach my $item (keys(%{$checks})) {
10415:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
10416:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
10417:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
10418:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
10419:                                                                              $$curr_rules{$udom}{$item});
10420:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
10421:                                 if ($rule_check{$rule}) {
10422:                                     $$rulematch{$user}{$item} = $rule;
10423:                                     if ($inst_response{$user} eq 'ok') {
10424:                                         if (ref($inst_results) eq 'HASH') {
10425:                                             if (ref($inst_results->{$user}) eq 'HASH') {
10426:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
10427:                                                     $$alerts{$item}{$udom}{$uname} = 1;
10428:                                                 } elsif ($item eq 'id') {
10429:                                                     if ($inst_results->{$user}->{'id'} eq '') {
10430:                                                         $$alerts{$item}{$udom}{$uname} = 1;
10431:                                                     }
10432:                                                 }
10433:                                             }
10434:                                         }
10435:                                     }
10436:                                     last;
10437:                                 }
10438:                             }
10439:                         }
10440:                     }
10441:                 }
10442:             }
10443:         }
10444:     }
10445:     return;
10446: }
10447: 
10448: sub user_rule_formats {
10449:     my ($domain,$domdesc,$curr_rules,$check) = @_;
10450:     my %text = ( 
10451:                  'username' => 'Usernames',
10452:                  'id'       => 'IDs',
10453:                );
10454:     my $output;
10455:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
10456:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
10457:         if (@{$ruleorder} > 0) {
10458:             $output = '<br />'.
10459:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
10460:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
10461:                       ' <ul>';
10462:             foreach my $rule (@{$ruleorder}) {
10463:                 if (ref($curr_rules) eq 'ARRAY') {
10464:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
10465:                         if (ref($rules->{$rule}) eq 'HASH') {
10466:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
10467:                                         $rules->{$rule}{'desc'}.'</li>';
10468:                         }
10469:                     }
10470:                 }
10471:             }
10472:             $output .= '</ul>';
10473:         }
10474:     }
10475:     return $output;
10476: }
10477: 
10478: sub instrule_disallow_msg {
10479:     my ($checkitem,$domdesc,$count,$mode) = @_;
10480:     my $response;
10481:     my %text = (
10482:                   item   => 'username',
10483:                   items  => 'usernames',
10484:                   match  => 'matches',
10485:                   do     => 'does',
10486:                   action => 'a username',
10487:                   one    => 'one',
10488:                );
10489:     if ($count > 1) {
10490:         $text{'item'} = 'usernames';
10491:         $text{'match'} ='match';
10492:         $text{'do'} = 'do';
10493:         $text{'action'} = 'usernames',
10494:         $text{'one'} = 'ones';
10495:     }
10496:     if ($checkitem eq 'id') {
10497:         $text{'items'} = 'IDs';
10498:         $text{'item'} = 'ID';
10499:         $text{'action'} = 'an ID';
10500:         if ($count > 1) {
10501:             $text{'item'} = 'IDs';
10502:             $text{'action'} = 'IDs';
10503:         }
10504:     }
10505:     $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 />';
10506:     if ($mode eq 'upload') {
10507:         if ($checkitem eq 'username') {
10508:             $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'}.");
10509:         } elsif ($checkitem eq 'id') {
10510:             $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.");
10511:         }
10512:     } elsif ($mode eq 'selfcreate') {
10513:         if ($checkitem eq 'id') {
10514:             $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.");
10515:         }
10516:     } else {
10517:         if ($checkitem eq 'username') {
10518:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
10519:         } elsif ($checkitem eq 'id') {
10520:             $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.");
10521:         }
10522:     }
10523:     return $response;
10524: }
10525: 
10526: sub personal_data_fieldtitles {
10527:     my %fieldtitles = &Apache::lonlocal::texthash (
10528:                         id => 'Student/Employee ID',
10529:                         permanentemail => 'E-mail address',
10530:                         lastname => 'Last Name',
10531:                         firstname => 'First Name',
10532:                         middlename => 'Middle Name',
10533:                         generation => 'Generation',
10534:                         gen => 'Generation',
10535:                         inststatus => 'Affiliation',
10536:                    );
10537:     return %fieldtitles;
10538: }
10539: 
10540: sub sorted_inst_types {
10541:     my ($dom) = @_;
10542:     my ($usertypes,$order);
10543:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
10544:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
10545:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
10546:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
10547:     } else {
10548:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
10549:     }
10550:     my $othertitle = &mt('All users');
10551:     if ($env{'request.course.id'}) {
10552:         $othertitle  = &mt('Any users');
10553:     }
10554:     my @types;
10555:     if (ref($order) eq 'ARRAY') {
10556:         @types = @{$order};
10557:     }
10558:     if (@types == 0) {
10559:         if (ref($usertypes) eq 'HASH') {
10560:             @types = sort(keys(%{$usertypes}));
10561:         }
10562:     }
10563:     if (keys(%{$usertypes}) > 0) {
10564:         $othertitle = &mt('Other users');
10565:     }
10566:     return ($othertitle,$usertypes,\@types);
10567: }
10568: 
10569: sub get_institutional_codes {
10570:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
10571: # Get complete list of course sections to update
10572:     my @currsections = ();
10573:     my @currxlists = ();
10574:     my (%unclutteredsec,%unclutteredlcsec);
10575:     my $coursecode = $$settings{'internal.coursecode'};
10576:     my $crskey = $crs.':'.$coursecode;
10577:     @{$unclutteredsec{$crskey}} = ();
10578:     @{$unclutteredlcsec{$crskey}} = ();
10579: 
10580:     if ($$settings{'internal.sectionnums'} ne '') {
10581:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
10582:     }
10583: 
10584:     if ($$settings{'internal.crosslistings'} ne '') {
10585:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
10586:     }
10587: 
10588:     if (@currxlists > 0) {
10589:         foreach my $xl (@currxlists) {
10590:             if ($xl =~ /^([^:]+):(\w*)$/) {
10591:                 unless (grep/^$1$/,@{$allcourses}) {
10592:                     push(@{$allcourses},$1);
10593:                     $$LC_code{$1} = $2;
10594:                 }
10595:             }
10596:         }
10597:     }
10598: 
10599:     if (@currsections > 0) {
10600:         foreach my $sec (@currsections) {
10601:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
10602:                 my $instsec = $1;
10603:                 my $lc_sec = $2;
10604:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
10605:                     push(@{$unclutteredsec{$crskey}},$instsec);
10606:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
10607:                 }
10608:             }
10609:         }
10610:     }
10611: 
10612:     if (@{$unclutteredsec{$crskey}} > 0) {
10613:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
10614:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
10615:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
10616:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
10617:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
10618:                     push(@{$allcourses},$sec);
10619:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
10620:                 }
10621:             }
10622:         }
10623:     }
10624:     return;
10625: }
10626: 
10627: sub get_standard_codeitems {
10628:     return ('Year','Semester','Department','Number','Section');
10629: }
10630: 
10631: =pod
10632: 
10633: =head1 Slot Helpers
10634: 
10635: =over 4
10636: 
10637: =item * sorted_slots()
10638: 
10639: Sorts an array of slot names in order of an optional sort key,
10640: default sort is by slot start time (earliest first). 
10641: 
10642: Inputs:
10643: 
10644: =over 4
10645: 
10646: slotsarr  - Reference to array of unsorted slot names.
10647: 
10648: slots     - Reference to hash of hash, where outer hash keys are slot names.
10649: 
10650: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
10651: 
10652: =back
10653: 
10654: Returns:
10655: 
10656: =over 4
10657: 
10658: sorted   - An array of slot names sorted by a specified sort key 
10659:            (default sort key is start time of the slot).
10660: 
10661: =back
10662: 
10663: =cut
10664: 
10665: 
10666: sub sorted_slots {
10667:     my ($slotsarr,$slots,$sortkey) = @_;
10668:     if ($sortkey eq '') {
10669:         $sortkey = 'starttime';
10670:     }
10671:     my @sorted;
10672:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
10673:         @sorted =
10674:             sort {
10675:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
10676:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
10677:                      }
10678:                      if (ref($slots->{$a})) { return -1;}
10679:                      if (ref($slots->{$b})) { return 1;}
10680:                      return 0;
10681:                  } @{$slotsarr};
10682:     }
10683:     return @sorted;
10684: }
10685: 
10686: =pod
10687: 
10688: =item * get_future_slots()
10689: 
10690: Inputs:
10691: 
10692: =over 4
10693: 
10694: cnum - course number
10695: 
10696: cdom - course domain
10697: 
10698: now - current UNIX time
10699: 
10700: symb - optional symb
10701: 
10702: =back
10703: 
10704: Returns:
10705: 
10706: =over 4
10707: 
10708: sorted_reservable - ref to array of student_schedulable slots currently 
10709:                     reservable, ordered by end date of reservation period.
10710: 
10711: reservable_now - ref to hash of student_schedulable slots currently
10712:                  reservable.
10713: 
10714:     Keys in inner hash are:
10715:     (a) symb: either blank or symb to which slot use is restricted.
10716:     (b) endreserve: end date of reservation period.
10717:     (c) uniqueperiod: start,end dates when slot is to be uniquely
10718:         selected.
10719: 
10720: sorted_future - ref to array of student_schedulable slots reservable in
10721:                 the future, ordered by start date of reservation period.
10722: 
10723: future_reservable - ref to hash of student_schedulable slots reservable
10724:                     in the future.
10725: 
10726:     Keys in inner hash are:
10727:     (a) symb: either blank or symb to which slot use is restricted.
10728:     (b) startreserve:  start date of reservation period.
10729:     (c) uniqueperiod: start,end dates when slot is to be uniquely
10730:         selected.
10731: 
10732: =back
10733: 
10734: =cut
10735: 
10736: sub get_future_slots {
10737:     my ($cnum,$cdom,$now,$symb) = @_;
10738:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
10739:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
10740:     foreach my $slot (keys(%slots)) {
10741:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
10742:         if ($symb) {
10743:             next if (($slots{$slot}->{'symb'} ne '') && 
10744:                      ($slots{$slot}->{'symb'} ne $symb));
10745:         }
10746:         if (($slots{$slot}->{'starttime'} > $now) &&
10747:             ($slots{$slot}->{'endtime'} > $now)) {
10748:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
10749:                 my $userallowed = 0;
10750:                 if ($slots{$slot}->{'allowedsections'}) {
10751:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
10752:                     if (!defined($env{'request.role.sec'})
10753:                         && grep(/^No section assigned$/,@allowed_sec)) {
10754:                         $userallowed=1;
10755:                     } else {
10756:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
10757:                             $userallowed=1;
10758:                         }
10759:                     }
10760:                     unless ($userallowed) {
10761:                         if (defined($env{'request.course.groups'})) {
10762:                             my @groups = split(/:/,$env{'request.course.groups'});
10763:                             foreach my $group (@groups) {
10764:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
10765:                                     $userallowed=1;
10766:                                     last;
10767:                                 }
10768:                             }
10769:                         }
10770:                     }
10771:                 }
10772:                 if ($slots{$slot}->{'allowedusers'}) {
10773:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
10774:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
10775:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
10776:                         $userallowed = 1;
10777:                     }
10778:                 }
10779:                 next unless($userallowed);
10780:             }
10781:             my $startreserve = $slots{$slot}->{'startreserve'};
10782:             my $endreserve = $slots{$slot}->{'endreserve'};
10783:             my $symb = $slots{$slot}->{'symb'};
10784:             my $uniqueperiod;
10785:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
10786:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
10787:             }
10788:             if (($startreserve < $now) &&
10789:                 (!$endreserve || $endreserve > $now)) {
10790:                 my $lastres = $endreserve;
10791:                 if (!$lastres) {
10792:                     $lastres = $slots{$slot}->{'starttime'};
10793:                 }
10794:                 $reservable_now{$slot} = {
10795:                                            symb       => $symb,
10796:                                            endreserve => $lastres,
10797:                                            uniqueperiod => $uniqueperiod,   
10798:                                          };
10799:             } elsif (($startreserve > $now) &&
10800:                      (!$endreserve || $endreserve > $startreserve)) {
10801:                 $future_reservable{$slot} = {
10802:                                               symb         => $symb,
10803:                                               startreserve => $startreserve,
10804:                                               uniqueperiod => $uniqueperiod,
10805:                                             };
10806:             }
10807:         }
10808:     }
10809:     my @unsorted_reservable = keys(%reservable_now);
10810:     if (@unsorted_reservable > 0) {
10811:         @sorted_reservable = 
10812:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
10813:     }
10814:     my @unsorted_future = keys(%future_reservable);
10815:     if (@unsorted_future > 0) {
10816:         @sorted_future =
10817:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
10818:     }
10819:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
10820: }
10821: 
10822: =pod
10823: 
10824: =back
10825: 
10826: =head1 HTTP Helpers
10827: 
10828: =over 4
10829: 
10830: =item * &get_unprocessed_cgi($query,$possible_names)
10831: 
10832: Modify the %env hash to contain unprocessed CGI form parameters held in
10833: $query.  The parameters listed in $possible_names (an array reference),
10834: will be set in $env{'form.name'} if they do not already exist.
10835: 
10836: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
10837: $possible_names is an ref to an array of form element names.  As an example:
10838: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
10839: will result in $env{'form.uname'} and $env{'form.udom'} being set.
10840: 
10841: =cut
10842: 
10843: sub get_unprocessed_cgi {
10844:   my ($query,$possible_names)= @_;
10845:   # $Apache::lonxml::debug=1;
10846:   foreach my $pair (split(/&/,$query)) {
10847:     my ($name, $value) = split(/=/,$pair);
10848:     $name = &unescape($name);
10849:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
10850:       $value =~ tr/+/ /;
10851:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
10852:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
10853:     }
10854:   }
10855: }
10856: 
10857: =pod
10858: 
10859: =item * &cacheheader() 
10860: 
10861: returns cache-controlling header code
10862: 
10863: =cut
10864: 
10865: sub cacheheader {
10866:     unless ($env{'request.method'} eq 'GET') { return ''; }
10867:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
10868:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
10869:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
10870:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
10871:     return $output;
10872: }
10873: 
10874: =pod
10875: 
10876: =item * &no_cache($r) 
10877: 
10878: specifies header code to not have cache
10879: 
10880: =cut
10881: 
10882: sub no_cache {
10883:     my ($r) = @_;
10884:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
10885: 	$env{'request.method'} ne 'GET') { return ''; }
10886:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
10887:     $r->no_cache(1);
10888:     $r->header_out("Expires" => $date);
10889:     $r->header_out("Pragma" => "no-cache");
10890: }
10891: 
10892: sub content_type {
10893:     my ($r,$type,$charset) = @_;
10894:     if ($r) {
10895: 	#  Note that printout.pl calls this with undef for $r.
10896: 	&no_cache($r);
10897:     }
10898:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
10899:     unless ($charset) {
10900: 	$charset=&Apache::lonlocal::current_encoding;
10901:     }
10902:     if ($charset) { $type.='; charset='.$charset; }
10903:     if ($r) {
10904: 	$r->content_type($type);
10905:     } else {
10906: 	print("Content-type: $type\n\n");
10907:     }
10908: }
10909: 
10910: =pod
10911: 
10912: =item * &add_to_env($name,$value) 
10913: 
10914: adds $name to the %env hash with value
10915: $value, if $name already exists, the entry is converted to an array
10916: reference and $value is added to the array.
10917: 
10918: =cut
10919: 
10920: sub add_to_env {
10921:   my ($name,$value)=@_;
10922:   if (defined($env{$name})) {
10923:     if (ref($env{$name})) {
10924:       #already have multiple values
10925:       push(@{ $env{$name} },$value);
10926:     } else {
10927:       #first time seeing multiple values, convert hash entry to an arrayref
10928:       my $first=$env{$name};
10929:       undef($env{$name});
10930:       push(@{ $env{$name} },$first,$value);
10931:     }
10932:   } else {
10933:     $env{$name}=$value;
10934:   }
10935: }
10936: 
10937: =pod
10938: 
10939: =item * &get_env_multiple($name) 
10940: 
10941: gets $name from the %env hash, it seemlessly handles the cases where multiple
10942: values may be defined and end up as an array ref.
10943: 
10944: returns an array of values
10945: 
10946: =cut
10947: 
10948: sub get_env_multiple {
10949:     my ($name) = @_;
10950:     my @values;
10951:     if (defined($env{$name})) {
10952:         # exists is it an array
10953:         if (ref($env{$name})) {
10954:             @values=@{ $env{$name} };
10955:         } else {
10956:             $values[0]=$env{$name};
10957:         }
10958:     }
10959:     return(@values);
10960: }
10961: 
10962: sub ask_for_embedded_content {
10963:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
10964:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
10965:         %currsubfile,%unused,$rem);
10966:     my $counter = 0;
10967:     my $numnew = 0;
10968:     my $numremref = 0;
10969:     my $numinvalid = 0;
10970:     my $numpathchg = 0;
10971:     my $numexisting = 0;
10972:     my $numunused = 0;
10973:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
10974:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
10975:     my $heading = &mt('Upload embedded files');
10976:     my $buttontext = &mt('Upload');
10977: 
10978:     if ($env{'request.course.id'}) {
10979:         if ($actionurl eq '/adm/dependencies') {
10980:             $navmap = Apache::lonnavmaps::navmap->new();
10981:         }
10982:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10983:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10984:     }
10985:     if (($actionurl eq '/adm/portfolio') ||
10986:         ($actionurl eq '/adm/coursegrp_portfolio')) {
10987:         my $current_path='/';
10988:         if ($env{'form.currentpath'}) {
10989:             $current_path = $env{'form.currentpath'};
10990:         }
10991:         if ($actionurl eq '/adm/coursegrp_portfolio') {
10992:             $udom = $cdom;
10993:             $uname = $cnum;
10994:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
10995:         } else {
10996:             $udom = $env{'user.domain'};
10997:             $uname = $env{'user.name'};
10998:             $url = '/userfiles/portfolio';
10999:         }
11000:         $toplevel = $url.'/';
11001:         $url .= $current_path;
11002:         $getpropath = 1;
11003:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
11004:              ($actionurl eq '/adm/imsimport')) { 
11005:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
11006:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
11007:         $toplevel = $url;
11008:         if ($rest ne '') {
11009:             $url .= $rest;
11010:         }
11011:     } elsif ($actionurl eq '/adm/coursedocs') {
11012:         if (ref($args) eq 'HASH') {
11013:             $url = $args->{'docs_url'};
11014:             $toplevel = $url;
11015:             if ($args->{'context'} eq 'paste') {
11016:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
11017:                 ($path) =
11018:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
11019:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
11020:                 $fileloc =~ s{^/}{};
11021:             }
11022:         }
11023:     } elsif ($actionurl eq '/adm/dependencies') {
11024:         if ($env{'request.course.id'} ne '') {
11025:             if (ref($args) eq 'HASH') {
11026:                 $url = $args->{'docs_url'};
11027:                 $title = $args->{'docs_title'};
11028:                 $toplevel = $url;
11029:                 unless ($toplevel =~ m{^/}) {
11030:                     $toplevel = "/$url";
11031:                 }
11032:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
11033:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
11034:                     $path = $1;
11035:                 } else {
11036:                     ($path) =
11037:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
11038:                 }
11039:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
11040:                     $fileloc = $toplevel;
11041:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
11042:                     my ($udom,$uname,$fname) =
11043:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
11044:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
11045:                 } else {
11046:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
11047:                 }
11048:                 $fileloc =~ s{^/}{};
11049:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
11050:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
11051:             }
11052:         }
11053:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
11054:         $udom = $cdom;
11055:         $uname = $cnum;
11056:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
11057:         $toplevel = $url;
11058:         $path = $url;
11059:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
11060:         $fileloc =~ s{^/}{};
11061:     }
11062:     foreach my $file (keys(%{$allfiles})) {
11063:         my $embed_file;
11064:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
11065:             $embed_file = $1;
11066:         } else {
11067:             $embed_file = $file;
11068:         }
11069:         my ($absolutepath,$cleaned_file);
11070:         if ($embed_file =~ m{^\w+://}) {
11071:             $cleaned_file = $embed_file;
11072:             $newfiles{$cleaned_file} = 1;
11073:             $mapping{$cleaned_file} = $embed_file;
11074:         } else {
11075:             $cleaned_file = &clean_path($embed_file);
11076:             if ($embed_file =~ m{^/}) {
11077:                 $absolutepath = $embed_file;
11078:             }
11079:             if ($cleaned_file =~ m{/}) {
11080:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
11081:                 $path = &check_for_traversal($path,$url,$toplevel);
11082:                 my $item = $fname;
11083:                 if ($path ne '') {
11084:                     $item = $path.'/'.$fname;
11085:                     $subdependencies{$path}{$fname} = 1;
11086:                 } else {
11087:                     $dependencies{$item} = 1;
11088:                 }
11089:                 if ($absolutepath) {
11090:                     $mapping{$item} = $absolutepath;
11091:                 } else {
11092:                     $mapping{$item} = $embed_file;
11093:                 }
11094:             } else {
11095:                 $dependencies{$embed_file} = 1;
11096:                 if ($absolutepath) {
11097:                     $mapping{$cleaned_file} = $absolutepath;
11098:                 } else {
11099:                     $mapping{$cleaned_file} = $embed_file;
11100:                 }
11101:             }
11102:         }
11103:     }
11104:     my $dirptr = 16384;
11105:     foreach my $path (keys(%subdependencies)) {
11106:         $currsubfile{$path} = {};
11107:         if (($actionurl eq '/adm/portfolio') ||
11108:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
11109:             my ($sublistref,$listerror) =
11110:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
11111:             if (ref($sublistref) eq 'ARRAY') {
11112:                 foreach my $line (@{$sublistref}) {
11113:                     my ($file_name,$rest) = split(/\&/,$line,2);
11114:                     $currsubfile{$path}{$file_name} = 1;
11115:                 }
11116:             }
11117:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11118:             if (opendir(my $dir,$url.'/'.$path)) {
11119:                 my @subdir_list = grep(!/^\./,readdir($dir));
11120:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
11121:             }
11122:         } elsif (($actionurl eq '/adm/dependencies') ||
11123:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11124:                   ($args->{'context'} eq 'paste')) ||
11125:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
11126:             if ($env{'request.course.id'} ne '') {
11127:                 my $dir;
11128:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
11129:                     $dir = $fileloc;
11130:                 } else {
11131:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
11132:                 }
11133:                 if ($dir ne '') {
11134:                     my ($sublistref,$listerror) =
11135:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
11136:                     if (ref($sublistref) eq 'ARRAY') {
11137:                         foreach my $line (@{$sublistref}) {
11138:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
11139:                                 undef,$mtime)=split(/\&/,$line,12);
11140:                             unless (($testdir&$dirptr) ||
11141:                                     ($file_name =~ /^\.\.?$/)) {
11142:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
11143:                             }
11144:                         }
11145:                     }
11146:                 }
11147:             }
11148:         }
11149:         foreach my $file (keys(%{$subdependencies{$path}})) {
11150:             if (exists($currsubfile{$path}{$file})) {
11151:                 my $item = $path.'/'.$file;
11152:                 unless ($mapping{$item} eq $item) {
11153:                     $pathchanges{$item} = 1;
11154:                 }
11155:                 $existing{$item} = 1;
11156:                 $numexisting ++;
11157:             } else {
11158:                 $newfiles{$path.'/'.$file} = 1;
11159:             }
11160:         }
11161:         if ($actionurl eq '/adm/dependencies') {
11162:             foreach my $path (keys(%currsubfile)) {
11163:                 if (ref($currsubfile{$path}) eq 'HASH') {
11164:                     foreach my $file (keys(%{$currsubfile{$path}})) {
11165:                          unless ($subdependencies{$path}{$file}) {
11166:                              next if (($rem ne '') &&
11167:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
11168:                                        (ref($navmap) &&
11169:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
11170:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
11171:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
11172:                              $unused{$path.'/'.$file} = 1; 
11173:                          }
11174:                     }
11175:                 }
11176:             }
11177:         }
11178:     }
11179:     my %currfile;
11180:     if (($actionurl eq '/adm/portfolio') ||
11181:         ($actionurl eq '/adm/coursegrp_portfolio')) {
11182:         my ($dirlistref,$listerror) =
11183:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
11184:         if (ref($dirlistref) eq 'ARRAY') {
11185:             foreach my $line (@{$dirlistref}) {
11186:                 my ($file_name,$rest) = split(/\&/,$line,2);
11187:                 $currfile{$file_name} = 1;
11188:             }
11189:         }
11190:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11191:         if (opendir(my $dir,$url)) {
11192:             my @dir_list = grep(!/^\./,readdir($dir));
11193:             map {$currfile{$_} = 1;} @dir_list;
11194:         }
11195:     } elsif (($actionurl eq '/adm/dependencies') ||
11196:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11197:               ($args->{'context'} eq 'paste')) ||
11198:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
11199:         if ($env{'request.course.id'} ne '') {
11200:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
11201:             if ($dir ne '') {
11202:                 my ($dirlistref,$listerror) =
11203:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
11204:                 if (ref($dirlistref) eq 'ARRAY') {
11205:                     foreach my $line (@{$dirlistref}) {
11206:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
11207:                             $size,undef,$mtime)=split(/\&/,$line,12);
11208:                         unless (($testdir&$dirptr) ||
11209:                                 ($file_name =~ /^\.\.?$/)) {
11210:                             $currfile{$file_name} = [$size,$mtime];
11211:                         }
11212:                     }
11213:                 }
11214:             }
11215:         }
11216:     }
11217:     foreach my $file (keys(%dependencies)) {
11218:         if (exists($currfile{$file})) {
11219:             unless ($mapping{$file} eq $file) {
11220:                 $pathchanges{$file} = 1;
11221:             }
11222:             $existing{$file} = 1;
11223:             $numexisting ++;
11224:         } else {
11225:             $newfiles{$file} = 1;
11226:         }
11227:     }
11228:     foreach my $file (keys(%currfile)) {
11229:         unless (($file eq $filename) ||
11230:                 ($file eq $filename.'.bak') ||
11231:                 ($dependencies{$file})) {
11232:             if ($actionurl eq '/adm/dependencies') {
11233:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
11234:                     next if (($rem ne '') &&
11235:                              (($env{"httpref.$rem".$file} ne '') ||
11236:                               (ref($navmap) &&
11237:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
11238:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
11239:                                 ($navmap->getResourceByUrl($rem.$1)))))));
11240:                 }
11241:             }
11242:             $unused{$file} = 1;
11243:         }
11244:     }
11245:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11246:         ($args->{'context'} eq 'paste')) {
11247:         $counter = scalar(keys(%existing));
11248:         $numpathchg = scalar(keys(%pathchanges));
11249:         return ($output,$counter,$numpathchg,\%existing);
11250:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
11251:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
11252:         $counter = scalar(keys(%existing));
11253:         $numpathchg = scalar(keys(%pathchanges));
11254:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
11255:     }
11256:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
11257:         if ($actionurl eq '/adm/dependencies') {
11258:             next if ($embed_file =~ m{^\w+://});
11259:         }
11260:         $upload_output .= &start_data_table_row().
11261:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
11262:                           '<span class="LC_filename">'.$embed_file.'</span>';
11263:         unless ($mapping{$embed_file} eq $embed_file) {
11264:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
11265:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
11266:         }
11267:         $upload_output .= '</td>';
11268:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
11269:             $upload_output.='<td align="right">'.
11270:                             '<span class="LC_info LC_fontsize_medium">'.
11271:                             &mt("URL points to web address").'</span>';
11272:             $numremref++;
11273:         } elsif ($args->{'error_on_invalid_names'}
11274:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
11275:             $upload_output.='<td align="right"><span class="LC_warning">'.
11276:                             &mt('Invalid characters').'</span>';
11277:             $numinvalid++;
11278:         } else {
11279:             $upload_output .= '<td>'.
11280:                               &embedded_file_element('upload_embedded',$counter,
11281:                                                      $embed_file,\%mapping,
11282:                                                      $allfiles,$codebase,'upload');
11283:             $counter ++;
11284:             $numnew ++;
11285:         }
11286:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
11287:     }
11288:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
11289:         if ($actionurl eq '/adm/dependencies') {
11290:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
11291:             $modify_output .= &start_data_table_row().
11292:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
11293:                               '<img src="'.&icon($embed_file).'" border="0" />'.
11294:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
11295:                               '<td>'.$size.'</td>'.
11296:                               '<td>'.$mtime.'</td>'.
11297:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
11298:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
11299:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
11300:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
11301:                               &embedded_file_element('upload_embedded',$counter,
11302:                                                      $embed_file,\%mapping,
11303:                                                      $allfiles,$codebase,'modify').
11304:                               '</div></td>'.
11305:                               &end_data_table_row()."\n";
11306:             $counter ++;
11307:         } else {
11308:             $upload_output .= &start_data_table_row().
11309:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
11310:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
11311:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
11312:                               &Apache::loncommon::end_data_table_row()."\n";
11313:         }
11314:     }
11315:     my $delidx = $counter;
11316:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
11317:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
11318:         $delete_output .= &start_data_table_row().
11319:                           '<td><img src="'.&icon($oldfile).'" />'.
11320:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
11321:                           '<td>'.$size.'</td>'.
11322:                           '<td>'.$mtime.'</td>'.
11323:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
11324:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
11325:                           &embedded_file_element('upload_embedded',$delidx,
11326:                                                  $oldfile,\%mapping,$allfiles,
11327:                                                  $codebase,'delete').'</td>'.
11328:                           &end_data_table_row()."\n"; 
11329:         $numunused ++;
11330:         $delidx ++;
11331:     }
11332:     if ($upload_output) {
11333:         $upload_output = &start_data_table().
11334:                          $upload_output.
11335:                          &end_data_table()."\n";
11336:     }
11337:     if ($modify_output) {
11338:         $modify_output = &start_data_table().
11339:                          &start_data_table_header_row().
11340:                          '<th>'.&mt('File').'</th>'.
11341:                          '<th>'.&mt('Size (KB)').'</th>'.
11342:                          '<th>'.&mt('Modified').'</th>'.
11343:                          '<th>'.&mt('Upload replacement?').'</th>'.
11344:                          &end_data_table_header_row().
11345:                          $modify_output.
11346:                          &end_data_table()."\n";
11347:     }
11348:     if ($delete_output) {
11349:         $delete_output = &start_data_table().
11350:                          &start_data_table_header_row().
11351:                          '<th>'.&mt('File').'</th>'.
11352:                          '<th>'.&mt('Size (KB)').'</th>'.
11353:                          '<th>'.&mt('Modified').'</th>'.
11354:                          '<th>'.&mt('Delete?').'</th>'.
11355:                          &end_data_table_header_row().
11356:                          $delete_output.
11357:                          &end_data_table()."\n";
11358:     }
11359:     my $applies = 0;
11360:     if ($numremref) {
11361:         $applies ++;
11362:     }
11363:     if ($numinvalid) {
11364:         $applies ++;
11365:     }
11366:     if ($numexisting) {
11367:         $applies ++;
11368:     }
11369:     if ($counter || $numunused) {
11370:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
11371:                   ' method="post" enctype="multipart/form-data">'."\n".
11372:                   $state.'<h3>'.$heading.'</h3>'; 
11373:         if ($actionurl eq '/adm/dependencies') {
11374:             if ($numnew) {
11375:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
11376:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
11377:                            $upload_output.'<br />'."\n";
11378:             }
11379:             if ($numexisting) {
11380:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
11381:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
11382:                            $modify_output.'<br />'."\n";
11383:                            $buttontext = &mt('Save changes');
11384:             }
11385:             if ($numunused) {
11386:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
11387:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
11388:                            $delete_output.'<br />'."\n";
11389:                            $buttontext = &mt('Save changes');
11390:             }
11391:         } else {
11392:             $output .= $upload_output.'<br />'."\n";
11393:         }
11394:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
11395:                    $counter.'" />'."\n";
11396:         if ($actionurl eq '/adm/dependencies') { 
11397:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
11398:                        $numnew.'" />'."\n";
11399:         } elsif ($actionurl eq '') {
11400:             $output .=  '<input type="hidden" name="phase" value="three" />';
11401:         }
11402:     } elsif ($applies) {
11403:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
11404:         if ($applies > 1) {
11405:             $output .=  
11406:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
11407:             if ($numremref) {
11408:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
11409:             }
11410:             if ($numinvalid) {
11411:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
11412:             }
11413:             if ($numexisting) {
11414:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
11415:             }
11416:             $output .= '</ul><br />';
11417:         } elsif ($numremref) {
11418:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
11419:         } elsif ($numinvalid) {
11420:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
11421:         } elsif ($numexisting) {
11422:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
11423:         }
11424:         $output .= $upload_output.'<br />';
11425:     }
11426:     my ($pathchange_output,$chgcount);
11427:     $chgcount = $counter;
11428:     if (keys(%pathchanges) > 0) {
11429:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
11430:             if ($counter) {
11431:                 $output .= &embedded_file_element('pathchange',$chgcount,
11432:                                                   $embed_file,\%mapping,
11433:                                                   $allfiles,$codebase,'change');
11434:             } else {
11435:                 $pathchange_output .= 
11436:                     &start_data_table_row().
11437:                     '<td><input type ="checkbox" name="namechange" value="'.
11438:                     $chgcount.'" checked="checked" /></td>'.
11439:                     '<td>'.$mapping{$embed_file}.'</td>'.
11440:                     '<td>'.$embed_file.
11441:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
11442:                                            \%mapping,$allfiles,$codebase,'change').
11443:                     '</td>'.&end_data_table_row();
11444:             }
11445:             $numpathchg ++;
11446:             $chgcount ++;
11447:         }
11448:     }
11449:     if (($counter) || ($numunused)) {
11450:         if ($numpathchg) {
11451:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
11452:                        $numpathchg.'" />'."\n";
11453:         }
11454:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
11455:             ($actionurl eq '/adm/imsimport')) {
11456:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
11457:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
11458:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
11459:         } elsif ($actionurl eq '/adm/dependencies') {
11460:             $output .= '<input type="hidden" name="action" value="process_changes" />';
11461:         }
11462:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
11463:     } elsif ($numpathchg) {
11464:         my %pathchange = ();
11465:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
11466:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11467:             $output .= '<p>'.&mt('or').'</p>'; 
11468:         }
11469:     }
11470:     return ($output,$counter,$numpathchg);
11471: }
11472: 
11473: =pod
11474: 
11475: =item * clean_path($name)
11476: 
11477: Performs clean-up of directories, subdirectories and filename in an
11478: embedded object, referenced in an HTML file which is being uploaded
11479: to a course or portfolio, where
11480: "Upload embedded images/multimedia files if HTML file" checkbox was
11481: checked.
11482: 
11483: Clean-up is similar to replacements in lonnet::clean_filename()
11484: except each / between sub-directory and next level is preserved.
11485: 
11486: =cut
11487: 
11488: sub clean_path {
11489:     my ($embed_file) = @_;
11490:     $embed_file =~s{^/+}{};
11491:     my @contents;
11492:     if ($embed_file =~ m{/}) {
11493:         @contents = split(/\//,$embed_file);
11494:     } else {
11495:         @contents = ($embed_file);
11496:     }
11497:     my $lastidx = scalar(@contents)-1;
11498:     for (my $i=0; $i<=$lastidx; $i++) {
11499:         $contents[$i]=~s{\\}{/}g;
11500:         $contents[$i]=~s/\s+/\_/g;
11501:         $contents[$i]=~s{[^/\w\.\-]}{}g;
11502:         if ($i == $lastidx) {
11503:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
11504:         }
11505:     }
11506:     if ($lastidx > 0) {
11507:         return join('/',@contents);
11508:     } else {
11509:         return $contents[0];
11510:     }
11511: }
11512: 
11513: sub embedded_file_element {
11514:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
11515:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
11516:                    (ref($codebase) eq 'HASH'));
11517:     my $output;
11518:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
11519:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
11520:     }
11521:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
11522:                &escape($embed_file).'" />';
11523:     unless (($context eq 'upload_embedded') && 
11524:             ($mapping->{$embed_file} eq $embed_file)) {
11525:         $output .='
11526:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
11527:     }
11528:     my $attrib;
11529:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
11530:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
11531:     }
11532:     $output .=
11533:         "\n\t\t".
11534:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
11535:         $attrib.'" />';
11536:     if (exists($codebase->{$mapping->{$embed_file}})) {
11537:         $output .=
11538:             "\n\t\t".
11539:             '<input name="codebase_'.$num.'" type="hidden" value="'.
11540:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
11541:     }
11542:     return $output;
11543: }
11544: 
11545: sub get_dependency_details {
11546:     my ($currfile,$currsubfile,$embed_file) = @_;
11547:     my ($size,$mtime,$showsize,$showmtime);
11548:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
11549:         if ($embed_file =~ m{/}) {
11550:             my ($path,$fname) = split(/\//,$embed_file);
11551:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
11552:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
11553:             }
11554:         } else {
11555:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
11556:                 ($size,$mtime) = @{$currfile->{$embed_file}};
11557:             }
11558:         }
11559:         $showsize = $size/1024.0;
11560:         $showsize = sprintf("%.1f",$showsize);
11561:         if ($mtime > 0) {
11562:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
11563:         }
11564:     }
11565:     return ($showsize,$showmtime);
11566: }
11567: 
11568: sub ask_embedded_js {
11569:     return <<"END";
11570: <script type="text/javascript"">
11571: // <![CDATA[
11572: function toggleBrowse(counter) {
11573:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
11574:     var fileid = document.getElementById('embedded_item_'+counter);
11575:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
11576:     if (chkboxid.checked == true) {
11577:         uploaddivid.style.display='block';
11578:     } else {
11579:         uploaddivid.style.display='none';
11580:         fileid.value = '';
11581:     }
11582: }
11583: // ]]>
11584: </script>
11585: 
11586: END
11587: }
11588: 
11589: sub upload_embedded {
11590:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
11591:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
11592:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
11593:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
11594:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
11595:         my $orig_uploaded_filename =
11596:             $env{'form.embedded_item_'.$i.'.filename'};
11597:         foreach my $type ('orig','ref','attrib','codebase') {
11598:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
11599:                 $env{'form.embedded_'.$type.'_'.$i} =
11600:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
11601:             }
11602:         }
11603:         my ($path,$fname) =
11604:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
11605:         # no path, whole string is fname
11606:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
11607:         $fname = &Apache::lonnet::clean_filename($fname);
11608:         # See if there is anything left
11609:         next if ($fname eq '');
11610: 
11611:         # Check if file already exists as a file or directory.
11612:         my ($state,$msg);
11613:         if ($context eq 'portfolio') {
11614:             my $port_path = $dirpath;
11615:             if ($group ne '') {
11616:                 $port_path = "groups/$group/$port_path";
11617:             }
11618:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
11619:                                               $fname,$group,'embedded_item_'.$i,
11620:                                               $dir_root,$port_path,$disk_quota,
11621:                                               $current_disk_usage,$uname,$udom);
11622:             if ($state eq 'will_exceed_quota'
11623:                 || $state eq 'file_locked') {
11624:                 $output .= $msg;
11625:                 next;
11626:             }
11627:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
11628:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
11629:             if ($state eq 'exists') {
11630:                 $output .= $msg;
11631:                 next;
11632:             }
11633:         }
11634:         # Check if extension is valid
11635:         if (($fname =~ /\.(\w+)$/) &&
11636:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
11637:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
11638:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
11639:             next;
11640:         } elsif (($fname =~ /\.(\w+)$/) &&
11641:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
11642:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
11643:             next;
11644:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
11645:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
11646:             next;
11647:         }
11648:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
11649:         my $subdir = $path;
11650:         $subdir =~ s{/+$}{};
11651:         if ($context eq 'portfolio') {
11652:             my $result;
11653:             if ($state eq 'existingfile') {
11654:                 $result=
11655:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
11656:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
11657:             } else {
11658:                 $result=
11659:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
11660:                                                     $dirpath.
11661:                                                     $env{'form.currentpath'}.$subdir);
11662:                 if ($result !~ m|^/uploaded/|) {
11663:                     $output .= '<span class="LC_error">'
11664:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11665:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11666:                                .'</span><br />';
11667:                     next;
11668:                 } else {
11669:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11670:                                $path.$fname.'</span>').'<br />';     
11671:                 }
11672:             }
11673:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
11674:             my $extendedsubdir = $dirpath.'/'.$subdir;
11675:             $extendedsubdir =~ s{/+$}{};
11676:             my $result =
11677:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
11678:             if ($result !~ m|^/uploaded/|) {
11679:                 $output .= '<span class="LC_error">'
11680:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11681:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11682:                            .'</span><br />';
11683:                     next;
11684:             } else {
11685:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11686:                            $path.$fname.'</span>').'<br />';
11687:                 if ($context eq 'syllabus') {
11688:                     &Apache::lonnet::make_public_indefinitely($result);
11689:                 }
11690:             }
11691:         } else {
11692: # Save the file
11693:             my $target = $env{'form.embedded_item_'.$i};
11694:             my $fullpath = $dir_root.$dirpath.'/'.$path;
11695:             my $dest = $fullpath.$fname;
11696:             my $url = $url_root.$dirpath.'/'.$path.$fname;
11697:             my @parts=split(/\//,"$dirpath/$path");
11698:             my $count;
11699:             my $filepath = $dir_root;
11700:             foreach my $subdir (@parts) {
11701:                 $filepath .= "/$subdir";
11702:                 if (!-e $filepath) {
11703:                     mkdir($filepath,0770);
11704:                 }
11705:             }
11706:             my $fh;
11707:             if (!open($fh,'>'.$dest)) {
11708:                 &Apache::lonnet::logthis('Failed to create '.$dest);
11709:                 $output .= '<span class="LC_error">'.
11710:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
11711:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11712:                            '</span><br />';
11713:             } else {
11714:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
11715:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
11716:                     $output .= '<span class="LC_error">'.
11717:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
11718:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11719:                               '</span><br />';
11720:                 } else {
11721:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11722:                                $url.'</span>').'<br />';
11723:                     unless ($context eq 'testbank') {
11724:                         $footer .= &mt('View embedded file: [_1]',
11725:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
11726:                     }
11727:                 }
11728:                 close($fh);
11729:             }
11730:         }
11731:         if ($env{'form.embedded_ref_'.$i}) {
11732:             $pathchange{$i} = 1;
11733:         }
11734:     }
11735:     if ($output) {
11736:         $output = '<p>'.$output.'</p>';
11737:     }
11738:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
11739:     $returnflag = 'ok';
11740:     my $numpathchgs = scalar(keys(%pathchange));
11741:     if ($numpathchgs > 0) {
11742:         if ($context eq 'portfolio') {
11743:             $output .= '<p>'.&mt('or').'</p>';
11744:         } elsif ($context eq 'testbank') {
11745:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
11746:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
11747:             $returnflag = 'modify_orightml';
11748:         }
11749:     }
11750:     return ($output.$footer,$returnflag,$numpathchgs);
11751: }
11752: 
11753: sub modify_html_form {
11754:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
11755:     my $end = 0;
11756:     my $modifyform;
11757:     if ($context eq 'upload_embedded') {
11758:         return unless (ref($pathchange) eq 'HASH');
11759:         if ($env{'form.number_embedded_items'}) {
11760:             $end += $env{'form.number_embedded_items'};
11761:         }
11762:         if ($env{'form.number_pathchange_items'}) {
11763:             $end += $env{'form.number_pathchange_items'};
11764:         }
11765:         if ($end) {
11766:             for (my $i=0; $i<$end; $i++) {
11767:                 if ($i < $env{'form.number_embedded_items'}) {
11768:                     next unless($pathchange->{$i});
11769:                 }
11770:                 $modifyform .=
11771:                     &start_data_table_row().
11772:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
11773:                     'checked="checked" /></td>'.
11774:                     '<td>'.$env{'form.embedded_ref_'.$i}.
11775:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
11776:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
11777:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
11778:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
11779:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
11780:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
11781:                     '<td>'.$env{'form.embedded_orig_'.$i}.
11782:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
11783:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
11784:                     &end_data_table_row();
11785:             }
11786:         }
11787:     } else {
11788:         $modifyform = $pathchgtable;
11789:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11790:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
11791:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11792:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
11793:         }
11794:     }
11795:     if ($modifyform) {
11796:         if ($actionurl eq '/adm/dependencies') {
11797:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
11798:         }
11799:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
11800:                '<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".
11801:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
11802:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
11803:                '</ol></p>'."\n".'<p>'.
11804:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
11805:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
11806:                &start_data_table()."\n".
11807:                &start_data_table_header_row().
11808:                '<th>'.&mt('Change?').'</th>'.
11809:                '<th>'.&mt('Current reference').'</th>'.
11810:                '<th>'.&mt('Required reference').'</th>'.
11811:                &end_data_table_header_row()."\n".
11812:                $modifyform.
11813:                &end_data_table().'<br />'."\n".$hiddenstate.
11814:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
11815:                '</form>'."\n";
11816:     }
11817:     return;
11818: }
11819: 
11820: sub modify_html_refs {
11821:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
11822:     my $container;
11823:     if ($context eq 'portfolio') {
11824:         $container = $env{'form.container'};
11825:     } elsif ($context eq 'coursedoc') {
11826:         $container = $env{'form.primaryurl'};
11827:     } elsif ($context eq 'manage_dependencies') {
11828:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
11829:         $container = "/$container";
11830:     } elsif ($context eq 'syllabus') {
11831:         $container = $url;
11832:     } else {
11833:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
11834:     }
11835:     my (%allfiles,%codebase,$output,$content);
11836:     my @changes = &get_env_multiple('form.namechange');
11837:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
11838:         if (wantarray) {
11839:             return ('',0,0); 
11840:         } else {
11841:             return;
11842:         }
11843:     }
11844:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
11845:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
11846:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
11847:             if (wantarray) {
11848:                 return ('',0,0);
11849:             } else {
11850:                 return;
11851:             }
11852:         } 
11853:         $content = &Apache::lonnet::getfile($container);
11854:         if ($content eq '-1') {
11855:             if (wantarray) {
11856:                 return ('',0,0);
11857:             } else {
11858:                 return;
11859:             }
11860:         }
11861:     } else {
11862:         unless ($container =~ /^\Q$dir_root\E/) {
11863:             if (wantarray) {
11864:                 return ('',0,0);
11865:             } else {
11866:                 return;
11867:             }
11868:         } 
11869:         if (open(my $fh,'<',$container)) {
11870:             $content = join('', <$fh>);
11871:             close($fh);
11872:         } else {
11873:             if (wantarray) {
11874:                 return ('',0,0);
11875:             } else {
11876:                 return;
11877:             }
11878:         }
11879:     }
11880:     my ($count,$codebasecount) = (0,0);
11881:     my $mm = new File::MMagic;
11882:     my $mime_type = $mm->checktype_contents($content);
11883:     if ($mime_type eq 'text/html') {
11884:         my $parse_result = 
11885:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
11886:                                                     \%codebase,\$content);
11887:         if ($parse_result eq 'ok') {
11888:             foreach my $i (@changes) {
11889:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
11890:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
11891:                 if ($allfiles{$ref}) {
11892:                     my $newname =  $orig;
11893:                     my ($attrib_regexp,$codebase);
11894:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
11895:                     if ($attrib_regexp =~ /:/) {
11896:                         $attrib_regexp =~ s/\:/|/g;
11897:                     }
11898:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
11899:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
11900:                         $count += $numchg;
11901:                         $allfiles{$newname} = $allfiles{$ref};
11902:                         delete($allfiles{$ref});
11903:                     }
11904:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
11905:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
11906:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
11907:                         $codebasecount ++;
11908:                     }
11909:                 }
11910:             }
11911:             my $skiprewrites;
11912:             if ($count || $codebasecount) {
11913:                 my $saveresult;
11914:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
11915:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
11916:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
11917:                     if ($url eq $container) {
11918:                         my ($fname) = ($container =~ m{/([^/]+)$});
11919:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
11920:                                             $count,'<span class="LC_filename">'.
11921:                                             $fname.'</span>').'</p>';
11922:                     } else {
11923:                          $output = '<p class="LC_error">'.
11924:                                    &mt('Error: update failed for: [_1].',
11925:                                    '<span class="LC_filename">'.
11926:                                    $container.'</span>').'</p>';
11927:                     }
11928:                     if ($context eq 'syllabus') {
11929:                         unless ($saveresult eq 'ok') {
11930:                             $skiprewrites = 1;
11931:                         }
11932:                     }
11933:                 } else {
11934:                     if (open(my $fh,'>',$container)) {
11935:                         print $fh $content;
11936:                         close($fh);
11937:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
11938:                                   $count,'<span class="LC_filename">'.
11939:                                   $container.'</span>').'</p>';
11940:                     } else {
11941:                          $output = '<p class="LC_error">'.
11942:                                    &mt('Error: could not update [_1].',
11943:                                    '<span class="LC_filename">'.
11944:                                    $container.'</span>').'</p>';
11945:                     }
11946:                 }
11947:             }
11948:             if (($context eq 'syllabus') && (!$skiprewrites)) {
11949:                 my ($actionurl,$state);
11950:                 $actionurl = "/public/$udom/$uname/syllabus";
11951:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
11952:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
11953:                                               \%codebase,
11954:                                               {'context' => 'rewrites',
11955:                                                'ignore_remote_references' => 1,});
11956:                 if (ref($mapping) eq 'HASH') {
11957:                     my $rewrites = 0;
11958:                     foreach my $key (keys(%{$mapping})) {
11959:                         next if ($key =~ m{^https?://});
11960:                         my $ref = $mapping->{$key};
11961:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
11962:                         my $attrib;
11963:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
11964:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
11965:                         }
11966:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
11967:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
11968:                             $rewrites += $numchg;
11969:                         }
11970:                     }
11971:                     if ($rewrites) {
11972:                         my $saveresult;
11973:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
11974:                         if ($url eq $container) {
11975:                             my ($fname) = ($container =~ m{/([^/]+)$});
11976:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
11977:                                             $count,'<span class="LC_filename">'.
11978:                                             $fname.'</span>').'</p>';
11979:                         } else {
11980:                             $output .= '<p class="LC_error">'.
11981:                                        &mt('Error: could not update links in [_1].',
11982:                                        '<span class="LC_filename">'.
11983:                                        $container.'</span>').'</p>';
11984: 
11985:                         }
11986:                     }
11987:                 }
11988:             }
11989:         } else {
11990:             &logthis('Failed to parse '.$container.
11991:                      ' to modify references: '.$parse_result);
11992:         }
11993:     }
11994:     if (wantarray) {
11995:         return ($output,$count,$codebasecount);
11996:     } else {
11997:         return $output;
11998:     }
11999: }
12000: 
12001: sub check_for_existing {
12002:     my ($path,$fname,$element) = @_;
12003:     my ($state,$msg);
12004:     if (-d $path.'/'.$fname) {
12005:         $state = 'exists';
12006:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
12007:     } elsif (-e $path.'/'.$fname) {
12008:         $state = 'exists';
12009:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
12010:     }
12011:     if ($state eq 'exists') {
12012:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
12013:     }
12014:     return ($state,$msg);
12015: }
12016: 
12017: sub check_for_upload {
12018:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
12019:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
12020:     my $filesize = length($env{'form.'.$element});
12021:     if (!$filesize) {
12022:         my $msg = '<span class="LC_error">'.
12023:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
12024:                       '<span class="LC_filename">'.$fname.'</span>',
12025:                       $filesize).'<br />'.
12026:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
12027:                   '</span>';
12028:         return ('zero_bytes',$msg);
12029:     }
12030:     $filesize =  $filesize/1000; #express in k (1024?)
12031:     my $getpropath = 1;
12032:     my ($dirlistref,$listerror) =
12033:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
12034:     my $found_file = 0;
12035:     my $locked_file = 0;
12036:     my @lockers;
12037:     my $navmap;
12038:     if ($env{'request.course.id'}) {
12039:         $navmap = Apache::lonnavmaps::navmap->new();
12040:     }
12041:     if (ref($dirlistref) eq 'ARRAY') {
12042:         foreach my $line (@{$dirlistref}) {
12043:             my ($file_name,$rest)=split(/\&/,$line,2);
12044:             if ($file_name eq $fname){
12045:                 $file_name = $path.$file_name;
12046:                 if ($group ne '') {
12047:                     $file_name = $group.$file_name;
12048:                 }
12049:                 $found_file = 1;
12050:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
12051:                     foreach my $lock (@lockers) {
12052:                         if (ref($lock) eq 'ARRAY') {
12053:                             my ($symb,$crsid) = @{$lock};
12054:                             if ($crsid eq $env{'request.course.id'}) {
12055:                                 if (ref($navmap)) {
12056:                                     my $res = $navmap->getBySymb($symb);
12057:                                     foreach my $part (@{$res->parts()}) { 
12058:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
12059:                                         unless (($slot_status == $res->RESERVED) ||
12060:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
12061:                                             $locked_file = 1;
12062:                                         }
12063:                                     }
12064:                                 } else {
12065:                                     $locked_file = 1;
12066:                                 }
12067:                             } else {
12068:                                 $locked_file = 1;
12069:                             }
12070:                         }
12071:                    }
12072:                 } else {
12073:                     my @info = split(/\&/,$rest);
12074:                     my $currsize = $info[6]/1000;
12075:                     if ($currsize < $filesize) {
12076:                         my $extra = $filesize - $currsize;
12077:                         if (($current_disk_usage + $extra) > $disk_quota) {
12078:                             my $msg = '<p class="LC_warning">'.
12079:                                       &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.',
12080:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
12081:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
12082:                                                    $disk_quota,$current_disk_usage).'</p>';
12083:                             return ('will_exceed_quota',$msg);
12084:                         }
12085:                     }
12086:                 }
12087:             }
12088:         }
12089:     }
12090:     if (($current_disk_usage + $filesize) > $disk_quota){
12091:         my $msg = '<p class="LC_warning">'.
12092:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
12093:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
12094:         return ('will_exceed_quota',$msg);
12095:     } elsif ($found_file) {
12096:         if ($locked_file) {
12097:             my $msg = '<p class="LC_warning">';
12098:             $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>');
12099:             $msg .= '</p>';
12100:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
12101:             return ('file_locked',$msg);
12102:         } else {
12103:             my $msg = '<p class="LC_error">';
12104:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
12105:             $msg .= '</p>';
12106:             return ('existingfile',$msg);
12107:         }
12108:     }
12109: }
12110: 
12111: sub check_for_traversal {
12112:     my ($path,$url,$toplevel) = @_;
12113:     my @parts=split(/\//,$path);
12114:     my $cleanpath;
12115:     my $fullpath = $url;
12116:     for (my $i=0;$i<@parts;$i++) {
12117:         next if ($parts[$i] eq '.');
12118:         if ($parts[$i] eq '..') {
12119:             $fullpath =~ s{([^/]+/)$}{};
12120:         } else {
12121:             $fullpath .= $parts[$i].'/';
12122:         }
12123:     }
12124:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
12125:         $cleanpath = $1;
12126:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
12127:         my $curr_toprel = $1;
12128:         my @parts = split(/\//,$curr_toprel);
12129:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
12130:         my @urlparts = split(/\//,$url_toprel);
12131:         my $doubledots;
12132:         my $startdiff = -1;
12133:         for (my $i=0; $i<@urlparts; $i++) {
12134:             if ($startdiff == -1) {
12135:                 unless ($urlparts[$i] eq $parts[$i]) {
12136:                     $startdiff = $i;
12137:                     $doubledots .= '../';
12138:                 }
12139:             } else {
12140:                 $doubledots .= '../';
12141:             }
12142:         }
12143:         if ($startdiff > -1) {
12144:             $cleanpath = $doubledots;
12145:             for (my $i=$startdiff; $i<@parts; $i++) {
12146:                 $cleanpath .= $parts[$i].'/';
12147:             }
12148:         }
12149:     }
12150:     $cleanpath =~ s{(/)$}{};
12151:     return $cleanpath;
12152: }
12153: 
12154: sub is_archive_file {
12155:     my ($mimetype) = @_;
12156:     if (($mimetype eq 'application/octet-stream') ||
12157:         ($mimetype eq 'application/x-stuffit') ||
12158:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
12159:         return 1;
12160:     }
12161:     return;
12162: }
12163: 
12164: sub decompress_form {
12165:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
12166:     my %lt = &Apache::lonlocal::texthash (
12167:         this => 'This file is an archive file.',
12168:         camt => 'This file is a Camtasia archive file.',
12169:         itsc => 'Its contents are as follows:',
12170:         youm => 'You may wish to extract its contents.',
12171:         extr => 'Extract contents',
12172:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
12173:         proa => 'Process automatically?',
12174:         yes  => 'Yes',
12175:         no   => 'No',
12176:         fold => 'Title for folder containing movie',
12177:         movi => 'Title for page containing embedded movie', 
12178:     );
12179:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
12180:     my ($is_camtasia,$topdir,%toplevel,@paths);
12181:     my $info = &list_archive_contents($fileloc,\@paths);
12182:     if (@paths) {
12183:         foreach my $path (@paths) {
12184:             $path =~ s{^/}{};
12185:             if ($path =~ m{^([^/]+)/$}) {
12186:                 $topdir = $1;
12187:             }
12188:             if ($path =~ m{^([^/]+)/}) {
12189:                 $toplevel{$1} = $path;
12190:             } else {
12191:                 $toplevel{$path} = $path;
12192:             }
12193:         }
12194:     }
12195:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
12196:         my @camtasia6 = ("$topdir/","$topdir/index.html",
12197:                         "$topdir/media/",
12198:                         "$topdir/media/$topdir.mp4",
12199:                         "$topdir/media/FirstFrame.png",
12200:                         "$topdir/media/player.swf",
12201:                         "$topdir/media/swfobject.js",
12202:                         "$topdir/media/expressInstall.swf");
12203:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
12204:                          "$topdir/$topdir.mp4",
12205:                          "$topdir/$topdir\_config.xml",
12206:                          "$topdir/$topdir\_controller.swf",
12207:                          "$topdir/$topdir\_embed.css",
12208:                          "$topdir/$topdir\_First_Frame.png",
12209:                          "$topdir/$topdir\_player.html",
12210:                          "$topdir/$topdir\_Thumbnails.png",
12211:                          "$topdir/playerProductInstall.swf",
12212:                          "$topdir/scripts/",
12213:                          "$topdir/scripts/config_xml.js",
12214:                          "$topdir/scripts/handlebars.js",
12215:                          "$topdir/scripts/jquery-1.7.1.min.js",
12216:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
12217:                          "$topdir/scripts/modernizr.js",
12218:                          "$topdir/scripts/player-min.js",
12219:                          "$topdir/scripts/swfobject.js",
12220:                          "$topdir/skins/",
12221:                          "$topdir/skins/configuration_express.xml",
12222:                          "$topdir/skins/express_show/",
12223:                          "$topdir/skins/express_show/player-min.css",
12224:                          "$topdir/skins/express_show/spritesheet.png");
12225:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
12226:                          "$topdir/$topdir.mp4",
12227:                          "$topdir/$topdir\_config.xml",
12228:                          "$topdir/$topdir\_controller.swf",
12229:                          "$topdir/$topdir\_embed.css",
12230:                          "$topdir/$topdir\_First_Frame.png",
12231:                          "$topdir/$topdir\_player.html",
12232:                          "$topdir/$topdir\_Thumbnails.png",
12233:                          "$topdir/playerProductInstall.swf",
12234:                          "$topdir/scripts/",
12235:                          "$topdir/scripts/config_xml.js",
12236:                          "$topdir/scripts/techsmith-smart-player.min.js",
12237:                          "$topdir/skins/",
12238:                          "$topdir/skins/configuration_express.xml",
12239:                          "$topdir/skins/express_show/",
12240:                          "$topdir/skins/express_show/spritesheet.min.css",
12241:                          "$topdir/skins/express_show/spritesheet.png",
12242:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
12243:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
12244:         if (@diffs == 0) {
12245:             $is_camtasia = 6;
12246:         } else {
12247:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
12248:             if (@diffs == 0) {
12249:                 $is_camtasia = 8;
12250:             } else {
12251:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
12252:                 if (@diffs == 0) {
12253:                     $is_camtasia = 8;
12254:                 }
12255:             }
12256:         }
12257:     }
12258:     my $output;
12259:     if ($is_camtasia) {
12260:         $output = <<"ENDCAM";
12261: <script type="text/javascript" language="Javascript">
12262: // <![CDATA[
12263: 
12264: function camtasiaToggle() {
12265:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
12266:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
12267:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
12268:                 document.getElementById('camtasia_titles').style.display='block';
12269:             } else {
12270:                 document.getElementById('camtasia_titles').style.display='none';
12271:             }
12272:         }
12273:     }
12274:     return;
12275: }
12276: 
12277: // ]]>
12278: </script>
12279: <p>$lt{'camt'}</p>
12280: ENDCAM
12281:     } else {
12282:         $output = '<p>'.$lt{'this'};
12283:         if ($info eq '') {
12284:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
12285:         } else {
12286:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
12287:                        '<div><pre>'.$info.'</pre></div>';
12288:         }
12289:     }
12290:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
12291:     my $duplicates;
12292:     my $num = 0;
12293:     if (ref($dirlist) eq 'ARRAY') {
12294:         foreach my $item (@{$dirlist}) {
12295:             if (ref($item) eq 'ARRAY') {
12296:                 if (exists($toplevel{$item->[0]})) {
12297:                     $duplicates .= 
12298:                         &start_data_table_row().
12299:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
12300:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
12301:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
12302:                         'value="1" />'.&mt('Yes').'</label>'.
12303:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
12304:                         '<td>'.$item->[0].'</td>';
12305:                     if ($item->[2]) {
12306:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
12307:                     } else {
12308:                         $duplicates .= '<td>'.&mt('File').'</td>';
12309:                     }
12310:                     $duplicates .= '<td>'.$item->[3].'</td>'.
12311:                                    '<td>'.
12312:                                    &Apache::lonlocal::locallocaltime($item->[4]).
12313:                                    '</td>'.
12314:                                    &end_data_table_row();
12315:                     $num ++;
12316:                 }
12317:             }
12318:         }
12319:     }
12320:     my $itemcount;
12321:     if (@paths > 0) {
12322:         $itemcount = scalar(@paths);
12323:     } else {
12324:         $itemcount = 1;
12325:     }
12326:     if ($is_camtasia) {
12327:         $output .= $lt{'auto'}.'<br />'.
12328:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
12329:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
12330:                    $lt{'yes'}.'</label>&nbsp;<label>'.
12331:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
12332:                    $lt{'no'}.'</label></span><br />'.
12333:                    '<div id="camtasia_titles" style="display:block">'.
12334:                    &Apache::lonhtmlcommon::start_pick_box().
12335:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
12336:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
12337:                    &Apache::lonhtmlcommon::row_closure().
12338:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
12339:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
12340:                    &Apache::lonhtmlcommon::row_closure(1).
12341:                    &Apache::lonhtmlcommon::end_pick_box().
12342:                    '</div>';
12343:     }
12344:     $output .= 
12345:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
12346:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
12347:         "\n";
12348:     if ($duplicates ne '') {
12349:         $output .= '<p><span class="LC_warning">'.
12350:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
12351:                    &start_data_table().
12352:                    &start_data_table_header_row().
12353:                    '<th>'.&mt('Overwrite?').'</th>'.
12354:                    '<th>'.&mt('Name').'</th>'.
12355:                    '<th>'.&mt('Type').'</th>'.
12356:                    '<th>'.&mt('Size').'</th>'.
12357:                    '<th>'.&mt('Last modified').'</th>'.
12358:                    &end_data_table_header_row().
12359:                    $duplicates.
12360:                    &end_data_table().
12361:                    '</p>';
12362:     }
12363:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
12364:     if (ref($hiddenelements) eq 'HASH') {
12365:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
12366:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
12367:         }
12368:     }
12369:     $output .= <<"END";
12370: <br />
12371: <input type="submit" name="decompress" value="$lt{'extr'}" />
12372: </form>
12373: $noextract
12374: END
12375:     return $output;
12376: }
12377: 
12378: sub decompression_utility {
12379:     my ($program) = @_;
12380:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
12381:     my $location;
12382:     if (grep(/^\Q$program\E$/,@utilities)) { 
12383:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
12384:                          '/usr/sbin/') {
12385:             if (-x $dir.$program) {
12386:                 $location = $dir.$program;
12387:                 last;
12388:             }
12389:         }
12390:     }
12391:     return $location;
12392: }
12393: 
12394: sub list_archive_contents {
12395:     my ($file,$pathsref) = @_;
12396:     my (@cmd,$output);
12397:     my $needsregexp;
12398:     if ($file =~ /\.zip$/) {
12399:         @cmd = (&decompression_utility('unzip'),"-l");
12400:         $needsregexp = 1;
12401:     } elsif (($file =~ m/\.tar\.gz$/) ||
12402:              ($file =~ /\.tgz$/)) {
12403:         @cmd = (&decompression_utility('tar'),"-ztf");
12404:     } elsif ($file =~ /\.tar\.bz2$/) {
12405:         @cmd = (&decompression_utility('tar'),"-jtf");
12406:     } elsif ($file =~ m|\.tar$|) {
12407:         @cmd = (&decompression_utility('tar'),"-tf");
12408:     }
12409:     if (@cmd) {
12410:         undef($!);
12411:         undef($@);
12412:         if (open(my $fh,"-|", @cmd, $file)) {
12413:             while (my $line = <$fh>) {
12414:                 $output .= $line;
12415:                 chomp($line);
12416:                 my $item;
12417:                 if ($needsregexp) {
12418:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
12419:                 } else {
12420:                     $item = $line;
12421:                 }
12422:                 if ($item ne '') {
12423:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
12424:                         push(@{$pathsref},$item);
12425:                     } 
12426:                 }
12427:             }
12428:             close($fh);
12429:         }
12430:     }
12431:     return $output;
12432: }
12433: 
12434: sub decompress_uploaded_file {
12435:     my ($file,$dir) = @_;
12436:     &Apache::lonnet::appenv({'cgi.file' => $file});
12437:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
12438:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
12439:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
12440:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
12441:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
12442:     my $decompressed = $env{'cgi.decompressed'};
12443:     &Apache::lonnet::delenv('cgi.file');
12444:     &Apache::lonnet::delenv('cgi.dir');
12445:     &Apache::lonnet::delenv('cgi.decompressed');
12446:     return ($decompressed,$result);
12447: }
12448: 
12449: sub process_decompression {
12450:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
12451:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
12452:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12453:                &mt('Unexpected file path.').'</p>'."\n";
12454:     }
12455:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
12456:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12457:                &mt('Unexpected course context.').'</p>'."\n";
12458:     }
12459:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
12460:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12461:                &mt('Filename contained unexpected characters.').'</p>'."\n";
12462:     }
12463:     my ($dir,$error,$warning,$output);
12464:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
12465:         $error = &mt('Filename not a supported archive file type.').
12466:                  '<br />'.&mt('Filename should end with one of: [_1].',
12467:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
12468:     } else {
12469:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
12470:         if ($docuhome eq 'no_host') {
12471:             $error = &mt('Could not determine home server for course.');
12472:         } else {
12473:             my @ids=&Apache::lonnet::current_machine_ids();
12474:             my $currdir = "$dir_root/$destination";
12475:             if (grep(/^\Q$docuhome\E$/,@ids)) {
12476:                 $dir = &LONCAPA::propath($docudom,$docuname).
12477:                        "$dir_root/$destination";
12478:             } else {
12479:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
12480:                        "$dir_root/$docudom/$docuname/$destination";
12481:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
12482:                     $error = &mt('Archive file not found.');
12483:                 }
12484:             }
12485:             my (@to_overwrite,@to_skip);
12486:             if ($env{'form.archive_overwrite_total'} > 0) {
12487:                 my $total = $env{'form.archive_overwrite_total'};
12488:                 for (my $i=0; $i<$total; $i++) {
12489:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
12490:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
12491:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
12492:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
12493:                     }
12494:                 }
12495:             }
12496:             my $numskip = scalar(@to_skip);
12497:             my $numoverwrite = scalar(@to_overwrite);
12498:             if (($numskip) && (!$numoverwrite)) {
12499:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
12500:             } elsif ($dir eq '') {
12501:                 $error = &mt('Directory containing archive file unavailable.');
12502:             } elsif (!$error) {
12503:                 my ($decompressed,$display);
12504:                 if (($numskip) || ($numoverwrite)) {
12505:                     my $tempdir = time.'_'.$$.int(rand(10000));
12506:                     mkdir("$dir/$tempdir",0755);
12507:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
12508:                         ($decompressed,$display) =
12509:                             &decompress_uploaded_file($file,"$dir/$tempdir");
12510:                         foreach my $item (@to_skip) {
12511:                             if (($item ne '') && ($item !~ /\.\./)) {
12512:                                 if (-f "$dir/$tempdir/$item") {
12513:                                     unlink("$dir/$tempdir/$item");
12514:                                 } elsif (-d "$dir/$tempdir/$item") {
12515:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
12516:                                 }
12517:                             }
12518:                         }
12519:                         foreach my $item (@to_overwrite) {
12520:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
12521:                                 if (($item ne '') && ($item !~ /\.\./)) {
12522:                                     if (-f "$dir/$item") {
12523:                                         unlink("$dir/$item");
12524:                                     } elsif (-d "$dir/$item") {
12525:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
12526:                                     }
12527:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
12528:                                 }
12529:                             }
12530:                         }
12531:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
12532:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
12533:                         }
12534:                     }
12535:                 } else {
12536:                     ($decompressed,$display) = 
12537:                         &decompress_uploaded_file($file,$dir);
12538:                 }
12539:                 if ($decompressed eq 'ok') {
12540:                     $output = '<p class="LC_info">'.
12541:                               &mt('Files extracted successfully from archive.').
12542:                               '</p>'."\n";
12543:                     my ($warning,$result,@contents);
12544:                     my ($newdirlistref,$newlisterror) =
12545:                         &Apache::lonnet::dirlist($currdir,$docudom,
12546:                                                  $docuname,1);
12547:                     my (%is_dir,%changes,@newitems);
12548:                     my $dirptr = 16384;
12549:                     if (ref($newdirlistref) eq 'ARRAY') {
12550:                         foreach my $dir_line (@{$newdirlistref}) {
12551:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12552:                             unless (($item =~ /^\.+$/) || ($item eq $file)) { 
12553:                                 push(@newitems,$item);
12554:                                 if ($dirptr&$testdir) {
12555:                                     $is_dir{$item} = 1;
12556:                                 }
12557:                                 $changes{$item} = 1;
12558:                             }
12559:                         }
12560:                     }
12561:                     if (keys(%changes) > 0) {
12562:                         foreach my $item (sort(@newitems)) {
12563:                             if ($changes{$item}) {
12564:                                 push(@contents,$item);
12565:                             }
12566:                         }
12567:                     }
12568:                     if (@contents > 0) {
12569:                         my $wantform;
12570:                         unless ($env{'form.autoextract_camtasia'}) {
12571:                             $wantform = 1;
12572:                         }
12573:                         my (%children,%parent,%dirorder,%titles);
12574:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
12575:                                                                 $currdir,\%is_dir,
12576:                                                                 \%children,\%parent,
12577:                                                                 \@contents,\%dirorder,
12578:                                                                 \%titles,$wantform);
12579:                         if ($datatable ne '') {
12580:                             $output .= &archive_options_form('decompressed',$datatable,
12581:                                                              $count,$hiddenelem);
12582:                             my $startcount = 6;
12583:                             $output .= &archive_javascript($startcount,$count,
12584:                                                            \%titles,\%children);
12585:                         }
12586:                         if ($env{'form.autoextract_camtasia'}) {
12587:                             my $version = $env{'form.autoextract_camtasia'};
12588:                             my %displayed;
12589:                             my $total = 1;
12590:                             $env{'form.archive_directory'} = [];
12591:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
12592:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
12593:                                 $path =~ s{/$}{};
12594:                                 my $item;
12595:                                 if ($path ne '') {
12596:                                     $item = "$path/$titles{$i}";
12597:                                 } else {
12598:                                     $item = $titles{$i};
12599:                                 }
12600:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
12601:                                 if ($item eq $contents[0]) {
12602:                                     push(@{$env{'form.archive_directory'}},$i);
12603:                                     $env{'form.archive_'.$i} = 'display';
12604:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
12605:                                     $displayed{'folder'} = $i;
12606:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
12607:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
12608:                                     $env{'form.archive_'.$i} = 'display';
12609:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
12610:                                     $displayed{'web'} = $i;
12611:                                 } else {
12612:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
12613:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
12614:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
12615:                                         push(@{$env{'form.archive_directory'}},$i);
12616:                                     }
12617:                                     $env{'form.archive_'.$i} = 'dependency';
12618:                                 }
12619:                                 $total ++;
12620:                             }
12621:                             for (my $i=1; $i<$total; $i++) {
12622:                                 next if ($i == $displayed{'web'});
12623:                                 next if ($i == $displayed{'folder'});
12624:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
12625:                             }
12626:                             $env{'form.phase'} = 'decompress_cleanup';
12627:                             $env{'form.archivedelete'} = 1;
12628:                             $env{'form.archive_count'} = $total-1;
12629:                             $output .=
12630:                                 &process_extracted_files('coursedocs',$docudom,
12631:                                                          $docuname,$destination,
12632:                                                          $dir_root,$hiddenelem);
12633:                         }
12634:                     } else {
12635:                         $warning = &mt('No new items extracted from archive file.');
12636:                     }
12637:                 } else {
12638:                     $output = $display;
12639:                     $error = &mt('An error occurred during extraction from the archive file.');
12640:                 }
12641:             }
12642:         }
12643:     }
12644:     if ($error) {
12645:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12646:                    $error.'</p>'."\n";
12647:     }
12648:     if ($warning) {
12649:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12650:     }
12651:     return $output;
12652: }
12653: 
12654: sub get_extracted {
12655:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
12656:         $titles,$wantform) = @_;
12657:     my $count = 0;
12658:     my $depth = 0;
12659:     my $datatable;
12660:     my @hierarchy;
12661:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
12662:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
12663:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
12664:     foreach my $item (@{$contents}) {
12665:         $count ++;
12666:         @{$dirorder->{$count}} = @hierarchy;
12667:         $titles->{$count} = $item;
12668:         &archive_hierarchy($depth,$count,$parent,$children);
12669:         if ($wantform) {
12670:             $datatable .= &archive_row($is_dir->{$item},$item,
12671:                                        $currdir,$depth,$count);
12672:         }
12673:         if ($is_dir->{$item}) {
12674:             $depth ++;
12675:             push(@hierarchy,$count);
12676:             $parent->{$depth} = $count;
12677:             $datatable .=
12678:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
12679:                                            \$depth,\$count,\@hierarchy,$dirorder,
12680:                                            $children,$parent,$titles,$wantform);
12681:             $depth --;
12682:             pop(@hierarchy);
12683:         }
12684:     }
12685:     return ($count,$datatable);
12686: }
12687: 
12688: sub recurse_extracted_archive {
12689:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
12690:         $children,$parent,$titles,$wantform) = @_;
12691:     my $result='';
12692:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
12693:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
12694:             (ref($dirorder) eq 'HASH')) {
12695:         return $result;
12696:     }
12697:     my $dirptr = 16384;
12698:     my ($newdirlistref,$newlisterror) =
12699:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
12700:     if (ref($newdirlistref) eq 'ARRAY') {
12701:         foreach my $dir_line (@{$newdirlistref}) {
12702:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12703:             unless ($item =~ /^\.+$/) {
12704:                 $$count ++;
12705:                 @{$dirorder->{$$count}} = @{$hierarchy};
12706:                 $titles->{$$count} = $item;
12707:                 &archive_hierarchy($$depth,$$count,$parent,$children);
12708: 
12709:                 my $is_dir;
12710:                 if ($dirptr&$testdir) {
12711:                     $is_dir = 1;
12712:                 }
12713:                 if ($wantform) {
12714:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
12715:                 }
12716:                 if ($is_dir) {
12717:                     $$depth ++;
12718:                     push(@{$hierarchy},$$count);
12719:                     $parent->{$$depth} = $$count;
12720:                     $result .=
12721:                         &recurse_extracted_archive("$currdir/$item",$docudom,
12722:                                                    $docuname,$depth,$count,
12723:                                                    $hierarchy,$dirorder,$children,
12724:                                                    $parent,$titles,$wantform);
12725:                     $$depth --;
12726:                     pop(@{$hierarchy});
12727:                 }
12728:             }
12729:         }
12730:     }
12731:     return $result;
12732: }
12733: 
12734: sub archive_hierarchy {
12735:     my ($depth,$count,$parent,$children) =@_;
12736:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
12737:         if (exists($parent->{$depth})) {
12738:              $children->{$parent->{$depth}} .= $count.':';
12739:         }
12740:     }
12741:     return;
12742: }
12743: 
12744: sub archive_row {
12745:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
12746:     my ($name) = ($item =~ m{([^/]+)$});
12747:     my %choices = &Apache::lonlocal::texthash (
12748:                                        'display'    => 'Add as file',
12749:                                        'dependency' => 'Include as dependency',
12750:                                        'discard'    => 'Discard',
12751:                                       );
12752:     if ($is_dir) {
12753:         $choices{'display'} = &mt('Add as folder'); 
12754:     }
12755:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
12756:     my $offset = 0;
12757:     foreach my $action ('display','dependency','discard') {
12758:         $offset ++;
12759:         if ($action ne 'display') {
12760:             $offset ++;
12761:         }  
12762:         $output .= '<td><span class="LC_nobreak">'.
12763:                    '<label><input type="radio" name="archive_'.$count.
12764:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
12765:         my $text = $choices{$action};
12766:         if ($is_dir) {
12767:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
12768:             if ($action eq 'display') {
12769:                 $text = &mt('Add as folder');
12770:             }
12771:         } else {
12772:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
12773: 
12774:         }
12775:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
12776:         if ($action eq 'dependency') {
12777:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
12778:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
12779:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
12780:                        '<option value=""></option>'."\n".
12781:                        '</select>'."\n".
12782:                        '</div>';
12783:         } elsif ($action eq 'display') {
12784:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
12785:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
12786:                        '</div>';
12787:         }
12788:         $output .= '</td>';
12789:     }
12790:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
12791:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
12792:     for (my $i=0; $i<$depth; $i++) {
12793:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
12794:     }
12795:     if ($is_dir) {
12796:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
12797:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
12798:     } else {
12799:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
12800:     }
12801:     $output .= '&nbsp;'.$name.'</td>'."\n".
12802:                &end_data_table_row();
12803:     return $output;
12804: }
12805: 
12806: sub archive_options_form {
12807:     my ($form,$display,$count,$hiddenelem) = @_;
12808:     my %lt = &Apache::lonlocal::texthash(
12809:                perm => 'Permanently remove archive file?',
12810:                hows => 'How should each extracted item be incorporated in the course?',
12811:                cont => 'Content actions for all',
12812:                addf => 'Add as folder/file',
12813:                incd => 'Include as dependency for a displayed file',
12814:                disc => 'Discard',
12815:                no   => 'No',
12816:                yes  => 'Yes',
12817:                save => 'Save',
12818:     );
12819:     my $output = <<"END";
12820: <form name="$form" method="post" action="">
12821: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
12822: <label>
12823:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
12824: </label>
12825: &nbsp;
12826: <label>
12827:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
12828: </span>
12829: </p>
12830: <input type="hidden" name="phase" value="decompress_cleanup" />
12831: <br />$lt{'hows'}
12832: <div class="LC_columnSection">
12833:   <fieldset>
12834:     <legend>$lt{'cont'}</legend>
12835:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
12836:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
12837:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
12838:   </fieldset>
12839: </div>
12840: END
12841:     return $output.
12842:            &start_data_table()."\n".
12843:            $display."\n".
12844:            &end_data_table()."\n".
12845:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
12846:            $hiddenelem.
12847:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
12848:            '</form>';
12849: }
12850: 
12851: sub archive_javascript {
12852:     my ($startcount,$numitems,$titles,$children) = @_;
12853:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
12854:     my $maintitle = $env{'form.comment'};
12855:     my $scripttag = <<START;
12856: <script type="text/javascript">
12857: // <![CDATA[
12858: 
12859: function checkAll(form,prefix) {
12860:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
12861:     for (var i=0; i < form.elements.length; i++) {
12862:         var id = form.elements[i].id;
12863:         if ((id != '') && (id != undefined)) {
12864:             if (idstr.test(id)) {
12865:                 if (form.elements[i].type == 'radio') {
12866:                     form.elements[i].checked = true;
12867:                     var nostart = i-$startcount;
12868:                     var offset = nostart%7;
12869:                     var count = (nostart-offset)/7;    
12870:                     dependencyCheck(form,count,offset);
12871:                 }
12872:             }
12873:         }
12874:     }
12875: }
12876: 
12877: function propagateCheck(form,count) {
12878:     if (count > 0) {
12879:         var startelement = $startcount + ((count-1) * 7);
12880:         for (var j=1; j<6; j++) {
12881:             if ((j != 2) && (j != 4)) {
12882:                 var item = startelement + j; 
12883:                 if (form.elements[item].type == 'radio') {
12884:                     if (form.elements[item].checked) {
12885:                         containerCheck(form,count,j);
12886:                         break;
12887:                     }
12888:                 }
12889:             }
12890:         }
12891:     }
12892: }
12893: 
12894: numitems = $numitems
12895: var titles = new Array(numitems);
12896: var parents = new Array(numitems);
12897: for (var i=0; i<numitems; i++) {
12898:     parents[i] = new Array;
12899: }
12900: var maintitle = '$maintitle';
12901: 
12902: START
12903: 
12904:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
12905:         my @contents = split(/:/,$children->{$container});
12906:         for (my $i=0; $i<@contents; $i ++) {
12907:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
12908:         }
12909:     }
12910: 
12911:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
12912:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
12913:     }
12914: 
12915:     $scripttag .= <<END;
12916: 
12917: function containerCheck(form,count,offset) {
12918:     if (count > 0) {
12919:         dependencyCheck(form,count,offset);
12920:         var item = (offset+$startcount)+7*(count-1);
12921:         form.elements[item].checked = true;
12922:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
12923:             if (parents[count].length > 0) {
12924:                 for (var j=0; j<parents[count].length; j++) {
12925:                     containerCheck(form,parents[count][j],offset);
12926:                 }
12927:             }
12928:         }
12929:     }
12930: }
12931: 
12932: function dependencyCheck(form,count,offset) {
12933:     if (count > 0) {
12934:         var chosen = (offset+$startcount)+7*(count-1);
12935:         var depitem = $startcount + ((count-1) * 7) + 4;
12936:         var currtype = form.elements[depitem].type;
12937:         if (form.elements[chosen].value == 'dependency') {
12938:             document.getElementById('arc_depon_'+count).style.display='block'; 
12939:             form.elements[depitem].options.length = 0;
12940:             form.elements[depitem].options[0] = new Option('Select','',true,true);
12941:             for (var i=1; i<=numitems; i++) {
12942:                 if (i == count) {
12943:                     continue;
12944:                 }
12945:                 var startelement = $startcount + (i-1) * 7;
12946:                 for (var j=1; j<6; j++) {
12947:                     if ((j != 2) && (j!= 4)) {
12948:                         var item = startelement + j;
12949:                         if (form.elements[item].type == 'radio') {
12950:                             if (form.elements[item].checked) {
12951:                                 if (form.elements[item].value == 'display') {
12952:                                     var n = form.elements[depitem].options.length;
12953:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
12954:                                 }
12955:                             }
12956:                         }
12957:                     }
12958:                 }
12959:             }
12960:         } else {
12961:             document.getElementById('arc_depon_'+count).style.display='none';
12962:             form.elements[depitem].options.length = 0;
12963:             form.elements[depitem].options[0] = new Option('Select','',true,true);
12964:         }
12965:         titleCheck(form,count,offset);
12966:     }
12967: }
12968: 
12969: function propagateSelect(form,count,offset) {
12970:     if (count > 0) {
12971:         var item = (1+offset+$startcount)+7*(count-1);
12972:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
12973:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
12974:             if (parents[count].length > 0) {
12975:                 for (var j=0; j<parents[count].length; j++) {
12976:                     containerSelect(form,parents[count][j],offset,picked);
12977:                 }
12978:             }
12979:         }
12980:     }
12981: }
12982: 
12983: function containerSelect(form,count,offset,picked) {
12984:     if (count > 0) {
12985:         var item = (offset+$startcount)+7*(count-1);
12986:         if (form.elements[item].type == 'radio') {
12987:             if (form.elements[item].value == 'dependency') {
12988:                 if (form.elements[item+1].type == 'select-one') {
12989:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
12990:                         if (form.elements[item+1].options[i].value == picked) {
12991:                             form.elements[item+1].selectedIndex = i;
12992:                             break;
12993:                         }
12994:                     }
12995:                 }
12996:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
12997:                     if (parents[count].length > 0) {
12998:                         for (var j=0; j<parents[count].length; j++) {
12999:                             containerSelect(form,parents[count][j],offset,picked);
13000:                         }
13001:                     }
13002:                 }
13003:             }
13004:         }
13005:     }
13006: }
13007: 
13008: function titleCheck(form,count,offset) {
13009:     if (count > 0) {
13010:         var chosen = (offset+$startcount)+7*(count-1);
13011:         var depitem = $startcount + ((count-1) * 7) + 2;
13012:         var currtype = form.elements[depitem].type;
13013:         if (form.elements[chosen].value == 'display') {
13014:             document.getElementById('arc_title_'+count).style.display='block';
13015:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
13016:                 document.getElementById('archive_title_'+count).value=maintitle;
13017:             }
13018:         } else {
13019:             document.getElementById('arc_title_'+count).style.display='none';
13020:             if (currtype == 'text') { 
13021:                 document.getElementById('archive_title_'+count).value='';
13022:             }
13023:         }
13024:     }
13025:     return;
13026: }
13027: 
13028: // ]]>
13029: </script>
13030: END
13031:     return $scripttag;
13032: }
13033: 
13034: sub process_extracted_files {
13035:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
13036:     my $numitems = $env{'form.archive_count'};
13037:     return if ((!$numitems) || ($numitems =~ /\D/));
13038:     my @ids=&Apache::lonnet::current_machine_ids();
13039:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
13040:         %folders,%containers,%mapinner,%prompttofetch);
13041:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
13042:     if (grep(/^\Q$docuhome\E$/,@ids)) {
13043:         $prefix = &LONCAPA::propath($docudom,$docuname);
13044:         $pathtocheck = "$dir_root/$destination";
13045:         $dir = $dir_root;
13046:         $ishome = 1;
13047:     } else {
13048:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
13049:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
13050:         $dir = "$dir_root/$docudom/$docuname";
13051:     }
13052:     my $currdir = "$dir_root/$destination";
13053:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
13054:     if ($env{'form.folderpath'}) {
13055:         my @items = split('&',$env{'form.folderpath'});
13056:         $folders{'0'} = $items[-2];
13057:         if ($env{'form.folderpath'} =~ /\:1$/) {
13058:             $containers{'0'}='page';
13059:         } else {
13060:             $containers{'0'}='sequence';
13061:         }
13062:     }
13063:     my @archdirs = &get_env_multiple('form.archive_directory');
13064:     if ($numitems) {
13065:         for (my $i=1; $i<=$numitems; $i++) {
13066:             my $path = $env{'form.archive_content_'.$i};
13067:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
13068:                 my $item = $1;
13069:                 $toplevelitems{$item} = $i;
13070:                 if (grep(/^\Q$i\E$/,@archdirs)) {
13071:                     $is_dir{$item} = 1;
13072:                 }
13073:             }
13074:         }
13075:     }
13076:     my ($output,%children,%parent,%titles,%dirorder,$result);
13077:     if (keys(%toplevelitems) > 0) {
13078:         my @contents = sort(keys(%toplevelitems));
13079:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
13080:                                            \%parent,\@contents,\%dirorder,\%titles);
13081:     }
13082:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
13083:     if ($numitems) {
13084:         for (my $i=1; $i<=$numitems; $i++) {
13085:             next if ($env{'form.archive_'.$i} eq 'dependency');
13086:             my $path = $env{'form.archive_content_'.$i};
13087:             if ($path =~ /^\Q$pathtocheck\E/) {
13088:                 if ($env{'form.archive_'.$i} eq 'discard') {
13089:                     if ($prefix ne '' && $path ne '') {
13090:                         if (-e $prefix.$path) {
13091:                             if ((@archdirs > 0) && 
13092:                                 (grep(/^\Q$i\E$/,@archdirs))) {
13093:                                 $todeletedir{$prefix.$path} = 1;
13094:                             } else {
13095:                                 $todelete{$prefix.$path} = 1;
13096:                             }
13097:                         }
13098:                     }
13099:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
13100:                     my ($docstitle,$title,$url,$outer);
13101:                     ($title) = ($path =~ m{/([^/]+)$});
13102:                     $docstitle = $env{'form.archive_title_'.$i};
13103:                     if ($docstitle eq '') {
13104:                         $docstitle = $title;
13105:                     }
13106:                     $outer = 0;
13107:                     if (ref($dirorder{$i}) eq 'ARRAY') {
13108:                         if (@{$dirorder{$i}} > 0) {
13109:                             foreach my $item (reverse(@{$dirorder{$i}})) {
13110:                                 if ($env{'form.archive_'.$item} eq 'display') {
13111:                                     $outer = $item;
13112:                                     last;
13113:                                 }
13114:                             }
13115:                         }
13116:                     }
13117:                     my ($errtext,$fatal) = 
13118:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
13119:                                                '/'.$folders{$outer}.'.'.
13120:                                                $containers{$outer});
13121:                     next if ($fatal);
13122:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
13123:                         if ($context eq 'coursedocs') {
13124:                             $mapinner{$i} = time;
13125:                             $folders{$i} = 'default_'.$mapinner{$i};
13126:                             $containers{$i} = 'sequence';
13127:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
13128:                                       $folders{$i}.'.'.$containers{$i};
13129:                             my $newidx = &LONCAPA::map::getresidx();
13130:                             $LONCAPA::map::resources[$newidx]=
13131:                                 $docstitle.':'.$url.':false:normal:res';
13132:                             push(@LONCAPA::map::order,$newidx);
13133:                             my ($outtext,$errtext) =
13134:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
13135:                                                         $docuname.'/'.$folders{$outer}.
13136:                                                         '.'.$containers{$outer},1,1);
13137:                             $newseqid{$i} = $newidx;
13138:                             unless ($errtext) {
13139:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
13140:                                                        &HTML::Entities::encode($docstitle,'<>&"'))..
13141:                                             '</li>'."\n";
13142:                             }
13143:                         }
13144:                     } else {
13145:                         if ($context eq 'coursedocs') {
13146:                             my $newidx=&LONCAPA::map::getresidx();
13147:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
13148:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
13149:                                       $title;
13150:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
13151:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
13152:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
13153:                                 }
13154:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
13155:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
13156:                                 }
13157:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
13158:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
13159:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
13160:                                         unless ($ishome) {
13161:                                             my $fetch = "$newdest{$i}/$title";
13162:                                             $fetch =~ s/^\Q$prefix$dir\E//;
13163:                                             $prompttofetch{$fetch} = 1;
13164:                                         }
13165:                                    }
13166:                                 }
13167:                                 $LONCAPA::map::resources[$newidx]=
13168:                                     $docstitle.':'.$url.':false:normal:res';
13169:                                 push(@LONCAPA::map::order, $newidx);
13170:                                 my ($outtext,$errtext)=
13171:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
13172:                                                             $docuname.'/'.$folders{$outer}.
13173:                                                             '.'.$containers{$outer},1,1);
13174:                                 unless ($errtext) {
13175:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
13176:                                         $result .= '<li>'.&mt('File: [_1] added to course',
13177:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
13178:                                                    '</li>'."\n";
13179:                                     }
13180:                                 }
13181:                             } else {
13182:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13183:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
13184:                             }
13185:                         }
13186:                     }
13187:                 }
13188:             } else {
13189:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13190:                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
13191:             }
13192:         }
13193:         for (my $i=1; $i<=$numitems; $i++) {
13194:             next unless ($env{'form.archive_'.$i} eq 'dependency');
13195:             my $path = $env{'form.archive_content_'.$i};
13196:             if ($path =~ /^\Q$pathtocheck\E/) {
13197:                 my ($title) = ($path =~ m{/([^/]+)$});
13198:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
13199:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
13200:                     if (ref($dirorder{$i}) eq 'ARRAY') {
13201:                         my ($itemidx,$fullpath,$relpath);
13202:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
13203:                             my $container = $dirorder{$referrer{$i}}->[-1];
13204:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
13205:                                 if ($dirorder{$i}->[$j] eq $container) {
13206:                                     $itemidx = $j;
13207:                                 }
13208:                             }
13209:                         }
13210:                         if ($itemidx eq '') {
13211:                             $itemidx =  0;
13212:                         }
13213:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
13214:                             if ($mapinner{$referrer{$i}}) {
13215:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
13216:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
13217:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
13218:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
13219:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
13220:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
13221:                                             if (!-e $fullpath) {
13222:                                                 mkdir($fullpath,0755);
13223:                                             }
13224:                                         }
13225:                                     } else {
13226:                                         last;
13227:                                     }
13228:                                 }
13229:                             }
13230:                         } elsif ($newdest{$referrer{$i}}) {
13231:                             $fullpath = $newdest{$referrer{$i}};
13232:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
13233:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
13234:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
13235:                                     last;
13236:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
13237:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
13238:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
13239:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
13240:                                         if (!-e $fullpath) {
13241:                                             mkdir($fullpath,0755);
13242:                                         }
13243:                                     }
13244:                                 } else {
13245:                                     last;
13246:                                 }
13247:                             }
13248:                         }
13249:                         if ($fullpath ne '') {
13250:                             if (-e "$prefix$path") {
13251:                                 unless (rename("$prefix$path","$fullpath/$title")) {
13252:                                      $warning .= &mt('Failed to rename dependency').'<br />';
13253:                                 }
13254:                             }
13255:                             if (-e "$fullpath/$title") {
13256:                                 my $showpath;
13257:                                 if ($relpath ne '') {
13258:                                     $showpath = "$relpath/$title";
13259:                                 } else {
13260:                                     $showpath = "/$title";
13261:                                 }
13262:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
13263:                                                       &HTML::Entities::encode($showpath,'<>&"')).
13264:                                            '</li>'."\n";
13265:                                 unless ($ishome) {
13266:                                     my $fetch = "$fullpath/$title";
13267:                                     $fetch =~ s/^\Q$prefix$dir\E//;
13268:                                     $prompttofetch{$fetch} = 1;
13269:                                 }
13270:                             }
13271:                         }
13272:                     }
13273:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
13274:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
13275:                                     &HTML::Entities::encode($path,'<>&"'),
13276:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
13277:                                 '<br />';
13278:                 }
13279:             } else {
13280:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13281:                                 &HTML::Entities::encode($path)).'<br />';
13282:             }
13283:         }
13284:         if (keys(%todelete)) {
13285:             foreach my $key (keys(%todelete)) {
13286:                 unlink($key);
13287:             }
13288:         }
13289:         if (keys(%todeletedir)) {
13290:             foreach my $key (keys(%todeletedir)) {
13291:                 rmdir($key);
13292:             }
13293:         }
13294:         foreach my $dir (sort(keys(%is_dir))) {
13295:             if (($pathtocheck ne '') && ($dir ne ''))  {
13296:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
13297:             }
13298:         }
13299:         if ($result ne '') {
13300:             $output .= '<ul>'."\n".
13301:                        $result."\n".
13302:                        '</ul>';
13303:         }
13304:         unless ($ishome) {
13305:             my $replicationfail;
13306:             foreach my $item (keys(%prompttofetch)) {
13307:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
13308:                 unless ($fetchresult eq 'ok') {
13309:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
13310:                 }
13311:             }
13312:             if ($replicationfail) {
13313:                 $output .= '<p class="LC_error">'.
13314:                            &mt('Course home server failed to retrieve:').'<ul>'.
13315:                            $replicationfail.
13316:                            '</ul></p>';
13317:             }
13318:         }
13319:     } else {
13320:         $warning = &mt('No items found in archive.');
13321:     }
13322:     if ($error) {
13323:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13324:                    $error.'</p>'."\n";
13325:     }
13326:     if ($warning) {
13327:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
13328:     }
13329:     return $output;
13330: }
13331: 
13332: sub cleanup_empty_dirs {
13333:     my ($path) = @_;
13334:     if (($path ne '') && (-d $path)) {
13335:         if (opendir(my $dirh,$path)) {
13336:             my @dircontents = grep(!/^\./,readdir($dirh));
13337:             my $numitems = 0;
13338:             foreach my $item (@dircontents) {
13339:                 if (-d "$path/$item") {
13340:                     &cleanup_empty_dirs("$path/$item");
13341:                     if (-e "$path/$item") {
13342:                         $numitems ++;
13343:                     }
13344:                 } else {
13345:                     $numitems ++;
13346:                 }
13347:             }
13348:             if ($numitems == 0) {
13349:                 rmdir($path);
13350:             }
13351:             closedir($dirh);
13352:         }
13353:     }
13354:     return;
13355: }
13356: 
13357: =pod
13358: 
13359: =item * &get_folder_hierarchy()
13360: 
13361: Provides hierarchy of names of folders/sub-folders containing the current
13362: item,
13363: 
13364: Inputs: 3
13365:      - $navmap - navmaps object
13366: 
13367:      - $map - url for map (either the trigger itself, or map containing
13368:                            the resource, which is the trigger).
13369: 
13370:      - $showitem - 1 => show title for map itself; 0 => do not show.
13371: 
13372: Outputs: 1 @pathitems - array of folder/subfolder names.
13373: 
13374: =cut
13375: 
13376: sub get_folder_hierarchy {
13377:     my ($navmap,$map,$showitem) = @_;
13378:     my @pathitems;
13379:     if (ref($navmap)) {
13380:         my $mapres = $navmap->getResourceByUrl($map);
13381:         if (ref($mapres)) {
13382:             my $pcslist = $mapres->map_hierarchy();
13383:             if ($pcslist ne '') {
13384:                 my @pcs = split(/,/,$pcslist);
13385:                 foreach my $pc (@pcs) {
13386:                     if ($pc == 1) {
13387:                         push(@pathitems,&mt('Main Content'));
13388:                     } else {
13389:                         my $res = $navmap->getByMapPc($pc);
13390:                         if (ref($res)) {
13391:                             my $title = $res->compTitle();
13392:                             $title =~ s/\W+/_/g;
13393:                             if ($title ne '') {
13394:                                 push(@pathitems,$title);
13395:                             }
13396:                         }
13397:                     }
13398:                 }
13399:             }
13400:             if ($showitem) {
13401:                 if ($mapres->{ID} eq '0.0') {
13402:                     push(@pathitems,&mt('Main Content'));
13403:                 } else {
13404:                     my $maptitle = $mapres->compTitle();
13405:                     $maptitle =~ s/\W+/_/g;
13406:                     if ($maptitle ne '') {
13407:                         push(@pathitems,$maptitle);
13408:                     }
13409:                 }
13410:             }
13411:         }
13412:     }
13413:     return @pathitems;
13414: }
13415: 
13416: =pod
13417: 
13418: =item * &get_turnedin_filepath()
13419: 
13420: Determines path in a user's portfolio file for storage of files uploaded
13421: to a specific essayresponse or dropbox item.
13422: 
13423: Inputs: 3 required + 1 optional.
13424: $symb is symb for resource, $uname and $udom are for current user (required).
13425: $caller is optional (can be "submission", if routine is called when storing
13426: an upoaded file when "Submit Answer" button was pressed).
13427: 
13428: Returns array containing $path and $multiresp. 
13429: $path is path in portfolio.  $multiresp is 1 if this resource contains more
13430: than one file upload item.  Callers of routine should append partid as a 
13431: subdirectory to $path in cases where $multiresp is 1.
13432: 
13433: Called by: homework/essayresponse.pm and homework/structuretags.pm
13434: 
13435: =cut
13436: 
13437: sub get_turnedin_filepath {
13438:     my ($symb,$uname,$udom,$caller) = @_;
13439:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
13440:     my $turnindir;
13441:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
13442:     $turnindir = $userhash{'turnindir'};
13443:     my ($path,$multiresp);
13444:     if ($turnindir eq '') {
13445:         if ($caller eq 'submission') {
13446:             $turnindir = &mt('turned in');
13447:             $turnindir =~ s/\W+/_/g;
13448:             my %newhash = (
13449:                             'turnindir' => $turnindir,
13450:                           );
13451:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
13452:         }
13453:     }
13454:     if ($turnindir ne '') {
13455:         $path = '/'.$turnindir.'/';
13456:         my ($multipart,$turnin,@pathitems);
13457:         my $navmap = Apache::lonnavmaps::navmap->new();
13458:         if (defined($navmap)) {
13459:             my $mapres = $navmap->getResourceByUrl($map);
13460:             if (ref($mapres)) {
13461:                 my $pcslist = $mapres->map_hierarchy();
13462:                 if ($pcslist ne '') {
13463:                     foreach my $pc (split(/,/,$pcslist)) {
13464:                         my $res = $navmap->getByMapPc($pc);
13465:                         if (ref($res)) {
13466:                             my $title = $res->compTitle();
13467:                             $title =~ s/\W+/_/g;
13468:                             if ($title ne '') {
13469:                                 if (($pc > 1) && (length($title) > 12)) {
13470:                                     $title = substr($title,0,12);
13471:                                 }
13472:                                 push(@pathitems,$title);
13473:                             }
13474:                         }
13475:                     }
13476:                 }
13477:                 my $maptitle = $mapres->compTitle();
13478:                 $maptitle =~ s/\W+/_/g;
13479:                 if ($maptitle ne '') {
13480:                     if (length($maptitle) > 12) {
13481:                         $maptitle = substr($maptitle,0,12);
13482:                     }
13483:                     push(@pathitems,$maptitle);
13484:                 }
13485:                 unless ($env{'request.state'} eq 'construct') {
13486:                     my $res = $navmap->getBySymb($symb);
13487:                     if (ref($res)) {
13488:                         my $partlist = $res->parts();
13489:                         my $totaluploads = 0;
13490:                         if (ref($partlist) eq 'ARRAY') {
13491:                             foreach my $part (@{$partlist}) {
13492:                                 my @types = $res->responseType($part);
13493:                                 my @ids = $res->responseIds($part);
13494:                                 for (my $i=0; $i < scalar(@ids); $i++) {
13495:                                     if ($types[$i] eq 'essay') {
13496:                                         my $partid = $part.'_'.$ids[$i];
13497:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
13498:                                             $totaluploads ++;
13499:                                         }
13500:                                     }
13501:                                 }
13502:                             }
13503:                             if ($totaluploads > 1) {
13504:                                 $multiresp = 1;
13505:                             }
13506:                         }
13507:                     }
13508:                 }
13509:             } else {
13510:                 return;
13511:             }
13512:         } else {
13513:             return;
13514:         }
13515:         my $restitle=&Apache::lonnet::gettitle($symb);
13516:         $restitle =~ s/\W+/_/g;
13517:         if ($restitle eq '') {
13518:             $restitle = ($resurl =~ m{/[^/]+$});
13519:             if ($restitle eq '') {
13520:                 $restitle = time;
13521:             }
13522:         }
13523:         if (length($restitle) > 12) {
13524:             $restitle = substr($restitle,0,12);
13525:         }
13526:         push(@pathitems,$restitle);
13527:         $path .= join('/',@pathitems);
13528:     }
13529:     return ($path,$multiresp);
13530: }
13531: 
13532: =pod
13533: 
13534: =back
13535: 
13536: =head1 CSV Upload/Handling functions
13537: 
13538: =over 4
13539: 
13540: =item * &upfile_store($r)
13541: 
13542: Store uploaded file, $r should be the HTTP Request object,
13543: needs $env{'form.upfile'}
13544: returns $datatoken to be put into hidden field
13545: 
13546: =cut
13547: 
13548: sub upfile_store {
13549:     my $r=shift;
13550:     $env{'form.upfile'}=~s/\r/\n/gs;
13551:     $env{'form.upfile'}=~s/\f/\n/gs;
13552:     $env{'form.upfile'}=~s/\n+/\n/gs;
13553:     $env{'form.upfile'}=~s/\n+$//gs;
13554: 
13555:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
13556:                                      '_enroll_'.$env{'request.course.id'}.'_'.
13557:                                      time.'_'.$$);
13558:     return if ($datatoken eq '');
13559: 
13560:     {
13561:         my $datafile = $r->dir_config('lonDaemons').
13562:                            '/tmp/'.$datatoken.'.tmp';
13563:         if ( open(my $fh,'>',$datafile) ) {
13564:             print $fh $env{'form.upfile'};
13565:             close($fh);
13566:         }
13567:     }
13568:     return $datatoken;
13569: }
13570: 
13571: =pod
13572: 
13573: =item * &load_tmp_file($r,$datatoken)
13574: 
13575: Load uploaded file from tmp, $r should be the HTTP Request object,
13576: $datatoken is the name to assign to the temporary file.
13577: sets $env{'form.upfile'} to the contents of the file
13578: 
13579: =cut
13580: 
13581: sub load_tmp_file {
13582:     my ($r,$datatoken) = @_;
13583:     return if ($datatoken eq '');
13584:     my @studentdata=();
13585:     {
13586:         my $studentfile = $r->dir_config('lonDaemons').
13587:                               '/tmp/'.$datatoken.'.tmp';
13588:         if ( open(my $fh,'<',$studentfile) ) {
13589:             @studentdata=<$fh>;
13590:             close($fh);
13591:         }
13592:     }
13593:     $env{'form.upfile'}=join('',@studentdata);
13594: }
13595: 
13596: sub valid_datatoken {
13597:     my ($datatoken) = @_;
13598:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
13599:         return $datatoken;
13600:     }
13601:     return;
13602: }
13603: 
13604: =pod
13605: 
13606: =item * &upfile_record_sep()
13607: 
13608: Separate uploaded file into records
13609: returns array of records,
13610: needs $env{'form.upfile'} and $env{'form.upfiletype'}
13611: 
13612: =cut
13613: 
13614: sub upfile_record_sep {
13615:     if ($env{'form.upfiletype'} eq 'xml') {
13616:     } else {
13617: 	my @records;
13618: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
13619: 	    if ($line=~/^\s*$/) { next; }
13620: 	    push(@records,$line);
13621: 	}
13622: 	return @records;
13623:     }
13624: }
13625: 
13626: =pod
13627: 
13628: =item * &record_sep($record)
13629: 
13630: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
13631: 
13632: =cut
13633: 
13634: sub takeleft {
13635:     my $index=shift;
13636:     return substr('0000'.$index,-4,4);
13637: }
13638: 
13639: sub record_sep {
13640:     my $record=shift;
13641:     my %components=();
13642:     if ($env{'form.upfiletype'} eq 'xml') {
13643:     } elsif ($env{'form.upfiletype'} eq 'space') {
13644:         my $i=0;
13645:         foreach my $field (split(/\s+/,$record)) {
13646:             $field=~s/^(\"|\')//;
13647:             $field=~s/(\"|\')$//;
13648:             $components{&takeleft($i)}=$field;
13649:             $i++;
13650:         }
13651:     } elsif ($env{'form.upfiletype'} eq 'tab') {
13652:         my $i=0;
13653:         foreach my $field (split(/\t/,$record)) {
13654:             $field=~s/^(\"|\')//;
13655:             $field=~s/(\"|\')$//;
13656:             $components{&takeleft($i)}=$field;
13657:             $i++;
13658:         }
13659:     } else {
13660:         my $separator=',';
13661:         if ($env{'form.upfiletype'} eq 'semisv') {
13662:             $separator=';';
13663:         }
13664:         my $i=0;
13665: # the character we are looking for to indicate the end of a quote or a record 
13666:         my $looking_for=$separator;
13667: # do not add the characters to the fields
13668:         my $ignore=0;
13669: # we just encountered a separator (or the beginning of the record)
13670:         my $just_found_separator=1;
13671: # store the field we are working on here
13672:         my $field='';
13673: # work our way through all characters in record
13674:         foreach my $character ($record=~/(.)/g) {
13675:             if ($character eq $looking_for) {
13676:                if ($character ne $separator) {
13677: # Found the end of a quote, again looking for separator
13678:                   $looking_for=$separator;
13679:                   $ignore=1;
13680:                } else {
13681: # Found a separator, store away what we got
13682:                   $components{&takeleft($i)}=$field;
13683: 	          $i++;
13684:                   $just_found_separator=1;
13685:                   $ignore=0;
13686:                   $field='';
13687:                }
13688:                next;
13689:             }
13690: # single or double quotation marks after a separator indicate beginning of a quote
13691: # we are now looking for the end of the quote and need to ignore separators
13692:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
13693:                $looking_for=$character;
13694:                next;
13695:             }
13696: # ignore would be true after we reached the end of a quote
13697:             if ($ignore) { next; }
13698:             if (($just_found_separator) && ($character=~/\s/)) { next; }
13699:             $field.=$character;
13700:             $just_found_separator=0; 
13701:         }
13702: # catch the very last entry, since we never encountered the separator
13703:         $components{&takeleft($i)}=$field;
13704:     }
13705:     return %components;
13706: }
13707: 
13708: ######################################################
13709: ######################################################
13710: 
13711: =pod
13712: 
13713: =item * &upfile_select_html()
13714: 
13715: Return HTML code to select a file from the users machine and specify 
13716: the file type.
13717: 
13718: =cut
13719: 
13720: ######################################################
13721: ######################################################
13722: sub upfile_select_html {
13723:     my %Types = (
13724:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
13725:                  semisv => &mt('Semicolon separated values'),
13726:                  space => &mt('Space separated'),
13727:                  tab   => &mt('Tabulator separated'),
13728: #                 xml   => &mt('HTML/XML'),
13729:                  );
13730:     my $Str = '<input type="file" name="upfile" size="50" />'.
13731:         '<br />'.&mt('Type').': <select name="upfiletype">';
13732:     foreach my $type (sort(keys(%Types))) {
13733:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
13734:     }
13735:     $Str .= "</select>\n";
13736:     return $Str;
13737: }
13738: 
13739: sub get_samples {
13740:     my ($records,$toget) = @_;
13741:     my @samples=({});
13742:     my $got=0;
13743:     foreach my $rec (@$records) {
13744: 	my %temp = &record_sep($rec);
13745: 	if (! grep(/\S/, values(%temp))) { next; }
13746: 	if (%temp) {
13747: 	    $samples[$got]=\%temp;
13748: 	    $got++;
13749: 	    if ($got == $toget) { last; }
13750: 	}
13751:     }
13752:     return \@samples;
13753: }
13754: 
13755: ######################################################
13756: ######################################################
13757: 
13758: =pod
13759: 
13760: =item * &csv_print_samples($r,$records)
13761: 
13762: Prints a table of sample values from each column uploaded $r is an
13763: Apache Request ref, $records is an arrayref from
13764: &Apache::loncommon::upfile_record_sep
13765: 
13766: =cut
13767: 
13768: ######################################################
13769: ######################################################
13770: sub csv_print_samples {
13771:     my ($r,$records) = @_;
13772:     my $samples = &get_samples($records,5);
13773: 
13774:     $r->print(&mt('Samples').'<br />'.&start_data_table().
13775:               &start_data_table_header_row());
13776:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
13777:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
13778:     $r->print(&end_data_table_header_row());
13779:     foreach my $hash (@$samples) {
13780: 	$r->print(&start_data_table_row());
13781: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13782: 	    $r->print('<td>');
13783: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
13784: 	    $r->print('</td>');
13785: 	}
13786: 	$r->print(&end_data_table_row());
13787:     }
13788:     $r->print(&end_data_table().'<br />'."\n");
13789: }
13790: 
13791: ######################################################
13792: ######################################################
13793: 
13794: =pod
13795: 
13796: =item * &csv_print_select_table($r,$records,$d)
13797: 
13798: Prints a table to create associations between values and table columns.
13799: 
13800: $r is an Apache Request ref,
13801: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
13802: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
13803: 
13804: =cut
13805: 
13806: ######################################################
13807: ######################################################
13808: sub csv_print_select_table {
13809:     my ($r,$records,$d) = @_;
13810:     my $i=0;
13811:     my $samples = &get_samples($records,1);
13812:     $r->print(&mt('Associate columns with student attributes.')."\n".
13813: 	      &start_data_table().&start_data_table_header_row().
13814:               '<th>'.&mt('Attribute').'</th>'.
13815:               '<th>'.&mt('Column').'</th>'.
13816:               &end_data_table_header_row()."\n");
13817:     foreach my $array_ref (@$d) {
13818: 	my ($value,$display,$defaultcol)=@{ $array_ref };
13819: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
13820: 
13821: 	$r->print('<td><select name="f'.$i.'"'.
13822: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
13823: 	$r->print('<option value="none"></option>');
13824: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13825: 	    $r->print('<option value="'.$sample.'"'.
13826:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
13827:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
13828: 	}
13829: 	$r->print('</select></td>'.&end_data_table_row()."\n");
13830: 	$i++;
13831:     }
13832:     $r->print(&end_data_table());
13833:     $i--;
13834:     return $i;
13835: }
13836: 
13837: ######################################################
13838: ######################################################
13839: 
13840: =pod
13841: 
13842: =item * &csv_samples_select_table($r,$records,$d)
13843: 
13844: Prints a table of sample values from the upload and can make associate samples to internal names.
13845: 
13846: $r is an Apache Request ref,
13847: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
13848: $d is an array of 2 element arrays (internal name, displayed name)
13849: 
13850: =cut
13851: 
13852: ######################################################
13853: ######################################################
13854: sub csv_samples_select_table {
13855:     my ($r,$records,$d) = @_;
13856:     my $i=0;
13857:     #
13858:     my $max_samples = 5;
13859:     my $samples = &get_samples($records,$max_samples);
13860:     $r->print(&start_data_table().
13861:               &start_data_table_header_row().'<th>'.
13862:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
13863:               &end_data_table_header_row());
13864: 
13865:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
13866: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
13867: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
13868: 	foreach my $option (@$d) {
13869: 	    my ($value,$display,$defaultcol)=@{ $option };
13870: 	    $r->print('<option value="'.$value.'"'.
13871:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
13872:                       $display.'</option>');
13873: 	}
13874: 	$r->print('</select></td><td>');
13875: 	foreach my $line (0..($max_samples-1)) {
13876: 	    if (defined($samples->[$line]{$key})) { 
13877: 		$r->print($samples->[$line]{$key}."<br />\n"); 
13878: 	    }
13879: 	}
13880: 	$r->print('</td>'.&end_data_table_row());
13881: 	$i++;
13882:     }
13883:     $r->print(&end_data_table());
13884:     $i--;
13885:     return($i);
13886: }
13887: 
13888: ######################################################
13889: ######################################################
13890: 
13891: =pod
13892: 
13893: =item * &clean_excel_name($name)
13894: 
13895: Returns a replacement for $name which does not contain any illegal characters.
13896: 
13897: =cut
13898: 
13899: ######################################################
13900: ######################################################
13901: sub clean_excel_name {
13902:     my ($name) = @_;
13903:     $name =~ s/[:\*\?\/\\]//g;
13904:     if (length($name) > 31) {
13905:         $name = substr($name,0,31);
13906:     }
13907:     return $name;
13908: }
13909: 
13910: =pod
13911: 
13912: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
13913: 
13914: Returns either 1 or undef
13915: 
13916: 1 if the part is to be hidden, undef if it is to be shown
13917: 
13918: Arguments are:
13919: 
13920: $id the id of the part to be checked
13921: $symb, optional the symb of the resource to check
13922: $udom, optional the domain of the user to check for
13923: $uname, optional the username of the user to check for
13924: 
13925: =cut
13926: 
13927: sub check_if_partid_hidden {
13928:     my ($id,$symb,$udom,$uname) = @_;
13929:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
13930: 					 $symb,$udom,$uname);
13931:     my $truth=1;
13932:     #if the string starts with !, then the list is the list to show not hide
13933:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
13934:     my @hiddenlist=split(/,/,$hiddenparts);
13935:     foreach my $checkid (@hiddenlist) {
13936: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
13937:     }
13938:     return !$truth;
13939: }
13940: 
13941: 
13942: ############################################################
13943: ############################################################
13944: 
13945: =pod
13946: 
13947: =back 
13948: 
13949: =head1 cgi-bin script and graphing routines
13950: 
13951: =over 4
13952: 
13953: =item * &get_cgi_id()
13954: 
13955: Inputs: none
13956: 
13957: Returns an id which can be used to pass environment variables
13958: to various cgi-bin scripts.  These environment variables will
13959: be removed from the users environment after a given time by
13960: the routine &Apache::lonnet::transfer_profile_to_env.
13961: 
13962: =cut
13963: 
13964: ############################################################
13965: ############################################################
13966: my $uniq=0;
13967: sub get_cgi_id {
13968:     $uniq=($uniq+1)%100000;
13969:     return (time.'_'.$$.'_'.$uniq);
13970: }
13971: 
13972: ############################################################
13973: ############################################################
13974: 
13975: =pod
13976: 
13977: =item * &DrawBarGraph()
13978: 
13979: Facilitates the plotting of data in a (stacked) bar graph.
13980: Puts plot definition data into the users environment in order for 
13981: graph.png to plot it.  Returns an <img> tag for the plot.
13982: The bars on the plot are labeled '1','2',...,'n'.
13983: 
13984: Inputs:
13985: 
13986: =over 4
13987: 
13988: =item $Title: string, the title of the plot
13989: 
13990: =item $xlabel: string, text describing the X-axis of the plot
13991: 
13992: =item $ylabel: string, text describing the Y-axis of the plot
13993: 
13994: =item $Max: scalar, the maximum Y value to use in the plot
13995: If $Max is < any data point, the graph will not be rendered.
13996: 
13997: =item $colors: array ref holding the colors to be used for the data sets when
13998: they are plotted.  If undefined, default values will be used.
13999: 
14000: =item $labels: array ref holding the labels to use on the x-axis for the bars.
14001: 
14002: =item @Values: An array of array references.  Each array reference holds data
14003: to be plotted in a stacked bar chart.
14004: 
14005: =item If the final element of @Values is a hash reference the key/value
14006: pairs will be added to the graph definition.
14007: 
14008: =back
14009: 
14010: Returns:
14011: 
14012: An <img> tag which references graph.png and the appropriate identifying
14013: information for the plot.
14014: 
14015: =cut
14016: 
14017: ############################################################
14018: ############################################################
14019: sub DrawBarGraph {
14020:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
14021:     #
14022:     if (! defined($colors)) {
14023:         $colors = ['#33ff00', 
14024:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
14025:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
14026:                   ]; 
14027:     }
14028:     my $extra_settings = {};
14029:     if (ref($Values[-1]) eq 'HASH') {
14030:         $extra_settings = pop(@Values);
14031:     }
14032:     #
14033:     my $identifier = &get_cgi_id();
14034:     my $id = 'cgi.'.$identifier;        
14035:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
14036:         return '';
14037:     }
14038:     #
14039:     my @Labels;
14040:     if (defined($labels)) {
14041:         @Labels = @$labels;
14042:     } else {
14043:         for (my $i=0;$i<@{$Values[0]};$i++) {
14044:             push(@Labels,$i+1);
14045:         }
14046:     }
14047:     #
14048:     my $NumBars = scalar(@{$Values[0]});
14049:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
14050:     my %ValuesHash;
14051:     my $NumSets=1;
14052:     foreach my $array (@Values) {
14053:         next if (! ref($array));
14054:         $ValuesHash{$id.'.data.'.$NumSets++} = 
14055:             join(',',@$array);
14056:     }
14057:     #
14058:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
14059:     if ($NumBars < 3) {
14060:         $width = 120+$NumBars*32;
14061:         $xskip = 1;
14062:         $bar_width = 30;
14063:     } elsif ($NumBars < 5) {
14064:         $width = 120+$NumBars*20;
14065:         $xskip = 1;
14066:         $bar_width = 20;
14067:     } elsif ($NumBars < 10) {
14068:         $width = 120+$NumBars*15;
14069:         $xskip = 1;
14070:         $bar_width = 15;
14071:     } elsif ($NumBars <= 25) {
14072:         $width = 120+$NumBars*11;
14073:         $xskip = 5;
14074:         $bar_width = 8;
14075:     } elsif ($NumBars <= 50) {
14076:         $width = 120+$NumBars*8;
14077:         $xskip = 5;
14078:         $bar_width = 4;
14079:     } else {
14080:         $width = 120+$NumBars*8;
14081:         $xskip = 5;
14082:         $bar_width = 4;
14083:     }
14084:     #
14085:     $Max = 1 if ($Max < 1);
14086:     if ( int($Max) < $Max ) {
14087:         $Max++;
14088:         $Max = int($Max);
14089:     }
14090:     $Title  = '' if (! defined($Title));
14091:     $xlabel = '' if (! defined($xlabel));
14092:     $ylabel = '' if (! defined($ylabel));
14093:     $ValuesHash{$id.'.title'}    = &escape($Title);
14094:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
14095:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
14096:     $ValuesHash{$id.'.y_max_value'} = $Max;
14097:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
14098:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
14099:     $ValuesHash{$id.'.PlotType'} = 'bar';
14100:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14101:     $ValuesHash{$id.'.height'}   = $height;
14102:     $ValuesHash{$id.'.width'}    = $width;
14103:     $ValuesHash{$id.'.xskip'}    = $xskip;
14104:     $ValuesHash{$id.'.bar_width'} = $bar_width;
14105:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
14106:     #
14107:     # Deal with other parameters
14108:     while (my ($key,$value) = each(%$extra_settings)) {
14109:         $ValuesHash{$id.'.'.$key} = $value;
14110:     }
14111:     #
14112:     &Apache::lonnet::appenv(\%ValuesHash);
14113:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14114: }
14115: 
14116: ############################################################
14117: ############################################################
14118: 
14119: =pod
14120: 
14121: =item * &DrawXYGraph()
14122: 
14123: Facilitates the plotting of data in an XY graph.
14124: Puts plot definition data into the users environment in order for 
14125: graph.png to plot it.  Returns an <img> tag for the plot.
14126: 
14127: Inputs:
14128: 
14129: =over 4
14130: 
14131: =item $Title: string, the title of the plot
14132: 
14133: =item $xlabel: string, text describing the X-axis of the plot
14134: 
14135: =item $ylabel: string, text describing the Y-axis of the plot
14136: 
14137: =item $Max: scalar, the maximum Y value to use in the plot
14138: If $Max is < any data point, the graph will not be rendered.
14139: 
14140: =item $colors: Array ref containing the hex color codes for the data to be 
14141: plotted in.  If undefined, default values will be used.
14142: 
14143: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
14144: 
14145: =item $Ydata: Array ref containing Array refs.  
14146: Each of the contained arrays will be plotted as a separate curve.
14147: 
14148: =item %Values: hash indicating or overriding any default values which are 
14149: passed to graph.png.  
14150: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
14151: 
14152: =back
14153: 
14154: Returns:
14155: 
14156: An <img> tag which references graph.png and the appropriate identifying
14157: information for the plot.
14158: 
14159: =cut
14160: 
14161: ############################################################
14162: ############################################################
14163: sub DrawXYGraph {
14164:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
14165:     #
14166:     # Create the identifier for the graph
14167:     my $identifier = &get_cgi_id();
14168:     my $id = 'cgi.'.$identifier;
14169:     #
14170:     $Title  = '' if (! defined($Title));
14171:     $xlabel = '' if (! defined($xlabel));
14172:     $ylabel = '' if (! defined($ylabel));
14173:     my %ValuesHash = 
14174:         (
14175:          $id.'.title'  => &escape($Title),
14176:          $id.'.xlabel' => &escape($xlabel),
14177:          $id.'.ylabel' => &escape($ylabel),
14178:          $id.'.y_max_value'=> $Max,
14179:          $id.'.labels'     => join(',',@$Xlabels),
14180:          $id.'.PlotType'   => 'XY',
14181:          );
14182:     #
14183:     if (defined($colors) && ref($colors) eq 'ARRAY') {
14184:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14185:     }
14186:     #
14187:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
14188:         return '';
14189:     }
14190:     my $NumSets=1;
14191:     foreach my $array (@{$Ydata}){
14192:         next if (! ref($array));
14193:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
14194:     }
14195:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
14196:     #
14197:     # Deal with other parameters
14198:     while (my ($key,$value) = each(%Values)) {
14199:         $ValuesHash{$id.'.'.$key} = $value;
14200:     }
14201:     #
14202:     &Apache::lonnet::appenv(\%ValuesHash);
14203:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14204: }
14205: 
14206: ############################################################
14207: ############################################################
14208: 
14209: =pod
14210: 
14211: =item * &DrawXYYGraph()
14212: 
14213: Facilitates the plotting of data in an XY graph with two Y axes.
14214: Puts plot definition data into the users environment in order for 
14215: graph.png to plot it.  Returns an <img> tag for the plot.
14216: 
14217: Inputs:
14218: 
14219: =over 4
14220: 
14221: =item $Title: string, the title of the plot
14222: 
14223: =item $xlabel: string, text describing the X-axis of the plot
14224: 
14225: =item $ylabel: string, text describing the Y-axis of the plot
14226: 
14227: =item $colors: Array ref containing the hex color codes for the data to be 
14228: plotted in.  If undefined, default values will be used.
14229: 
14230: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
14231: 
14232: =item $Ydata1: The first data set
14233: 
14234: =item $Min1: The minimum value of the left Y-axis
14235: 
14236: =item $Max1: The maximum value of the left Y-axis
14237: 
14238: =item $Ydata2: The second data set
14239: 
14240: =item $Min2: The minimum value of the right Y-axis
14241: 
14242: =item $Max2: The maximum value of the left Y-axis
14243: 
14244: =item %Values: hash indicating or overriding any default values which are 
14245: passed to graph.png.  
14246: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
14247: 
14248: =back
14249: 
14250: Returns:
14251: 
14252: An <img> tag which references graph.png and the appropriate identifying
14253: information for the plot.
14254: 
14255: =cut
14256: 
14257: ############################################################
14258: ############################################################
14259: sub DrawXYYGraph {
14260:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
14261:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
14262:     #
14263:     # Create the identifier for the graph
14264:     my $identifier = &get_cgi_id();
14265:     my $id = 'cgi.'.$identifier;
14266:     #
14267:     $Title  = '' if (! defined($Title));
14268:     $xlabel = '' if (! defined($xlabel));
14269:     $ylabel = '' if (! defined($ylabel));
14270:     my %ValuesHash = 
14271:         (
14272:          $id.'.title'  => &escape($Title),
14273:          $id.'.xlabel' => &escape($xlabel),
14274:          $id.'.ylabel' => &escape($ylabel),
14275:          $id.'.labels' => join(',',@$Xlabels),
14276:          $id.'.PlotType' => 'XY',
14277:          $id.'.NumSets' => 2,
14278:          $id.'.two_axes' => 1,
14279:          $id.'.y1_max_value' => $Max1,
14280:          $id.'.y1_min_value' => $Min1,
14281:          $id.'.y2_max_value' => $Max2,
14282:          $id.'.y2_min_value' => $Min2,
14283:          );
14284:     #
14285:     if (defined($colors) && ref($colors) eq 'ARRAY') {
14286:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14287:     }
14288:     #
14289:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
14290:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
14291:         return '';
14292:     }
14293:     my $NumSets=1;
14294:     foreach my $array ($Ydata1,$Ydata2){
14295:         next if (! ref($array));
14296:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
14297:     }
14298:     #
14299:     # Deal with other parameters
14300:     while (my ($key,$value) = each(%Values)) {
14301:         $ValuesHash{$id.'.'.$key} = $value;
14302:     }
14303:     #
14304:     &Apache::lonnet::appenv(\%ValuesHash);
14305:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14306: }
14307: 
14308: ############################################################
14309: ############################################################
14310: 
14311: =pod
14312: 
14313: =back 
14314: 
14315: =head1 Statistics helper routines?  
14316: 
14317: Bad place for them but what the hell.
14318: 
14319: =over 4
14320: 
14321: =item * &chartlink()
14322: 
14323: Returns a link to the chart for a specific student.  
14324: 
14325: Inputs:
14326: 
14327: =over 4
14328: 
14329: =item $linktext: The text of the link
14330: 
14331: =item $sname: The students username
14332: 
14333: =item $sdomain: The students domain
14334: 
14335: =back
14336: 
14337: =back
14338: 
14339: =cut
14340: 
14341: ############################################################
14342: ############################################################
14343: sub chartlink {
14344:     my ($linktext, $sname, $sdomain) = @_;
14345:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
14346:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
14347:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
14348:        '">'.$linktext.'</a>';
14349: }
14350: 
14351: #######################################################
14352: #######################################################
14353: 
14354: =pod
14355: 
14356: =head1 Course Environment Routines
14357: 
14358: =over 4
14359: 
14360: =item * &restore_course_settings()
14361: 
14362: =item * &store_course_settings()
14363: 
14364: Restores/Store indicated form parameters from the course environment.
14365: Will not overwrite existing values of the form parameters.
14366: 
14367: Inputs: 
14368: a scalar describing the data (e.g. 'chart', 'problem_analysis')
14369: 
14370: a hash ref describing the data to be stored.  For example:
14371:    
14372: %Save_Parameters = ('Status' => 'scalar',
14373:     'chartoutputmode' => 'scalar',
14374:     'chartoutputdata' => 'scalar',
14375:     'Section' => 'array',
14376:     'Group' => 'array',
14377:     'StudentData' => 'array',
14378:     'Maps' => 'array');
14379: 
14380: Returns: both routines return nothing
14381: 
14382: =back
14383: 
14384: =cut
14385: 
14386: #######################################################
14387: #######################################################
14388: sub store_course_settings {
14389:     return &store_settings($env{'request.course.id'},@_);
14390: }
14391: 
14392: sub store_settings {
14393:     # save to the environment
14394:     # appenv the same items, just to be safe
14395:     my $udom  = $env{'user.domain'};
14396:     my $uname = $env{'user.name'};
14397:     my ($context,$prefix,$Settings) = @_;
14398:     my %SaveHash;
14399:     my %AppHash;
14400:     while (my ($setting,$type) = each(%$Settings)) {
14401:         my $basename = join('.','internal',$context,$prefix,$setting);
14402:         my $envname = 'environment.'.$basename;
14403:         if (exists($env{'form.'.$setting})) {
14404:             # Save this value away
14405:             if ($type eq 'scalar' &&
14406:                 (! exists($env{$envname}) || 
14407:                  $env{$envname} ne $env{'form.'.$setting})) {
14408:                 $SaveHash{$basename} = $env{'form.'.$setting};
14409:                 $AppHash{$envname}   = $env{'form.'.$setting};
14410:             } elsif ($type eq 'array') {
14411:                 my $stored_form;
14412:                 if (ref($env{'form.'.$setting})) {
14413:                     $stored_form = join(',',
14414:                                         map {
14415:                                             &escape($_);
14416:                                         } sort(@{$env{'form.'.$setting}}));
14417:                 } else {
14418:                     $stored_form = 
14419:                         &escape($env{'form.'.$setting});
14420:                 }
14421:                 # Determine if the array contents are the same.
14422:                 if ($stored_form ne $env{$envname}) {
14423:                     $SaveHash{$basename} = $stored_form;
14424:                     $AppHash{$envname}   = $stored_form;
14425:                 }
14426:             }
14427:         }
14428:     }
14429:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
14430:                                           $udom,$uname);
14431:     if ($put_result !~ /^(ok|delayed)/) {
14432:         &Apache::lonnet::logthis('unable to save form parameters, '.
14433:                                  'got error:'.$put_result);
14434:     }
14435:     # Make sure these settings stick around in this session, too
14436:     &Apache::lonnet::appenv(\%AppHash);
14437:     return;
14438: }
14439: 
14440: sub restore_course_settings {
14441:     return &restore_settings($env{'request.course.id'},@_);
14442: }
14443: 
14444: sub restore_settings {
14445:     my ($context,$prefix,$Settings) = @_;
14446:     while (my ($setting,$type) = each(%$Settings)) {
14447:         next if (exists($env{'form.'.$setting}));
14448:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
14449:             '.'.$setting;
14450:         if (exists($env{$envname})) {
14451:             if ($type eq 'scalar') {
14452:                 $env{'form.'.$setting} = $env{$envname};
14453:             } elsif ($type eq 'array') {
14454:                 $env{'form.'.$setting} = [ 
14455:                                            map { 
14456:                                                &unescape($_); 
14457:                                            } split(',',$env{$envname})
14458:                                            ];
14459:             }
14460:         }
14461:     }
14462: }
14463: 
14464: #######################################################
14465: #######################################################
14466: 
14467: =pod
14468: 
14469: =head1 Domain E-mail Routines  
14470: 
14471: =over 4
14472: 
14473: =item * &build_recipient_list()
14474: 
14475: Build recipient lists for following types of e-mail:
14476: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
14477: (d) Help requests, (e) Course requests needing approval, (f) loncapa
14478: module change checking, student/employee ID conflict checks, as
14479: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
14480: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
14481: 
14482: Inputs:
14483: defmail (scalar - email address of default recipient),
14484: mailing type (scalar: errormail, packagesmail, helpdeskmail,
14485: requestsmail, updatesmail, or idconflictsmail).
14486: 
14487: defdom (domain for which to retrieve configuration settings),
14488: 
14489: origmail (scalar - email address of recipient from loncapa.conf,
14490: i.e., predates configuration by DC via domainprefs.pm
14491: 
14492: $requname username of requester (if mailing type is helpdeskmail)
14493: 
14494: $requdom domain of requester (if mailing type is helpdeskmail)
14495: 
14496: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
14497: 
14498: Returns: comma separated list of addresses to which to send e-mail.
14499: 
14500: =back
14501: 
14502: =cut
14503: 
14504: ############################################################
14505: ############################################################
14506: sub build_recipient_list {
14507:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
14508:     my @recipients;
14509:     my ($otheremails,$lastresort,$allbcc,$addtext);
14510:     my %domconfig =
14511:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
14512:     if (ref($domconfig{'contacts'}) eq 'HASH') {
14513:         if (exists($domconfig{'contacts'}{$mailing})) {
14514:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
14515:                 my @contacts = ('adminemail','supportemail');
14516:                 foreach my $item (@contacts) {
14517:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
14518:                         my $addr = $domconfig{'contacts'}{$item}; 
14519:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
14520:                             push(@recipients,$addr);
14521:                         }
14522:                     }
14523:                 }
14524:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
14525:                 if ($mailing eq 'helpdeskmail') {
14526:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
14527:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
14528:                         my @ok_bccs;
14529:                         foreach my $bcc (@bccs) {
14530:                             $bcc =~ s/^\s+//g;
14531:                             $bcc =~ s/\s+$//g;
14532:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14533:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14534:                                     push(@ok_bccs,$bcc);
14535:                                 }
14536:                             }
14537:                         }
14538:                         if (@ok_bccs > 0) {
14539:                             $allbcc = join(', ',@ok_bccs);
14540:                         }
14541:                     }
14542:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
14543:                 }
14544:             }
14545:         } elsif ($origmail ne '') {
14546:             $lastresort = $origmail;
14547:         }
14548:         if ($mailing eq 'helpdeskmail') {
14549:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
14550:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
14551:                 my ($inststatus,$inststatus_checked);
14552:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
14553:                     ($env{'user.domain'} ne 'public')) {
14554:                     $inststatus_checked = 1;
14555:                     $inststatus = $env{'environment.inststatus'};
14556:                 }
14557:                 unless ($inststatus_checked) {
14558:                     if (($requname ne '') && ($requdom ne '')) {
14559:                         if (($requname =~ /^$match_username$/) &&
14560:                             ($requdom =~ /^$match_domain$/) &&
14561:                             (&Apache::lonnet::domain($requdom))) {
14562:                             my $requhome = &Apache::lonnet::homeserver($requname,
14563:                                                                       $requdom);
14564:                             unless ($requhome eq 'no_host') {
14565:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
14566:                                 $inststatus = $userenv{'inststatus'};
14567:                                 $inststatus_checked = 1;
14568:                             }
14569:                         }
14570:                     }
14571:                 }
14572:                 unless ($inststatus_checked) {
14573:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
14574:                         my %srch = (srchby     => 'email',
14575:                                     srchdomain => $defdom,
14576:                                     srchterm   => $reqemail,
14577:                                     srchtype   => 'exact');
14578:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
14579:                         foreach my $uname (keys(%srch_results)) {
14580:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
14581:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
14582:                                 $inststatus_checked = 1;
14583:                                 last;
14584:                             }
14585:                         }
14586:                         unless ($inststatus_checked) {
14587:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
14588:                             if ($dirsrchres eq 'ok') {
14589:                                 foreach my $uname (keys(%srch_results)) {
14590:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
14591:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
14592:                                         $inststatus_checked = 1;
14593:                                         last;
14594:                                     }
14595:                                 }
14596:                             }
14597:                         }
14598:                     }
14599:                 }
14600:                 if ($inststatus ne '') {
14601:                     foreach my $status (split(/\:/,$inststatus)) {
14602:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
14603:                             my @contacts = ('adminemail','supportemail');
14604:                             foreach my $item (@contacts) {
14605:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
14606:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
14607:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
14608:                                         push(@recipients,$addr);
14609:                                     }
14610:                                 }
14611:                             }
14612:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
14613:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
14614:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
14615:                                 my @ok_bccs;
14616:                                 foreach my $bcc (@bccs) {
14617:                                     $bcc =~ s/^\s+//g;
14618:                                     $bcc =~ s/\s+$//g;
14619:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14620:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14621:                                             push(@ok_bccs,$bcc);
14622:                                         }
14623:                                     }
14624:                                 }
14625:                                 if (@ok_bccs > 0) {
14626:                                     $allbcc = join(', ',@ok_bccs);
14627:                                 }
14628:                             }
14629:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
14630:                             last;
14631:                         }
14632:                     }
14633:                 }
14634:             }
14635:         }
14636:     } elsif ($origmail ne '') {
14637:         $lastresort = $origmail;
14638:     }
14639:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
14640:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
14641:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
14642:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
14643:             my %what = (
14644:                           perlvar => 1,
14645:                        );
14646:             my $primary = &Apache::lonnet::domain($defdom,'primary');
14647:             if ($primary) {
14648:                 my $gotaddr;
14649:                 my ($result,$returnhash) =
14650:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
14651:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
14652:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
14653:                         $lastresort = $returnhash->{'lonSupportEMail'};
14654:                         $gotaddr = 1;
14655:                     }
14656:                 }
14657:                 unless ($gotaddr) {
14658:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
14659:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
14660:                     unless ($uintdom eq $intdom) {
14661:                         my %domconfig =
14662:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
14663:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
14664:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
14665:                                 my @contacts = ('adminemail','supportemail');
14666:                                 foreach my $item (@contacts) {
14667:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
14668:                                         my $addr = $domconfig{'contacts'}{$item};
14669:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
14670:                                             push(@recipients,$addr);
14671:                                         }
14672:                                     }
14673:                                 }
14674:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
14675:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
14676:                                 }
14677:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
14678:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
14679:                                     my @ok_bccs;
14680:                                     foreach my $bcc (@bccs) {
14681:                                         $bcc =~ s/^\s+//g;
14682:                                         $bcc =~ s/\s+$//g;
14683:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14684:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14685:                                                 push(@ok_bccs,$bcc);
14686:                                             }
14687:                                         }
14688:                                     }
14689:                                     if (@ok_bccs > 0) {
14690:                                         $allbcc = join(', ',@ok_bccs);
14691:                                     }
14692:                                 }
14693:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
14694:                             }
14695:                         }
14696:                     }
14697:                 }
14698:             }
14699:         }
14700:     }
14701:     if (defined($defmail)) {
14702:         if ($defmail ne '') {
14703:             push(@recipients,$defmail);
14704:         }
14705:     }
14706:     if ($otheremails) {
14707:         my @others;
14708:         if ($otheremails =~ /,/) {
14709:             @others = split(/,/,$otheremails);
14710:         } else {
14711:             push(@others,$otheremails);
14712:         }
14713:         foreach my $addr (@others) {
14714:             if (!grep(/^\Q$addr\E$/,@recipients)) {
14715:                 push(@recipients,$addr);
14716:             }
14717:         }
14718:     }
14719:     if ($mailing eq 'helpdeskmail') {
14720:         if ((!@recipients) && ($lastresort ne '')) {
14721:             push(@recipients,$lastresort);
14722:         }
14723:     } elsif ($lastresort ne '') {
14724:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
14725:             push(@recipients,$lastresort);
14726:         }
14727:     }
14728:     my $recipientlist = join(',',@recipients);
14729:     if (wantarray) {
14730:         return ($recipientlist,$allbcc,$addtext);
14731:     } else {
14732:         return $recipientlist;
14733:     }
14734: }
14735: 
14736: ############################################################
14737: ############################################################
14738: 
14739: =pod
14740: 
14741: =head1 Course Catalog Routines
14742: 
14743: =over 4
14744: 
14745: =item * &gather_categories()
14746: 
14747: Converts category definitions - keys of categories hash stored in  
14748: coursecategories in configuration.db on the primary library server in a 
14749: domain - to an array.  Also generates javascript and idx hash used to 
14750: generate Domain Coordinator interface for editing Course Categories.
14751: 
14752: Inputs:
14753: 
14754: categories (reference to hash of category definitions).
14755: 
14756: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14757:       categories and subcategories).
14758: 
14759: idx (reference to hash of counters used in Domain Coordinator interface for 
14760:       editing Course Categories).
14761: 
14762: jsarray (reference to array of categories used to create Javascript arrays for
14763:          Domain Coordinator interface for editing Course Categories).
14764: 
14765: Returns: nothing
14766: 
14767: Side effects: populates cats, idx and jsarray. 
14768: 
14769: =cut
14770: 
14771: sub gather_categories {
14772:     my ($categories,$cats,$idx,$jsarray) = @_;
14773:     my %counters;
14774:     my $num = 0;
14775:     foreach my $item (keys(%{$categories})) {
14776:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
14777:         if ($container eq '' && $depth == 0) {
14778:             $cats->[$depth][$categories->{$item}] = $cat;
14779:         } else {
14780:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
14781:         }
14782:         my ($escitem,$tail) = split(/:/,$item,2);
14783:         if ($counters{$tail} eq '') {
14784:             $counters{$tail} = $num;
14785:             $num ++;
14786:         }
14787:         if (ref($idx) eq 'HASH') {
14788:             $idx->{$item} = $counters{$tail};
14789:         }
14790:         if (ref($jsarray) eq 'ARRAY') {
14791:             push(@{$jsarray->[$counters{$tail}]},$item);
14792:         }
14793:     }
14794:     return;
14795: }
14796: 
14797: =pod
14798: 
14799: =item * &extract_categories()
14800: 
14801: Used to generate breadcrumb trails for course categories.
14802: 
14803: Inputs:
14804: 
14805: categories (reference to hash of category definitions).
14806: 
14807: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14808:       categories and subcategories).
14809: 
14810: trails (reference to array of breacrumb trails for each category).
14811: 
14812: allitems (reference to hash - key is category key 
14813:          (format: escaped(name):escaped(parent category):depth in hierarchy).
14814: 
14815: idx (reference to hash of counters used in Domain Coordinator interface for
14816:       editing Course Categories).
14817: 
14818: jsarray (reference to array of categories used to create Javascript arrays for
14819:          Domain Coordinator interface for editing Course Categories).
14820: 
14821: subcats (reference to hash of arrays containing all subcategories within each 
14822:          category, -recursive)
14823: 
14824: maxd (reference to hash used to hold max depth for all top-level categories).
14825: 
14826: Returns: nothing
14827: 
14828: Side effects: populates trails and allitems hash references.
14829: 
14830: =cut
14831: 
14832: sub extract_categories {
14833:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
14834:     if (ref($categories) eq 'HASH') {
14835:         &gather_categories($categories,$cats,$idx,$jsarray);
14836:         if (ref($cats->[0]) eq 'ARRAY') {
14837:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
14838:                 my $name = $cats->[0][$i];
14839:                 my $item = &escape($name).'::0';
14840:                 my $trailstr;
14841:                 if ($name eq 'instcode') {
14842:                     $trailstr = &mt('Official courses (with institutional codes)');
14843:                 } elsif ($name eq 'communities') {
14844:                     $trailstr = &mt('Communities');
14845:                 } else {
14846:                     $trailstr = $name;
14847:                 }
14848:                 if ($allitems->{$item} eq '') {
14849:                     push(@{$trails},$trailstr);
14850:                     $allitems->{$item} = scalar(@{$trails})-1;
14851:                 }
14852:                 my @parents = ($name);
14853:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
14854:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
14855:                         my $category = $cats->[1]{$name}[$j];
14856:                         if (ref($subcats) eq 'HASH') {
14857:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
14858:                         }
14859:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
14860:                     }
14861:                 } else {
14862:                     if (ref($subcats) eq 'HASH') {
14863:                         $subcats->{$item} = [];
14864:                     }
14865:                     if (ref($maxd) eq 'HASH') {
14866:                         $maxd->{$name} = 1;
14867:                     }
14868:                 }
14869:             }
14870:         }
14871:     }
14872:     return;
14873: }
14874: 
14875: =pod
14876: 
14877: =item * &recurse_categories()
14878: 
14879: Recursively used to generate breadcrumb trails for course categories.
14880: 
14881: Inputs:
14882: 
14883: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14884:       categories and subcategories).
14885: 
14886: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
14887: 
14888: category (current course category, for which breadcrumb trail is being generated).
14889: 
14890: trails (reference to array of breadcrumb trails for each category).
14891: 
14892: allitems (reference to hash - key is category key
14893:          (format: escaped(name):escaped(parent category):depth in hierarchy).
14894: 
14895: parents (array containing containers directories for current category, 
14896:          back to top level). 
14897: 
14898: Returns: nothing
14899: 
14900: Side effects: populates trails and allitems hash references
14901: 
14902: =cut
14903: 
14904: sub recurse_categories {
14905:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
14906:     my $shallower = $depth - 1;
14907:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
14908:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
14909:             my $name = $cats->[$depth]{$category}[$k];
14910:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
14911:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
14912:             if ($allitems->{$item} eq '') {
14913:                 push(@{$trails},$trailstr);
14914:                 $allitems->{$item} = scalar(@{$trails})-1;
14915:             }
14916:             my $deeper = $depth+1;
14917:             push(@{$parents},$category);
14918:             if (ref($subcats) eq 'HASH') {
14919:                 my $subcat = &escape($name).':'.$category.':'.$depth;
14920:                 for (my $j=@{$parents}; $j>=0; $j--) {
14921:                     my $higher;
14922:                     if ($j > 0) {
14923:                         $higher = &escape($parents->[$j]).':'.
14924:                                   &escape($parents->[$j-1]).':'.$j;
14925:                     } else {
14926:                         $higher = &escape($parents->[$j]).'::'.$j;
14927:                     }
14928:                     push(@{$subcats->{$higher}},$subcat);
14929:                 }
14930:             }
14931:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
14932:                                 $subcats,$maxd);
14933:             pop(@{$parents});
14934:         }
14935:     } else {
14936:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
14937:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
14938:         if ($allitems->{$item} eq '') {
14939:             push(@{$trails},$trailstr);
14940:             $allitems->{$item} = scalar(@{$trails})-1;
14941:         }
14942:         if (ref($maxd) eq 'HASH') {
14943:             if ($depth > $maxd->{$parents->[0]}) {
14944:                 $maxd->{$parents->[0]} = $depth;
14945:             }
14946:         }
14947:     }
14948:     return;
14949: }
14950: 
14951: =pod
14952: 
14953: =item * &assign_categories_table()
14954: 
14955: Create a datatable for display of hierarchical categories in a domain,
14956: with checkboxes to allow a course to be categorized. 
14957: 
14958: Inputs:
14959: 
14960: cathash - reference to hash of categories defined for the domain (from
14961:           configuration.db)
14962: 
14963: currcat - scalar with an & separated list of categories assigned to a course. 
14964: 
14965: type    - scalar contains course type (Course or Community).
14966: 
14967: disabled - scalar (optional) contains disabled="disabled" if input elements are
14968:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
14969: 
14970: Returns: $output (markup to be displayed) 
14971: 
14972: =cut
14973: 
14974: sub assign_categories_table {
14975:     my ($cathash,$currcat,$type,$disabled) = @_;
14976:     my $output;
14977:     if (ref($cathash) eq 'HASH') {
14978:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
14979:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
14980:         $maxdepth = scalar(@cats);
14981:         if (@cats > 0) {
14982:             my $itemcount = 0;
14983:             if (ref($cats[0]) eq 'ARRAY') {
14984:                 my @currcategories;
14985:                 if ($currcat ne '') {
14986:                     @currcategories = split('&',$currcat);
14987:                 }
14988:                 my $table;
14989:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
14990:                     my $parent = $cats[0][$i];
14991:                     next if ($parent eq 'instcode');
14992:                     if ($type eq 'Community') {
14993:                         next unless ($parent eq 'communities');
14994:                     } else {
14995:                         next if ($parent eq 'communities');
14996:                     }
14997:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
14998:                     my $item = &escape($parent).'::0';
14999:                     my $checked = '';
15000:                     if (@currcategories > 0) {
15001:                         if (grep(/^\Q$item\E$/,@currcategories)) {
15002:                             $checked = ' checked="checked"';
15003:                         }
15004:                     }
15005:                     my $parent_title = $parent;
15006:                     if ($parent eq 'communities') {
15007:                         $parent_title = &mt('Communities');
15008:                     }
15009:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
15010:                               '<input type="checkbox" name="usecategory" value="'.
15011:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
15012:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
15013:                     my $depth = 1;
15014:                     push(@path,$parent);
15015:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
15016:                     pop(@path);
15017:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
15018:                     $itemcount ++;
15019:                 }
15020:                 if ($itemcount) {
15021:                     $output = &Apache::loncommon::start_data_table().
15022:                               $table.
15023:                               &Apache::loncommon::end_data_table();
15024:                 }
15025:             }
15026:         }
15027:     }
15028:     return $output;
15029: }
15030: 
15031: =pod
15032: 
15033: =item * &assign_category_rows()
15034: 
15035: Create a datatable row for display of nested categories in a domain,
15036: with checkboxes to allow a course to be categorized,called recursively.
15037: 
15038: Inputs:
15039: 
15040: itemcount - track row number for alternating colors
15041: 
15042: cats - reference to array of arrays/hashes which encapsulates hierarchy of
15043:       categories and subcategories.
15044: 
15045: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
15046: 
15047: parent - parent of current category item
15048: 
15049: path - Array containing all categories back up through the hierarchy from the
15050:        current category to the top level.
15051: 
15052: currcategories - reference to array of current categories assigned to the course
15053: 
15054: disabled - scalar (optional) contains disabled="disabled" if input elements are
15055:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
15056: 
15057: Returns: $output (markup to be displayed).
15058: 
15059: =cut
15060: 
15061: sub assign_category_rows {
15062:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
15063:     my ($text,$name,$item,$chgstr);
15064:     if (ref($cats) eq 'ARRAY') {
15065:         my $maxdepth = scalar(@{$cats});
15066:         if (ref($cats->[$depth]) eq 'HASH') {
15067:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
15068:                 my $numchildren = @{$cats->[$depth]{$parent}};
15069:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
15070:                 $text .= '<td><table class="LC_data_table">';
15071:                 for (my $j=0; $j<$numchildren; $j++) {
15072:                     $name = $cats->[$depth]{$parent}[$j];
15073:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
15074:                     my $deeper = $depth+1;
15075:                     my $checked = '';
15076:                     if (ref($currcategories) eq 'ARRAY') {
15077:                         if (@{$currcategories} > 0) {
15078:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
15079:                                 $checked = ' checked="checked"';
15080:                             }
15081:                         }
15082:                     }
15083:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
15084:                              '<input type="checkbox" name="usecategory" value="'.
15085:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
15086:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
15087:                              '</td><td>';
15088:                     if (ref($path) eq 'ARRAY') {
15089:                         push(@{$path},$name);
15090:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
15091:                         pop(@{$path});
15092:                     }
15093:                     $text .= '</td></tr>';
15094:                 }
15095:                 $text .= '</table></td>';
15096:             }
15097:         }
15098:     }
15099:     return $text;
15100: }
15101: 
15102: =pod
15103: 
15104: =back
15105: 
15106: =cut
15107: 
15108: ############################################################
15109: ############################################################
15110: 
15111: 
15112: sub commit_customrole {
15113:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
15114:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
15115:                          ($start?', '.&mt('starting').' '.localtime($start):'').
15116:                          ($end?', ending '.localtime($end):'').': <b>'.
15117:               &Apache::lonnet::assigncustomrole(
15118:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
15119:                  '</b><br />';
15120:     return $output;
15121: }
15122: 
15123: sub commit_standardrole {
15124:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
15125:     my ($output,$logmsg,$linefeed);
15126:     if ($context eq 'auto') {
15127:         $linefeed = "\n";
15128:     } else {
15129:         $linefeed = "<br />\n";
15130:     }  
15131:     if ($three eq 'st') {
15132:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
15133:                                          $one,$two,$sec,$context,$credits);
15134:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
15135:             ($result eq 'unknown_course') || ($result eq 'refused')) {
15136:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
15137:         } else {
15138:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
15139:                ($start?', '.&mt('starting').' '.localtime($start):'').
15140:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
15141:             if ($context eq 'auto') {
15142:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
15143:             } else {
15144:                $output .= '<b>'.$result.'</b>'.$linefeed.
15145:                &mt('Add to classlist').': <b>ok</b>';
15146:             }
15147:             $output .= $linefeed;
15148:         }
15149:     } else {
15150:         $output = &mt('Assigning').' '.$three.' in '.$url.
15151:                ($start?', '.&mt('starting').' '.localtime($start):'').
15152:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
15153:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
15154:         if ($context eq 'auto') {
15155:             $output .= $result.$linefeed;
15156:         } else {
15157:             $output .= '<b>'.$result.'</b>'.$linefeed;
15158:         }
15159:     }
15160:     return $output;
15161: }
15162: 
15163: sub commit_studentrole {
15164:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
15165:         $credits) = @_;
15166:     my ($result,$linefeed,$oldsecurl,$newsecurl);
15167:     if ($context eq 'auto') {
15168:         $linefeed = "\n";
15169:     } else {
15170:         $linefeed = '<br />'."\n";
15171:     }
15172:     if (defined($one) && defined($two)) {
15173:         my $cid=$one.'_'.$two;
15174:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
15175:         my $secchange = 0;
15176:         my $expire_role_result;
15177:         my $modify_section_result;
15178:         if ($oldsec ne '-1') { 
15179:             if ($oldsec ne $sec) {
15180:                 $secchange = 1;
15181:                 my $now = time;
15182:                 my $uurl='/'.$cid;
15183:                 $uurl=~s/\_/\//g;
15184:                 if ($oldsec) {
15185:                     $uurl.='/'.$oldsec;
15186:                 }
15187:                 $oldsecurl = $uurl;
15188:                 $expire_role_result = 
15189:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
15190:                 if ($env{'request.course.sec'} ne '') { 
15191:                     if ($expire_role_result eq 'refused') {
15192:                         my @roles = ('st');
15193:                         my @statuses = ('previous');
15194:                         my @roledoms = ($one);
15195:                         my $withsec = 1;
15196:                         my %roleshash = 
15197:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
15198:                                               \@statuses,\@roles,\@roledoms,$withsec);
15199:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
15200:                             my ($oldstart,$oldend) = 
15201:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
15202:                             if ($oldend > 0 && $oldend <= $now) {
15203:                                 $expire_role_result = 'ok';
15204:                             }
15205:                         }
15206:                     }
15207:                 }
15208:                 $result = $expire_role_result;
15209:             }
15210:         }
15211:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
15212:             $modify_section_result = 
15213:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
15214:                                                            undef,undef,undef,$sec,
15215:                                                            $end,$start,'','',$cid,
15216:                                                            '',$context,$credits);
15217:             if ($modify_section_result =~ /^ok/) {
15218:                 if ($secchange == 1) {
15219:                     if ($sec eq '') {
15220:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
15221:                     } else {
15222:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
15223:                     }
15224:                 } elsif ($oldsec eq '-1') {
15225:                     if ($sec eq '') {
15226:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
15227:                     } else {
15228:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
15229:                     }
15230:                 } else {
15231:                     if ($sec eq '') {
15232:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
15233:                     } else {
15234:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
15235:                     }
15236:                 }
15237:             } else {
15238:                 if ($secchange) {       
15239:                     $$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;
15240:                 } else {
15241:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
15242:                 }
15243:             }
15244:             $result = $modify_section_result;
15245:         } elsif ($secchange == 1) {
15246:             if ($oldsec eq '') {
15247:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
15248:             } else {
15249:                 $$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;
15250:             }
15251:             if ($expire_role_result eq 'refused') {
15252:                 my $newsecurl = '/'.$cid;
15253:                 $newsecurl =~ s/\_/\//g;
15254:                 if ($sec ne '') {
15255:                     $newsecurl.='/'.$sec;
15256:                 }
15257:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
15258:                     if ($sec eq '') {
15259:                         $$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;
15260:                     } else {
15261:                         $$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;
15262:                     }
15263:                 }
15264:             }
15265:         }
15266:     } else {
15267:         $$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;
15268:         $result = "error: incomplete course id\n";
15269:     }
15270:     return $result;
15271: }
15272: 
15273: sub show_role_extent {
15274:     my ($scope,$context,$role) = @_;
15275:     $scope =~ s{^/}{};
15276:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
15277:     push(@courseroles,'co');
15278:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
15279:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
15280:         $scope =~ s{/}{_};
15281:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
15282:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
15283:         my ($audom,$auname) = split(/\//,$scope);
15284:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
15285:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
15286:     } else {
15287:         $scope =~ s{/$}{};
15288:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
15289:                    &Apache::lonnet::domain($scope,'description').'</span>');
15290:     }
15291: }
15292: 
15293: ############################################################
15294: ############################################################
15295: 
15296: sub check_clone {
15297:     my ($args,$linefeed) = @_;
15298:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
15299:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
15300:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
15301:     my $clonemsg;
15302:     my $can_clone = 0;
15303:     my $lctype = lc($args->{'crstype'});
15304:     if ($lctype ne 'community') {
15305:         $lctype = 'course';
15306:     }
15307:     if ($clonehome eq 'no_host') {
15308:         if ($args->{'crstype'} eq 'Community') {
15309:             $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
15310:         } else {
15311:             $clonemsg = &mt('No new course created.').$linefeed.&mt('A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
15312:         }     
15313:     } else {
15314: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
15315:         if ($args->{'crstype'} eq 'Community') {
15316:             if ($clonedesc{'type'} ne 'Community') {
15317:                  $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
15318:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
15319:             }
15320:         }
15321: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
15322:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
15323: 	    $can_clone = 1;
15324: 	} else {
15325: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
15326: 						 $args->{'clonedomain'},$args->{'clonecourse'});
15327:             if ($clonehash{'cloners'} eq '') {
15328:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
15329:                 if ($domdefs{'canclone'}) {
15330:                     unless ($domdefs{'canclone'} eq 'none') {
15331:                         if ($domdefs{'canclone'} eq 'domain') {
15332:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
15333:                                 $can_clone = 1;
15334:                             }
15335:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
15336:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
15337:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
15338:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
15339:                                 $can_clone = 1;
15340:                             }
15341:                         }
15342:                     }
15343:                 }
15344:             } else {
15345: 	        my @cloners = split(/,/,$clonehash{'cloners'});
15346:                 if (grep(/^\*$/,@cloners)) {
15347:                     $can_clone = 1;
15348:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
15349:                     $can_clone = 1;
15350:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
15351:                     $can_clone = 1;
15352:                 }
15353:                 unless ($can_clone) {
15354:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
15355:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
15356:                         my (%gotdomdefaults,%gotcodedefaults);
15357:                         foreach my $cloner (@cloners) {
15358:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
15359:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
15360:                                 my (%codedefaults,@code_order);
15361:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
15362:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
15363:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
15364:                                     }
15365:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
15366:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
15367:                                     }
15368:                                 } else {
15369:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
15370:                                                                             \%codedefaults,
15371:                                                                             \@code_order);
15372:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
15373:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
15374:                                 }
15375:                                 if (@code_order > 0) {
15376:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
15377:                                                                                 $cloner,$clonehash{'internal.coursecode'},
15378:                                                                                 $args->{'crscode'})) {
15379:                                         $can_clone = 1;
15380:                                         last;
15381:                                     }
15382:                                 }
15383:                             }
15384:                         }
15385:                     }
15386:                 }
15387:             }
15388:             unless ($can_clone) {
15389:                 my $ccrole = 'cc';
15390:                 if ($args->{'crstype'} eq 'Community') {
15391:                     $ccrole = 'co';
15392:                 }
15393:                 my %roleshash =
15394:                     &Apache::lonnet::get_my_roles($args->{'ccuname'},
15395:                                                   $args->{'ccdomain'},
15396:                                                   'userroles',['active'],[$ccrole],
15397:                                                   [$args->{'clonedomain'}]);
15398:                 if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
15399:                     $can_clone = 1;
15400:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
15401:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
15402:                     $can_clone = 1;
15403:                 }
15404:             }
15405:             unless ($can_clone) {
15406:                 if ($args->{'crstype'} eq 'Community') {
15407:                     $clonemsg = &mt('No new community created.').$linefeed.&mt('The new community could not be cloned from the existing community because the new community owner ([_1]) does not have cloning rights in the existing community ([_2]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
15408:                 } else {
15409:                     $clonemsg = &mt('No new course created.').$linefeed.&mt('The new course could not be cloned from the existing course because the new course owner ([_1]) does not have cloning rights in the existing course ([_2]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
15410: 	        }
15411: 	    }
15412:         }
15413:     }
15414:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
15415: }
15416: 
15417: sub construct_course {
15418:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
15419:         $cnum,$category,$coderef) = @_;
15420:     my $outcome;
15421:     my $linefeed =  '<br />'."\n";
15422:     if ($context eq 'auto') {
15423:         $linefeed = "\n";
15424:     }
15425: 
15426: #
15427: # Are we cloning?
15428: #
15429:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
15430:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
15431: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
15432: 	if ($context ne 'auto') {
15433:             if ($clonemsg ne '') {
15434: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
15435:             }
15436: 	}
15437: 	$outcome .= $clonemsg.$linefeed;
15438: 
15439:         if (!$can_clone) {
15440: 	    return (0,$outcome);
15441: 	}
15442:     }
15443: 
15444: #
15445: # Open course
15446: #
15447:     my $crstype = lc($args->{'crstype'});
15448:     my %cenv=();
15449:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
15450:                                              $args->{'cdescr'},
15451:                                              $args->{'curl'},
15452:                                              $args->{'course_home'},
15453:                                              $args->{'nonstandard'},
15454:                                              $args->{'crscode'},
15455:                                              $args->{'ccuname'}.':'.
15456:                                              $args->{'ccdomain'},
15457:                                              $args->{'crstype'},
15458:                                              $cnum,$context,$category);
15459: 
15460:     # Note: The testing routines depend on this being output; see 
15461:     # Utils::Course. This needs to at least be output as a comment
15462:     # if anyone ever decides to not show this, and Utils::Course::new
15463:     # will need to be suitably modified.
15464:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
15465:     if ($$courseid =~ /^error:/) {
15466:         return (0,$outcome);
15467:     }
15468: 
15469: #
15470: # Check if created correctly
15471: #
15472:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
15473:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
15474:     if ($crsuhome eq 'no_host') {
15475:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
15476:         return (0,$outcome);
15477:     }
15478:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
15479: 
15480: #
15481: # Do the cloning
15482: #   
15483:     if ($can_clone && $cloneid) {
15484: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
15485: 	if ($context ne 'auto') {
15486: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
15487: 	}
15488: 	$outcome .= $clonemsg.$linefeed;
15489: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
15490: # Copy all files
15491: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
15492: # Restore URL
15493: 	$cenv{'url'}=$oldcenv{'url'};
15494: # Restore title
15495: 	$cenv{'description'}=$oldcenv{'description'};
15496: # Restore creation date, creator and creation context.
15497:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
15498:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
15499:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
15500: # Mark as cloned
15501: 	$cenv{'clonedfrom'}=$cloneid;
15502: # Need to clone grading mode
15503:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
15504:         $cenv{'grading'}=$newenv{'grading'};
15505: # Do not clone these environment entries
15506:         &Apache::lonnet::del('environment',
15507:                   ['default_enrollment_start_date',
15508:                    'default_enrollment_end_date',
15509:                    'question.email',
15510:                    'policy.email',
15511:                    'comment.email',
15512:                    'pch.users.denied',
15513:                    'plc.users.denied',
15514:                    'hidefromcat',
15515:                    'checkforpriv',
15516:                    'categories'],
15517:                    $$crsudom,$$crsunum);
15518:         if ($args->{'textbook'}) {
15519:             $cenv{'internal.textbook'} = $args->{'textbook'};
15520:         }
15521:     }
15522: 
15523: #
15524: # Set environment (will override cloned, if existing)
15525: #
15526:     my @sections = ();
15527:     my @xlists = ();
15528:     if ($args->{'crstype'}) {
15529:         $cenv{'type'}=$args->{'crstype'};
15530:     }
15531:     if ($args->{'crsid'}) {
15532:         $cenv{'courseid'}=$args->{'crsid'};
15533:     }
15534:     if ($args->{'crscode'}) {
15535:         $cenv{'internal.coursecode'}=$args->{'crscode'};
15536:     }
15537:     if ($args->{'crsquota'} ne '') {
15538:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
15539:     } else {
15540:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
15541:     }
15542:     if ($args->{'ccuname'}) {
15543:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
15544:                                         ':'.$args->{'ccdomain'};
15545:     } else {
15546:         $cenv{'internal.courseowner'} = $args->{'curruser'};
15547:     }
15548:     if ($args->{'defaultcredits'}) {
15549:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
15550:     }
15551:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
15552:     if ($args->{'crssections'}) {
15553:         $cenv{'internal.sectionnums'} = '';
15554:         if ($args->{'crssections'} =~ m/,/) {
15555:             @sections = split/,/,$args->{'crssections'};
15556:         } else {
15557:             $sections[0] = $args->{'crssections'};
15558:         }
15559:         if (@sections > 0) {
15560:             foreach my $item (@sections) {
15561:                 my ($sec,$gp) = split/:/,$item;
15562:                 my $class = $args->{'crscode'}.$sec;
15563:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
15564:                 $cenv{'internal.sectionnums'} .= $item.',';
15565:                 unless ($addcheck eq 'ok') {
15566:                     push(@badclasses,$class);
15567:                 }
15568:             }
15569:             $cenv{'internal.sectionnums'} =~ s/,$//;
15570:         }
15571:     }
15572: # do not hide course coordinator from staff listing, 
15573: # even if privileged
15574:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15575: # add course coordinator's domain to domains to check for privileged users
15576: # if different to course domain
15577:     if ($$crsudom ne $args->{'ccdomain'}) {
15578:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
15579:     }
15580: # add crosslistings
15581:     if ($args->{'crsxlist'}) {
15582:         $cenv{'internal.crosslistings'}='';
15583:         if ($args->{'crsxlist'} =~ m/,/) {
15584:             @xlists = split/,/,$args->{'crsxlist'};
15585:         } else {
15586:             $xlists[0] = $args->{'crsxlist'};
15587:         }
15588:         if (@xlists > 0) {
15589:             foreach my $item (@xlists) {
15590:                 my ($xl,$gp) = split/:/,$item;
15591:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
15592:                 $cenv{'internal.crosslistings'} .= $item.',';
15593:                 unless ($addcheck eq 'ok') {
15594:                     push(@badclasses,$xl);
15595:                 }
15596:             }
15597:             $cenv{'internal.crosslistings'} =~ s/,$//;
15598:         }
15599:     }
15600:     if ($args->{'autoadds'}) {
15601:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
15602:     }
15603:     if ($args->{'autodrops'}) {
15604:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
15605:     }
15606: # check for notification of enrollment changes
15607:     my @notified = ();
15608:     if ($args->{'notify_owner'}) {
15609:         if ($args->{'ccuname'} ne '') {
15610:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
15611:         }
15612:     }
15613:     if ($args->{'notify_dc'}) {
15614:         if ($uname ne '') { 
15615:             push(@notified,$uname.':'.$udom);
15616:         }
15617:     }
15618:     if (@notified > 0) {
15619:         my $notifylist;
15620:         if (@notified > 1) {
15621:             $notifylist = join(',',@notified);
15622:         } else {
15623:             $notifylist = $notified[0];
15624:         }
15625:         $cenv{'internal.notifylist'} = $notifylist;
15626:     }
15627:     if (@badclasses > 0) {
15628:         my %lt=&Apache::lonlocal::texthash(
15629:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
15630:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
15631:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
15632:         );
15633:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
15634:                            &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'};
15635:         if ($context eq 'auto') {
15636:             $outcome .= $badclass_msg.$linefeed;
15637:         } else {
15638:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
15639:         }
15640:         foreach my $item (@badclasses) {
15641:             if ($context eq 'auto') {
15642:                 $outcome .= " - $item\n";
15643:             } else {
15644:                 $outcome .= "<li>$item</li>\n";
15645:             }
15646:         }
15647:         if ($context eq 'auto') {
15648:             $outcome .= $linefeed;
15649:         } else {
15650:             $outcome .= "</ul><br /><br /></div>\n";
15651:         }
15652:     }
15653:     if ($args->{'no_end_date'}) {
15654:         $args->{'endaccess'} = 0;
15655:     }
15656:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
15657:     $cenv{'internal.autoend'}=$args->{'enrollend'};
15658:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
15659:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
15660:     if ($args->{'showphotos'}) {
15661:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
15662:     }
15663:     $cenv{'internal.authtype'} = $args->{'authtype'};
15664:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
15665:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
15666:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
15667:             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'); 
15668:             if ($context eq 'auto') {
15669:                 $outcome .= $krb_msg;
15670:             } else {
15671:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
15672:             }
15673:             $outcome .= $linefeed;
15674:         }
15675:     }
15676:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
15677:        if ($args->{'setpolicy'}) {
15678:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15679:        }
15680:        if ($args->{'setcontent'}) {
15681:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15682:        }
15683:        if ($args->{'setcomment'}) {
15684:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15685:        }
15686:     }
15687:     if ($args->{'reshome'}) {
15688: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
15689: 	$cenv{'reshome'}=~s/\/+$/\//;
15690:     }
15691: #
15692: # course has keyed access
15693: #
15694:     if ($args->{'setkeys'}) {
15695:        $cenv{'keyaccess'}='yes';
15696:     }
15697: # if specified, key authority is not course, but user
15698: # only active if keyaccess is yes
15699:     if ($args->{'keyauth'}) {
15700: 	my ($user,$domain) = split(':',$args->{'keyauth'});
15701: 	$user = &LONCAPA::clean_username($user);
15702: 	$domain = &LONCAPA::clean_username($domain);
15703: 	if ($user ne '' && $domain ne '') {
15704: 	    $cenv{'keyauth'}=$user.':'.$domain;
15705: 	}
15706:     }
15707: 
15708: #
15709: #  generate and store uniquecode (available to course requester), if course should have one.
15710: #
15711:     if ($args->{'uniquecode'}) {
15712:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
15713:         if ($code) {
15714:             $cenv{'internal.uniquecode'} = $code;
15715:             my %crsinfo =
15716:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
15717:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
15718:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
15719:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
15720:             }
15721:             if (ref($coderef)) {
15722:                 $$coderef = $code;
15723:             }
15724:         }
15725:     }
15726: 
15727:     if ($args->{'disresdis'}) {
15728:         $cenv{'pch.roles.denied'}='st';
15729:     }
15730:     if ($args->{'disablechat'}) {
15731:         $cenv{'plc.roles.denied'}='st';
15732:     }
15733: 
15734:     # Record we've not yet viewed the Course Initialization Helper for this 
15735:     # course
15736:     $cenv{'course.helper.not.run'} = 1;
15737:     #
15738:     # Use new Randomseed
15739:     #
15740:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
15741:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
15742:     #
15743:     # The encryption code and receipt prefix for this course
15744:     #
15745:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
15746:     $cenv{'internal.encpref'}=100+int(9*rand(99));
15747:     #
15748:     # By default, use standard grading
15749:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
15750: 
15751:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
15752:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
15753: #
15754: # Open all assignments
15755: #
15756:     if ($args->{'openall'}) {
15757:        my $opendate = time;
15758:        if ($args->{'openallfrom'} =~ /^\d+$/) {
15759:            $opendate = $args->{'openallfrom'};
15760:        }
15761:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
15762:        my %storecontent = ($storeunder         => $opendate,
15763:                            $storeunder.'.type' => 'date_start');
15764:        $outcome .= &mt('All assignments open starting [_1]',
15765:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
15766:                    &Apache::lonnet::cput
15767:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
15768:    }
15769: #
15770: # Set first page
15771: #
15772:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
15773: 	    || ($cloneid)) {
15774: 	use LONCAPA::map;
15775: 	$outcome .= &mt('Setting first resource').': ';
15776: 
15777: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
15778:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
15779: 
15780:         $outcome .= ($fatal?$errtext:'read ok').' - ';
15781:         my $title; my $url;
15782:         if ($args->{'firstres'} eq 'syl') {
15783: 	    $title=&mt('Syllabus');
15784:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
15785:         } else {
15786:             $title=&mt('Table of Contents');
15787:             $url='/adm/navmaps';
15788:         }
15789: 
15790:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
15791: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
15792: 
15793: 	if ($errtext) { $fatal=2; }
15794:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
15795:     }
15796: 
15797:     return (1,$outcome);
15798: }
15799: 
15800: sub make_unique_code {
15801:     my ($cdom,$cnum) = @_;
15802:     # get lock on uniquecodes db
15803:     my $lockhash = {
15804:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
15805:                                                   ':'.$env{'user.domain'},
15806:                    };
15807:     my $tries = 0;
15808:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
15809:     my ($code,$error);
15810: 
15811:     while (($gotlock ne 'ok') && ($tries<3)) {
15812:         $tries ++;
15813:         sleep 1;
15814:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
15815:     }
15816:     if ($gotlock eq 'ok') {
15817:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
15818:         my $gotcode;
15819:         my $attempts = 0;
15820:         while ((!$gotcode) && ($attempts < 100)) {
15821:             $code = &generate_code();
15822:             if (!exists($currcodes{$code})) {
15823:                 $gotcode = 1;
15824:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
15825:                     $error = 'nostore';
15826:                 }
15827:             }
15828:             $attempts ++;
15829:         }
15830:         my @del_lock = ($cnum."\0".'uniquecodes');
15831:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
15832:     } else {
15833:         $error = 'nolock';
15834:     }
15835:     return ($code,$error);
15836: }
15837: 
15838: sub generate_code {
15839:     my $code;
15840:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
15841:     for (my $i=0; $i<6; $i++) {
15842:         my $lettnum = int (rand 2);
15843:         my $item = '';
15844:         if ($lettnum) {
15845:             $item = $letts[int( rand(18) )];
15846:         } else {
15847:             $item = 1+int( rand(8) );
15848:         }
15849:         $code .= $item;
15850:     }
15851:     return $code;
15852: }
15853: 
15854: ############################################################
15855: ############################################################
15856: 
15857: #SD
15858: # only Community and Course, or anything else?
15859: sub course_type {
15860:     my ($cid) = @_;
15861:     if (!defined($cid)) {
15862:         $cid = $env{'request.course.id'};
15863:     }
15864:     if (defined($env{'course.'.$cid.'.type'})) {
15865:         return $env{'course.'.$cid.'.type'};
15866:     } else {
15867:         return 'Course';
15868:     }
15869: }
15870: 
15871: sub group_term {
15872:     my $crstype = &course_type();
15873:     my %names = (
15874:                   'Course' => 'group',
15875:                   'Community' => 'group',
15876:                 );
15877:     return $names{$crstype};
15878: }
15879: 
15880: sub course_types {
15881:     my @types = ('official','unofficial','community','textbook');
15882:     my %typename = (
15883:                          official   => 'Official course',
15884:                          unofficial => 'Unofficial course',
15885:                          community  => 'Community',
15886:                          textbook   => 'Textbook course',
15887:                    );
15888:     return (\@types,\%typename);
15889: }
15890: 
15891: sub icon {
15892:     my ($file)=@_;
15893:     my $curfext = lc((split(/\./,$file))[-1]);
15894:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
15895:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
15896:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
15897: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
15898: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
15899: 	            $curfext.".gif") {
15900: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
15901: 		$curfext.".gif";
15902: 	}
15903:     }
15904:     return &lonhttpdurl($iconname);
15905: } 
15906: 
15907: sub lonhttpdurl {
15908: #
15909: # Had been used for "small fry" static images on separate port 8080.
15910: # Modify here if lightweight http functionality desired again.
15911: # Currently eliminated due to increasing firewall issues.
15912: #
15913:     my ($url)=@_;
15914:     return $url;
15915: }
15916: 
15917: sub connection_aborted {
15918:     my ($r)=@_;
15919:     $r->print(" ");$r->rflush();
15920:     my $c = $r->connection;
15921:     return $c->aborted();
15922: }
15923: 
15924: #    Escapes strings that may have embedded 's that will be put into
15925: #    strings as 'strings'.
15926: sub escape_single {
15927:     my ($input) = @_;
15928:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
15929:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
15930:     return $input;
15931: }
15932: 
15933: #  Same as escape_single, but escape's "'s  This 
15934: #  can be used for  "strings"
15935: sub escape_double {
15936:     my ($input) = @_;
15937:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
15938:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
15939:     return $input;
15940: }
15941:  
15942: #   Escapes the last element of a full URL.
15943: sub escape_url {
15944:     my ($url)   = @_;
15945:     my @urlslices = split(/\//, $url,-1);
15946:     my $lastitem = &escape(pop(@urlslices));
15947:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
15948: }
15949: 
15950: sub compare_arrays {
15951:     my ($arrayref1,$arrayref2) = @_;
15952:     my (@difference,%count);
15953:     @difference = ();
15954:     %count = ();
15955:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
15956:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
15957:         foreach my $element (keys(%count)) {
15958:             if ($count{$element} == 1) {
15959:                 push(@difference,$element);
15960:             }
15961:         }
15962:     }
15963:     return @difference;
15964: }
15965: 
15966: sub lon_status_items {
15967:     my %defaults = (
15968:                      E         => 100,
15969:                      W         => 4,
15970:                      N         => 1,
15971:                      U         => 5,
15972:                      threshold => 200,
15973:                      sysmail   => 2500,
15974:                    );
15975:     my %names = (
15976:                    E => 'Errors',
15977:                    W => 'Warnings',
15978:                    N => 'Notices',
15979:                    U => 'Unsent',
15980:                 );
15981:     return (\%defaults,\%names);
15982: }
15983: 
15984: # -------------------------------------------------------- Initialize user login
15985: sub init_user_environment {
15986:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
15987:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
15988: 
15989:     my $public=($username eq 'public' && $domain eq 'public');
15990: 
15991: # See if old ID present, if so, remove
15992: 
15993:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
15994:     my $now=time;
15995: 
15996:     if ($public) {
15997: 	my $max_public=100;
15998: 	my $oldest;
15999: 	my $oldest_time=0;
16000: 	for(my $next=1;$next<=$max_public;$next++) {
16001: 	    if (-e $lonids."/publicuser_$next.id") {
16002: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
16003: 		if ($mtime<$oldest_time || !$oldest_time) {
16004: 		    $oldest_time=$mtime;
16005: 		    $oldest=$next;
16006: 		}
16007: 	    } else {
16008: 		$cookie="publicuser_$next";
16009: 		last;
16010: 	    }
16011: 	}
16012: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
16013:     } else {
16014: 	# if this isn't a robot, kill any existing non-robot sessions
16015: 	if (!$args->{'robot'}) {
16016: 	    opendir(DIR,$lonids);
16017: 	    while ($filename=readdir(DIR)) {
16018: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
16019:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
16020:                             &GDBM_READER(),0640)) {
16021:                         my $linkedfile;
16022:                         if (exists($oldenv{'user.linkedenv'})) {
16023:                             $linkedfile = $oldenv{'user.linkedenv'};
16024:                         }
16025:                         untie(%oldenv);
16026:                         if (unlink("$lonids/$filename")) {
16027:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
16028:                                 if (-l "$lonids/$linkedfile.id") {
16029:                                     unlink("$lonids/$linkedfile.id");
16030:                                 }
16031:                             }
16032:                         }
16033:                     } else {
16034:                         unlink($lonids.'/'.$filename);
16035:                     }
16036: 		}
16037: 	    }
16038: 	    closedir(DIR);
16039: # If there is a undeleted lockfile for the user's paste buffer remove it.
16040:             my $namespace = 'nohist_courseeditor';
16041:             my $lockingkey = 'paste'."\0".'locked_num';
16042:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
16043:                                                 $domain,$username);
16044:             if (exists($lockhash{$lockingkey})) {
16045:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
16046:                 unless ($delresult eq 'ok') {
16047:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
16048:                 }
16049:             }
16050: 	}
16051: # Give them a new cookie
16052: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
16053: 		                   : $now.$$.int(rand(10000)));
16054: 	$cookie="$username\_$id\_$domain\_$authhost";
16055:     
16056: # Initialize roles
16057: 
16058: 	($userroles,$firstaccenv,$timerintenv) = 
16059:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
16060:     }
16061: # ------------------------------------ Check browser type and MathML capability
16062: 
16063:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
16064:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
16065: 
16066: # ------------------------------------------------------------- Get environment
16067: 
16068:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
16069:     my ($tmp) = keys(%userenv);
16070:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
16071:     } else {
16072: 	undef(%userenv);
16073:     }
16074:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
16075: 	$form->{'interface'}=$userenv{'interface'};
16076:     }
16077:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
16078: 
16079: # --------------- Do not trust query string to be put directly into environment
16080:     foreach my $option ('interface','localpath','localres') {
16081:         $form->{$option}=~s/[\n\r\=]//gs;
16082:     }
16083: # --------------------------------------------------------- Write first profile
16084: 
16085:     {
16086:         my $ip = &Apache::lonnet::get_requestor_ip();
16087: 	my %initial_env = 
16088: 	    ("user.name"          => $username,
16089: 	     "user.domain"        => $domain,
16090: 	     "user.home"          => $authhost,
16091: 	     "browser.type"       => $clientbrowser,
16092: 	     "browser.version"    => $clientversion,
16093: 	     "browser.mathml"     => $clientmathml,
16094: 	     "browser.unicode"    => $clientunicode,
16095: 	     "browser.os"         => $clientos,
16096:              "browser.mobile"     => $clientmobile,
16097:              "browser.info"       => $clientinfo,
16098:              "browser.osversion"  => $clientosversion,
16099: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
16100: 	     "request.course.fn"  => '',
16101: 	     "request.course.uri" => '',
16102: 	     "request.course.sec" => '',
16103: 	     "request.role"       => 'cm',
16104: 	     "request.role.adv"   => $env{'user.adv'},
16105: 	     "request.host"       => $ip,);
16106: 
16107:         if ($form->{'localpath'}) {
16108: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
16109: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
16110:         }
16111: 	
16112: 	if ($form->{'interface'}) {
16113: 	    $form->{'interface'}=~s/\W//gs;
16114: 	    $initial_env{"browser.interface"} = $form->{'interface'};
16115: 	    $env{'browser.interface'}=$form->{'interface'};
16116: 	}
16117: 
16118:         if ($form->{'iptoken'}) {
16119:             my $lonhost = $r->dir_config('lonHostID');
16120:             $initial_env{"user.noloadbalance"} = $lonhost;
16121:             $env{'user.noloadbalance'} = $lonhost;
16122:         }
16123: 
16124:         if ($form->{'noloadbalance'}) {
16125:             my @hosts = &Apache::lonnet::current_machine_ids();
16126:             my $hosthere = $form->{'noloadbalance'};
16127:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
16128:                 $initial_env{"user.noloadbalance"} = $hosthere;
16129:                 $env{'user.noloadbalance'} = $hosthere;
16130:             }
16131:         }
16132: 
16133:         unless ($domain eq 'public') {
16134:             my %is_adv = ( is_adv => $env{'user.adv'} );
16135:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
16136: 
16137:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
16138:                 $userenv{'availabletools.'.$tool} = 
16139:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
16140:                                                       undef,\%userenv,\%domdef,\%is_adv);
16141:             }
16142: 
16143:             foreach my $crstype ('official','unofficial','community','textbook') {
16144:                 $userenv{'canrequest.'.$crstype} =
16145:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
16146:                                                       'reload','requestcourses',
16147:                                                       \%userenv,\%domdef,\%is_adv);
16148:             }
16149: 
16150:             $userenv{'canrequest.author'} =
16151:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
16152:                                                   'reload','requestauthor',
16153:                                                   \%userenv,\%domdef,\%is_adv);
16154:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
16155:                                                  $domain,$username);
16156:             my $reqstatus = $reqauthor{'author_status'};
16157:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
16158:                 if (ref($reqauthor{'author'}) eq 'HASH') {
16159:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
16160:                                                       $reqauthor{'author'}{'timestamp'};
16161:                 }
16162:             }
16163:         }
16164: 
16165: 	$env{'user.environment'} = "$lonids/$cookie.id";
16166: 
16167: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
16168: 		 &GDBM_WRCREAT(),0640)) {
16169: 	    &_add_to_env(\%disk_env,\%initial_env);
16170: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
16171: 	    &_add_to_env(\%disk_env,$userroles);
16172:             if (ref($firstaccenv) eq 'HASH') {
16173:                 &_add_to_env(\%disk_env,$firstaccenv);
16174:             }
16175:             if (ref($timerintenv) eq 'HASH') {
16176:                 &_add_to_env(\%disk_env,$timerintenv);
16177:             }
16178: 	    if (ref($args->{'extra_env'})) {
16179: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
16180: 	    }
16181: 	    untie(%disk_env);
16182: 	} else {
16183: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
16184: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
16185: 	    return 'error: '.$!;
16186: 	}
16187:     }
16188:     $env{'request.role'}='cm';
16189:     $env{'request.role.adv'}=$env{'user.adv'};
16190:     $env{'browser.type'}=$clientbrowser;
16191: 
16192:     return $cookie;
16193: 
16194: }
16195: 
16196: sub _add_to_env {
16197:     my ($idf,$env_data,$prefix) = @_;
16198:     if (ref($env_data) eq 'HASH') {
16199:         while (my ($key,$value) = each(%$env_data)) {
16200: 	    $idf->{$prefix.$key} = $value;
16201: 	    $env{$prefix.$key}   = $value;
16202:         }
16203:     }
16204: }
16205: 
16206: # --- Get the symbolic name of a problem and the url
16207: sub get_symb {
16208:     my ($request,$silent) = @_;
16209:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
16210:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
16211:     if ($symb eq '') {
16212:         if (!$silent) {
16213:             if (ref($request)) { 
16214:                 $request->print("Unable to handle ambiguous references:$url:.");
16215:             }
16216:             return ();
16217:         }
16218:     }
16219:     &Apache::lonenc::check_decrypt(\$symb);
16220:     return ($symb);
16221: }
16222: 
16223: # --------------------------------------------------------------Get annotation
16224: 
16225: sub get_annotation {
16226:     my ($symb,$enc) = @_;
16227: 
16228:     my $key = $symb;
16229:     if (!$enc) {
16230:         $key =
16231:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
16232:     }
16233:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
16234:     return $annotation{$key};
16235: }
16236: 
16237: sub clean_symb {
16238:     my ($symb,$delete_enc) = @_;
16239: 
16240:     &Apache::lonenc::check_decrypt(\$symb);
16241:     my $enc = $env{'request.enc'};
16242:     if ($delete_enc) {
16243:         delete($env{'request.enc'});
16244:     }
16245: 
16246:     return ($symb,$enc);
16247: }
16248: 
16249: ############################################################
16250: ############################################################
16251: 
16252: =pod
16253: 
16254: =head1 Routines for building display used to search for courses
16255: 
16256: 
16257: =over 4
16258: 
16259: =item * &build_filters()
16260: 
16261: Create markup for a table used to set filters to use when selecting
16262: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
16263: and quotacheck.pl
16264: 
16265: 
16266: Inputs:
16267: 
16268: filterlist - anonymous array of fields to include as potential filters
16269: 
16270: crstype - course type
16271: 
16272: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
16273:               to pop-open a course selector (will contain "extra element").
16274: 
16275: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
16276: 
16277: filter - anonymous hash of criteria and their values
16278: 
16279: action - form action
16280: 
16281: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
16282: 
16283: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
16284: 
16285: cloneruname - username of owner of new course who wants to clone
16286: 
16287: clonerudom - domain of owner of new course who wants to clone
16288: 
16289: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
16290: 
16291: codetitlesref - reference to array of titles of components in institutional codes (official courses)
16292: 
16293: codedom - domain
16294: 
16295: formname - value of form element named "form".
16296: 
16297: fixeddom - domain, if fixed.
16298: 
16299: prevphase - value to assign to form element named "phase" when going back to the previous screen
16300: 
16301: cnameelement - name of form element in form on opener page which will receive title of selected course
16302: 
16303: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
16304: 
16305: cdomelement - name of form element in form on opener page which will receive domain of selected course
16306: 
16307: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
16308: 
16309: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
16310: 
16311: clonewarning - warning message about missing information for intended course owner when DC creates a course
16312: 
16313: 
16314: Returns: $output - HTML for display of search criteria, and hidden form elements.
16315: 
16316: 
16317: Side Effects: None
16318: 
16319: =cut
16320: 
16321: # ---------------------------------------------- search for courses based on last activity etc.
16322: 
16323: sub build_filters {
16324:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
16325:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
16326:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
16327:         $cnameelement,$cnumelement,$cdomelement,$setroles,
16328:         $clonetext,$clonewarning) = @_;
16329:     my ($list,$jscript);
16330:     my $onchange = 'javascript:updateFilters(this)';
16331:     my ($domainselectform,$sincefilterform,$createdfilterform,
16332:         $ownerdomselectform,$persondomselectform,$instcodeform,
16333:         $typeselectform,$instcodetitle);
16334:     if ($formname eq '') {
16335:         $formname = $caller;
16336:     }
16337:     foreach my $item (@{$filterlist}) {
16338:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
16339:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
16340:             if ($item eq 'domainfilter') {
16341:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
16342:             } elsif ($item eq 'coursefilter') {
16343:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
16344:             } elsif ($item eq 'ownerfilter') {
16345:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
16346:             } elsif ($item eq 'ownerdomfilter') {
16347:                 $filter->{'ownerdomfilter'} =
16348:                     &LONCAPA::clean_domain($filter->{$item});
16349:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
16350:                                                        'ownerdomfilter',1);
16351:             } elsif ($item eq 'personfilter') {
16352:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
16353:             } elsif ($item eq 'persondomfilter') {
16354:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
16355:                                                         'persondomfilter',1);
16356:             } else {
16357:                 $filter->{$item} =~ s/\W//g;
16358:             }
16359:             if (!$filter->{$item}) {
16360:                 $filter->{$item} = '';
16361:             }
16362:         }
16363:         if ($item eq 'domainfilter') {
16364:             my $allow_blank = 1;
16365:             if ($formname eq 'portform') {
16366:                 $allow_blank=0;
16367:             } elsif ($formname eq 'studentform') {
16368:                 $allow_blank=0;
16369:             }
16370:             if ($fixeddom) {
16371:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
16372:                                     ' value="'.$codedom.'" />'.
16373:                                     &Apache::lonnet::domain($codedom,'description');
16374:             } else {
16375:                 $domainselectform = &select_dom_form($filter->{$item},
16376:                                                      'domainfilter',
16377:                                                       $allow_blank,'',$onchange);
16378:             }
16379:         } else {
16380:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
16381:         }
16382:     }
16383: 
16384:     # last course activity filter and selection
16385:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
16386: 
16387:     # course created filter and selection
16388:     if (exists($filter->{'createdfilter'})) {
16389:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
16390:     }
16391: 
16392:     my %lt = &Apache::lonlocal::texthash(
16393:                 'cac' => "$crstype Activity",
16394:                 'ccr' => "$crstype Created",
16395:                 'cde' => "$crstype Title",
16396:                 'cdo' => "$crstype Domain",
16397:                 'ins' => 'Institutional Code',
16398:                 'inc' => 'Institutional Categorization',
16399:                 'cow' => "$crstype Owner/Co-owner",
16400:                 'cop' => "$crstype Personnel Includes",
16401:                 'cog' => 'Type',
16402:              );
16403: 
16404:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
16405:         my $typeval = 'Course';
16406:         if ($crstype eq 'Community') {
16407:             $typeval = 'Community';
16408:         }
16409:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
16410:     } else {
16411:         $typeselectform =  '<select name="type" size="1"';
16412:         if ($onchange) {
16413:             $typeselectform .= ' onchange="'.$onchange.'"';
16414:         }
16415:         $typeselectform .= '>'."\n";
16416:         foreach my $posstype ('Course','Community') {
16417:             $typeselectform.='<option value="'.$posstype.'"'.
16418:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
16419:         }
16420:         $typeselectform.="</select>";
16421:     }
16422: 
16423:     my ($cloneableonlyform,$cloneabletitle);
16424:     if (exists($filter->{'cloneableonly'})) {
16425:         my $cloneableon = '';
16426:         my $cloneableoff = ' checked="checked"';
16427:         if ($filter->{'cloneableonly'}) {
16428:             $cloneableon = $cloneableoff;
16429:             $cloneableoff = '';
16430:         }
16431:         $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>';
16432:         if ($formname eq 'ccrs') {
16433:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
16434:         } else {
16435:             $cloneabletitle = &mt('Cloneable by you');
16436:         }
16437:     }
16438:     my $officialjs;
16439:     if ($crstype eq 'Course') {
16440:         if (exists($filter->{'instcodefilter'})) {
16441: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
16442: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
16443:             if ($codedom) {
16444:                 $officialjs = 1;
16445:                 ($instcodeform,$jscript,$$numtitlesref) =
16446:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
16447:                                                                   $officialjs,$codetitlesref);
16448:                 if ($jscript) {
16449:                     $jscript = '<script type="text/javascript">'."\n".
16450:                                '// <![CDATA['."\n".
16451:                                $jscript."\n".
16452:                                '// ]]>'."\n".
16453:                                '</script>'."\n";
16454:                 }
16455:             }
16456:             if ($instcodeform eq '') {
16457:                 $instcodeform =
16458:                     '<input type="text" name="instcodefilter" size="10" value="'.
16459:                     $list->{'instcodefilter'}.'" />';
16460:                 $instcodetitle = $lt{'ins'};
16461:             } else {
16462:                 $instcodetitle = $lt{'inc'};
16463:             }
16464:             if ($fixeddom) {
16465:                 $instcodetitle .= '<br />('.$codedom.')';
16466:             }
16467:         }
16468:     }
16469:     my $output = qq|
16470: <form method="post" name="filterpicker" action="$action">
16471: <input type="hidden" name="form" value="$formname" />
16472: |;
16473:     if ($formname eq 'modifycourse') {
16474:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
16475:                    '<input type="hidden" name="prevphase" value="'.
16476:                    $prevphase.'" />'."\n";
16477:     } elsif ($formname eq 'quotacheck') {
16478:         $output .= qq|
16479: <input type="hidden" name="sortby" value="" />
16480: <input type="hidden" name="sortorder" value="" />
16481: |;
16482:     } else {
16483:         my $name_input;
16484:         if ($cnameelement ne '') {
16485:             $name_input = '<input type="hidden" name="cnameelement" value="'.
16486:                           $cnameelement.'" />';
16487:         }
16488:         $output .= qq|
16489: <input type="hidden" name="cnumelement" value="$cnumelement" />
16490: <input type="hidden" name="cdomelement" value="$cdomelement" />
16491: $name_input
16492: $roleelement
16493: $multelement
16494: $typeelement
16495: |;
16496:         if ($formname eq 'portform') {
16497:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
16498:         }
16499:     }
16500:     if ($fixeddom) {
16501:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
16502:     }
16503:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
16504:     if ($sincefilterform) {
16505:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
16506:                   .$sincefilterform
16507:                   .&Apache::lonhtmlcommon::row_closure();
16508:     }
16509:     if ($createdfilterform) {
16510:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
16511:                   .$createdfilterform
16512:                   .&Apache::lonhtmlcommon::row_closure();
16513:     }
16514:     if ($domainselectform) {
16515:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
16516:                   .$domainselectform
16517:                   .&Apache::lonhtmlcommon::row_closure();
16518:     }
16519:     if ($typeselectform) {
16520:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
16521:             $output .= $typeselectform;
16522:         } else {
16523:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
16524:                       .$typeselectform
16525:                       .&Apache::lonhtmlcommon::row_closure();
16526:         }
16527:     }
16528:     if ($instcodeform) {
16529:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
16530:                   .$instcodeform
16531:                   .&Apache::lonhtmlcommon::row_closure();
16532:     }
16533:     if (exists($filter->{'ownerfilter'})) {
16534:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
16535:                    '<table><tr><td>'.&mt('Username').'<br />'.
16536:                    '<input type="text" name="ownerfilter" size="20" value="'.
16537:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
16538:                    $ownerdomselectform.'</td></tr></table>'.
16539:                    &Apache::lonhtmlcommon::row_closure();
16540:     }
16541:     if (exists($filter->{'personfilter'})) {
16542:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
16543:                    '<table><tr><td>'.&mt('Username').'<br />'.
16544:                    '<input type="text" name="personfilter" size="20" value="'.
16545:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
16546:                    $persondomselectform.'</td></tr></table>'.
16547:                    &Apache::lonhtmlcommon::row_closure();
16548:     }
16549:     if (exists($filter->{'coursefilter'})) {
16550:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
16551:                   .'<input type="text" name="coursefilter" size="25" value="'
16552:                   .$list->{'coursefilter'}.'" />'
16553:                   .&Apache::lonhtmlcommon::row_closure();
16554:     }
16555:     if ($cloneableonlyform) {
16556:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
16557:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
16558:     }
16559:     if (exists($filter->{'descriptfilter'})) {
16560:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
16561:                   .'<input type="text" name="descriptfilter" size="40" value="'
16562:                   .$list->{'descriptfilter'}.'" />'
16563:                   .&Apache::lonhtmlcommon::row_closure(1);
16564:     }
16565:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
16566:                '<input type="hidden" name="updater" value="" />'."\n".
16567:                '<input type="submit" name="gosearch" value="'.
16568:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
16569:     return $jscript.$clonewarning.$output;
16570: }
16571: 
16572: =pod
16573: 
16574: =item * &timebased_select_form()
16575: 
16576: Create markup for a dropdown list used to select a time-based
16577: filter e.g., Course Activity, Course Created, when searching for courses
16578: or communities
16579: 
16580: Inputs:
16581: 
16582: item - name of form element (sincefilter or createdfilter)
16583: 
16584: filter - anonymous hash of criteria and their values
16585: 
16586: Returns: HTML for a select box contained a blank, then six time selections,
16587:          with value set in incoming form variables currently selected.
16588: 
16589: Side Effects: None
16590: 
16591: =cut
16592: 
16593: sub timebased_select_form {
16594:     my ($item,$filter) = @_;
16595:     if (ref($filter) eq 'HASH') {
16596:         $filter->{$item} =~ s/[^\d-]//g;
16597:         if (!$filter->{$item}) { $filter->{$item}=-1; }
16598:         return &select_form(
16599:                             $filter->{$item},
16600:                             $item,
16601:                             {      '-1' => '',
16602:                                 '86400' => &mt('today'),
16603:                                '604800' => &mt('last week'),
16604:                               '2592000' => &mt('last month'),
16605:                               '7776000' => &mt('last three months'),
16606:                              '15552000' => &mt('last six months'),
16607:                              '31104000' => &mt('last year'),
16608:                     'select_form_order' =>
16609:                            ['-1','86400','604800','2592000','7776000',
16610:                             '15552000','31104000']});
16611:     }
16612: }
16613: 
16614: =pod
16615: 
16616: =item * &js_changer()
16617: 
16618: Create script tag containing Javascript used to submit course search form
16619: when course type or domain is changed, and also to hide 'Searching ...' on
16620: page load completion for page showing search result.
16621: 
16622: Inputs: None
16623: 
16624: Returns: markup containing updateFilters() and hideSearching() javascript functions.
16625: 
16626: Side Effects: None
16627: 
16628: =cut
16629: 
16630: sub js_changer {
16631:     return <<ENDJS;
16632: <script type="text/javascript">
16633: // <![CDATA[
16634: function updateFilters(caller) {
16635:     if (typeof(caller) != "undefined") {
16636:         document.filterpicker.updater.value = caller.name;
16637:     }
16638:     document.filterpicker.submit();
16639: }
16640: 
16641: function hideSearching() {
16642:     if (document.getElementById('searching')) {
16643:         document.getElementById('searching').style.display = 'none';
16644:     }
16645:     return;
16646: }
16647: 
16648: // ]]>
16649: </script>
16650: 
16651: ENDJS
16652: }
16653: 
16654: =pod
16655: 
16656: =item * &search_courses()
16657: 
16658: Process selected filters form course search form and pass to lonnet::courseiddump
16659: to retrieve a hash for which keys are courseIDs which match the selected filters.
16660: 
16661: Inputs:
16662: 
16663: dom - domain being searched
16664: 
16665: type - course type ('Course' or 'Community' or '.' if any).
16666: 
16667: filter - anonymous hash of criteria and their values
16668: 
16669: numtitles - for institutional codes - number of categories
16670: 
16671: cloneruname - optional username of new course owner
16672: 
16673: clonerudom - optional domain of new course owner
16674: 
16675: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
16676:             (used when DC is using course creation form)
16677: 
16678: codetitles - reference to array of titles of components in institutional codes (official courses).
16679: 
16680: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
16681:            (and so can clone automatically)
16682: 
16683: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
16684: 
16685: reqinstcode - institutional code of new course, where search_courses is used to identify potential
16686:               courses to clone
16687: 
16688: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
16689: 
16690: 
16691: Side Effects: None
16692: 
16693: =cut
16694: 
16695: 
16696: sub search_courses {
16697:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
16698:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
16699:     my (%courses,%showcourses,$cloner);
16700:     if (($filter->{'ownerfilter'} ne '') ||
16701:         ($filter->{'ownerdomfilter'} ne '')) {
16702:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
16703:                                        $filter->{'ownerdomfilter'};
16704:     }
16705:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
16706:         if (!$filter->{$item}) {
16707:             $filter->{$item}='.';
16708:         }
16709:     }
16710:     my $now = time;
16711:     my $timefilter =
16712:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
16713:     my ($createdbefore,$createdafter);
16714:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
16715:         $createdbefore = $now;
16716:         $createdafter = $now-$filter->{'createdfilter'};
16717:     }
16718:     my ($instcodefilter,$regexpok);
16719:     if ($numtitles) {
16720:         if ($env{'form.official'} eq 'on') {
16721:             $instcodefilter =
16722:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
16723:             $regexpok = 1;
16724:         } elsif ($env{'form.official'} eq 'off') {
16725:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
16726:             unless ($instcodefilter eq '') {
16727:                 $regexpok = -1;
16728:             }
16729:         }
16730:     } else {
16731:         $instcodefilter = $filter->{'instcodefilter'};
16732:     }
16733:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
16734:     if ($type eq '') { $type = '.'; }
16735: 
16736:     if (($clonerudom ne '') && ($cloneruname ne '')) {
16737:         $cloner = $cloneruname.':'.$clonerudom;
16738:     }
16739:     %courses = &Apache::lonnet::courseiddump($dom,
16740:                                              $filter->{'descriptfilter'},
16741:                                              $timefilter,
16742:                                              $instcodefilter,
16743:                                              $filter->{'combownerfilter'},
16744:                                              $filter->{'coursefilter'},
16745:                                              undef,undef,$type,$regexpok,undef,undef,
16746:                                              undef,undef,$cloner,$cc_clone,
16747:                                              $filter->{'cloneableonly'},
16748:                                              $createdbefore,$createdafter,undef,
16749:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
16750:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
16751:         my $ccrole;
16752:         if ($type eq 'Community') {
16753:             $ccrole = 'co';
16754:         } else {
16755:             $ccrole = 'cc';
16756:         }
16757:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
16758:                                                      $filter->{'persondomfilter'},
16759:                                                      'userroles',undef,
16760:                                                      [$ccrole,'in','ad','ep','ta','cr'],
16761:                                                      $dom);
16762:         foreach my $role (keys(%rolehash)) {
16763:             my ($cnum,$cdom,$courserole) = split(':',$role);
16764:             my $cid = $cdom.'_'.$cnum;
16765:             if (exists($courses{$cid})) {
16766:                 if (ref($courses{$cid}) eq 'HASH') {
16767:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
16768:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
16769:                             push(@{$courses{$cid}{roles}},$courserole);
16770:                         }
16771:                     } else {
16772:                         $courses{$cid}{roles} = [$courserole];
16773:                     }
16774:                     $showcourses{$cid} = $courses{$cid};
16775:                 }
16776:             }
16777:         }
16778:         %courses = %showcourses;
16779:     }
16780:     return %courses;
16781: }
16782: 
16783: =pod
16784: 
16785: =back
16786: 
16787: =head1 Routines for version requirements for current course.
16788: 
16789: =over 4
16790: 
16791: =item * &check_release_required()
16792: 
16793: Compares required LON-CAPA version with version on server, and
16794: if required version is newer looks for a server with the required version.
16795: 
16796: Looks first at servers in user's owen domain; if none suitable, looks at
16797: servers in course's domain are permitted to host sessions for user's domain.
16798: 
16799: Inputs:
16800: 
16801: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
16802: 
16803: $courseid - Course ID of current course
16804: 
16805: $rolecode - User's current role in course (for switchserver query string).
16806: 
16807: $required - LON-CAPA version needed by course (format: Major.Minor).
16808: 
16809: 
16810: Returns:
16811: 
16812: $switchserver - query string tp append to /adm/switchserver call (if
16813:                 current server's LON-CAPA version is too old.
16814: 
16815: $warning - Message is displayed if no suitable server could be found.
16816: 
16817: =cut
16818: 
16819: sub check_release_required {
16820:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
16821:     my ($switchserver,$warning);
16822:     if ($required ne '') {
16823:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
16824:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
16825:         if ($reqdmajor ne '' && $reqdminor ne '') {
16826:             my $otherserver;
16827:             if (($major eq '' && $minor eq '') ||
16828:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
16829:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
16830:                 my $switchlcrev =
16831:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
16832:                                                            $userdomserver);
16833:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
16834:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
16835:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
16836:                     my $cdom = $env{'course.'.$courseid.'.domain'};
16837:                     if ($cdom ne $env{'user.domain'}) {
16838:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
16839:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
16840:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
16841:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
16842:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
16843:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
16844:                         my $canhost =
16845:                             &Apache::lonnet::can_host_session($env{'user.domain'},
16846:                                                               $coursedomserver,
16847:                                                               $remoterev,
16848:                                                               $udomdefaults{'remotesessions'},
16849:                                                               $defdomdefaults{'hostedsessions'});
16850: 
16851:                         if ($canhost) {
16852:                             $otherserver = $coursedomserver;
16853:                         } else {
16854:                             $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.");
16855:                         }
16856:                     } else {
16857:                         $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).");
16858:                     }
16859:                 } else {
16860:                     $otherserver = $userdomserver;
16861:                 }
16862:             }
16863:             if ($otherserver ne '') {
16864:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
16865:             }
16866:         }
16867:     }
16868:     return ($switchserver,$warning);
16869: }
16870: 
16871: =pod
16872: 
16873: =item * &check_release_result()
16874: 
16875: Inputs:
16876: 
16877: $switchwarning - Warning message if no suitable server found to host session.
16878: 
16879: $switchserver - query string to append to /adm/switchserver containing lonHostID
16880:                 and current role.
16881: 
16882: Returns: HTML to display with information about requirement to switch server.
16883:          Either displaying warning with link to Roles/Courses screen or
16884:          display link to switchserver.
16885: 
16886: =cut
16887: 
16888: sub check_release_result {
16889:     my ($switchwarning,$switchserver) = @_;
16890:     my $output = &start_page('Selected course unavailable on this server').
16891:                  '<p class="LC_warning">';
16892:     if ($switchwarning) {
16893:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
16894:         if (&show_course()) {
16895:             $output .= &mt('Display courses');
16896:         } else {
16897:             $output .= &mt('Display roles');
16898:         }
16899:         $output .= '</a>';
16900:     } elsif ($switchserver) {
16901:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
16902:                    '<br />'.
16903:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
16904:                    &mt('Switch Server').
16905:                    '</a>';
16906:     }
16907:     $output .= '</p>'.&end_page();
16908:     return $output;
16909: }
16910: 
16911: =pod
16912: 
16913: =item * &needs_coursereinit()
16914: 
16915: Determine if course contents stored for user's session needs to be
16916: refreshed, because content has changed since "Big Hash" last tied.
16917: 
16918: Check for change is made if time last checked is more than 10 minutes ago
16919: (by default).
16920: 
16921: Inputs:
16922: 
16923: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
16924: 
16925: $interval (optional) - Time which may elapse (in s) between last check for content
16926:                        change in current course. (default: 600 s).
16927: 
16928: Returns: an array; first element is:
16929: 
16930: =over 4
16931: 
16932: 'switch' - if content updates mean user's session
16933:            needs to be switched to a server running a newer LON-CAPA version
16934: 
16935: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
16936:            on current server hosting user's session
16937: 
16938: ''       - if no action required.
16939: 
16940: =back
16941: 
16942: If first item element is 'switch':
16943: 
16944: second item is $switchwarning - Warning message if no suitable server found to host session.
16945: 
16946: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
16947:                               and current role.
16948: 
16949: otherwise: no other elements returned.
16950: 
16951: =back
16952: 
16953: =cut
16954: 
16955: sub needs_coursereinit {
16956:     my ($loncaparev,$interval) = @_;
16957:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
16958:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
16959:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
16960:     my $now = time;
16961:     if ($interval eq '') {
16962:         $interval = 600;
16963:     }
16964:     if (($now-$env{'request.course.timechecked'})>$interval) {
16965:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
16966:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
16967:         if ($lastchange > $env{'request.course.tied'}) {
16968:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
16969:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
16970:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
16971:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
16972:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
16973:                                              $curr_reqd_hash{'internal.releaserequired'}});
16974:                     my ($switchserver,$switchwarning) =
16975:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
16976:                                                 $curr_reqd_hash{'internal.releaserequired'});
16977:                     if ($switchwarning ne '' || $switchserver ne '') {
16978:                         return ('switch',$switchwarning,$switchserver);
16979:                     }
16980:                 }
16981:             }
16982:             return ('update');
16983:         }
16984:     }
16985:     return ();
16986: }
16987: 
16988: sub update_content_constraints {
16989:     my ($cdom,$cnum,$chome,$cid) = @_;
16990:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
16991:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
16992:     my %checkresponsetypes;
16993:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
16994:         my ($item,$name,$value) = split(/:/,$key);
16995:         if ($item eq 'resourcetag') {
16996:             if ($name eq 'responsetype') {
16997:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
16998:             }
16999:         }
17000:     }
17001:     my $navmap = Apache::lonnavmaps::navmap->new();
17002:     if (defined($navmap)) {
17003:         my %allresponses;
17004:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
17005:             my %responses = $res->responseTypes();
17006:             foreach my $key (keys(%responses)) {
17007:                 next unless(exists($checkresponsetypes{$key}));
17008:                 $allresponses{$key} += $responses{$key};
17009:             }
17010:         }
17011:         foreach my $key (keys(%allresponses)) {
17012:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
17013:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
17014:                 ($reqdmajor,$reqdminor) = ($major,$minor);
17015:             }
17016:         }
17017:         undef($navmap);
17018:     }
17019:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
17020:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
17021:     }
17022:     return;
17023: }
17024: 
17025: sub allmaps_incourse {
17026:     my ($cdom,$cnum,$chome,$cid) = @_;
17027:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
17028:         $cid = $env{'request.course.id'};
17029:         $cdom = $env{'course.'.$cid.'.domain'};
17030:         $cnum = $env{'course.'.$cid.'.num'};
17031:         $chome = $env{'course.'.$cid.'.home'};
17032:     }
17033:     my %allmaps = ();
17034:     my $lastchange =
17035:         &Apache::lonnet::get_coursechange($cdom,$cnum);
17036:     if ($lastchange > $env{'request.course.tied'}) {
17037:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
17038:         unless ($ferr) {
17039:             &update_content_constraints($cdom,$cnum,$chome,$cid);
17040:         }
17041:     }
17042:     my $navmap = Apache::lonnavmaps::navmap->new();
17043:     if (defined($navmap)) {
17044:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
17045:             $allmaps{$res->src()} = 1;
17046:         }
17047:     }
17048:     return \%allmaps;
17049: }
17050: 
17051: sub parse_supplemental_title {
17052:     my ($title) = @_;
17053: 
17054:     my ($foldertitle,$renametitle);
17055:     if ($title =~ /&amp;&amp;&amp;/) {
17056:         $title = &HTML::Entites::decode($title);
17057:     }
17058:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
17059:         $renametitle=$4;
17060:         my ($time,$uname,$udom) = ($1,$2,$3);
17061:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
17062:         my $name =  &plainname($uname,$udom);
17063:         $name = &HTML::Entities::encode($name,'"<>&\'');
17064:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
17065:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
17066:             $name.': <br />'.$foldertitle;
17067:     }
17068:     if (wantarray) {
17069:         return ($title,$foldertitle,$renametitle);
17070:     }
17071:     return $title;
17072: }
17073: 
17074: sub recurse_supplemental {
17075:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
17076:     if ($suppmap) {
17077:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
17078:         if ($fatal) {
17079:             $errors ++;
17080:         } else {
17081:             if ($#LONCAPA::map::resources > 0) {
17082:                 foreach my $res (@LONCAPA::map::resources) {
17083:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
17084:                     if (($src ne '') && ($status eq 'res')) {
17085:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
17086:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
17087:                         } else {
17088:                             $numfiles ++;
17089:                         }
17090:                     }
17091:                 }
17092:             }
17093:         }
17094:     }
17095:     return ($numfiles,$errors);
17096: }
17097: 
17098: sub symb_to_docspath {
17099:     my ($symb,$navmapref) = @_;
17100:     return unless ($symb && ref($navmapref));
17101:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
17102:     if ($resurl=~/\.(sequence|page)$/) {
17103:         $mapurl=$resurl;
17104:     } elsif ($resurl eq 'adm/navmaps') {
17105:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
17106:     }
17107:     my $mapresobj;
17108:     unless (ref($$navmapref)) {
17109:         $$navmapref = Apache::lonnavmaps::navmap->new();
17110:     }
17111:     if (ref($$navmapref)) {
17112:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
17113:     }
17114:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
17115:     my $type=$2;
17116:     my $path;
17117:     if (ref($mapresobj)) {
17118:         my $pcslist = $mapresobj->map_hierarchy();
17119:         if ($pcslist ne '') {
17120:             foreach my $pc (split(/,/,$pcslist)) {
17121:                 next if ($pc <= 1);
17122:                 my $res = $$navmapref->getByMapPc($pc);
17123:                 if (ref($res)) {
17124:                     my $thisurl = $res->src();
17125:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
17126:                     my $thistitle = $res->title();
17127:                     $path .= '&'.
17128:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
17129:                              &escape($thistitle).
17130:                              ':'.$res->randompick().
17131:                              ':'.$res->randomout().
17132:                              ':'.$res->encrypted().
17133:                              ':'.$res->randomorder().
17134:                              ':'.$res->is_page();
17135:                 }
17136:             }
17137:         }
17138:         $path =~ s/^\&//;
17139:         my $maptitle = $mapresobj->title();
17140:         if ($mapurl eq 'default') {
17141:             $maptitle = 'Main Content';
17142:         }
17143:         $path .= (($path ne '')? '&' : '').
17144:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
17145:                  &escape($maptitle).
17146:                  ':'.$mapresobj->randompick().
17147:                  ':'.$mapresobj->randomout().
17148:                  ':'.$mapresobj->encrypted().
17149:                  ':'.$mapresobj->randomorder().
17150:                  ':'.$mapresobj->is_page();
17151:     } else {
17152:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
17153:         my $ispage = (($type eq 'page')? 1 : '');
17154:         if ($mapurl eq 'default') {
17155:             $maptitle = 'Main Content';
17156:         }
17157:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
17158:                 &escape($maptitle).':::::'.$ispage;
17159:     }
17160:     unless ($mapurl eq 'default') {
17161:         $path = 'default&'.
17162:                 &escape('Main Content').
17163:                 ':::::&'.$path;
17164:     }
17165:     return $path;
17166: }
17167: 
17168: sub captcha_display {
17169:     my ($context,$lonhost,$defdom) = @_;
17170:     my ($output,$error);
17171:     my ($captcha,$pubkey,$privkey,$version) =
17172:         &get_captcha_config($context,$lonhost,$defdom);
17173:     if ($captcha eq 'original') {
17174:         $output = &create_captcha();
17175:         unless ($output) {
17176:             $error = 'captcha';
17177:         }
17178:     } elsif ($captcha eq 'recaptcha') {
17179:         $output = &create_recaptcha($pubkey,$version);
17180:         unless ($output) {
17181:             $error = 'recaptcha';
17182:         }
17183:     }
17184:     return ($output,$error,$captcha,$version);
17185: }
17186: 
17187: sub captcha_response {
17188:     my ($context,$lonhost,$defdom) = @_;
17189:     my ($captcha_chk,$captcha_error);
17190:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
17191:     if ($captcha eq 'original') {
17192:         ($captcha_chk,$captcha_error) = &check_captcha();
17193:     } elsif ($captcha eq 'recaptcha') {
17194:         $captcha_chk = &check_recaptcha($privkey,$version);
17195:     } else {
17196:         $captcha_chk = 1;
17197:     }
17198:     return ($captcha_chk,$captcha_error);
17199: }
17200: 
17201: sub get_captcha_config {
17202:     my ($context,$lonhost,$dom_in_effect) = @_;
17203:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
17204:     my $hostname = &Apache::lonnet::hostname($lonhost);
17205:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
17206:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
17207:     if ($context eq 'usercreation') {
17208:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
17209:         if (ref($domconfig{$context}) eq 'HASH') {
17210:             $hashtocheck = $domconfig{$context}{'cancreate'};
17211:             if (ref($hashtocheck) eq 'HASH') {
17212:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
17213:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
17214:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
17215:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
17216:                     }
17217:                     if ($privkey && $pubkey) {
17218:                         $captcha = 'recaptcha';
17219:                         $version = $hashtocheck->{'recaptchaversion'};
17220:                         if ($version ne '2') {
17221:                             $version = 1;
17222:                         }
17223:                     } else {
17224:                         $captcha = 'original';
17225:                     }
17226:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
17227:                     $captcha = 'original';
17228:                 }
17229:             }
17230:         } else {
17231:             $captcha = 'captcha';
17232:         }
17233:     } elsif ($context eq 'login') {
17234:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
17235:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
17236:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
17237:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
17238:             if ($privkey && $pubkey) {
17239:                 $captcha = 'recaptcha';
17240:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
17241:                 if ($version ne '2') {
17242:                     $version = 1;
17243:                 }
17244:             } else {
17245:                 $captcha = 'original';
17246:             }
17247:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
17248:             $captcha = 'original';
17249:         }
17250:     } elsif ($context eq 'passwords') {
17251:         if ($dom_in_effect) {
17252:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
17253:             if ($passwdconf{'captcha'} eq 'recaptcha') {
17254:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
17255:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
17256:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
17257:                 }
17258:                 if ($privkey && $pubkey) {
17259:                     $captcha = 'recaptcha';
17260:                     $version = $passwdconf{'recaptchaversion'};
17261:                     if ($version ne '2') {
17262:                         $version = 1;
17263:                     }
17264:                 } else {
17265:                     $captcha = 'original';
17266:                 }
17267:             } elsif ($passwdconf{'captcha'} ne 'notused') {
17268:                 $captcha = 'original';
17269:             }
17270:         }
17271:     }
17272:     return ($captcha,$pubkey,$privkey,$version);
17273: }
17274: 
17275: sub create_captcha {
17276:     my %captcha_params = &captcha_settings();
17277:     my ($output,$maxtries,$tries) = ('',10,0);
17278:     while ($tries < $maxtries) {
17279:         $tries ++;
17280:         my $captcha = Authen::Captcha->new (
17281:                                            output_folder => $captcha_params{'output_dir'},
17282:                                            data_folder   => $captcha_params{'db_dir'},
17283:                                           );
17284:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
17285: 
17286:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
17287:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
17288:                       '<span class="LC_nobreak">'.
17289:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
17290:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
17291:                       '</span><br />'.
17292:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
17293:             last;
17294:         }
17295:     }
17296:     if ($output eq '') {
17297:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
17298:     }
17299:     return $output;
17300: }
17301: 
17302: sub captcha_settings {
17303:     my %captcha_params = (
17304:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
17305:                            www_output_dir => "/captchaspool",
17306:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
17307:                            numchars       => '5',
17308:                          );
17309:     return %captcha_params;
17310: }
17311: 
17312: sub check_captcha {
17313:     my ($captcha_chk,$captcha_error);
17314:     my $code = $env{'form.code'};
17315:     my $md5sum = $env{'form.crypt'};
17316:     my %captcha_params = &captcha_settings();
17317:     my $captcha = Authen::Captcha->new(
17318:                       output_folder => $captcha_params{'output_dir'},
17319:                       data_folder   => $captcha_params{'db_dir'},
17320:                   );
17321:     $captcha_chk = $captcha->check_code($code,$md5sum);
17322:     my %captcha_hash = (
17323:                         0       => 'Code not checked (file error)',
17324:                        -1      => 'Failed: code expired',
17325:                        -2      => 'Failed: invalid code (not in database)',
17326:                        -3      => 'Failed: invalid code (code does not match crypt)',
17327:     );
17328:     if ($captcha_chk != 1) {
17329:         $captcha_error = $captcha_hash{$captcha_chk}
17330:     }
17331:     return ($captcha_chk,$captcha_error);
17332: }
17333: 
17334: sub create_recaptcha {
17335:     my ($pubkey,$version) = @_;
17336:     if ($version >= 2) {
17337:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
17338:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
17339:     } else {
17340:         my $use_ssl;
17341:         if ($ENV{'SERVER_PORT'} == 443) {
17342:             $use_ssl = 1;
17343:         }
17344:         my $captcha = Captcha::reCAPTCHA->new;
17345:         return $captcha->get_options_setter({theme => 'white'})."\n".
17346:                $captcha->get_html($pubkey,undef,$use_ssl).
17347:                &mt('If the text is hard to read, [_1] will replace them.',
17348:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
17349:                '<br /><br />';
17350:      }
17351: }
17352: 
17353: sub check_recaptcha {
17354:     my ($privkey,$version) = @_;
17355:     my $captcha_chk;
17356:     my $ip = &Apache::lonnet::get_requestor_ip(); 
17357:     if ($version >= 2) {
17358:         my $ua = LWP::UserAgent->new;
17359:         $ua->timeout(10);
17360:         my %info = (
17361:                      secret   => $privkey,
17362:                      response => $env{'form.g-recaptcha-response'},
17363:                      remoteip => $ip,
17364:                    );
17365:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
17366:         if ($response->is_success)  {
17367:             my $data = JSON::DWIW->from_json($response->decoded_content);
17368:             if (ref($data) eq 'HASH') {
17369:                 if ($data->{'success'}) {
17370:                     $captcha_chk = 1;
17371:                 }
17372:             }
17373:         }
17374:     } else {
17375:         my $captcha = Captcha::reCAPTCHA->new;
17376:         my $captcha_result =
17377:             $captcha->check_answer(
17378:                                     $privkey,
17379:                                     $ip,
17380:                                     $env{'form.recaptcha_challenge_field'},
17381:                                     $env{'form.recaptcha_response_field'},
17382:                                   );
17383:         if ($captcha_result->{is_valid}) {
17384:             $captcha_chk = 1;
17385:         }
17386:     }
17387:     return $captcha_chk;
17388: }
17389: 
17390: sub emailusername_info {
17391:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
17392:     my %titles = &Apache::lonlocal::texthash (
17393:                      lastname      => 'Last Name',
17394:                      firstname     => 'First Name',
17395:                      institution   => 'School/college/university',
17396:                      location      => "School's city, state/province, country",
17397:                      web           => "School's web address",
17398:                      officialemail => 'E-mail address at institution (if different)',
17399:                      id            => 'Student/Employee ID',
17400:                  );
17401:     return (\@fields,\%titles);
17402: }
17403: 
17404: sub cleanup_html {
17405:     my ($incoming) = @_;
17406:     my $outgoing;
17407:     if ($incoming ne '') {
17408:         $outgoing = $incoming;
17409:         $outgoing =~ s/;/&#059;/g;
17410:         $outgoing =~ s/\#/&#035;/g;
17411:         $outgoing =~ s/\&/&#038;/g;
17412:         $outgoing =~ s/</&#060;/g;
17413:         $outgoing =~ s/>/&#062;/g;
17414:         $outgoing =~ s/\(/&#040/g;
17415:         $outgoing =~ s/\)/&#041;/g;
17416:         $outgoing =~ s/"/&#034;/g;
17417:         $outgoing =~ s/'/&#039;/g;
17418:         $outgoing =~ s/\$/&#036;/g;
17419:         $outgoing =~ s{/}{&#047;}g;
17420:         $outgoing =~ s/=/&#061;/g;
17421:         $outgoing =~ s/\\/&#092;/g
17422:     }
17423:     return $outgoing;
17424: }
17425: 
17426: # Checks for critical messages and returns a redirect url if one exists.
17427: # $interval indicates how often to check for messages.
17428: sub critical_redirect {
17429:     my ($interval) = @_;
17430:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
17431:         return ();
17432:     }
17433:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
17434:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
17435:                                         $env{'user.name'});
17436:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
17437:         my $redirecturl;
17438:         if ($what[0]) {
17439:             if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
17440:                 $redirecturl='/adm/email?critical=display';
17441:                 my $url=&Apache::lonnet::absolute_url().$redirecturl;
17442:                 return (1, $url);
17443:             }
17444:         }
17445:     }
17446:     return ();
17447: }
17448: 
17449: # Use:
17450: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
17451: #
17452: ##################################################
17453: #          password associated functions         #
17454: ##################################################
17455: sub des_keys {
17456:     # Make a new key for DES encryption.
17457:     # Each key has two parts which are returned separately.
17458:     # Please note:  Each key must be passed through the &hex function
17459:     # before it is output to the web browser.  The hex versions cannot
17460:     # be used to decrypt.
17461:     my @hexstr=('0','1','2','3','4','5','6','7',
17462:                 '8','9','a','b','c','d','e','f');
17463:     my $lkey='';
17464:     for (0..7) {
17465:         $lkey.=$hexstr[rand(15)];
17466:     }
17467:     my $ukey='';
17468:     for (0..7) {
17469:         $ukey.=$hexstr[rand(15)];
17470:     }
17471:     return ($lkey,$ukey);
17472: }
17473: 
17474: sub des_decrypt {
17475:     my ($key,$cyphertext) = @_;
17476:     my $keybin=pack("H16",$key);
17477:     my $cypher;
17478:     if ($Crypt::DES::VERSION>=2.03) {
17479:         $cypher=new Crypt::DES $keybin;
17480:     } else {
17481:         $cypher=new DES $keybin;
17482:     }
17483:     my $plaintext='';
17484:     my $cypherlength = length($cyphertext);
17485:     my $numchunks = int($cypherlength/32);
17486:     for (my $j=0; $j<$numchunks; $j++) {
17487:         my $start = $j*32;
17488:         my $cypherblock = substr($cyphertext,$start,32);
17489:         my $chunk =
17490:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
17491:         $chunk .=
17492:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
17493:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
17494:         $plaintext .= $chunk;
17495:     }
17496:     return $plaintext;
17497: }
17498: 
17499: sub is_nonframeable {
17500:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
17501:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
17502:     return if (($remprotocol eq '') || ($remhost eq ''));
17503: 
17504:     $remprotocol = lc($remprotocol);
17505:     $remhost = lc($remhost);
17506:     my $remport = 80;
17507:     if ($remprotocol eq 'https') {
17508:         $remport = 443;
17509:     }
17510:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
17511:     if ($cached) {
17512:         unless ($nocache) {
17513:             if ($result) {
17514:                 return 1;
17515:             } else {
17516:                 return 0;
17517:             }
17518:         }
17519:     }
17520:     my $uselink;
17521:     my $request = new HTTP::Request('HEAD',$url);
17522:     my $ua = LWP::UserAgent->new;
17523:     $ua->timeout(5);
17524:     my $response=$ua->request($request);
17525:     if ($response->is_success()) {
17526:         my $secpolicy = lc($response->header('content-security-policy'));
17527:         my $xframeop = lc($response->header('x-frame-options'));
17528:         $secpolicy =~ s/^\s+|\s+$//g;
17529:         $xframeop =~ s/^\s+|\s+$//g;
17530:         if (($secpolicy ne '') || ($xframeop ne '')) {
17531:             my $remotehost = $remprotocol.'://'.$remhost;
17532:             my ($origin,$protocol,$port);
17533:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
17534:                 $port = $ENV{'SERVER_PORT'};
17535:             } else {
17536:                 $port = 80;
17537:             }
17538:             if ($absolute eq '') {
17539:                 $protocol = 'http:';
17540:                 if ($port == 443) {
17541:                     $protocol = 'https:';
17542:                 }
17543:                 $origin = $protocol.'//'.lc($hostname);
17544:             } else {
17545:                 $origin = lc($absolute);
17546:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
17547:             }
17548:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
17549:                 my $framepolicy = $1;
17550:                 $framepolicy =~ s/^\s+|\s+$//g;
17551:                 my @policies = split(/\s+/,$framepolicy);
17552:                 if (@policies) {
17553:                     if (grep(/^\Q'none'\E$/,@policies)) {
17554:                         $uselink = 1;
17555:                     } else {
17556:                         $uselink = 1;
17557:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
17558:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
17559:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
17560:                             undef($uselink);
17561:                         }
17562:                         if ($uselink) {
17563:                             if (grep(/^\Q'self'\E$/,@policies)) {
17564:                                 if (($origin ne '') && ($remotehost eq $origin)) {
17565:                                     undef($uselink);
17566:                                 }
17567:                             }
17568:                         }
17569:                         if ($uselink) {
17570:                             my @possok;
17571:                             if ($ip ne '') {
17572:                                 push(@possok,$ip);
17573:                             }
17574:                             my $hoststr = '';
17575:                             foreach my $part (reverse(split(/\./,$hostname))) {
17576:                                 if ($hoststr eq '') {
17577:                                     $hoststr = $part;
17578:                                 } else {
17579:                                     $hoststr = "$part.$hoststr";
17580:                                 }
17581:                                 if ($hoststr eq $hostname) {
17582:                                     push(@possok,$hostname);
17583:                                 } else {
17584:                                     push(@possok,"*.$hoststr");
17585:                                 }
17586:                             }
17587:                             if (@possok) {
17588:                                 foreach my $poss (@possok) {
17589:                                     last if (!$uselink);
17590:                                     foreach my $policy (@policies) {
17591:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
17592:                                             undef($uselink);
17593:                                             last;
17594:                                         }
17595:                                     }
17596:                                 }
17597:                             }
17598:                         }
17599:                     }
17600:                 }
17601:             } elsif ($xframeop ne '') {
17602:                 $uselink = 1;
17603:                 my @policies = split(/\s*,\s*/,$xframeop);
17604:                 if (@policies) {
17605:                     unless (grep(/^deny$/,@policies)) {
17606:                         if ($origin ne '') {
17607:                             if (grep(/^sameorigin$/,@policies)) {
17608:                                 if ($remotehost eq $origin) {
17609:                                     undef($uselink);
17610:                                 }
17611:                             }
17612:                             if ($uselink) {
17613:                                 foreach my $policy (@policies) {
17614:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
17615:                                         my $allowfrom = $1;
17616:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
17617:                                             undef($uselink);
17618:                                             last;
17619:                                         }
17620:                                     }
17621:                                 }
17622:                             }
17623:                         }
17624:                     }
17625:                 }
17626:             }
17627:         }
17628:     }
17629:     if ($nocache) {
17630:         if ($cached) {
17631:             my $devalidate;
17632:             if ($uselink && !$result) {
17633:                 $devalidate = 1;
17634:             } elsif (!$uselink && $result) {
17635:                 $devalidate = 1;
17636:             }
17637:             if ($devalidate) {
17638:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
17639:             }
17640:         }
17641:     } else {
17642:         if ($uselink) {
17643:             $result = 1;
17644:         } else {
17645:             $result = 0;
17646:         }
17647:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
17648:     }
17649:     return $uselink;
17650: }
17651: 
17652: 1;
17653: __END__;
17654: 

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