File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1075.2.161.2.4: download - view: text, annotated - select for diffs
Sun Jan 23 02:02:48 2022 UTC (2 years, 5 months ago) by raeburn
Branches: version_2_11_4_msu
- For 2.11.4 (modified)
  Include changes in 1.1304, 1.1075.2.164, and part of 1.1359 and part of
  1.1372 omitted from rev. 1.1075.2.161.2.1

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1075.2.161.2.4 2022/01/23 02:02:48 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: use String::CRC32();
   87: use Short::URL();
   88: 
   89: # ---------------------------------------------- Designs
   90: use vars qw(%defaultdesign);
   91: 
   92: my $readit;
   93: 
   94: 
   95: ##
   96: ## Global Variables
   97: ##
   98: 
   99: 
  100: # ----------------------------------------------- SSI with retries:
  101: #
  102: 
  103: =pod
  104: 
  105: =head1 Server Side include with retries:
  106: 
  107: =over 4
  108: 
  109: =item * &ssi_with_retries(resource,retries form)
  110: 
  111: Performs an ssi with some number of retries.  Retries continue either
  112: until the result is ok or until the retry count supplied by the
  113: caller is exhausted.  
  114: 
  115: Inputs:
  116: 
  117: =over 4
  118: 
  119: resource   - Identifies the resource to insert.
  120: 
  121: retries    - Count of the number of retries allowed.
  122: 
  123: form       - Hash that identifies the rendering options.
  124: 
  125: =back
  126: 
  127: Returns:
  128: 
  129: =over 4
  130: 
  131: content    - The content of the response.  If retries were exhausted this is empty.
  132: 
  133: response   - The response from the last attempt (which may or may not have been successful.
  134: 
  135: =back
  136: 
  137: =back
  138: 
  139: =cut
  140: 
  141: sub ssi_with_retries {
  142:     my ($resource, $retries, %form) = @_;
  143: 
  144: 
  145:     my $ok = 0;			# True if we got a good response.
  146:     my $content;
  147:     my $response;
  148: 
  149:     # Try to get the ssi done. within the retries count:
  150: 
  151:     do {
  152: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  153: 	$ok      = $response->is_success;
  154:         if (!$ok) {
  155:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  156:         }
  157: 	$retries--;
  158:     } while (!$ok && ($retries > 0));
  159: 
  160:     if (!$ok) {
  161: 	$content = '';		# On error return an empty content.
  162:     }
  163:     return ($content, $response);
  164: 
  165: }
  166: 
  167: 
  168: 
  169: # ----------------------------------------------- Filetypes/Languages/Copyright
  170: my %language;
  171: my %supported_language;
  172: my %latex_language;		# For choosing hyphenation in <transl..>
  173: my %latex_language_bykey;	# for choosing hyphenation from metadata
  174: my %cprtag;
  175: my %scprtag;
  176: my %fe; my %fd; my %fm;
  177: my %category_extensions;
  178: 
  179: # ---------------------------------------------- Thesaurus variables
  180: #
  181: # %Keywords:
  182: #      A hash used by &keyword to determine if a word is considered a keyword.
  183: # $thesaurus_db_file 
  184: #      Scalar containing the full path to the thesaurus database.
  185: 
  186: my %Keywords;
  187: my $thesaurus_db_file;
  188: 
  189: #
  190: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  191: # thesaurus.tab, and filecategories.tab.
  192: #
  193: BEGIN {
  194:     # Variable initialization
  195:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  196:     #
  197:     unless ($readit) {
  198: # ------------------------------------------------------------------- languages
  199:     {
  200:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  201:                                    '/language.tab';
  202:         if ( open(my $fh,'<',$langtabfile) ) {
  203:             while (my $line = <$fh>) {
  204:                 next if ($line=~/^\#/);
  205:                 chomp($line);
  206:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  207:                 $language{$key}=$val.' - '.$enc;
  208:                 if ($sup) {
  209:                     $supported_language{$key}=$sup;
  210:                 }
  211: 		if ($latex) {
  212: 		    $latex_language_bykey{$key} = $latex;
  213: 		    $latex_language{$two} = $latex;
  214: 		}
  215:             }
  216:             close($fh);
  217:         }
  218:     }
  219: # ------------------------------------------------------------------ copyrights
  220:     {
  221:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  222:                                   '/copyright.tab';
  223:         if ( open (my $fh,'<',$copyrightfile) ) {
  224:             while (my $line = <$fh>) {
  225:                 next if ($line=~/^\#/);
  226:                 chomp($line);
  227:                 my ($key,$val)=(split(/\s+/,$line,2));
  228:                 $cprtag{$key}=$val;
  229:             }
  230:             close($fh);
  231:         }
  232:     }
  233: # ----------------------------------------------------------- source copyrights
  234:     {
  235:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  236:                                   '/source_copyright.tab';
  237:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
  238:             while (my $line = <$fh>) {
  239:                 next if ($line =~ /^\#/);
  240:                 chomp($line);
  241:                 my ($key,$val)=(split(/\s+/,$line,2));
  242:                 $scprtag{$key}=$val;
  243:             }
  244:             close($fh);
  245:         }
  246:     }
  247: 
  248: # -------------------------------------------------------------- default domain designs
  249:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  250:     my $designfile = $designdir.'/default.tab';
  251:     if ( open (my $fh,'<',$designfile) ) {
  252:         while (my $line = <$fh>) {
  253:             next if ($line =~ /^\#/);
  254:             chomp($line);
  255:             my ($key,$val)=(split(/\=/,$line));
  256:             if ($val) { $defaultdesign{$key}=$val; }
  257:         }
  258:         close($fh);
  259:     }
  260: 
  261: # ------------------------------------------------------------- file categories
  262:     {
  263:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  264:                                   '/filecategories.tab';
  265:         if ( open (my $fh,'<',$categoryfile) ) {
  266: 	    while (my $line = <$fh>) {
  267: 		next if ($line =~ /^\#/);
  268: 		chomp($line);
  269:                 my ($extension,$category)=(split(/\s+/,$line,2));
  270:                 push(@{$category_extensions{lc($category)}},$extension);
  271:             }
  272:             close($fh);
  273:         }
  274: 
  275:     }
  276: # ------------------------------------------------------------------ file types
  277:     {
  278:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  279:                '/filetypes.tab';
  280:         if ( open (my $fh,'<',$typesfile) ) {
  281:             while (my $line = <$fh>) {
  282: 		next if ($line =~ /^\#/);
  283: 		chomp($line);
  284:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  285:                 if ($descr ne '') {
  286:                     $fe{$ending}=lc($emb);
  287:                     $fd{$ending}=$descr;
  288:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  289:                 }
  290:             }
  291:             close($fh);
  292:         }
  293:     }
  294:     &Apache::lonnet::logthis(
  295:              "<span style='color:yellow;'>INFO: Read file types</span>");
  296:     $readit=1;
  297:     }  # end of unless($readit) 
  298:     
  299: }
  300: 
  301: ###############################################################
  302: ##           HTML and Javascript Helper Functions            ##
  303: ###############################################################
  304: 
  305: =pod 
  306: 
  307: =head1 HTML and Javascript Functions
  308: 
  309: =over 4
  310: 
  311: =item * &browser_and_searcher_javascript()
  312: 
  313: X<browsing, javascript>X<searching, javascript>Returns a string
  314: containing javascript with two functions, C<openbrowser> and
  315: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  316: tags.
  317: 
  318: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  319: 
  320: inputs: formname, elementname, only, omit
  321: 
  322: formname and elementname indicate the name of the html form and name of
  323: the element that the results of the browsing selection are to be placed in. 
  324: 
  325: Specifying 'only' will restrict the browser to displaying only files
  326: with the given extension.  Can be a comma separated list.
  327: 
  328: Specifying 'omit' will restrict the browser to NOT displaying files
  329: with the given extension.  Can be a comma separated list.
  330: 
  331: =item * &opensearcher(formname,elementname) [javascript]
  332: 
  333: Inputs: formname, elementname
  334: 
  335: formname and elementname specify the name of the html form and the name
  336: of the element the selection from the search results will be placed in.
  337: 
  338: =cut
  339: 
  340: sub browser_and_searcher_javascript {
  341:     my ($mode)=@_;
  342:     if (!defined($mode)) { $mode='edit'; }
  343:     my $resurl=&escape_single(&lastresurl());
  344:     return <<END;
  345: // <!-- BEGIN LON-CAPA Internal
  346:     var editbrowser = null;
  347:     function openbrowser(formname,elementname,only,omit,titleelement) {
  348:         var url = '$resurl/?';
  349:         if (editbrowser == null) {
  350:             url += 'launch=1&';
  351:         }
  352:         url += 'catalogmode=interactive&';
  353:         url += 'mode=$mode&';
  354:         url += 'inhibitmenu=yes&';
  355:         url += 'form=' + formname + '&';
  356:         if (only != null) {
  357:             url += 'only=' + only + '&';
  358:         } else {
  359:             url += 'only=&';
  360: 	}
  361:         if (omit != null) {
  362:             url += 'omit=' + omit + '&';
  363:         } else {
  364:             url += 'omit=&';
  365: 	}
  366:         if (titleelement != null) {
  367:             url += 'titleelement=' + titleelement + '&';
  368:         } else {
  369: 	    url += 'titleelement=&';
  370: 	}
  371:         url += 'element=' + elementname + '';
  372:         var title = 'Browser';
  373:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  374:         options += ',width=700,height=600';
  375:         editbrowser = open(url,title,options,'1');
  376:         editbrowser.focus();
  377:     }
  378:     var editsearcher;
  379:     function opensearcher(formname,elementname,titleelement) {
  380:         var url = '/adm/searchcat?';
  381:         if (editsearcher == null) {
  382:             url += 'launch=1&';
  383:         }
  384:         url += 'catalogmode=interactive&';
  385:         url += 'mode=$mode&';
  386:         url += 'form=' + formname + '&';
  387:         if (titleelement != null) {
  388:             url += 'titleelement=' + titleelement + '&';
  389:         } else {
  390: 	    url += 'titleelement=&';
  391: 	}
  392:         url += 'element=' + elementname + '';
  393:         var title = 'Search';
  394:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  395:         options += ',width=700,height=600';
  396:         editsearcher = open(url,title,options,'1');
  397:         editsearcher.focus();
  398:     }
  399: // END LON-CAPA Internal -->
  400: END
  401: }
  402: 
  403: sub lastresurl {
  404:     if ($env{'environment.lastresurl'}) {
  405: 	return $env{'environment.lastresurl'}
  406:     } else {
  407: 	return '/res';
  408:     }
  409: }
  410: 
  411: sub storeresurl {
  412:     my $resurl=&Apache::lonnet::clutter(shift);
  413:     unless ($resurl=~/^\/res/) { return 0; }
  414:     $resurl=~s/\/$//;
  415:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  416:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  417:     return 1;
  418: }
  419: 
  420: sub studentbrowser_javascript {
  421:    unless (
  422:             (($env{'request.course.id'}) && 
  423:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  424: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  425: 					  '/'.$env{'request.course.sec'})
  426: 	      ))
  427:          || ($env{'request.role'}=~/^(au|dc|su)/)
  428:           ) { return ''; }  
  429:    return (<<'ENDSTDBRW');
  430: <script type="text/javascript" language="Javascript">
  431: // <![CDATA[
  432:     var stdeditbrowser;
  433:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv) {
  434:         var url = '/adm/pickstudent?';
  435:         var filter;
  436: 	if (!ignorefilter) {
  437: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  438: 	}
  439:         if (filter != null) {
  440:            if (filter != '') {
  441:                url += 'filter='+filter+'&';
  442: 	   }
  443:         }
  444:         url += 'form=' + formname + '&unameelement='+uname+
  445:                                     '&udomelement='+udom+
  446:                                     '&clicker='+clicker;
  447: 	if (roleflag) { url+="&roles=1"; }
  448:         if (courseadv == 'condition') {
  449:             if (document.getElementById('courseadv')) {
  450:                 courseadv = document.getElementById('courseadv').value;
  451:             }
  452:         }
  453:         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
  454:         var title = 'Student_Browser';
  455:         var options = 'scrollbars=1,resizable=1,menubar=0';
  456:         options += ',width=700,height=600';
  457:         stdeditbrowser = open(url,title,options,'1');
  458:         stdeditbrowser.focus();
  459:     }
  460: // ]]>
  461: </script>
  462: ENDSTDBRW
  463: }
  464: 
  465: sub resourcebrowser_javascript {
  466:    unless ($env{'request.course.id'}) { return ''; }
  467:    return (<<'ENDRESBRW');
  468: <script type="text/javascript" language="Javascript">
  469: // <![CDATA[
  470:     var reseditbrowser;
  471:     function openresbrowser(formname,reslink) {
  472:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  473:         var title = 'Resource_Browser';
  474:         var options = 'scrollbars=1,resizable=1,menubar=0';
  475:         options += ',width=700,height=500';
  476:         reseditbrowser = open(url,title,options,'1');
  477:         reseditbrowser.focus();
  478:     }
  479: // ]]>
  480: </script>
  481: ENDRESBRW
  482: }
  483: 
  484: sub selectstudent_link {
  485:    my ($form,$unameele,$udomele,$courseadv,$clickerid)=@_;
  486:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  487:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  488:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  489:    if ($env{'request.course.id'}) {  
  490:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  491: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  492: 					'/'.$env{'request.course.sec'})) {
  493: 	   return '';
  494:        }
  495:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  496:        if ($courseadv eq 'only') {
  497:            $callargs .= ",'',1,'$courseadv'";
  498:        } elsif ($courseadv eq 'none') {
  499:            $callargs .= ",'','','$courseadv'";
  500:        } elsif ($courseadv eq 'condition') {
  501:            $callargs .= ",'','','$courseadv'";
  502:        }
  503:        return '<span class="LC_nobreak">'.
  504:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  505:               &mt('Select User').'</a></span>';
  506:    }
  507:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  508:        $callargs .= ",'',1"; 
  509:        return '<span class="LC_nobreak">'.
  510:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  511:               &mt('Select User').'</a></span>';
  512:    }
  513:    return '';
  514: }
  515: 
  516: sub selectresource_link {
  517:    my ($form,$reslink,$arg)=@_;
  518:    
  519:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  520:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  521:    unless ($env{'request.course.id'}) { return $arg; }
  522:    return '<span class="LC_nobreak">'.
  523:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  524:               $arg.'</a></span>';
  525: }
  526: 
  527: 
  528: 
  529: sub authorbrowser_javascript {
  530:     return <<"ENDAUTHORBRW";
  531: <script type="text/javascript" language="JavaScript">
  532: // <![CDATA[
  533: var stdeditbrowser;
  534: 
  535: function openauthorbrowser(formname,udom) {
  536:     var url = '/adm/pickauthor?';
  537:     url += 'form='+formname+'&roledom='+udom;
  538:     var title = 'Author_Browser';
  539:     var options = 'scrollbars=1,resizable=1,menubar=0';
  540:     options += ',width=700,height=600';
  541:     stdeditbrowser = open(url,title,options,'1');
  542:     stdeditbrowser.focus();
  543: }
  544: 
  545: // ]]>
  546: </script>
  547: ENDAUTHORBRW
  548: }
  549: 
  550: sub coursebrowser_javascript {
  551:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
  552:         $credits_element,$instcode) = @_;
  553:     my $wintitle = 'Course_Browser';
  554:     if ($crstype eq 'Community') {
  555:         $wintitle = 'Community_Browser';
  556:     }
  557:     my $id_functions = &javascript_index_functions();
  558:     my $output = '
  559: <script type="text/javascript" language="JavaScript">
  560: // <![CDATA[
  561:     var stdeditbrowser;'."\n";
  562: 
  563:     $output .= <<"ENDSTDBRW";
  564:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  565:         var url = '/adm/pickcourse?';
  566:         var formid = getFormIdByName(formname);
  567:         var domainfilter = getDomainFromSelectbox(formname,udom);
  568:         if (domainfilter != null) {
  569:            if (domainfilter != '') {
  570:                url += 'domainfilter='+domainfilter+'&';
  571: 	   }
  572:         }
  573:         url += 'form=' + formname + '&cnumelement='+uname+
  574: 	                            '&cdomelement='+udom+
  575:                                     '&cnameelement='+desc;
  576:         if (extra_element !=null && extra_element != '') {
  577:             if (formname == 'rolechoice' || formname == 'studentform') {
  578:                 url += '&roleelement='+extra_element;
  579:                 if (domainfilter == null || domainfilter == '') {
  580:                     url += '&domainfilter='+extra_element;
  581:                 }
  582:             }
  583:             else {
  584:                 if (formname == 'portform') {
  585:                     url += '&setroles='+extra_element;
  586:                 } else {
  587:                     if (formname == 'rules') {
  588:                         url += '&fixeddom='+extra_element; 
  589:                     }
  590:                 }
  591:             }     
  592:         }
  593:         if (type != null && type != '') {
  594:             url += '&type='+type;
  595:         }
  596:         if (type_elem != null && type_elem != '') {
  597:             url += '&typeelement='+type_elem;
  598:         }
  599:         if (formname == 'ccrs') {
  600:             var ownername = document.forms[formid].ccuname.value;
  601:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  602:             url += '&cloner='+ownername+':'+ownerdom;
  603:             if (type == 'Course') {
  604:                 url += '&crscode='+document.forms[formid].crscode.value;
  605:             }
  606:         }
  607:         if (formname == 'requestcrs') {
  608:             url += '&crsdom=$domainfilter&crscode=$instcode';
  609:         }
  610:         if (multflag !=null && multflag != '') {
  611:             url += '&multiple='+multflag;
  612:         }
  613:         var title = '$wintitle';
  614:         var options = 'scrollbars=1,resizable=1,menubar=0';
  615:         options += ',width=700,height=600';
  616:         stdeditbrowser = open(url,title,options,'1');
  617:         stdeditbrowser.focus();
  618:     }
  619: $id_functions
  620: ENDSTDBRW
  621:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
  622:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
  623:                                       $credits_element);
  624:     }
  625:     $output .= '
  626: // ]]>
  627: </script>';
  628:     return $output;
  629: }
  630: 
  631: sub javascript_index_functions {
  632:     return <<"ENDJS";
  633: 
  634: function getFormIdByName(formname) {
  635:     for (var i=0;i<document.forms.length;i++) {
  636:         if (document.forms[i].name == formname) {
  637:             return i;
  638:         }
  639:     }
  640:     return -1;
  641: }
  642: 
  643: function getIndexByName(formid,item) {
  644:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  645:         if (document.forms[formid].elements[i].name == item) {
  646:             return i;
  647:         }
  648:     }
  649:     return -1;
  650: }
  651: 
  652: function getDomainFromSelectbox(formname,udom) {
  653:     var userdom;
  654:     var formid = getFormIdByName(formname);
  655:     if (formid > -1) {
  656:         var domid = getIndexByName(formid,udom);
  657:         if (domid > -1) {
  658:             if (document.forms[formid].elements[domid].type == 'select-one') {
  659:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  660:             }
  661:             if (document.forms[formid].elements[domid].type == 'hidden') {
  662:                 userdom=document.forms[formid].elements[domid].value;
  663:             }
  664:         }
  665:     }
  666:     return userdom;
  667: }
  668: 
  669: ENDJS
  670: 
  671: }
  672: 
  673: sub javascript_array_indexof {
  674:     return <<ENDJS;
  675: <script type="text/javascript" language="JavaScript">
  676: // <![CDATA[
  677: 
  678: if (!Array.prototype.indexOf) {
  679:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  680:         "use strict";
  681:         if (this === void 0 || this === null) {
  682:             throw new TypeError();
  683:         }
  684:         var t = Object(this);
  685:         var len = t.length >>> 0;
  686:         if (len === 0) {
  687:             return -1;
  688:         }
  689:         var n = 0;
  690:         if (arguments.length > 0) {
  691:             n = Number(arguments[1]);
  692:             if (n !== n) { // shortcut for verifying if it's NaN
  693:                 n = 0;
  694:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  695:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  696:             }
  697:         }
  698:         if (n >= len) {
  699:             return -1;
  700:         }
  701:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  702:         for (; k < len; k++) {
  703:             if (k in t && t[k] === searchElement) {
  704:                 return k;
  705:             }
  706:         }
  707:         return -1;
  708:     }
  709: }
  710: 
  711: // ]]>
  712: </script>
  713: 
  714: ENDJS
  715: 
  716: }
  717: 
  718: sub userbrowser_javascript {
  719:     my $id_functions = &javascript_index_functions();
  720:     return <<"ENDUSERBRW";
  721: 
  722: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  723:     var url = '/adm/pickuser?';
  724:     var userdom = getDomainFromSelectbox(formname,udom);
  725:     if (userdom != null) {
  726:        if (userdom != '') {
  727:            url += 'srchdom='+userdom+'&';
  728:        }
  729:     }
  730:     url += 'form=' + formname + '&unameelement='+uname+
  731:                                 '&udomelement='+udom+
  732:                                 '&ulastelement='+ulast+
  733:                                 '&ufirstelement='+ufirst+
  734:                                 '&uemailelement='+uemail+
  735:                                 '&hideudomelement='+hideudom+
  736:                                 '&coursedom='+crsdom;
  737:     if ((caller != null) && (caller != undefined)) {
  738:         url += '&caller='+caller;
  739:     }
  740:     var title = 'User_Browser';
  741:     var options = 'scrollbars=1,resizable=1,menubar=0';
  742:     options += ',width=700,height=600';
  743:     var stdeditbrowser = open(url,title,options,'1');
  744:     stdeditbrowser.focus();
  745: }
  746: 
  747: function fix_domain (formname,udom,origdom,uname) {
  748:     var formid = getFormIdByName(formname);
  749:     if (formid > -1) {
  750:         var unameid = getIndexByName(formid,uname);
  751:         var domid = getIndexByName(formid,udom);
  752:         var hidedomid = getIndexByName(formid,origdom);
  753:         if (hidedomid > -1) {
  754:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  755:             var unameval = document.forms[formid].elements[unameid].value;
  756:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  757:                 if (domid > -1) {
  758:                     var slct = document.forms[formid].elements[domid];
  759:                     if (slct.type == 'select-one') {
  760:                         var i;
  761:                         for (i=0;i<slct.length;i++) {
  762:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  763:                         }
  764:                     }
  765:                     if (slct.type == 'hidden') {
  766:                         slct.value = fixeddom;
  767:                     }
  768:                 }
  769:             }
  770:         }
  771:     }
  772:     return;
  773: }
  774: 
  775: $id_functions
  776: ENDUSERBRW
  777: }
  778: 
  779: sub setsec_javascript {
  780:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
  781:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  782:         $communityrolestr);
  783:     if ($role_element ne '') {
  784:         my @allroles = ('st','ta','ep','in','ad');
  785:         foreach my $crstype ('Course','Community') {
  786:             if ($crstype eq 'Community') {
  787:                 foreach my $role (@allroles) {
  788:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  789:                 }
  790:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  791:             } else {
  792:                 foreach my $role (@allroles) {
  793:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  794:                 }
  795:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  796:             }
  797:         }
  798:         $rolestr = '"'.join('","',@allroles).'"';
  799:         $courserolestr = '"'.join('","',@courserolenames).'"';
  800:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  801:     }
  802:     my $setsections = qq|
  803: function setSect(sectionlist) {
  804:     var sectionsArray = new Array();
  805:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  806:         sectionsArray = sectionlist.split(",");
  807:     }
  808:     var numSections = sectionsArray.length;
  809:     document.$formname.$sec_element.length = 0;
  810:     if (numSections == 0) {
  811:         document.$formname.$sec_element.multiple=false;
  812:         document.$formname.$sec_element.size=1;
  813:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  814:     } else {
  815:         if (numSections == 1) {
  816:             document.$formname.$sec_element.multiple=false;
  817:             document.$formname.$sec_element.size=1;
  818:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  819:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  820:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  821:         } else {
  822:             for (var i=0; i<numSections; i++) {
  823:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  824:             }
  825:             document.$formname.$sec_element.multiple=true
  826:             if (numSections < 3) {
  827:                 document.$formname.$sec_element.size=numSections;
  828:             } else {
  829:                 document.$formname.$sec_element.size=3;
  830:             }
  831:             document.$formname.$sec_element.options[0].selected = false
  832:         }
  833:     }
  834: }
  835: 
  836: function setRole(crstype) {
  837: |;
  838:     if ($role_element eq '') {
  839:         $setsections .= '    return;
  840: }
  841: ';
  842:     } else {
  843:         $setsections .= qq|
  844:     var elementLength = document.$formname.$role_element.length;
  845:     var allroles = Array($rolestr);
  846:     var courserolenames = Array($courserolestr);
  847:     var communityrolenames = Array($communityrolestr);
  848:     if (elementLength != undefined) {
  849:         if (document.$formname.$role_element.options[5].value == 'cc') {
  850:             if (crstype == 'Course') {
  851:                 return;
  852:             } else {
  853:                 allroles[5] = 'co';
  854:                 for (var i=0; i<6; i++) {
  855:                     document.$formname.$role_element.options[i].value = allroles[i];
  856:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  857:                 }
  858:             }
  859:         } else {
  860:             if (crstype == 'Community') {
  861:                 return;
  862:             } else {
  863:                 allroles[5] = 'cc';
  864:                 for (var i=0; i<6; i++) {
  865:                     document.$formname.$role_element.options[i].value = allroles[i];
  866:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  867:                 }
  868:             }
  869:         }
  870:     }
  871:     return;
  872: }
  873: |;
  874:     }
  875:     if ($credits_element) {
  876:         $setsections .= qq|
  877: function setCredits(defaultcredits) {
  878:     document.$formname.$credits_element.value = defaultcredits;
  879:     return;
  880: }
  881: |;
  882:     }
  883:     return $setsections;
  884: }
  885: 
  886: sub selectcourse_link {
  887:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  888:        $typeelement) = @_;
  889:    my $type = $selecttype;
  890:    my $linktext = &mt('Select Course');
  891:    if ($selecttype eq 'Community') {
  892:        $linktext = &mt('Select Community');
  893:    } elsif ($selecttype eq 'Course/Community') {
  894:        $linktext = &mt('Select Course/Community');
  895:        $type = '';
  896:    } elsif ($selecttype eq 'Select') {
  897:        $linktext = &mt('Select');
  898:        $type = '';
  899:    }
  900:    return '<span class="LC_nobreak">'
  901:          ."<a href='"
  902:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  903:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  904:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  905:          ."'>".$linktext.'</a>'
  906:          .'</span>';
  907: }
  908: 
  909: sub selectauthor_link {
  910:    my ($form,$udom)=@_;
  911:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  912:           &mt('Select Author').'</a>';
  913: }
  914: 
  915: sub selectuser_link {
  916:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  917:         $coursedom,$linktext,$caller) = @_;
  918:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  919:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  920:            ');">'.$linktext.'</a>';
  921: }
  922: 
  923: sub check_uncheck_jscript {
  924:     my $jscript = <<"ENDSCRT";
  925: function checkAll(field) {
  926:     if (field.length > 0) {
  927:         for (i = 0; i < field.length; i++) {
  928:             if (!field[i].disabled) {
  929:                 field[i].checked = true;
  930:             }
  931:         }
  932:     } else {
  933:         if (!field.disabled) {
  934:             field.checked = true;
  935:         }
  936:     }
  937: }
  938:  
  939: function uncheckAll(field) {
  940:     if (field.length > 0) {
  941:         for (i = 0; i < field.length; i++) {
  942:             field[i].checked = false ;
  943:         }
  944:     } else {
  945:         field.checked = false ;
  946:     }
  947: }
  948: ENDSCRT
  949:     return $jscript;
  950: }
  951: 
  952: sub select_timezone {
  953:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  954:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  955:    if ($includeempty) {
  956:        $output .= '<option value=""';
  957:        if (($selected eq '') || ($selected eq 'local')) {
  958:            $output .= ' selected="selected" ';
  959:        }
  960:        $output .= '> </option>';
  961:    }
  962:    my @timezones = DateTime::TimeZone->all_names;
  963:    foreach my $tzone (@timezones) {
  964:        $output.= '<option value="'.$tzone.'"';
  965:        if ($tzone eq $selected) {
  966:            $output.=' selected="selected"';
  967:        }
  968:        $output.=">$tzone</option>\n";
  969:    }
  970:    $output.="</select>";
  971:    return $output;
  972: }
  973: 
  974: sub select_datelocale {
  975:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  976:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  977:     if ($includeempty) {
  978:         $output .= '<option value=""';
  979:         if ($selected eq '') {
  980:             $output .= ' selected="selected" ';
  981:         }
  982:         $output .= '> </option>';
  983:     }
  984:     my @languages = &Apache::lonlocal::preferred_languages();
  985:     my (@possibles,%locale_names);
  986:     my @locales = DateTime::Locale->ids();
  987:     foreach my $id (@locales) {
  988:         if ($id ne '') {
  989:             my ($en_terr,$native_terr);
  990:             my $loc = DateTime::Locale->load($id);
  991:             if (ref($loc)) {
  992:                 $en_terr = $loc->name();
  993:                 $native_terr = $loc->native_name();
  994:                 if (grep(/^en$/,@languages) || !@languages) {
  995:                     if ($en_terr ne '') {
  996:                         $locale_names{$id} = '('.$en_terr.')';
  997:                     } elsif ($native_terr ne '') {
  998:                         $locale_names{$id} = $native_terr;
  999:                     }
 1000:                 } else {
 1001:                     if ($native_terr ne '') {
 1002:                         $locale_names{$id} = $native_terr.' ';
 1003:                     } elsif ($en_terr ne '') {
 1004:                         $locale_names{$id} = '('.$en_terr.')';
 1005:                     }
 1006:                 }
 1007:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
 1008:                 push(@possibles,$id);
 1009:             }
 1010:         }
 1011:     }
 1012:     foreach my $item (sort(@possibles)) {
 1013:         $output.= '<option value="'.$item.'"';
 1014:         if ($item eq $selected) {
 1015:             $output.=' selected="selected"';
 1016:         }
 1017:         $output.=">$item";
 1018:         if ($locale_names{$item} ne '') {
 1019:             $output.='  '.$locale_names{$item};
 1020:         }
 1021:         $output.="</option>\n";
 1022:     }
 1023:     $output.="</select>";
 1024:     return $output;
 1025: }
 1026: 
 1027: sub select_language {
 1028:     my ($name,$selected,$includeempty,$noedit) = @_;
 1029:     my %langchoices;
 1030:     if ($includeempty) {
 1031:         %langchoices = ('' => 'No language preference');
 1032:     }
 1033:     foreach my $id (&languageids()) {
 1034:         my $code = &supportedlanguagecode($id);
 1035:         if ($code) {
 1036:             $langchoices{$code} = &plainlanguagedescription($id);
 1037:         }
 1038:     }
 1039:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
 1040:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
 1041: }
 1042: 
 1043: =pod
 1044: 
 1045: =item * &linked_select_forms(...)
 1046: 
 1047: linked_select_forms returns a string containing a <script></script> block
 1048: and html for two <select> menus.  The select menus will be linked in that
 1049: changing the value of the first menu will result in new values being placed
 1050: in the second menu.  The values in the select menu will appear in alphabetical
 1051: order unless a defined order is provided.
 1052: 
 1053: linked_select_forms takes the following ordered inputs:
 1054: 
 1055: =over 4
 1056: 
 1057: =item * $formname, the name of the <form> tag
 1058: 
 1059: =item * $middletext, the text which appears between the <select> tags
 1060: 
 1061: =item * $firstdefault, the default value for the first menu
 1062: 
 1063: =item * $firstselectname, the name of the first <select> tag
 1064: 
 1065: =item * $secondselectname, the name of the second <select> tag
 1066: 
 1067: =item * $hashref, a reference to a hash containing the data for the menus.
 1068: 
 1069: =item * $menuorder, the order of values in the first menu
 1070: 
 1071: =item * $onchangefirst, additional javascript call to execute for an onchange
 1072:         event for the first <select> tag
 1073: 
 1074: =item * $onchangesecond, additional javascript call to execute for an onchange
 1075:         event for the second <select> tag
 1076: 
 1077: =back 
 1078: 
 1079: Below is an example of such a hash.  Only the 'text', 'default', and 
 1080: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1081: values for the first select menu.  The text that coincides with the 
 1082: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1083: and text for the second menu are given in the hash pointed to by 
 1084: $menu{$choice1}->{'select2'}.  
 1085: 
 1086:  my %menu = ( A1 => { text =>"Choice A1" ,
 1087:                        default => "B3",
 1088:                        select2 => { 
 1089:                            B1 => "Choice B1",
 1090:                            B2 => "Choice B2",
 1091:                            B3 => "Choice B3",
 1092:                            B4 => "Choice B4"
 1093:                            },
 1094:                        order => ['B4','B3','B1','B2'],
 1095:                    },
 1096:                A2 => { text =>"Choice A2" ,
 1097:                        default => "C2",
 1098:                        select2 => { 
 1099:                            C1 => "Choice C1",
 1100:                            C2 => "Choice C2",
 1101:                            C3 => "Choice C3"
 1102:                            },
 1103:                        order => ['C2','C1','C3'],
 1104:                    },
 1105:                A3 => { text =>"Choice A3" ,
 1106:                        default => "D6",
 1107:                        select2 => { 
 1108:                            D1 => "Choice D1",
 1109:                            D2 => "Choice D2",
 1110:                            D3 => "Choice D3",
 1111:                            D4 => "Choice D4",
 1112:                            D5 => "Choice D5",
 1113:                            D6 => "Choice D6",
 1114:                            D7 => "Choice D7"
 1115:                            },
 1116:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1117:                    }
 1118:                );
 1119: 
 1120: =cut
 1121: 
 1122: sub linked_select_forms {
 1123:     my ($formname,
 1124:         $middletext,
 1125:         $firstdefault,
 1126:         $firstselectname,
 1127:         $secondselectname, 
 1128:         $hashref,
 1129:         $menuorder,
 1130:         $onchangefirst,
 1131:         $onchangesecond
 1132:         ) = @_;
 1133:     my $second = "document.$formname.$secondselectname";
 1134:     my $first = "document.$formname.$firstselectname";
 1135:     # output the javascript to do the changing
 1136:     my $result = '';
 1137:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1138:     $result.="// <![CDATA[\n";
 1139:     $result.="var select2data = new Object();\n";
 1140:     $" = '","';
 1141:     my $debug = '';
 1142:     foreach my $s1 (sort(keys(%$hashref))) {
 1143:         $result.="select2data.d_$s1 = new Object();\n";        
 1144:         $result.="select2data.d_$s1.def = new String('".
 1145:             $hashref->{$s1}->{'default'}."');\n";
 1146:         $result.="select2data.d_$s1.values = new Array(";
 1147:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1148:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1149:             @s2values = @{$hashref->{$s1}->{'order'}};
 1150:         }
 1151:         $result.="\"@s2values\");\n";
 1152:         $result.="select2data.d_$s1.texts = new Array(";        
 1153:         my @s2texts;
 1154:         foreach my $value (@s2values) {
 1155:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
 1156:         }
 1157:         $result.="\"@s2texts\");\n";
 1158:     }
 1159:     $"=' ';
 1160:     $result.= <<"END";
 1161: 
 1162: function select1_changed() {
 1163:     // Determine new choice
 1164:     var newvalue = "d_" + $first.value;
 1165:     // update select2
 1166:     var values     = select2data[newvalue].values;
 1167:     var texts      = select2data[newvalue].texts;
 1168:     var select2def = select2data[newvalue].def;
 1169:     var i;
 1170:     // out with the old
 1171:     for (i = 0; i < $second.options.length; i++) {
 1172:         $second.options[i] = null;
 1173:     }
 1174:     // in with the nuclear
 1175:     for (i=0;i<values.length; i++) {
 1176:         $second.options[i] = new Option(values[i]);
 1177:         $second.options[i].value = values[i];
 1178:         $second.options[i].text = texts[i];
 1179:         if (values[i] == select2def) {
 1180:             $second.options[i].selected = true;
 1181:         }
 1182:     }
 1183: }
 1184: // ]]>
 1185: </script>
 1186: END
 1187:     # output the initial values for the selection lists
 1188:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
 1189:     my @order = sort(keys(%{$hashref}));
 1190:     if (ref($menuorder) eq 'ARRAY') {
 1191:         @order = @{$menuorder};
 1192:     }
 1193:     foreach my $value (@order) {
 1194:         $result.="    <option value=\"$value\" ";
 1195:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1196:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1197:     }
 1198:     $result .= "</select>\n";
 1199:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1200:     $result .= $middletext;
 1201:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
 1202:     if ($onchangesecond) {
 1203:         $result .= ' onchange="'.$onchangesecond.'"';
 1204:     }
 1205:     $result .= ">\n";
 1206:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1207:     
 1208:     my @secondorder = sort(keys(%select2));
 1209:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1210:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1211:     }
 1212:     foreach my $value (@secondorder) {
 1213:         $result.="    <option value=\"$value\" ";        
 1214:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1215:         $result.=">".&mt($select2{$value})."</option>\n";
 1216:     }
 1217:     $result .= "</select>\n";
 1218:     #    return $debug;
 1219:     return $result;
 1220: }   #  end of sub linked_select_forms {
 1221: 
 1222: =pod
 1223: 
 1224: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1225: 
 1226: Returns a string corresponding to an HTML link to the given help
 1227: $topic, where $topic corresponds to the name of a .tex file in
 1228: /home/httpd/html/adm/help/tex, with underscores replaced by
 1229: spaces. 
 1230: 
 1231: $text will optionally be linked to the same topic, allowing you to
 1232: link text in addition to the graphic. If you do not want to link
 1233: text, but wish to specify one of the later parameters, pass an
 1234: empty string. 
 1235: 
 1236: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1237: the link will not open a new window. If false, the link will open
 1238: a new window using Javascript. (Default is false.) 
 1239: 
 1240: $width and $height are optional numerical parameters that will
 1241: override the width and height of the popped up window, which may
 1242: be useful for certain help topics with big pictures included.
 1243: 
 1244: $imgid is the id of the img tag used for the help icon. This may be
 1245: used in a javascript call to switch the image src.  See 
 1246: lonhtmlcommon::htmlareaselectactive() for an example.
 1247: 
 1248: =cut
 1249: 
 1250: sub help_open_topic {
 1251:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1252:     $text = "" if (not defined $text);
 1253:     $stayOnPage = 0 if (not defined $stayOnPage);
 1254:     $width = 500 if (not defined $width);
 1255:     $height = 400 if (not defined $height);
 1256:     my $filename = $topic;
 1257:     $filename =~ s/ /_/g;
 1258: 
 1259:     my $template = "";
 1260:     my $link;
 1261:     
 1262:     $topic=~s/\W/\_/g;
 1263: 
 1264:     if (!$stayOnPage) {
 1265:         if ($env{'browser.mobile'}) {
 1266: 	    $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1267:         } else {
 1268:             $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1269:         }
 1270:     } elsif ($stayOnPage eq 'popup') {
 1271:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1272:     } else {
 1273: 	$link = "/adm/help/${filename}.hlp";
 1274:     }
 1275: 
 1276:     # Add the text
 1277:     if ($text ne "") {	
 1278: 	$template.='<span class="LC_help_open_topic">'
 1279:                   .'<a target="_top" href="'.$link.'">'
 1280:                   .$text.'</a>';
 1281:     }
 1282: 
 1283:     # (Always) Add the graphic
 1284:     my $title = &mt('Online Help');
 1285:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1286:     if ($imgid ne '') {
 1287:         $imgid = ' id="'.$imgid.'"';
 1288:     }
 1289:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
 1290:               .'<img src="'.$helpicon.'" border="0"'
 1291:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1292:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1293:               .' /></a>';
 1294:     if ($text ne "") {	
 1295:         $template.='</span>';
 1296:     }
 1297:     return $template;
 1298: 
 1299: }
 1300: 
 1301: # This is a quicky function for Latex cheatsheet editing, since it 
 1302: # appears in at least four places
 1303: sub helpLatexCheatsheet {
 1304:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1305:     my $out;
 1306:     my $addOther = '';
 1307:     if ($topic) {
 1308: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1309:     }
 1310:     $out = '<span>' # Start cheatsheet
 1311: 	  .$addOther
 1312:           .'<span>'
 1313: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1314: 	  .'</span> <span>'
 1315: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1316: 	  .'</span>';
 1317:     unless ($not_author) {
 1318:         $out .= ' <span>'
 1319: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1320: 	       .'</span> <span>'
 1321:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
 1322:                .'</span>';
 1323:     }
 1324:     $out .= '</span>'; # End cheatsheet
 1325:     return $out;
 1326: }
 1327: 
 1328: sub general_help {
 1329:     my $helptopic='Student_Intro';
 1330:     if ($env{'request.role'}=~/^(ca|au)/) {
 1331: 	$helptopic='Authoring_Intro';
 1332:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1333: 	$helptopic='Course_Coordination_Intro';
 1334:     } elsif ($env{'request.role'}=~/^dc/) {
 1335:         $helptopic='Domain_Coordination_Intro';
 1336:     }
 1337:     return $helptopic;
 1338: }
 1339: 
 1340: sub update_help_link {
 1341:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1342:     my $origurl = $ENV{'REQUEST_URI'};
 1343:     $origurl=~s|^/~|/priv/|;
 1344:     my $timestamp = time;
 1345:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1346:         $$datum = &escape($$datum);
 1347:     }
 1348: 
 1349:     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";
 1350:     my $output .= <<"ENDOUTPUT";
 1351: <script type="text/javascript">
 1352: // <![CDATA[
 1353: banner_link = '$banner_link';
 1354: // ]]>
 1355: </script>
 1356: ENDOUTPUT
 1357:     return $output;
 1358: }
 1359: 
 1360: # now just updates the help link and generates a blue icon
 1361: sub help_open_menu {
 1362:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1363: 	= @_;    
 1364:     $stayOnPage = 1;
 1365:     my $output;
 1366:     if ($component_help) {
 1367: 	if (!$text) {
 1368: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1369: 				       $width,$height);
 1370: 	} else {
 1371: 	    my $help_text;
 1372: 	    $help_text=&unescape($topic);
 1373: 	    $output='<table><tr><td>'.
 1374: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1375: 				 $width,$height).'</td></tr></table>';
 1376: 	}
 1377:     }
 1378:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1379:     return $output.$banner_link;
 1380: }
 1381: 
 1382: sub top_nav_help {
 1383:     my ($text,$linkattr) = @_;
 1384:     $text = &mt($text);
 1385:     my $stay_on_page;
 1386:     unless ($env{'environment.remote'} eq 'on') {
 1387:         $stay_on_page = 1;
 1388:     }
 1389:     my ($link,$banner_link);
 1390:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
 1391:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1392: 	                         : "javascript:helpMenu('open')";
 1393:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1394:     }
 1395:     my $title = &mt('Get help');
 1396:     if ($link) {
 1397:         return <<"END";
 1398: $banner_link
 1399: <a href="$link" title="$title" $linkattr>$text</a>
 1400: END
 1401:     } else {
 1402:         return '&nbsp;'.$text.'&nbsp;';
 1403:     }
 1404: }
 1405: 
 1406: sub help_menu_js {
 1407:     my ($httphost) = @_;
 1408:     my $stayOnPage = 1;
 1409:     my $width = 620;
 1410:     my $height = 600;
 1411:     my $helptopic=&general_help();
 1412:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
 1413:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1414:     my $start_page =
 1415:         &Apache::loncommon::start_page('Help Menu', undef,
 1416: 				       {'frameset'    => 1,
 1417: 					'js_ready'    => 1,
 1418:                                         'use_absolute' => $httphost,
 1419: 					'add_entries' => {
 1420: 					    'border' => '0',
 1421: 					    'rows'   => "110,*",},});
 1422:     my $end_page =
 1423:         &Apache::loncommon::end_page({'frameset' => 1,
 1424: 				      'js_ready' => 1,});
 1425: 
 1426:     my $template .= <<"ENDTEMPLATE";
 1427: <script type="text/javascript">
 1428: // <![CDATA[
 1429: // <!-- BEGIN LON-CAPA Internal
 1430: var banner_link = '';
 1431: function helpMenu(target) {
 1432:     var caller = this;
 1433:     if (target == 'open') {
 1434:         var newWindow = null;
 1435:         try {
 1436:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1437:         }
 1438:         catch(error) {
 1439:             writeHelp(caller);
 1440:             return;
 1441:         }
 1442:         if (newWindow) {
 1443:             caller = newWindow;
 1444:         }
 1445:     }
 1446:     writeHelp(caller);
 1447:     return;
 1448: }
 1449: function writeHelp(caller) {
 1450:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
 1451:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
 1452:     caller.document.close();
 1453:     caller.focus();
 1454: }
 1455: // END LON-CAPA Internal -->
 1456: // ]]>
 1457: </script>
 1458: ENDTEMPLATE
 1459:     return $template;
 1460: }
 1461: 
 1462: sub help_open_bug {
 1463:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1464:     unless ($env{'user.adv'}) { return ''; }
 1465:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1466:     $text = "" if (not defined $text);
 1467: 	$stayOnPage=1;
 1468:     $width = 600 if (not defined $width);
 1469:     $height = 600 if (not defined $height);
 1470: 
 1471:     $topic=~s/\W+/\+/g;
 1472:     my $link='';
 1473:     my $template='';
 1474:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1475: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1476:     if (!$stayOnPage)
 1477:     {
 1478: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1479:     }
 1480:     else
 1481:     {
 1482: 	$link = $url;
 1483:     }
 1484:     # Add the text
 1485:     if ($text ne "")
 1486:     {
 1487: 	$template .= 
 1488:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1489:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1490:     }
 1491: 
 1492:     # Add the graphic
 1493:     my $title = &mt('Report a Bug');
 1494:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1495:     $template .= <<"ENDTEMPLATE";
 1496:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1497: ENDTEMPLATE
 1498:     if ($text ne '') { $template.='</td></tr></table>' };
 1499:     return $template;
 1500: 
 1501: }
 1502: 
 1503: sub help_open_faq {
 1504:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1505:     unless ($env{'user.adv'}) { return ''; }
 1506:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1507:     $text = "" if (not defined $text);
 1508: 	$stayOnPage=1;
 1509:     $width = 350 if (not defined $width);
 1510:     $height = 400 if (not defined $height);
 1511: 
 1512:     $topic=~s/\W+/\+/g;
 1513:     my $link='';
 1514:     my $template='';
 1515:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1516:     if (!$stayOnPage)
 1517:     {
 1518: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1519:     }
 1520:     else
 1521:     {
 1522: 	$link = $url;
 1523:     }
 1524: 
 1525:     # Add the text
 1526:     if ($text ne "")
 1527:     {
 1528: 	$template .= 
 1529:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1530:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1531:     }
 1532: 
 1533:     # Add the graphic
 1534:     my $title = &mt('View the FAQ');
 1535:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1536:     $template .= <<"ENDTEMPLATE";
 1537:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1538: ENDTEMPLATE
 1539:     if ($text ne '') { $template.='</td></tr></table>' };
 1540:     return $template;
 1541: 
 1542: }
 1543: 
 1544: ###############################################################
 1545: ###############################################################
 1546: 
 1547: =pod
 1548: 
 1549: =item * &change_content_javascript():
 1550: 
 1551: This and the next function allow you to create small sections of an
 1552: otherwise static HTML page that you can update on the fly with
 1553: Javascript, even in Netscape 4.
 1554: 
 1555: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1556: must be written to the HTML page once. It will prove the Javascript
 1557: function "change(name, content)". Calling the change function with the
 1558: name of the section 
 1559: you want to update, matching the name passed to C<changable_area>, and
 1560: the new content you want to put in there, will put the content into
 1561: that area.
 1562: 
 1563: B<Note>: Netscape 4 only reserves enough space for the changable area
 1564: to contain room for the original contents. You need to "make space"
 1565: for whatever changes you wish to make, and be B<sure> to check your
 1566: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1567: it's adequate for updating a one-line status display, but little more.
 1568: This script will set the space to 100% width, so you only need to
 1569: worry about height in Netscape 4.
 1570: 
 1571: Modern browsers are much less limiting, and if you can commit to the
 1572: user not using Netscape 4, this feature may be used freely with
 1573: pretty much any HTML.
 1574: 
 1575: =cut
 1576: 
 1577: sub change_content_javascript {
 1578:     # If we're on Netscape 4, we need to use Layer-based code
 1579:     if ($env{'browser.type'} eq 'netscape' &&
 1580: 	$env{'browser.version'} =~ /^4\./) {
 1581: 	return (<<NETSCAPE4);
 1582: 	function change(name, content) {
 1583: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1584: 	    doc.open();
 1585: 	    doc.write(content);
 1586: 	    doc.close();
 1587: 	}
 1588: NETSCAPE4
 1589:     } else {
 1590: 	# Otherwise, we need to use semi-standards-compliant code
 1591: 	# (technically, "innerHTML" isn't standard but the equivalent
 1592: 	# is really scary, and every useful browser supports it
 1593: 	return (<<DOMBASED);
 1594: 	function change(name, content) {
 1595: 	    element = document.getElementById(name);
 1596: 	    element.innerHTML = content;
 1597: 	}
 1598: DOMBASED
 1599:     }
 1600: }
 1601: 
 1602: =pod
 1603: 
 1604: =item * &changable_area($name,$origContent):
 1605: 
 1606: This provides a "changable area" that can be modified on the fly via
 1607: the Javascript code provided in C<change_content_javascript>. $name is
 1608: the name you will use to reference the area later; do not repeat the
 1609: same name on a given HTML page more then once. $origContent is what
 1610: the area will originally contain, which can be left blank.
 1611: 
 1612: =cut
 1613: 
 1614: sub changable_area {
 1615:     my ($name, $origContent) = @_;
 1616: 
 1617:     if ($env{'browser.type'} eq 'netscape' &&
 1618: 	$env{'browser.version'} =~ /^4\./) {
 1619: 	# If this is netscape 4, we need to use the Layer tag
 1620: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1621:     } else {
 1622: 	return "<span id='$name'>$origContent</span>";
 1623:     }
 1624: }
 1625: 
 1626: =pod
 1627: 
 1628: =item * &viewport_geometry_js 
 1629: 
 1630: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1631: 
 1632: =cut
 1633: 
 1634: 
 1635: sub viewport_geometry_js { 
 1636:     return <<"GEOMETRY";
 1637: var Geometry = {};
 1638: function init_geometry() {
 1639:     if (Geometry.init) { return };
 1640:     Geometry.init=1;
 1641:     if (window.innerHeight) {
 1642:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1643:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1644:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1645:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1646:     }
 1647:     else if (document.documentElement && document.documentElement.clientHeight) {
 1648:         Geometry.getViewportHeight =
 1649:             function() { return document.documentElement.clientHeight; };
 1650:         Geometry.getViewportWidth =
 1651:             function() { return document.documentElement.clientWidth; };
 1652: 
 1653:         Geometry.getHorizontalScroll =
 1654:             function() { return document.documentElement.scrollLeft; };
 1655:         Geometry.getVerticalScroll =
 1656:             function() { return document.documentElement.scrollTop; };
 1657:     }
 1658:     else if (document.body.clientHeight) {
 1659:         Geometry.getViewportHeight =
 1660:             function() { return document.body.clientHeight; };
 1661:         Geometry.getViewportWidth =
 1662:             function() { return document.body.clientWidth; };
 1663:         Geometry.getHorizontalScroll =
 1664:             function() { return document.body.scrollLeft; };
 1665:         Geometry.getVerticalScroll =
 1666:             function() { return document.body.scrollTop; };
 1667:     }
 1668: }
 1669: 
 1670: GEOMETRY
 1671: }
 1672: 
 1673: =pod
 1674: 
 1675: =item * &viewport_size_js()
 1676: 
 1677: 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. 
 1678: 
 1679: =cut
 1680: 
 1681: sub viewport_size_js {
 1682:     my $geometry = &viewport_geometry_js();
 1683:     return <<"DIMS";
 1684: 
 1685: $geometry
 1686: 
 1687: function getViewportDims(width,height) {
 1688:     init_geometry();
 1689:     width.value = Geometry.getViewportWidth();
 1690:     height.value = Geometry.getViewportHeight();
 1691:     return;
 1692: }
 1693: 
 1694: DIMS
 1695: }
 1696: 
 1697: =pod
 1698: 
 1699: =item * &resize_textarea_js()
 1700: 
 1701: emits the needed javascript to resize a textarea to be as big as possible
 1702: 
 1703: creates a function resize_textrea that takes two IDs first should be
 1704: the id of the element to resize, second should be the id of a div that
 1705: surrounds everything that comes after the textarea, this routine needs
 1706: to be attached to the <body> for the onload and onresize events.
 1707: 
 1708: =back
 1709: 
 1710: =cut
 1711: 
 1712: sub resize_textarea_js {
 1713:     my $geometry = &viewport_geometry_js();
 1714:     return <<"RESIZE";
 1715:     <script type="text/javascript">
 1716: // <![CDATA[
 1717: $geometry
 1718: 
 1719: function getX(element) {
 1720:     var x = 0;
 1721:     while (element) {
 1722: 	x += element.offsetLeft;
 1723: 	element = element.offsetParent;
 1724:     }
 1725:     return x;
 1726: }
 1727: function getY(element) {
 1728:     var y = 0;
 1729:     while (element) {
 1730: 	y += element.offsetTop;
 1731: 	element = element.offsetParent;
 1732:     }
 1733:     return y;
 1734: }
 1735: 
 1736: 
 1737: function resize_textarea(textarea_id,bottom_id) {
 1738:     init_geometry();
 1739:     var textarea        = document.getElementById(textarea_id);
 1740:     //alert(textarea);
 1741: 
 1742:     var textarea_top    = getY(textarea);
 1743:     var textarea_height = textarea.offsetHeight;
 1744:     var bottom          = document.getElementById(bottom_id);
 1745:     var bottom_top      = getY(bottom);
 1746:     var bottom_height   = bottom.offsetHeight;
 1747:     var window_height   = Geometry.getViewportHeight();
 1748:     var fudge           = 23;
 1749:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1750:     if (new_height < 300) {
 1751: 	new_height = 300;
 1752:     }
 1753:     textarea.style.height=new_height+'px';
 1754: }
 1755: // ]]>
 1756: </script>
 1757: RESIZE
 1758: 
 1759: }
 1760: 
 1761: sub colorfuleditor_js {
 1762:     return <<"COLORFULEDIT"
 1763: <script type="text/javascript">
 1764: // <![CDATA[>
 1765:     function fold_box(curDepth, lastresource){
 1766: 
 1767:     // we need a list because there can be several blocks you need to fold in one tag
 1768:         var block = document.getElementsByName('foldblock_'+curDepth);
 1769:     // but there is only one folding button per tag
 1770:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
 1771: 
 1772:         if(block.item(0).style.display == 'none'){
 1773: 
 1774:             foldbutton.value = '@{[&mt("Hide")]}';
 1775:             for (i = 0; i < block.length; i++){
 1776:                 block.item(i).style.display = '';
 1777:             }
 1778:         }else{
 1779: 
 1780:             foldbutton.value = '@{[&mt("Show")]}';
 1781:             for (i = 0; i < block.length; i++){
 1782:                 // block.item(i).style.visibility = 'collapse';
 1783:                 block.item(i).style.display = 'none';
 1784:             }
 1785:         };
 1786:         saveState(lastresource);
 1787:     }
 1788: 
 1789:     function saveState (lastresource) {
 1790: 
 1791:         var tag_list = getTagList();
 1792:         if(tag_list != null){
 1793:             var timestamp = new Date().getTime();
 1794:             var key = lastresource;
 1795: 
 1796:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
 1797:             // starting with timestamp
 1798:             var value = timestamp+';';
 1799: 
 1800:             // building the list of key-value pairs
 1801:             for(var i = 0; i < tag_list.length; i++){
 1802:                 value += tag_list[i]+',';
 1803:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
 1804:             }
 1805: 
 1806:             // only iterate whole storage if nothing to override
 1807:             if(localStorage.getItem(key) == null){
 1808: 
 1809:                 // prevent storage from growing large
 1810:                 if(localStorage.length > 50){
 1811:                     var regex_getTimestamp = /^(?:\d)+;/;
 1812:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
 1813:                     var oldest_key;
 1814: 
 1815:                     for(var i = 1; i < localStorage.length; i++){
 1816:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
 1817:                             oldest_key = localStorage.key(i);
 1818:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
 1819:                         }
 1820:                     }
 1821:                     localStorage.removeItem(oldest_key);
 1822:                 }
 1823:             }
 1824:             localStorage.setItem(key,value);
 1825:         }
 1826:     }
 1827: 
 1828:     // restore folding status of blocks (on page load)
 1829:     function restoreState (lastresource) {
 1830:         if(localStorage.getItem(lastresource) != null){
 1831:             var key = lastresource;
 1832:             var value = localStorage.getItem(key);
 1833:             var regex_delTimestamp = /^\d+;/;
 1834: 
 1835:             value.replace(regex_delTimestamp, '');
 1836: 
 1837:             var valueArr = value.split(';');
 1838:             var pairs;
 1839:             var elements;
 1840:             for (var i = 0; i < valueArr.length; i++){
 1841:                 pairs = valueArr[i].split(',');
 1842:                 elements = document.getElementsByName(pairs[0]);
 1843: 
 1844:                 for (var j = 0; j < elements.length; j++){
 1845:                     elements[j].style.display = pairs[1];
 1846:                     if (pairs[1] == "none"){
 1847:                         var regex_id = /([_\\d]+)\$/;
 1848:                         regex_id.exec(pairs[0]);
 1849:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
 1850:                     }
 1851:                 }
 1852:             }
 1853:         }
 1854:     }
 1855: 
 1856:     function getTagList () {
 1857: 
 1858:         var stringToSearch = document.lonhomework.innerHTML;
 1859: 
 1860:         var ret = new Array();
 1861:         var regex_findBlock = /(foldblock_.*?)"/g;
 1862:         var tag_list = stringToSearch.match(regex_findBlock);
 1863: 
 1864:         if(tag_list != null){
 1865:             for(var i = 0; i < tag_list.length; i++){
 1866:                 ret.push(tag_list[i].replace(/"/, ''));
 1867:             }
 1868:         }
 1869:         return ret;
 1870:     }
 1871: 
 1872:     function saveScrollPosition (resource) {
 1873:         var tag_list = getTagList();
 1874: 
 1875:         // we dont always want to jump to the first block
 1876:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
 1877:         if(\$(window).scrollTop() > 170){
 1878:             if(tag_list != null){
 1879:                 var result;
 1880:                 for(var i = 0; i < tag_list.length; i++){
 1881:                     if(isElementInViewport(tag_list[i])){
 1882:                         result += tag_list[i]+';';
 1883:                     }
 1884:                 }
 1885:                 sessionStorage.setItem('anchor_'+resource, result);
 1886:             }
 1887:         } else {
 1888:             // we dont need to save zero, just delete the item to leave everything tidy
 1889:             sessionStorage.removeItem('anchor_'+resource);
 1890:         }
 1891:     }
 1892: 
 1893:     function restoreScrollPosition(resource){
 1894: 
 1895:         var elem = sessionStorage.getItem('anchor_'+resource);
 1896:         if(elem != null){
 1897:             var tag_list = elem.split(';');
 1898:             var elem_list;
 1899: 
 1900:             for(var i = 0; i < tag_list.length; i++){
 1901:                 elem_list = document.getElementsByName(tag_list[i]);
 1902: 
 1903:                 if(elem_list.length > 0){
 1904:                     elem = elem_list[0];
 1905:                     break;
 1906:                 }
 1907:             }
 1908:             elem.scrollIntoView();
 1909:         }
 1910:     }
 1911: 
 1912:     function isElementInViewport(el) {
 1913: 
 1914:         // change to last element instead of first
 1915:         var elem = document.getElementsByName(el);
 1916:         var rect = elem[0].getBoundingClientRect();
 1917: 
 1918:         return (
 1919:             rect.top >= 0 &&
 1920:             rect.left >= 0 &&
 1921:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
 1922:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
 1923:         );
 1924:     }
 1925: 
 1926:     function autosize(depth){
 1927:         var cmInst = window['cm'+depth];
 1928:         var fitsizeButton = document.getElementById('fitsize'+depth);
 1929: 
 1930:         // is fixed size, switching to dynamic
 1931:         if (sessionStorage.getItem("autosized_"+depth) == null) {
 1932:             cmInst.setSize("","auto");
 1933:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
 1934:             sessionStorage.setItem("autosized_"+depth, "yes");
 1935: 
 1936:         // is dynamic size, switching to fixed
 1937:         } else {
 1938:             cmInst.setSize("","300px");
 1939:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
 1940:             sessionStorage.removeItem("autosized_"+depth);
 1941:         }
 1942:     }
 1943: 
 1944: 
 1945: 
 1946: // ]]>
 1947: </script>
 1948: COLORFULEDIT
 1949: }
 1950: 
 1951: sub xmleditor_js {
 1952:     return <<XMLEDIT
 1953: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
 1954: <script type="text/javascript">
 1955: // <![CDATA[>
 1956: 
 1957:     function saveScrollPosition (resource) {
 1958: 
 1959:         var scrollPos = \$(window).scrollTop();
 1960:         sessionStorage.setItem(resource,scrollPos);
 1961:     }
 1962: 
 1963:     function restoreScrollPosition(resource){
 1964: 
 1965:         var scrollPos = sessionStorage.getItem(resource);
 1966:         \$(window).scrollTop(scrollPos);
 1967:     }
 1968: 
 1969:     // unless internet explorer
 1970:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
 1971: 
 1972:         \$(document).ready(function() {
 1973:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
 1974:         });
 1975:     }
 1976: 
 1977:     // inserts text at cursor position into codemirror (xml editor only)
 1978:     function insertText(text){
 1979:         cm.focus();
 1980:         var curPos = cm.getCursor();
 1981:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
 1982:     }
 1983: // ]]>
 1984: </script>
 1985: XMLEDIT
 1986: }
 1987: 
 1988: sub insert_folding_button {
 1989:     my $curDepth = $Apache::lonxml::curdepth;
 1990:     my $lastresource = $env{'request.ambiguous'};
 1991: 
 1992:     return "<input type=\"button\" id=\"folding_btn_$curDepth\"
 1993:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
 1994: }
 1995: 
 1996: 
 1997: =pod
 1998: 
 1999: =head1 Excel and CSV file utility routines
 2000: 
 2001: =cut
 2002: 
 2003: ###############################################################
 2004: ###############################################################
 2005: 
 2006: =pod
 2007: 
 2008: =over 4
 2009: 
 2010: =item * &csv_translate($text) 
 2011: 
 2012: Translate $text to allow it to be output as a 'comma separated values' 
 2013: format.
 2014: 
 2015: =cut
 2016: 
 2017: ###############################################################
 2018: ###############################################################
 2019: sub csv_translate {
 2020:     my $text = shift;
 2021:     $text =~ s/\"/\"\"/g;
 2022:     $text =~ s/\n/ /g;
 2023:     return $text;
 2024: }
 2025: 
 2026: ###############################################################
 2027: ###############################################################
 2028: 
 2029: =pod
 2030: 
 2031: =item * &define_excel_formats()
 2032: 
 2033: Define some commonly used Excel cell formats.
 2034: 
 2035: Currently supported formats:
 2036: 
 2037: =over 4
 2038: 
 2039: =item header
 2040: 
 2041: =item bold
 2042: 
 2043: =item h1
 2044: 
 2045: =item h2
 2046: 
 2047: =item h3
 2048: 
 2049: =item h4
 2050: 
 2051: =item i
 2052: 
 2053: =item date
 2054: 
 2055: =back
 2056: 
 2057: Inputs: $workbook
 2058: 
 2059: Returns: $format, a hash reference.
 2060: 
 2061: 
 2062: =cut
 2063: 
 2064: ###############################################################
 2065: ###############################################################
 2066: sub define_excel_formats {
 2067:     my ($workbook) = @_;
 2068:     my $format;
 2069:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 2070:                                                 bottom    => 1,
 2071:                                                 align     => 'center');
 2072:     $format->{'bold'} = $workbook->add_format(bold=>1);
 2073:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 2074:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 2075:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 2076:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 2077:     $format->{'i'}    = $workbook->add_format(italic=>1);
 2078:     $format->{'date'} = $workbook->add_format(num_format=>
 2079:                                             'mm/dd/yyyy hh:mm:ss');
 2080:     return $format;
 2081: }
 2082: 
 2083: ###############################################################
 2084: ###############################################################
 2085: 
 2086: =pod
 2087: 
 2088: =item * &create_workbook()
 2089: 
 2090: Create an Excel worksheet.  If it fails, output message on the
 2091: request object and return undefs.
 2092: 
 2093: Inputs: Apache request object
 2094: 
 2095: Returns (undef) on failure, 
 2096:     Excel worksheet object, scalar with filename, and formats 
 2097:     from &Apache::loncommon::define_excel_formats on success
 2098: 
 2099: =cut
 2100: 
 2101: ###############################################################
 2102: ###############################################################
 2103: sub create_workbook {
 2104:     my ($r) = @_;
 2105:         #
 2106:     # Create the excel spreadsheet
 2107:     my $filename = '/prtspool/'.
 2108:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2109:         time.'_'.rand(1000000000).'.xls';
 2110:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 2111:     if (! defined($workbook)) {
 2112:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 2113:         $r->print(
 2114:             '<p class="LC_error">'
 2115:            .&mt('Problems occurred in creating the new Excel file.')
 2116:            .' '.&mt('This error has been logged.')
 2117:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2118:            .'</p>'
 2119:         );
 2120:         return (undef);
 2121:     }
 2122:     #
 2123:     $workbook->set_tempdir(LONCAPA::tempdir());
 2124:     #
 2125:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 2126:     return ($workbook,$filename,$format);
 2127: }
 2128: 
 2129: ###############################################################
 2130: ###############################################################
 2131: 
 2132: =pod
 2133: 
 2134: =item * &create_text_file()
 2135: 
 2136: Create a file to write to and eventually make available to the user.
 2137: If file creation fails, outputs an error message on the request object and 
 2138: return undefs.
 2139: 
 2140: Inputs: Apache request object, and file suffix
 2141: 
 2142: Returns (undef) on failure, 
 2143:     Filehandle and filename on success.
 2144: 
 2145: =cut
 2146: 
 2147: ###############################################################
 2148: ###############################################################
 2149: sub create_text_file {
 2150:     my ($r,$suffix) = @_;
 2151:     if (! defined($suffix)) { $suffix = 'txt'; };
 2152:     my $fh;
 2153:     my $filename = '/prtspool/'.
 2154:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2155:         time.'_'.rand(1000000000).'.'.$suffix;
 2156:     $fh = Apache::File->new('>/home/httpd'.$filename);
 2157:     if (! defined($fh)) {
 2158:         $r->log_error("Couldn't open $filename for output $!");
 2159:         $r->print(
 2160:             '<p class="LC_error">'
 2161:            .&mt('Problems occurred in creating the output file.')
 2162:            .' '.&mt('This error has been logged.')
 2163:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2164:            .'</p>'
 2165:         );
 2166:     }
 2167:     return ($fh,$filename)
 2168: }
 2169: 
 2170: 
 2171: =pod 
 2172: 
 2173: =back
 2174: 
 2175: =cut
 2176: 
 2177: ###############################################################
 2178: ##        Home server <option> list generating code          ##
 2179: ###############################################################
 2180: 
 2181: # ------------------------------------------
 2182: 
 2183: sub domain_select {
 2184:     my ($name,$value,$multiple)=@_;
 2185:     my %domains=map { 
 2186: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 2187:     } &Apache::lonnet::all_domains();
 2188:     if ($multiple) {
 2189: 	$domains{''}=&mt('Any domain');
 2190: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2191: 	return &multiple_select_form($name,$value,4,\%domains);
 2192:     } else {
 2193: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2194: 	return &select_form($name,$value,\%domains);
 2195:     }
 2196: }
 2197: 
 2198: #-------------------------------------------
 2199: 
 2200: =pod
 2201: 
 2202: =head1 Routines for form select boxes
 2203: 
 2204: =over 4
 2205: 
 2206: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 2207: 
 2208: Returns a string containing a <select> element int multiple mode
 2209: 
 2210: 
 2211: Args:
 2212:   $name - name of the <select> element
 2213:   $value - scalar or array ref of values that should already be selected
 2214:   $size - number of rows long the select element is
 2215:   $hash - the elements should be 'option' => 'shown text'
 2216:           (shown text should already have been &mt())
 2217:   $order - (optional) array ref of the order to show the elements in
 2218: 
 2219: =cut
 2220: 
 2221: #-------------------------------------------
 2222: sub multiple_select_form {
 2223:     my ($name,$value,$size,$hash,$order)=@_;
 2224:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 2225:     my $output='';
 2226:     if (! defined($size)) {
 2227:         $size = 4;
 2228:         if (scalar(keys(%$hash))<4) {
 2229:             $size = scalar(keys(%$hash));
 2230:         }
 2231:     }
 2232:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 2233:     my @order;
 2234:     if (ref($order) eq 'ARRAY')  {
 2235:         @order = @{$order};
 2236:     } else {
 2237:         @order = sort(keys(%$hash));
 2238:     }
 2239:     if (exists($$hash{'select_form_order'})) {
 2240:         @order = @{$$hash{'select_form_order'}};
 2241:     }
 2242:         
 2243:     foreach my $key (@order) {
 2244:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 2245:         $output.='selected="selected" ' if ($selected{$key});
 2246:         $output.='>'.$hash->{$key}."</option>\n";
 2247:     }
 2248:     $output.="</select>\n";
 2249:     return $output;
 2250: }
 2251: 
 2252: #-------------------------------------------
 2253: 
 2254: =pod
 2255: 
 2256: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
 2257: 
 2258: Returns a string containing a <select name='$name' size='1'> form to 
 2259: allow a user to select options from a ref to a hash containing:
 2260: option_name => displayed text. An optional $onchange can include
 2261: a javascript onchange item, e.g., onchange="this.form.submit();".
 2262: An optional arg -- $readonly -- if true will cause the select form
 2263: to be disabled, e.g., for the case where an instructor has a section-
 2264: specific role, and is viewing/modifying parameters.  
 2265: 
 2266: See lonrights.pm for an example invocation and use.
 2267: 
 2268: =cut
 2269: 
 2270: #-------------------------------------------
 2271: sub select_form {
 2272:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
 2273:     return unless (ref($hashref) eq 'HASH');
 2274:     if ($onchange) {
 2275:         $onchange = ' onchange="'.$onchange.'"';
 2276:     }
 2277:     my $disabled;
 2278:     if ($readonly) {
 2279:         $disabled = ' disabled="disabled"';
 2280:     }
 2281:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2282:     my @keys;
 2283:     if (exists($hashref->{'select_form_order'})) {
 2284: 	@keys=@{$hashref->{'select_form_order'}};
 2285:     } else {
 2286: 	@keys=sort(keys(%{$hashref}));
 2287:     }
 2288:     foreach my $key (@keys) {
 2289:         $selectform.=
 2290: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2291:             ($key eq $def ? 'selected="selected" ' : '').
 2292:                 ">".$hashref->{$key}."</option>\n";
 2293:     }
 2294:     $selectform.="</select>";
 2295:     return $selectform;
 2296: }
 2297: 
 2298: # For display filters
 2299: 
 2300: sub display_filter {
 2301:     my ($context) = @_;
 2302:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2303:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2304:     my $phraseinput = 'hidden';
 2305:     my $includeinput = 'hidden';
 2306:     my ($checked,$includetypestext);
 2307:     if ($env{'form.displayfilter'} eq 'containing') {
 2308:         $phraseinput = 'text'; 
 2309:         if ($context eq 'parmslog') {
 2310:             $includeinput = 'checkbox';
 2311:             if ($env{'form.includetypes'}) {
 2312:                 $checked = ' checked="checked"';
 2313:             }
 2314:             $includetypestext = &mt('Include parameter types');
 2315:         }
 2316:     } else {
 2317:         $includetypestext = '&nbsp;';
 2318:     }
 2319:     my ($additional,$secondid,$thirdid);
 2320:     if ($context eq 'parmslog') {
 2321:         $additional = 
 2322:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2323:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2324:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2325:             '</label>';
 2326:         $secondid = 'includetypes';
 2327:         $thirdid = 'includetypestext';
 2328:     }
 2329:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2330:                                                     '$secondid','$thirdid')";
 2331:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2332: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 2333: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2334: 	   '</label></span> <span class="LC_nobreak">'.
 2335:            &mt('Filter: [_1]',
 2336: 	   &select_form($env{'form.displayfilter'},
 2337: 			'displayfilter',
 2338: 			{'currentfolder' => 'Current folder/page',
 2339: 			 'containing' => 'Containing phrase',
 2340: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2341: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2342:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2343:                          '" />'.$additional;
 2344: }
 2345: 
 2346: sub display_filter_js {
 2347:     my $includetext = &mt('Include parameter types');
 2348:     return <<"ENDJS";
 2349:   
 2350: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2351:     var firstType = 'hidden';
 2352:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2353:         firstType = 'text';
 2354:     }
 2355:     firstObject = document.getElementById(firstid);
 2356:     if (typeof(firstObject) == 'object') {
 2357:         if (firstObject.type != firstType) {
 2358:             changeInputType(firstObject,firstType);
 2359:         }
 2360:     }
 2361:     if (context == 'parmslog') {
 2362:         var secondType = 'hidden';
 2363:         if (firstType == 'text') {
 2364:             secondType = 'checkbox';
 2365:         }
 2366:         secondObject = document.getElementById(secondid);  
 2367:         if (typeof(secondObject) == 'object') {
 2368:             if (secondObject.type != secondType) {
 2369:                 changeInputType(secondObject,secondType);
 2370:             }
 2371:         }
 2372:         var textItem = document.getElementById(thirdid);
 2373:         var currtext = textItem.innerHTML;
 2374:         var newtext;
 2375:         if (firstType == 'text') {
 2376:             newtext = '$includetext';
 2377:         } else {
 2378:             newtext = '&nbsp;';
 2379:         }
 2380:         if (currtext != newtext) {
 2381:             textItem.innerHTML = newtext;
 2382:         }
 2383:     }
 2384:     return;
 2385: }
 2386: 
 2387: function changeInputType(oldObject,newType) {
 2388:     var newObject = document.createElement('input');
 2389:     newObject.type = newType;
 2390:     if (oldObject.size) {
 2391:         newObject.size = oldObject.size;
 2392:     }
 2393:     if (oldObject.value) {
 2394:         newObject.value = oldObject.value;
 2395:     }
 2396:     if (oldObject.name) {
 2397:         newObject.name = oldObject.name;
 2398:     }
 2399:     if (oldObject.id) {
 2400:         newObject.id = oldObject.id;
 2401:     }
 2402:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2403:     return;
 2404: }
 2405: 
 2406: ENDJS
 2407: }
 2408: 
 2409: sub gradeleveldescription {
 2410:     my $gradelevel=shift;
 2411:     my %gradelevels=(0 => 'Not specified',
 2412: 		     1 => 'Grade 1',
 2413: 		     2 => 'Grade 2',
 2414: 		     3 => 'Grade 3',
 2415: 		     4 => 'Grade 4',
 2416: 		     5 => 'Grade 5',
 2417: 		     6 => 'Grade 6',
 2418: 		     7 => 'Grade 7',
 2419: 		     8 => 'Grade 8',
 2420: 		     9 => 'Grade 9',
 2421: 		     10 => 'Grade 10',
 2422: 		     11 => 'Grade 11',
 2423: 		     12 => 'Grade 12',
 2424: 		     13 => 'Grade 13',
 2425: 		     14 => '100 Level',
 2426: 		     15 => '200 Level',
 2427: 		     16 => '300 Level',
 2428: 		     17 => '400 Level',
 2429: 		     18 => 'Graduate Level');
 2430:     return &mt($gradelevels{$gradelevel});
 2431: }
 2432: 
 2433: sub select_level_form {
 2434:     my ($deflevel,$name)=@_;
 2435:     unless ($deflevel) { $deflevel=0; }
 2436:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2437:     for (my $i=0; $i<=18; $i++) {
 2438:         $selectform.="<option value=\"$i\" ".
 2439:             ($i==$deflevel ? 'selected="selected" ' : '').
 2440:                 ">".&gradeleveldescription($i)."</option>\n";
 2441:     }
 2442:     $selectform.="</select>";
 2443:     return $selectform;
 2444: }
 2445: 
 2446: #-------------------------------------------
 2447: 
 2448: =pod
 2449: 
 2450: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
 2451: 
 2452: Returns a string containing a <select name='$name' size='1'> form to 
 2453: allow a user to select the domain to preform an operation in.  
 2454: See loncreateuser.pm for an example invocation and use.
 2455: 
 2456: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2457: selected");
 2458: 
 2459: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2460: 
 2461: 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.
 2462: 
 2463: The optional $incdoms is a reference to an array of domains which will be the only available options.
 2464: 
 2465: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
 2466: 
 2467: The optional $disabled argument, if true, adds the disabled attribute to the select tag. 
 2468: 
 2469: =cut
 2470: 
 2471: #-------------------------------------------
 2472: sub select_dom_form {
 2473:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
 2474:     if ($onchange) {
 2475:         $onchange = ' onchange="'.$onchange.'"';
 2476:     }
 2477:     if ($disabled) {
 2478:         $disabled = ' disabled="disabled"';
 2479:     }
 2480:     my (@domains,%exclude);
 2481:     if (ref($incdoms) eq 'ARRAY') {
 2482:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2483:     } else {
 2484:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2485:     }
 2486:     if ($includeempty) { @domains=('',@domains); }
 2487:     if (ref($excdoms) eq 'ARRAY') {
 2488:         map { $exclude{$_} = 1; } @{$excdoms};
 2489:     }
 2490:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2491:     foreach my $dom (@domains) {
 2492:         next if ($exclude{$dom});
 2493:         $selectdomain.="<option value=\"$dom\" ".
 2494:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2495:         if ($showdomdesc) {
 2496:             if ($dom ne '') {
 2497:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2498:                 if ($domdesc ne '') {
 2499:                     $selectdomain .= ' ('.$domdesc.')';
 2500:                 }
 2501:             } 
 2502:         }
 2503:         $selectdomain .= "</option>\n";
 2504:     }
 2505:     $selectdomain.="</select>";
 2506:     return $selectdomain;
 2507: }
 2508: 
 2509: #-------------------------------------------
 2510: 
 2511: =pod
 2512: 
 2513: =item * &home_server_form_item($domain,$name,$defaultflag)
 2514: 
 2515: input: 4 arguments (two required, two optional) - 
 2516:     $domain - domain of new user
 2517:     $name - name of form element
 2518:     $default - Value of 'default' causes a default item to be first 
 2519:                             option, and selected by default. 
 2520:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2521:                             if 1 server found, or default, if 0 found.
 2522: output: returns 2 items: 
 2523: (a) form element which contains either:
 2524:    (i) <select name="$name">
 2525:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2526:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2527:        </select>
 2528:        form item if there are multiple library servers in $domain, or
 2529:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2530:        if there is only one library server in $domain.
 2531: 
 2532: (b) number of library servers found.
 2533: 
 2534: See loncreateuser.pm for example of use.
 2535: 
 2536: =cut
 2537: 
 2538: #-------------------------------------------
 2539: sub home_server_form_item {
 2540:     my ($domain,$name,$default,$hide) = @_;
 2541:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2542:     my $result;
 2543:     my $numlib = keys(%servers);
 2544:     if ($numlib > 1) {
 2545:         $result .= '<select name="'.$name.'" />'."\n";
 2546:         if ($default) {
 2547:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2548:                        '</option>'."\n";
 2549:         }
 2550:         foreach my $hostid (sort(keys(%servers))) {
 2551:             $result.= '<option value="'.$hostid.'">'.
 2552: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2553:         }
 2554:         $result .= '</select>'."\n";
 2555:     } elsif ($numlib == 1) {
 2556:         my $hostid;
 2557:         foreach my $item (keys(%servers)) {
 2558:             $hostid = $item;
 2559:         }
 2560:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2561:                    $hostid.'" />';
 2562:                    if (!$hide) {
 2563:                        $result .= $hostid.' '.$servers{$hostid};
 2564:                    }
 2565:                    $result .= "\n";
 2566:     } elsif ($default) {
 2567:         $result .= '<input type="hidden" name="'.$name.
 2568:                    '" value="default" />';
 2569:                    if (!$hide) {
 2570:                        $result .= &mt('default');
 2571:                    }
 2572:                    $result .= "\n";
 2573:     }
 2574:     return ($result,$numlib);
 2575: }
 2576: 
 2577: =pod
 2578: 
 2579: =back 
 2580: 
 2581: =cut
 2582: 
 2583: ###############################################################
 2584: ##                  Decoding User Agent                      ##
 2585: ###############################################################
 2586: 
 2587: =pod
 2588: 
 2589: =head1 Decoding the User Agent
 2590: 
 2591: =over 4
 2592: 
 2593: =item * &decode_user_agent()
 2594: 
 2595: Inputs: $r
 2596: 
 2597: Outputs:
 2598: 
 2599: =over 4
 2600: 
 2601: =item * $httpbrowser
 2602: 
 2603: =item * $clientbrowser
 2604: 
 2605: =item * $clientversion
 2606: 
 2607: =item * $clientmathml
 2608: 
 2609: =item * $clientunicode
 2610: 
 2611: =item * $clientos
 2612: 
 2613: =item * $clientmobile
 2614: 
 2615: =item * $clientinfo
 2616: 
 2617: =item * $clientosversion
 2618: 
 2619: =back
 2620: 
 2621: =back 
 2622: 
 2623: =cut
 2624: 
 2625: ###############################################################
 2626: ###############################################################
 2627: sub decode_user_agent {
 2628:     my ($r)=@_;
 2629:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2630:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2631:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2632:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2633:     my $clientbrowser='unknown';
 2634:     my $clientversion='0';
 2635:     my $clientmathml='';
 2636:     my $clientunicode='0';
 2637:     my $clientmobile=0;
 2638:     my $clientosversion='';
 2639:     for (my $i=0;$i<=$#browsertype;$i++) {
 2640:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
 2641: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2642: 	    $clientbrowser=$bname;
 2643:             $httpbrowser=~/$vreg/i;
 2644: 	    $clientversion=$1;
 2645:             $clientmathml=($clientversion>=$minv);
 2646:             $clientunicode=($clientversion>=$univ);
 2647: 	}
 2648:     }
 2649:     my $clientos='unknown';
 2650:     my $clientinfo;
 2651:     if (($httpbrowser=~/linux/i) ||
 2652:         ($httpbrowser=~/unix/i) ||
 2653:         ($httpbrowser=~/ux/i) ||
 2654:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2655:     if (($httpbrowser=~/vax/i) ||
 2656:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2657:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2658:     if (($httpbrowser=~/mac/i) ||
 2659:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2660:     if ($httpbrowser=~/win/i) {
 2661:         $clientos='win';
 2662:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
 2663:             $clientosversion = $1;
 2664:         }
 2665:     }
 2666:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2667:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 2668:         $clientmobile=lc($1);
 2669:     }
 2670:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 2671:         $clientinfo = 'firefox-'.$1;
 2672:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 2673:         $clientinfo = 'chromeframe-'.$1;
 2674:     }
 2675:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2676:             $clientunicode,$clientos,$clientmobile,$clientinfo,
 2677:             $clientosversion);
 2678: }
 2679: 
 2680: ###############################################################
 2681: ##    Authentication changing form generation subroutines    ##
 2682: ###############################################################
 2683: ##
 2684: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2685: ## hash, and have reasonable default values.
 2686: ##
 2687: ##    formname = the name given in the <form> tag.
 2688: #-------------------------------------------
 2689: 
 2690: =pod
 2691: 
 2692: =head1 Authentication Routines
 2693: 
 2694: =over 4
 2695: 
 2696: =item * &authform_xxxxxx()
 2697: 
 2698: The authform_xxxxxx subroutines provide javascript and html forms which 
 2699: handle some of the conveniences required for authentication forms.  
 2700: This is not an optimal method, but it works.  
 2701: 
 2702: =over 4
 2703: 
 2704: =item * authform_header
 2705: 
 2706: =item * authform_authorwarning
 2707: 
 2708: =item * authform_nochange
 2709: 
 2710: =item * authform_kerberos
 2711: 
 2712: =item * authform_internal
 2713: 
 2714: =item * authform_filesystem
 2715: 
 2716: =back
 2717: 
 2718: See loncreateuser.pm for invocation and use examples.
 2719: 
 2720: =cut
 2721: 
 2722: #-------------------------------------------
 2723: sub authform_header{  
 2724:     my %in = (
 2725:         formname => 'cu',
 2726:         kerb_def_dom => '',
 2727:         @_,
 2728:     );
 2729:     $in{'formname'} = 'document.' . $in{'formname'};
 2730:     my $result='';
 2731: 
 2732: #---------------------------------------------- Code for upper case translation
 2733:     my $Javascript_toUpperCase;
 2734:     unless ($in{kerb_def_dom}) {
 2735:         $Javascript_toUpperCase =<<"END";
 2736:         switch (choice) {
 2737:            case 'krb': currentform.elements[choicearg].value =
 2738:                currentform.elements[choicearg].value.toUpperCase();
 2739:                break;
 2740:            default:
 2741:         }
 2742: END
 2743:     } else {
 2744:         $Javascript_toUpperCase = "";
 2745:     }
 2746: 
 2747:     my $radioval = "'nochange'";
 2748:     if (defined($in{'curr_authtype'})) {
 2749:         if ($in{'curr_authtype'} ne '') {
 2750:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2751:         }
 2752:     }
 2753:     my $argfield = 'null';
 2754:     if (defined($in{'mode'})) {
 2755:         if ($in{'mode'} eq 'modifycourse')  {
 2756:             if (defined($in{'curr_autharg'})) {
 2757:                 if ($in{'curr_autharg'} ne '') {
 2758:                     $argfield = "'$in{'curr_autharg'}'";
 2759:                 }
 2760:             }
 2761:         }
 2762:     }
 2763: 
 2764:     $result.=<<"END";
 2765: var current = new Object();
 2766: current.radiovalue = $radioval;
 2767: current.argfield = $argfield;
 2768: 
 2769: function changed_radio(choice,currentform) {
 2770:     var choicearg = choice + 'arg';
 2771:     // If a radio button in changed, we need to change the argfield
 2772:     if (current.radiovalue != choice) {
 2773:         current.radiovalue = choice;
 2774:         if (current.argfield != null) {
 2775:             currentform.elements[current.argfield].value = '';
 2776:         }
 2777:         if (choice == 'nochange') {
 2778:             current.argfield = null;
 2779:         } else {
 2780:             current.argfield = choicearg;
 2781:             switch(choice) {
 2782:                 case 'krb': 
 2783:                     currentform.elements[current.argfield].value = 
 2784:                         "$in{'kerb_def_dom'}";
 2785:                 break;
 2786:               default:
 2787:                 break;
 2788:             }
 2789:         }
 2790:     }
 2791:     return;
 2792: }
 2793: 
 2794: function changed_text(choice,currentform) {
 2795:     var choicearg = choice + 'arg';
 2796:     if (currentform.elements[choicearg].value !='') {
 2797:         $Javascript_toUpperCase
 2798:         // clear old field
 2799:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2800:             currentform.elements[current.argfield].value = '';
 2801:         }
 2802:         current.argfield = choicearg;
 2803:     }
 2804:     set_auth_radio_buttons(choice,currentform);
 2805:     return;
 2806: }
 2807: 
 2808: function set_auth_radio_buttons(newvalue,currentform) {
 2809:     var numauthchoices = currentform.login.length;
 2810:     if (typeof numauthchoices  == "undefined") {
 2811:         return;
 2812:     } 
 2813:     var i=0;
 2814:     while (i < numauthchoices) {
 2815:         if (currentform.login[i].value == newvalue) { break; }
 2816:         i++;
 2817:     }
 2818:     if (i == numauthchoices) {
 2819:         return;
 2820:     }
 2821:     current.radiovalue = newvalue;
 2822:     currentform.login[i].checked = true;
 2823:     return;
 2824: }
 2825: END
 2826:     return $result;
 2827: }
 2828: 
 2829: sub authform_authorwarning {
 2830:     my $result='';
 2831:     $result='<i>'.
 2832:         &mt('As a general rule, only authors or co-authors should be '.
 2833:             'filesystem authenticated '.
 2834:             '(which allows access to the server filesystem).')."</i>\n";
 2835:     return $result;
 2836: }
 2837: 
 2838: sub authform_nochange {
 2839:     my %in = (
 2840:               formname => 'document.cu',
 2841:               kerb_def_dom => 'MSU.EDU',
 2842:               @_,
 2843:           );
 2844:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
 2845:     my $result;
 2846:     if (!$authnum) {
 2847:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 2848:     } else {
 2849:         $result = '<label>'.&mt('[_1] Do not change login data',
 2850:                   '<input type="radio" name="login" value="nochange" '.
 2851:                   'checked="checked" onclick="'.
 2852:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2853: 	    '</label>';
 2854:     }
 2855:     return $result;
 2856: }
 2857: 
 2858: sub authform_kerberos {
 2859:     my %in = (
 2860:               formname => 'document.cu',
 2861:               kerb_def_dom => 'MSU.EDU',
 2862:               kerb_def_auth => 'krb4',
 2863:               @_,
 2864:               );
 2865:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2866:         $autharg,$jscall,$disabled);
 2867:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2868:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2869:        $check5 = ' checked="checked"';
 2870:     } else {
 2871:        $check4 = ' checked="checked"';
 2872:     }
 2873:     if ($in{'readonly'}) {
 2874:         $disabled = ' disabled="disabled"';
 2875:     }
 2876:     $krbarg = $in{'kerb_def_dom'};
 2877:     if (defined($in{'curr_authtype'})) {
 2878:         if ($in{'curr_authtype'} eq 'krb') {
 2879:             $krbcheck = ' checked="checked"';
 2880:             if (defined($in{'mode'})) {
 2881:                 if ($in{'mode'} eq 'modifyuser') {
 2882:                     $krbcheck = '';
 2883:                 }
 2884:             }
 2885:             if (defined($in{'curr_kerb_ver'})) {
 2886:                 if ($in{'curr_krb_ver'} eq '5') {
 2887:                     $check5 = ' checked="checked"';
 2888:                     $check4 = '';
 2889:                 } else {
 2890:                     $check4 = ' checked="checked"';
 2891:                     $check5 = '';
 2892:                 }
 2893:             }
 2894:             if (defined($in{'curr_autharg'})) {
 2895:                 $krbarg = $in{'curr_autharg'};
 2896:             }
 2897:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2898:                 if (defined($in{'curr_autharg'})) {
 2899:                     $result = 
 2900:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2901:         $in{'curr_autharg'},$krbver);
 2902:                 } else {
 2903:                     $result =
 2904:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2905:                 }
 2906:                 return $result; 
 2907:             }
 2908:         }
 2909:     } else {
 2910:         if ($authnum == 1) {
 2911:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2912:         }
 2913:     }
 2914:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2915:         return;
 2916:     } elsif ($authtype eq '') {
 2917:         if (defined($in{'mode'})) {
 2918:             if ($in{'mode'} eq 'modifycourse') {
 2919:                 if ($authnum == 1) {
 2920:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
 2921:                 }
 2922:             }
 2923:         }
 2924:     }
 2925:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2926:     if ($authtype eq '') {
 2927:         $authtype = '<input type="radio" name="login" value="krb" '.
 2928:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2929:                     $krbcheck.$disabled.' />';
 2930:     }
 2931:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2932:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 2933:          $in{'curr_authtype'} eq 'krb5') ||
 2934:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 2935:          $in{'curr_authtype'} eq 'krb4')) {
 2936:         $result .= &mt
 2937:         ('[_1] Kerberos authenticated with domain [_2] '.
 2938:          '[_3] Version 4 [_4] Version 5 [_5]',
 2939:          '<label>'.$authtype,
 2940:          '</label><input type="text" size="10" name="krbarg" '.
 2941:              'value="'.$krbarg.'" '.
 2942:              'onchange="'.$jscall.'"'.$disabled.' />',
 2943:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
 2944:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
 2945: 	 '</label>');
 2946:     } elsif ($can_assign{'krb4'}) {
 2947:         $result .= &mt
 2948:         ('[_1] Kerberos authenticated with domain [_2] '.
 2949:          '[_3] Version 4 [_4]',
 2950:          '<label>'.$authtype,
 2951:          '</label><input type="text" size="10" name="krbarg" '.
 2952:              'value="'.$krbarg.'" '.
 2953:              'onchange="'.$jscall.'"'.$disabled.' />',
 2954:          '<label><input type="hidden" name="krbver" value="4" />',
 2955:          '</label>');
 2956:     } elsif ($can_assign{'krb5'}) {
 2957:         $result .= &mt
 2958:         ('[_1] Kerberos authenticated with domain [_2] '.
 2959:          '[_3] Version 5 [_4]',
 2960:          '<label>'.$authtype,
 2961:          '</label><input type="text" size="10" name="krbarg" '.
 2962:              'value="'.$krbarg.'" '.
 2963:              'onchange="'.$jscall.'"'.$disabled.' />',
 2964:          '<label><input type="hidden" name="krbver" value="5" />',
 2965:          '</label>');
 2966:     }
 2967:     return $result;
 2968: }
 2969: 
 2970: sub authform_internal {
 2971:     my %in = (
 2972:                 formname => 'document.cu',
 2973:                 kerb_def_dom => 'MSU.EDU',
 2974:                 @_,
 2975:                 );
 2976:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
 2977:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2978:     if ($in{'readonly'}) {
 2979:         $disabled = ' disabled="disabled"';
 2980:     }
 2981:     if (defined($in{'curr_authtype'})) {
 2982:         if ($in{'curr_authtype'} eq 'int') {
 2983:             if ($can_assign{'int'}) {
 2984:                 $intcheck = 'checked="checked" ';
 2985:                 if (defined($in{'mode'})) {
 2986:                     if ($in{'mode'} eq 'modifyuser') {
 2987:                         $intcheck = '';
 2988:                     }
 2989:                 }
 2990:                 if (defined($in{'curr_autharg'})) {
 2991:                     $intarg = $in{'curr_autharg'};
 2992:                 }
 2993:             } else {
 2994:                 $result = &mt('Currently internally authenticated.');
 2995:                 return $result;
 2996:             }
 2997:         }
 2998:     } else {
 2999:         if ($authnum == 1) {
 3000:             $authtype = '<input type="hidden" name="login" value="int" />';
 3001:         }
 3002:     }
 3003:     if (!$can_assign{'int'}) {
 3004:         return;
 3005:     } elsif ($authtype eq '') {
 3006:         if (defined($in{'mode'})) {
 3007:             if ($in{'mode'} eq 'modifycourse') {
 3008:                 if ($authnum == 1) {
 3009:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
 3010:                 }
 3011:             }
 3012:         }
 3013:     }
 3014:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 3015:     if ($authtype eq '') {
 3016:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 3017:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
 3018:     }
 3019:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 3020:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3021:     $result = &mt
 3022:         ('[_1] Internally authenticated (with initial password [_2])',
 3023:          '<label>'.$authtype,'</label>'.$autharg);
 3024:     $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>';
 3025:     return $result;
 3026: }
 3027: 
 3028: sub authform_local {
 3029:     my %in = (
 3030:               formname => 'document.cu',
 3031:               kerb_def_dom => 'MSU.EDU',
 3032:               @_,
 3033:               );
 3034:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
 3035:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3036:     if ($in{'readonly'}) {
 3037:         $disabled = ' disabled="disabled"';
 3038:     }
 3039:     if (defined($in{'curr_authtype'})) {
 3040:         if ($in{'curr_authtype'} eq 'loc') {
 3041:             if ($can_assign{'loc'}) {
 3042:                 $loccheck = 'checked="checked" ';
 3043:                 if (defined($in{'mode'})) {
 3044:                     if ($in{'mode'} eq 'modifyuser') {
 3045:                         $loccheck = '';
 3046:                     }
 3047:                 }
 3048:                 if (defined($in{'curr_autharg'})) {
 3049:                     $locarg = $in{'curr_autharg'};
 3050:                 }
 3051:             } else {
 3052:                 $result = &mt('Currently using local (institutional) authentication.');
 3053:                 return $result;
 3054:             }
 3055:         }
 3056:     } else {
 3057:         if ($authnum == 1) {
 3058:             $authtype = '<input type="hidden" name="login" value="loc" />';
 3059:         }
 3060:     }
 3061:     if (!$can_assign{'loc'}) {
 3062:         return;
 3063:     } elsif ($authtype eq '') {
 3064:         if (defined($in{'mode'})) {
 3065:             if ($in{'mode'} eq 'modifycourse') {
 3066:                 if ($authnum == 1) {
 3067:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
 3068:                 }
 3069:             }
 3070:         }
 3071:     }
 3072:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 3073:     if ($authtype eq '') {
 3074:         $authtype = '<input type="radio" name="login" value="loc" '.
 3075:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 3076:                     $jscall.'"'.$disabled.' />';
 3077:     }
 3078:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 3079:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3080:     $result = &mt('[_1] Local Authentication with argument [_2]',
 3081:                   '<label>'.$authtype,'</label>'.$autharg);
 3082:     return $result;
 3083: }
 3084: 
 3085: sub authform_filesystem {
 3086:     my %in = (
 3087:               formname => 'document.cu',
 3088:               kerb_def_dom => 'MSU.EDU',
 3089:               @_,
 3090:               );
 3091:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
 3092:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3093:     if ($in{'readonly'}) {
 3094:         $disabled = ' disabled="disabled"';
 3095:     }
 3096:     if (defined($in{'curr_authtype'})) {
 3097:         if ($in{'curr_authtype'} eq 'fsys') {
 3098:             if ($can_assign{'fsys'}) {
 3099:                 $fsyscheck = 'checked="checked" ';
 3100:                 if (defined($in{'mode'})) {
 3101:                     if ($in{'mode'} eq 'modifyuser') {
 3102:                         $fsyscheck = '';
 3103:                     }
 3104:                 }
 3105:             } else {
 3106:                 $result = &mt('Currently Filesystem Authenticated.');
 3107:                 return $result;
 3108:             }           
 3109:         }
 3110:     } else {
 3111:         if ($authnum == 1) {
 3112:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 3113:         }
 3114:     }
 3115:     if (!$can_assign{'fsys'}) {
 3116:         return;
 3117:     } elsif ($authtype eq '') {
 3118:         if (defined($in{'mode'})) {
 3119:             if ($in{'mode'} eq 'modifycourse') {
 3120:                 if ($authnum == 1) {
 3121:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
 3122:                 }
 3123:             }
 3124:         }
 3125:     }
 3126:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 3127:     if ($authtype eq '') {
 3128:         $authtype = '<input type="radio" name="login" value="fsys" '.
 3129:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 3130:                     $jscall.'"'.$disabled.' />';
 3131:     }
 3132:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
 3133:                ' onchange="'.$jscall.'"'.$disabled.' />';
 3134:     $result = &mt
 3135:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 3136:          '<label>'.$authtype,'</label>'.$autharg);
 3137:     return $result;
 3138: }
 3139: 
 3140: sub get_assignable_auth {
 3141:     my ($dom) = @_;
 3142:     if ($dom eq '') {
 3143:         $dom = $env{'request.role.domain'};
 3144:     }
 3145:     my %can_assign = (
 3146:                           krb4 => 1,
 3147:                           krb5 => 1,
 3148:                           int  => 1,
 3149:                           loc  => 1,
 3150:                      );
 3151:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 3152:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 3153:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 3154:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 3155:             my $context;
 3156:             if ($env{'request.role'} =~ /^au/) {
 3157:                 $context = 'author';
 3158:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
 3159:                 $context = 'domain';
 3160:             } elsif ($env{'request.course.id'}) {
 3161:                 $context = 'course';
 3162:             }
 3163:             if ($context) {
 3164:                 if (ref($authhash->{$context}) eq 'HASH') {
 3165:                    %can_assign = %{$authhash->{$context}}; 
 3166:                 }
 3167:             }
 3168:         }
 3169:     }
 3170:     my $authnum = 0;
 3171:     foreach my $key (keys(%can_assign)) {
 3172:         if ($can_assign{$key}) {
 3173:             $authnum ++;
 3174:         }
 3175:     }
 3176:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 3177:         $authnum --;
 3178:     }
 3179:     return ($authnum,%can_assign);
 3180: }
 3181: 
 3182: sub check_passwd_rules {
 3183:     my ($domain,$plainpass) = @_;
 3184:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
 3185:     my ($min,$max,@chars,@brokerule,$warning);
 3186:     $min = $Apache::lonnet::passwdmin;
 3187:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
 3188:         if ($passwdconf{'min'} =~ /^\d+$/) {
 3189:             if ($passwdconf{'min'} > $min) {
 3190:                 $min = $passwdconf{'min'};
 3191:             }
 3192:         }
 3193:         if ($passwdconf{'max'} =~ /^\d+$/) {
 3194:             $max = $passwdconf{'max'};
 3195:         }
 3196:         @chars = @{$passwdconf{'chars'}};
 3197:     }
 3198:     if (($min) && (length($plainpass) < $min)) {
 3199:         push(@brokerule,'min');
 3200:     }
 3201:     if (($max) && (length($plainpass) > $max)) {
 3202:         push(@brokerule,'max');
 3203:     }
 3204:     if (@chars) {
 3205:         my %rules;
 3206:         map { $rules{$_} = 1; } @chars;
 3207:         if ($rules{'uc'}) {
 3208:             unless ($plainpass =~ /[A-Z]/) {
 3209:                 push(@brokerule,'uc');
 3210:             }
 3211:         }
 3212:         if ($rules{'lc'}) {
 3213:             unless ($plainpass =~ /[a-z]/) {
 3214:                 push(@brokerule,'lc');
 3215:             }
 3216:         }
 3217:         if ($rules{'num'}) {
 3218:             unless ($plainpass =~ /\d/) {
 3219:                 push(@brokerule,'num');
 3220:             }
 3221:         }
 3222:         if ($rules{'spec'}) {
 3223:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
 3224:                 push(@brokerule,'spec');
 3225:             }
 3226:         }
 3227:     }
 3228:     if (@brokerule) {
 3229:         my %rulenames = &Apache::lonlocal::texthash(
 3230:             uc   => 'At least one upper case letter',
 3231:             lc   => 'At least one lower case letter',
 3232:             num  => 'At least one number',
 3233:             spec => 'At least one non-alphanumeric',
 3234:         );
 3235:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
 3236:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
 3237:         $rulenames{'num'} .= ': 0123456789';
 3238:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
 3239:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
 3240:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
 3241:         $warning = &mt('Password did not satisfy the following:').'<ul>';
 3242:         foreach my $rule ('min','max','uc','lc','num','spec') {
 3243:             if (grep(/^$rule$/,@brokerule)) {
 3244:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
 3245:             }
 3246:         }
 3247:         $warning .= '</ul>';
 3248:     }
 3249:     if (wantarray) {
 3250:         return @brokerule;
 3251:     }
 3252:     return $warning;
 3253: }
 3254: 
 3255: ###############################################################
 3256: ##    Get Kerberos Defaults for Domain                 ##
 3257: ###############################################################
 3258: ##
 3259: ## Returns default kerberos version and an associated argument
 3260: ## as listed in file domain.tab. If not listed, provides
 3261: ## appropriate default domain and kerberos version.
 3262: ##
 3263: #-------------------------------------------
 3264: 
 3265: =pod
 3266: 
 3267: =item * &get_kerberos_defaults()
 3268: 
 3269: get_kerberos_defaults($target_domain) returns the default kerberos
 3270: version and domain. If not found, it defaults to version 4 and the 
 3271: domain of the server.
 3272: 
 3273: =over 4
 3274: 
 3275: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 3276: 
 3277: =back
 3278: 
 3279: =back
 3280: 
 3281: =cut
 3282: 
 3283: #-------------------------------------------
 3284: sub get_kerberos_defaults {
 3285:     my $domain=shift;
 3286:     my ($krbdef,$krbdefdom);
 3287:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 3288:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 3289:         $krbdef = $domdefaults{'auth_def'};
 3290:         $krbdefdom = $domdefaults{'auth_arg_def'};
 3291:     } else {
 3292:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 3293:         my $krbdefdom=$1;
 3294:         $krbdefdom=~tr/a-z/A-Z/;
 3295:         $krbdef = "krb4";
 3296:     }
 3297:     return ($krbdef,$krbdefdom);
 3298: }
 3299: 
 3300: 
 3301: ###############################################################
 3302: ##                Thesaurus Functions                        ##
 3303: ###############################################################
 3304: 
 3305: =pod
 3306: 
 3307: =head1 Thesaurus Functions
 3308: 
 3309: =over 4
 3310: 
 3311: =item * &initialize_keywords()
 3312: 
 3313: Initializes the package variable %Keywords if it is empty.  Uses the
 3314: package variable $thesaurus_db_file.
 3315: 
 3316: =cut
 3317: 
 3318: ###################################################
 3319: 
 3320: sub initialize_keywords {
 3321:     return 1 if (scalar keys(%Keywords));
 3322:     # If we are here, %Keywords is empty, so fill it up
 3323:     #   Make sure the file we need exists...
 3324:     if (! -e $thesaurus_db_file) {
 3325:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 3326:                                  " failed because it does not exist");
 3327:         return 0;
 3328:     }
 3329:     #   Set up the hash as a database
 3330:     my %thesaurus_db;
 3331:     if (! tie(%thesaurus_db,'GDBM_File',
 3332:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3333:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 3334:                                  $thesaurus_db_file);
 3335:         return 0;
 3336:     } 
 3337:     #  Get the average number of appearances of a word.
 3338:     my $avecount = $thesaurus_db{'average.count'};
 3339:     #  Put keywords (those that appear > average) into %Keywords
 3340:     while (my ($word,$data)=each (%thesaurus_db)) {
 3341:         my ($count,undef) = split /:/,$data;
 3342:         $Keywords{$word}++ if ($count > $avecount);
 3343:     }
 3344:     untie %thesaurus_db;
 3345:     # Remove special values from %Keywords.
 3346:     foreach my $value ('total.count','average.count') {
 3347:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 3348:   }
 3349:     return 1;
 3350: }
 3351: 
 3352: ###################################################
 3353: 
 3354: =pod
 3355: 
 3356: =item * &keyword($word)
 3357: 
 3358: Returns true if $word is a keyword.  A keyword is a word that appears more 
 3359: than the average number of times in the thesaurus database.  Calls 
 3360: &initialize_keywords
 3361: 
 3362: =cut
 3363: 
 3364: ###################################################
 3365: 
 3366: sub keyword {
 3367:     return if (!&initialize_keywords());
 3368:     my $word=lc(shift());
 3369:     $word=~s/\W//g;
 3370:     return exists($Keywords{$word});
 3371: }
 3372: 
 3373: ###############################################################
 3374: 
 3375: =pod 
 3376: 
 3377: =item * &get_related_words()
 3378: 
 3379: Look up a word in the thesaurus.  Takes a scalar argument and returns
 3380: an array of words.  If the keyword is not in the thesaurus, an empty array
 3381: will be returned.  The order of the words returned is determined by the
 3382: database which holds them.
 3383: 
 3384: Uses global $thesaurus_db_file.
 3385: 
 3386: 
 3387: =cut
 3388: 
 3389: ###############################################################
 3390: sub get_related_words {
 3391:     my $keyword = shift;
 3392:     my %thesaurus_db;
 3393:     if (! -e $thesaurus_db_file) {
 3394:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 3395:                                  "failed because the file does not exist");
 3396:         return ();
 3397:     }
 3398:     if (! tie(%thesaurus_db,'GDBM_File',
 3399:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3400:         return ();
 3401:     } 
 3402:     my @Words=();
 3403:     my $count=0;
 3404:     if (exists($thesaurus_db{$keyword})) {
 3405: 	# The first element is the number of times
 3406: 	# the word appears.  We do not need it now.
 3407: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 3408: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 3409: 	my $threshold=$mostfrequentcount/10;
 3410:         foreach my $possibleword (@RelatedWords) {
 3411:             my ($word,$wordcount)=split(/\,/,$possibleword);
 3412:             if ($wordcount>$threshold) {
 3413: 		push(@Words,$word);
 3414:                 $count++;
 3415:                 if ($count>10) { last; }
 3416: 	    }
 3417:         }
 3418:     }
 3419:     untie %thesaurus_db;
 3420:     return @Words;
 3421: }
 3422: 
 3423: =pod
 3424: 
 3425: =back
 3426: 
 3427: =cut
 3428: 
 3429: # -------------------------------------------------------------- Plaintext name
 3430: =pod
 3431: 
 3432: =head1 User Name Functions
 3433: 
 3434: =over 4
 3435: 
 3436: =item * &plainname($uname,$udom,$first)
 3437: 
 3438: Takes a users logon name and returns it as a string in
 3439: "first middle last generation" form 
 3440: if $first is set to 'lastname' then it returns it as
 3441: 'lastname generation, firstname middlename' if their is a lastname
 3442: 
 3443: =cut
 3444: 
 3445: 
 3446: ###############################################################
 3447: sub plainname {
 3448:     my ($uname,$udom,$first)=@_;
 3449:     return if (!defined($uname) || !defined($udom));
 3450:     my %names=&getnames($uname,$udom);
 3451:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 3452: 					  $names{'middlename'},
 3453: 					  $names{'lastname'},
 3454: 					  $names{'generation'},$first);
 3455:     $name=~s/^\s+//;
 3456:     $name=~s/\s+$//;
 3457:     $name=~s/\s+/ /g;
 3458:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 3459:     return $name;
 3460: }
 3461: 
 3462: # -------------------------------------------------------------------- Nickname
 3463: =pod
 3464: 
 3465: =item * &nickname($uname,$udom)
 3466: 
 3467: Gets a users name and returns it as a string as
 3468: 
 3469: "&quot;nickname&quot;"
 3470: 
 3471: if the user has a nickname or
 3472: 
 3473: "first middle last generation"
 3474: 
 3475: if the user does not
 3476: 
 3477: =cut
 3478: 
 3479: sub nickname {
 3480:     my ($uname,$udom)=@_;
 3481:     return if (!defined($uname) || !defined($udom));
 3482:     my %names=&getnames($uname,$udom);
 3483:     my $name=$names{'nickname'};
 3484:     if ($name) {
 3485:        $name='&quot;'.$name.'&quot;'; 
 3486:     } else {
 3487:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 3488: 	     $names{'lastname'}.' '.$names{'generation'};
 3489:        $name=~s/\s+$//;
 3490:        $name=~s/\s+/ /g;
 3491:     }
 3492:     return $name;
 3493: }
 3494: 
 3495: sub getnames {
 3496:     my ($uname,$udom)=@_;
 3497:     return if (!defined($uname) || !defined($udom));
 3498:     if ($udom eq 'public' && $uname eq 'public') {
 3499: 	return ('lastname' => &mt('Public'));
 3500:     }
 3501:     my $id=$uname.':'.$udom;
 3502:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 3503:     if ($cached) {
 3504: 	return %{$names};
 3505:     } else {
 3506: 	my %loadnames=&Apache::lonnet::get('environment',
 3507:                     ['firstname','middlename','lastname','generation','nickname'],
 3508: 					 $udom,$uname);
 3509: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 3510: 	return %loadnames;
 3511:     }
 3512: }
 3513: 
 3514: # -------------------------------------------------------------------- getemails
 3515: 
 3516: =pod
 3517: 
 3518: =item * &getemails($uname,$udom)
 3519: 
 3520: Gets a user's email information and returns it as a hash with keys:
 3521: notification, critnotification, permanentemail
 3522: 
 3523: For notification and critnotification, values are comma-separated lists 
 3524: of e-mail addresses; for permanentemail, value is a single e-mail address.
 3525:  
 3526: 
 3527: =cut
 3528: 
 3529: 
 3530: sub getemails {
 3531:     my ($uname,$udom)=@_;
 3532:     if ($udom eq 'public' && $uname eq 'public') {
 3533: 	return;
 3534:     }
 3535:     if (!$udom) { $udom=$env{'user.domain'}; }
 3536:     if (!$uname) { $uname=$env{'user.name'}; }
 3537:     my $id=$uname.':'.$udom;
 3538:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 3539:     if ($cached) {
 3540: 	return %{$names};
 3541:     } else {
 3542: 	my %loadnames=&Apache::lonnet::get('environment',
 3543:                     			   ['notification','critnotification',
 3544: 					    'permanentemail'],
 3545: 					   $udom,$uname);
 3546: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 3547: 	return %loadnames;
 3548:     }
 3549: }
 3550: 
 3551: sub flush_email_cache {
 3552:     my ($uname,$udom)=@_;
 3553:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3554:     if (!$uname) { $uname=$env{'user.name'};   }
 3555:     return if ($udom eq 'public' && $uname eq 'public');
 3556:     my $id=$uname.':'.$udom;
 3557:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 3558: }
 3559: 
 3560: # -------------------------------------------------------------------- getlangs
 3561: 
 3562: =pod
 3563: 
 3564: =item * &getlangs($uname,$udom)
 3565: 
 3566: Gets a user's language preference and returns it as a hash with key:
 3567: language.
 3568: 
 3569: =cut
 3570: 
 3571: 
 3572: sub getlangs {
 3573:     my ($uname,$udom) = @_;
 3574:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3575:     if (!$uname) { $uname=$env{'user.name'};   }
 3576:     my $id=$uname.':'.$udom;
 3577:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 3578:     if ($cached) {
 3579:         return %{$langs};
 3580:     } else {
 3581:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 3582:                                            $udom,$uname);
 3583:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 3584:         return %loadlangs;
 3585:     }
 3586: }
 3587: 
 3588: sub flush_langs_cache {
 3589:     my ($uname,$udom)=@_;
 3590:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3591:     if (!$uname) { $uname=$env{'user.name'};   }
 3592:     return if ($udom eq 'public' && $uname eq 'public');
 3593:     my $id=$uname.':'.$udom;
 3594:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 3595: }
 3596: 
 3597: # ------------------------------------------------------------------ Screenname
 3598: 
 3599: =pod
 3600: 
 3601: =item * &screenname($uname,$udom)
 3602: 
 3603: Gets a users screenname and returns it as a string
 3604: 
 3605: =cut
 3606: 
 3607: sub screenname {
 3608:     my ($uname,$udom)=@_;
 3609:     if ($uname eq $env{'user.name'} &&
 3610: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 3611:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 3612:     return $names{'screenname'};
 3613: }
 3614: 
 3615: 
 3616: # ------------------------------------------------------------- Confirm Wrapper
 3617: =pod
 3618: 
 3619: =item * &confirmwrapper($message)
 3620: 
 3621: Wrap messages about completion of operation in box
 3622: 
 3623: =cut
 3624: 
 3625: sub confirmwrapper {
 3626:     my ($message)=@_;
 3627:     if ($message) {
 3628:         return "\n".'<div class="LC_confirm_box">'."\n"
 3629:                .$message."\n"
 3630:                .'</div>'."\n";
 3631:     } else {
 3632:         return $message;
 3633:     }
 3634: }
 3635: 
 3636: # ------------------------------------------------------------- Message Wrapper
 3637: 
 3638: sub messagewrapper {
 3639:     my ($link,$username,$domain,$subject,$text)=@_;
 3640:     return 
 3641:         '<a href="/adm/email?compose=individual&amp;'.
 3642:         'recname='.$username.'&amp;recdom='.$domain.
 3643: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3644:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3645: }
 3646: 
 3647: # --------------------------------------------------------------- Notes Wrapper
 3648: 
 3649: sub noteswrapper {
 3650:     my ($link,$un,$do)=@_;
 3651:     return 
 3652: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3653: }
 3654: 
 3655: # ------------------------------------------------------------- Aboutme Wrapper
 3656: 
 3657: sub aboutmewrapper {
 3658:     my ($link,$username,$domain,$target,$class)=@_;
 3659:     if (!defined($username)  && !defined($domain)) {
 3660:         return;
 3661:     }
 3662:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 3663: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3664: }
 3665: 
 3666: # ------------------------------------------------------------ Syllabus Wrapper
 3667: 
 3668: sub syllabuswrapper {
 3669:     my ($linktext,$coursedir,$domain)=@_;
 3670:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3671: }
 3672: 
 3673: # -----------------------------------------------------------------------------
 3674: 
 3675: sub track_student_link {
 3676:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3677:     my $link ="/adm/trackstudent?";
 3678:     my $title = 'View recent activity';
 3679:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3680:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3681:         $link .= "selected_student=$sname:$sdom";
 3682:         $title .= ' of this student';
 3683:     } 
 3684:     if (defined($target) && $target !~ /^\s*$/) {
 3685:         $target = qq{target="$target"};
 3686:     } else {
 3687:         $target = '';
 3688:     }
 3689:     if ($start) { $link.='&amp;start='.$start; }
 3690:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3691:     $title = &mt($title);
 3692:     $linktext = &mt($linktext);
 3693:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3694: 	&help_open_topic('View_recent_activity');
 3695: }
 3696: 
 3697: sub slot_reservations_link {
 3698:     my ($linktext,$sname,$sdom,$target) = @_;
 3699:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3700:     my $title = 'View slot reservation history';
 3701:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3702:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3703:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3704:         $title .= ' of this student';
 3705:     }
 3706:     if (defined($target) && $target !~ /^\s*$/) {
 3707:         $target = qq{target="$target"};
 3708:     } else {
 3709:         $target = '';
 3710:     }
 3711:     $title = &mt($title);
 3712:     $linktext = &mt($linktext);
 3713:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3714: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3715: 
 3716: }
 3717: 
 3718: # ===================================================== Display a student photo
 3719: 
 3720: 
 3721: sub student_image_tag {
 3722:     my ($domain,$user)=@_;
 3723:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3724:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3725: 	return '<img src="'.$imgsrc.'" align="right" />';
 3726:     } else {
 3727: 	return '';
 3728:     }
 3729: }
 3730: 
 3731: =pod
 3732: 
 3733: =back
 3734: 
 3735: =head1 Access .tab File Data
 3736: 
 3737: =over 4
 3738: 
 3739: =item * &languageids() 
 3740: 
 3741: returns list of all language ids
 3742: 
 3743: =cut
 3744: 
 3745: sub languageids {
 3746:     return sort(keys(%language));
 3747: }
 3748: 
 3749: =pod
 3750: 
 3751: =item * &languagedescription() 
 3752: 
 3753: returns description of a specified language id
 3754: 
 3755: =cut
 3756: 
 3757: sub languagedescription {
 3758:     my $code=shift;
 3759:     return  ($supported_language{$code}?'* ':'').
 3760:             $language{$code}.
 3761: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 3762: }
 3763: 
 3764: =pod
 3765: 
 3766: =item * &plainlanguagedescription
 3767: 
 3768: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 3769: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 3770: 
 3771: =cut
 3772: 
 3773: sub plainlanguagedescription {
 3774:     my $code=shift;
 3775:     return $language{$code};
 3776: }
 3777: 
 3778: =pod
 3779: 
 3780: =item * &supportedlanguagecode
 3781: 
 3782: Returns the supported language code (e.g. sptutf maps to pt) given a language
 3783: code.
 3784: 
 3785: =cut
 3786: 
 3787: sub supportedlanguagecode {
 3788:     my $code=shift;
 3789:     return $supported_language{$code};
 3790: }
 3791: 
 3792: =pod
 3793: 
 3794: =item * &latexlanguage()
 3795: 
 3796: Given a language key code returns the correspondnig language to use
 3797: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 3798: is no supported hyphenation for the language code.
 3799: 
 3800: =cut
 3801: 
 3802: sub latexlanguage {
 3803:     my $code = shift;
 3804:     return $latex_language{$code};
 3805: }
 3806: 
 3807: =pod
 3808: 
 3809: =item * &latexhyphenation()
 3810: 
 3811: Same as above but what's supplied is the language as it might be stored
 3812: in the metadata.
 3813: 
 3814: =cut
 3815: 
 3816: sub latexhyphenation {
 3817:     my $key = shift;
 3818:     return $latex_language_bykey{$key};
 3819: }
 3820: 
 3821: =pod
 3822: 
 3823: =item * &copyrightids() 
 3824: 
 3825: returns list of all copyrights
 3826: 
 3827: =cut
 3828: 
 3829: sub copyrightids {
 3830:     return sort(keys(%cprtag));
 3831: }
 3832: 
 3833: =pod
 3834: 
 3835: =item * &copyrightdescription() 
 3836: 
 3837: returns description of a specified copyright id
 3838: 
 3839: =cut
 3840: 
 3841: sub copyrightdescription {
 3842:     return &mt($cprtag{shift(@_)});
 3843: }
 3844: 
 3845: =pod
 3846: 
 3847: =item * &source_copyrightids() 
 3848: 
 3849: returns list of all source copyrights
 3850: 
 3851: =cut
 3852: 
 3853: sub source_copyrightids {
 3854:     return sort(keys(%scprtag));
 3855: }
 3856: 
 3857: =pod
 3858: 
 3859: =item * &source_copyrightdescription() 
 3860: 
 3861: returns description of a specified source copyright id
 3862: 
 3863: =cut
 3864: 
 3865: sub source_copyrightdescription {
 3866:     return &mt($scprtag{shift(@_)});
 3867: }
 3868: 
 3869: =pod
 3870: 
 3871: =item * &filecategories() 
 3872: 
 3873: returns list of all file categories
 3874: 
 3875: =cut
 3876: 
 3877: sub filecategories {
 3878:     return sort(keys(%category_extensions));
 3879: }
 3880: 
 3881: =pod
 3882: 
 3883: =item * &filecategorytypes() 
 3884: 
 3885: returns list of file types belonging to a given file
 3886: category
 3887: 
 3888: =cut
 3889: 
 3890: sub filecategorytypes {
 3891:     my ($cat) = @_;
 3892:     return @{$category_extensions{lc($cat)}};
 3893: }
 3894: 
 3895: =pod
 3896: 
 3897: =item * &fileembstyle() 
 3898: 
 3899: returns embedding style for a specified file type
 3900: 
 3901: =cut
 3902: 
 3903: sub fileembstyle {
 3904:     return $fe{lc(shift(@_))};
 3905: }
 3906: 
 3907: sub filemimetype {
 3908:     return $fm{lc(shift(@_))};
 3909: }
 3910: 
 3911: 
 3912: sub filecategoryselect {
 3913:     my ($name,$value)=@_;
 3914:     return &select_form($value,$name,
 3915:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 3916: }
 3917: 
 3918: =pod
 3919: 
 3920: =item * &filedescription() 
 3921: 
 3922: returns description for a specified file type
 3923: 
 3924: =cut
 3925: 
 3926: sub filedescription {
 3927:     my $file_description = $fd{lc(shift())};
 3928:     $file_description =~ s:([\[\]]):~$1:g;
 3929:     return &mt($file_description);
 3930: }
 3931: 
 3932: =pod
 3933: 
 3934: =item * &filedescriptionex() 
 3935: 
 3936: returns description for a specified file type with
 3937: extra formatting
 3938: 
 3939: =cut
 3940: 
 3941: sub filedescriptionex {
 3942:     my $ex=shift;
 3943:     my $file_description = $fd{lc($ex)};
 3944:     $file_description =~ s:([\[\]]):~$1:g;
 3945:     return '.'.$ex.' '.&mt($file_description);
 3946: }
 3947: 
 3948: # End of .tab access
 3949: =pod
 3950: 
 3951: =back
 3952: 
 3953: =cut
 3954: 
 3955: # ------------------------------------------------------------------ File Types
 3956: sub fileextensions {
 3957:     return sort(keys(%fe));
 3958: }
 3959: 
 3960: # ----------------------------------------------------------- Display Languages
 3961: # returns a hash with all desired display languages
 3962: #
 3963: 
 3964: sub display_languages {
 3965:     my %languages=();
 3966:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3967: 	$languages{$lang}=1;
 3968:     }
 3969:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3970:     if ($env{'form.displaylanguage'}) {
 3971: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3972: 	    $languages{$lang}=1;
 3973:         }
 3974:     }
 3975:     return %languages;
 3976: }
 3977: 
 3978: sub languages {
 3979:     my ($possible_langs) = @_;
 3980:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3981:     if (!ref($possible_langs)) {
 3982: 	if( wantarray ) {
 3983: 	    return @preferred_langs;
 3984: 	} else {
 3985: 	    return $preferred_langs[0];
 3986: 	}
 3987:     }
 3988:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3989:     my @preferred_possibilities;
 3990:     foreach my $preferred_lang (@preferred_langs) {
 3991: 	if (exists($possibilities{$preferred_lang})) {
 3992: 	    push(@preferred_possibilities, $preferred_lang);
 3993: 	}
 3994:     }
 3995:     if( wantarray ) {
 3996: 	return @preferred_possibilities;
 3997:     }
 3998:     return $preferred_possibilities[0];
 3999: }
 4000: 
 4001: sub user_lang {
 4002:     my ($touname,$toudom,$fromcid) = @_;
 4003:     my @userlangs;
 4004:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 4005:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 4006:                     $env{'course.'.$fromcid.'.languages'}));
 4007:     } else {
 4008:         my %langhash = &getlangs($touname,$toudom);
 4009:         if ($langhash{'languages'} ne '') {
 4010:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 4011:         } else {
 4012:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 4013:             if ($domdefs{'lang_def'} ne '') {
 4014:                 @userlangs = ($domdefs{'lang_def'});
 4015:             }
 4016:         }
 4017:     }
 4018:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 4019:     my $user_lh = Apache::localize->get_handle(@languages);
 4020:     return $user_lh;
 4021: }
 4022: 
 4023: 
 4024: ###############################################################
 4025: ##               Student Answer Attempts                     ##
 4026: ###############################################################
 4027: 
 4028: =pod
 4029: 
 4030: =head1 Alternate Problem Views
 4031: 
 4032: =over 4
 4033: 
 4034: =item * &get_previous_attempt($symb, $username, $domain, $course,
 4035:     $getattempt, $regexp, $gradesub, $usec, $identifier)
 4036: 
 4037: Return string with previous attempt on problem. Arguments:
 4038: 
 4039: =over 4
 4040: 
 4041: =item * $symb: Problem, including path
 4042: 
 4043: =item * $username: username of the desired student
 4044: 
 4045: =item * $domain: domain of the desired student
 4046: 
 4047: =item * $course: Course ID
 4048: 
 4049: =item * $getattempt: Leave blank for all attempts, otherwise put
 4050:     something
 4051: 
 4052: =item * $regexp: if string matches this regexp, the string will be
 4053:     sent to $gradesub
 4054: 
 4055: =item * $gradesub: routine that processes the string if it matches $regexp
 4056: 
 4057: =item * $usec: section of the desired student
 4058: 
 4059: =item * $identifier: counter for student (multiple students one problem) or
 4060:     problem (one student; whole sequence).
 4061: 
 4062: =back
 4063: 
 4064: The output string is a table containing all desired attempts, if any.
 4065: 
 4066: =cut
 4067: 
 4068: sub get_previous_attempt {
 4069:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
 4070:   my $prevattempts='';
 4071:   no strict 'refs';
 4072:   if ($symb) {
 4073:     my (%returnhash)=
 4074:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 4075:     if ($returnhash{'version'}) {
 4076:       my %lasthash=();
 4077:       my $version;
 4078:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 4079:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
 4080:             if ($key =~ /\.rawrndseed$/) {
 4081:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
 4082:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
 4083:             } else {
 4084:                 $lasthash{$key}=$returnhash{$version.':'.$key};
 4085:             }
 4086:         }
 4087:       }
 4088:       $prevattempts=&start_data_table().&start_data_table_header_row();
 4089:       $prevattempts.='<th>'.&mt('History').'</th>';
 4090:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
 4091:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 4092:       foreach my $key (sort(keys(%lasthash))) {
 4093: 	my ($ign,@parts) = split(/\./,$key);
 4094: 	if ($#parts > 0) {
 4095: 	  my $data=$parts[-1];
 4096:           next if ($data eq 'foilorder');
 4097: 	  pop(@parts);
 4098:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 4099:           if ($data eq 'type') {
 4100:               unless ($showsurv) {
 4101:                   my $id = join(',',@parts);
 4102:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 4103:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 4104:                       $lasthidden{$ign.'.'.$id} = 1;
 4105:                   }
 4106:               }
 4107:               if ($identifier ne '') {
 4108:                   my $id = join(',',@parts);
 4109:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
 4110:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
 4111:                       $hidestatus{$ign.'.'.$id} = 1;
 4112:                   }
 4113:               }
 4114:           } elsif ($data eq 'regrader') {
 4115:               if (($identifier ne '') && (@parts)) {
 4116:                   my $id = join(',',@parts);
 4117:                   $regraded{$ign.'.'.$id} = 1;
 4118:               }
 4119:           } 
 4120: 	} else {
 4121: 	  if ($#parts == 0) {
 4122: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 4123: 	  } else {
 4124: 	    $prevattempts.='<th>'.$ign.'</th>';
 4125: 	  }
 4126: 	}
 4127:       }
 4128:       $prevattempts.=&end_data_table_header_row();
 4129:       if ($getattempt eq '') {
 4130:         my (%solved,%resets,%probstatus);
 4131:         if (($identifier ne '') && (keys(%regraded) > 0)) {
 4132:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 4133:                 foreach my $id (keys(%regraded)) {
 4134:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
 4135:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
 4136:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
 4137:                         push(@{$resets{$id}},$version);
 4138:                     }
 4139:                 }
 4140:             }
 4141:         }
 4142: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 4143:             my (@hidden,@unsolved);
 4144:             if (%typeparts) {
 4145:                 foreach my $id (keys(%typeparts)) {
 4146:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
 4147:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 4148:                         push(@hidden,$id);
 4149:                     } elsif ($identifier ne '') {
 4150:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
 4151:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
 4152:                                 ($hidestatus{$id})) {
 4153:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
 4154:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
 4155:                                 push(@{$solved{$id}},$version);
 4156:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
 4157:                                      (ref($solved{$id}) eq 'ARRAY')) {
 4158:                                 my $skip;
 4159:                                 if (ref($resets{$id}) eq 'ARRAY') {
 4160:                                     foreach my $reset (@{$resets{$id}}) {
 4161:                                         if ($reset > $solved{$id}[-1]) {
 4162:                                             $skip=1;
 4163:                                             last;
 4164:                                         }
 4165:                                     }
 4166:                                 }
 4167:                                 unless ($skip) {
 4168:                                     my ($ign,$partslist) = split(/\./,$id,2);
 4169:                                     push(@unsolved,$partslist);
 4170:                                 }
 4171:                             }
 4172:                         }
 4173:                     }
 4174:                 }
 4175:             }
 4176:             $prevattempts.=&start_data_table_row().
 4177:                            '<td>'.&mt('Transaction [_1]',$version);
 4178:             if (@unsolved) {
 4179:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
 4180:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
 4181:                                  &mt('Hide').'</label></span>';
 4182:             }
 4183:             $prevattempts .= '</td>';
 4184:             if (@hidden) {
 4185:                 foreach my $key (sort(keys(%lasthash))) {
 4186:                     next if ($key =~ /\.foilorder$/);
 4187:                     my $hide;
 4188:                     foreach my $id (@hidden) {
 4189:                         if ($key =~ /^\Q$id\E/) {
 4190:                             $hide = 1;
 4191:                             last;
 4192:                         }
 4193:                     }
 4194:                     if ($hide) {
 4195:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4196:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 4197:                             my $value = &format_previous_attempt_value($key,
 4198:                                              $returnhash{$version.':'.$key});
 4199:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4200:                         } else {
 4201:                             $prevattempts.='<td>&nbsp;</td>';
 4202:                         }
 4203:                     } else {
 4204:                         if ($key =~ /\./) {
 4205:                             my $value = $returnhash{$version.':'.$key};
 4206:                             if ($key =~ /\.rndseed$/) {
 4207:                                 my ($id) = ($key =~ /^(.+)\.rndseed$/);
 4208:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4209:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4210:                                 }
 4211:                             }
 4212:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4213:                                            '&nbsp;</td>';
 4214:                         } else {
 4215:                             $prevattempts.='<td>&nbsp;</td>';
 4216:                         }
 4217:                     }
 4218:                 }
 4219:             } else {
 4220: 	        foreach my $key (sort(keys(%lasthash))) {
 4221:                     next if ($key =~ /\.foilorder$/);
 4222:                     my $value = $returnhash{$version.':'.$key};
 4223:                     if ($key =~ /\.rndseed$/) {
 4224:                         my ($id) = ($key =~ /^(.+)\.rndseed$/);
 4225:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4226:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4227:                         }
 4228:                     }
 4229:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4230:                                    '&nbsp;</td>';
 4231: 	        }
 4232:             }
 4233: 	    $prevattempts.=&end_data_table_row();
 4234: 	 }
 4235:       }
 4236:       my @currhidden = keys(%lasthidden);
 4237:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 4238:       foreach my $key (sort(keys(%lasthash))) {
 4239:           next if ($key =~ /\.foilorder$/);
 4240:           if (%typeparts) {
 4241:               my $hidden;
 4242:               foreach my $id (@currhidden) {
 4243:                   if ($key =~ /^\Q$id\E/) {
 4244:                       $hidden = 1;
 4245:                       last;
 4246:                   }
 4247:               }
 4248:               if ($hidden) {
 4249:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4250:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 4251:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4252:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4253:                           $value = &$gradesub($value);
 4254:                       }
 4255:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4256:                   } else {
 4257:                       $prevattempts.='<td>&nbsp;</td>';
 4258:                   }
 4259:               } else {
 4260:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4261:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4262:                       $value = &$gradesub($value);
 4263:                   }
 4264:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4265:               }
 4266:           } else {
 4267: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4268: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4269:                   $value = &$gradesub($value);
 4270:               }
 4271: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4272:           }
 4273:       }
 4274:       $prevattempts.= &end_data_table_row().&end_data_table();
 4275:     } else {
 4276:       $prevattempts=
 4277: 	  &start_data_table().&start_data_table_row().
 4278: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 4279: 	  &end_data_table_row().&end_data_table();
 4280:     }
 4281:   } else {
 4282:     $prevattempts=
 4283: 	  &start_data_table().&start_data_table_row().
 4284: 	  '<td>'.&mt('No data.').'</td>'.
 4285: 	  &end_data_table_row().&end_data_table();
 4286:   }
 4287: }
 4288: 
 4289: sub format_previous_attempt_value {
 4290:     my ($key,$value) = @_;
 4291:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 4292: 	$value = &Apache::lonlocal::locallocaltime($value);
 4293:     } elsif (ref($value) eq 'ARRAY') {
 4294: 	$value = '('.join(', ', @{ $value }).')';
 4295:     } elsif ($key =~ /answerstring$/) {
 4296:         my %answers = &Apache::lonnet::str2hash($value);
 4297:         my @anskeys = sort(keys(%answers));
 4298:         if (@anskeys == 1) {
 4299:             my $answer = $answers{$anskeys[0]};
 4300:             if ($answer =~ m{\0}) {
 4301:                 $answer =~ s{\0}{,}g;
 4302:             }
 4303:             my $tag_internal_answer_name = 'INTERNAL';
 4304:             if ($anskeys[0] eq $tag_internal_answer_name) {
 4305:                 $value = $answer; 
 4306:             } else {
 4307:                 $value = $anskeys[0].'='.$answer;
 4308:             }
 4309:         } else {
 4310:             foreach my $ans (@anskeys) {
 4311:                 my $answer = $answers{$ans};
 4312:                 if ($answer =~ m{\0}) {
 4313:                     $answer =~ s{\0}{,}g;
 4314:                 }
 4315:                 $value .=  $ans.'='.$answer.'<br />';;
 4316:             } 
 4317:         }
 4318:     } else {
 4319: 	$value = &unescape($value);
 4320:     }
 4321:     return $value;
 4322: }
 4323: 
 4324: 
 4325: sub relative_to_absolute {
 4326:     my ($url,$output)=@_;
 4327:     my $parser=HTML::TokeParser->new(\$output);
 4328:     my $token;
 4329:     my $thisdir=$url;
 4330:     my @rlinks=();
 4331:     while ($token=$parser->get_token) {
 4332: 	if ($token->[0] eq 'S') {
 4333: 	    if ($token->[1] eq 'a') {
 4334: 		if ($token->[2]->{'href'}) {
 4335: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 4336: 		}
 4337: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 4338: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 4339: 	    } elsif ($token->[1] eq 'base') {
 4340: 		$thisdir=$token->[2]->{'href'};
 4341: 	    }
 4342: 	}
 4343:     }
 4344:     $thisdir=~s-/[^/]*$--;
 4345:     foreach my $link (@rlinks) {
 4346: 	unless (($link=~/^https?\:\/\//i) ||
 4347: 		($link=~/^\//) ||
 4348: 		($link=~/^javascript:/i) ||
 4349: 		($link=~/^mailto:/i) ||
 4350: 		($link=~/^\#/)) {
 4351: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 4352: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 4353: 	}
 4354:     }
 4355: # -------------------------------------------------- Deal with Applet codebases
 4356:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 4357:     return $output;
 4358: }
 4359: 
 4360: =pod
 4361: 
 4362: =item * &get_student_view()
 4363: 
 4364: show a snapshot of what student was looking at
 4365: 
 4366: =cut
 4367: 
 4368: sub get_student_view {
 4369:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 4370:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4371:   my (%form);
 4372:   my @elements=('symb','courseid','domain','username');
 4373:   foreach my $element (@elements) {
 4374:       $form{'grade_'.$element}=eval '$'.$element #'
 4375:   }
 4376:   if (defined($moreenv)) {
 4377:       %form=(%form,%{$moreenv});
 4378:   }
 4379:   if (defined($target)) { $form{'grade_target'} = $target; }
 4380:   $feedurl=&Apache::lonnet::clutter($feedurl);
 4381:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 4382:   $userview=~s/\<body[^\>]*\>//gi;
 4383:   $userview=~s/\<\/body\>//gi;
 4384:   $userview=~s/\<html\>//gi;
 4385:   $userview=~s/\<\/html\>//gi;
 4386:   $userview=~s/\<head\>//gi;
 4387:   $userview=~s/\<\/head\>//gi;
 4388:   $userview=~s/action\s*\=/would_be_action\=/gi;
 4389:   $userview=&relative_to_absolute($feedurl,$userview);
 4390:   if (wantarray) {
 4391:      return ($userview,$response);
 4392:   } else {
 4393:      return $userview;
 4394:   }
 4395: }
 4396: 
 4397: sub get_student_view_with_retries {
 4398:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 4399: 
 4400:     my $ok = 0;                 # True if we got a good response.
 4401:     my $content;
 4402:     my $response;
 4403: 
 4404:     # Try to get the student_view done. within the retries count:
 4405:     
 4406:     do {
 4407:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 4408:          $ok      = $response->is_success;
 4409:          if (!$ok) {
 4410:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 4411:          }
 4412:          $retries--;
 4413:     } while (!$ok && ($retries > 0));
 4414:     
 4415:     if (!$ok) {
 4416:        $content = '';          # On error return an empty content.
 4417:     }
 4418:     if (wantarray) {
 4419:        return ($content, $response);
 4420:     } else {
 4421:        return $content;
 4422:     }
 4423: }
 4424: 
 4425: sub css_links {
 4426:     my ($currsymb,$level) = @_;
 4427:     my ($links,@symbs,%cssrefs,%httpref);
 4428:     if ($level eq 'map') {
 4429:         my $navmap = Apache::lonnavmaps::navmap->new();
 4430:         if (ref($navmap)) {
 4431:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
 4432:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
 4433:             foreach my $res (@resources) {
 4434:                 if (ref($res) && $res->symb()) {
 4435:                     push(@symbs,$res->symb());
 4436:                 }
 4437:             }
 4438:         }
 4439:     } else {
 4440:         @symbs = ($currsymb);
 4441:     }
 4442:     foreach my $symb (@symbs) {
 4443:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
 4444:         if ($css_href =~ /\S/) {
 4445:             unless ($css_href =~ m{https?://}) {
 4446:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
 4447:                 my $proburl =  &Apache::lonnet::clutter($url);
 4448:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
 4449:                 unless ($css_href =~ m{^/}) {
 4450:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
 4451:                 }
 4452:                 if ($css_href =~ m{^/(res|uploaded)/}) {
 4453:                     unless (($httpref{'httpref.'.$css_href}) ||
 4454:                             (&Apache::lonnet::is_on_map($css_href))) {
 4455:                         my $thisurl = $proburl;
 4456:                         if ($env{'httpref.'.$proburl}) {
 4457:                             $thisurl = $env{'httpref.'.$proburl};
 4458:                         }
 4459:                         $httpref{'httpref.'.$css_href} = $thisurl;
 4460:                     }
 4461:                 }
 4462:             }
 4463:             $cssrefs{$css_href} = 1;
 4464:         }
 4465:     }
 4466:     if (keys(%httpref)) {
 4467:         &Apache::lonnet::appenv(\%httpref);
 4468:     }
 4469:     if (keys(%cssrefs)) {
 4470:         foreach my $css_href (keys(%cssrefs)) {
 4471:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
 4472:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
 4473:         }
 4474:     }
 4475:     return $links;
 4476: }
 4477: 
 4478: =pod
 4479: 
 4480: =item * &get_student_answers() 
 4481: 
 4482: show a snapshot of how student was answering problem
 4483: 
 4484: =cut
 4485: 
 4486: sub get_student_answers {
 4487:   my ($symb,$username,$domain,$courseid,%form) = @_;
 4488:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4489:   my (%moreenv);
 4490:   my @elements=('symb','courseid','domain','username');
 4491:   foreach my $element (@elements) {
 4492:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 4493:   }
 4494:   $moreenv{'grade_target'}='answer';
 4495:   %moreenv=(%form,%moreenv);
 4496:   $feedurl = &Apache::lonnet::clutter($feedurl);
 4497:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 4498:   return $userview;
 4499: }
 4500: 
 4501: =pod
 4502: 
 4503: =item * &submlink()
 4504: 
 4505: Inputs: $text $uname $udom $symb $target
 4506: 
 4507: Returns: A link to grades.pm such as to see the SUBM view of a student
 4508: 
 4509: =cut
 4510: 
 4511: ###############################################
 4512: sub submlink {
 4513:     my ($text,$uname,$udom,$symb,$target)=@_;
 4514:     if (!($uname && $udom)) {
 4515: 	(my $cursymb, my $courseid,$udom,$uname)=
 4516: 	    &Apache::lonnet::whichuser($symb);
 4517: 	if (!$symb) { $symb=$cursymb; }
 4518:     }
 4519:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4520:     $symb=&escape($symb);
 4521:     if ($target) { $target=" target=\"$target\""; }
 4522:     return
 4523:         '<a href="/adm/grades?command=submission'.
 4524:         '&amp;symb='.$symb.
 4525:         '&amp;student='.$uname.
 4526:         '&amp;userdom='.$udom.'"'.
 4527:         $target.'>'.$text.'</a>';
 4528: }
 4529: ##############################################
 4530: 
 4531: =pod
 4532: 
 4533: =item * &pgrdlink()
 4534: 
 4535: Inputs: $text $uname $udom $symb $target
 4536: 
 4537: Returns: A link to grades.pm such as to see the PGRD view of a student
 4538: 
 4539: =cut
 4540: 
 4541: ###############################################
 4542: sub pgrdlink {
 4543:     my $link=&submlink(@_);
 4544:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 4545:     return $link;
 4546: }
 4547: ##############################################
 4548: 
 4549: =pod
 4550: 
 4551: =item * &pprmlink()
 4552: 
 4553: Inputs: $text $uname $udom $symb $target
 4554: 
 4555: Returns: A link to parmset.pm such as to see the PPRM view of a
 4556: student and a specific resource
 4557: 
 4558: =cut
 4559: 
 4560: ###############################################
 4561: sub pprmlink {
 4562:     my ($text,$uname,$udom,$symb,$target)=@_;
 4563:     if (!($uname && $udom)) {
 4564: 	(my $cursymb, my $courseid,$udom,$uname)=
 4565: 	    &Apache::lonnet::whichuser($symb);
 4566: 	if (!$symb) { $symb=$cursymb; }
 4567:     }
 4568:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4569:     $symb=&escape($symb);
 4570:     if ($target) { $target="target=\"$target\""; }
 4571:     return '<a href="/adm/parmset?command=set&amp;'.
 4572: 	'symb='.$symb.'&amp;uname='.$uname.
 4573: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 4574: }
 4575: ##############################################
 4576: 
 4577: =pod
 4578: 
 4579: =back
 4580: 
 4581: =cut
 4582: 
 4583: ###############################################
 4584: 
 4585: 
 4586: sub timehash {
 4587:     my ($thistime) = @_;
 4588:     my $timezone = &Apache::lonlocal::gettimezone();
 4589:     my $dt = DateTime->from_epoch(epoch => $thistime)
 4590:                      ->set_time_zone($timezone);
 4591:     my $wday = $dt->day_of_week();
 4592:     if ($wday == 7) { $wday = 0; }
 4593:     return ( 'second' => $dt->second(),
 4594:              'minute' => $dt->minute(),
 4595:              'hour'   => $dt->hour(),
 4596:              'day'     => $dt->day_of_month(),
 4597:              'month'   => $dt->month(),
 4598:              'year'    => $dt->year(),
 4599:              'weekday' => $wday,
 4600:              'dayyear' => $dt->day_of_year(),
 4601:              'dlsav'   => $dt->is_dst() );
 4602: }
 4603: 
 4604: sub utc_string {
 4605:     my ($date)=@_;
 4606:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 4607: }
 4608: 
 4609: sub maketime {
 4610:     my %th=@_;
 4611:     my ($epoch_time,$timezone,$dt);
 4612:     $timezone = &Apache::lonlocal::gettimezone();
 4613:     eval {
 4614:         $dt = DateTime->new( year   => $th{'year'},
 4615:                              month  => $th{'month'},
 4616:                              day    => $th{'day'},
 4617:                              hour   => $th{'hour'},
 4618:                              minute => $th{'minute'},
 4619:                              second => $th{'second'},
 4620:                              time_zone => $timezone,
 4621:                          );
 4622:     };
 4623:     if (!$@) {
 4624:         $epoch_time = $dt->epoch;
 4625:         if ($epoch_time) {
 4626:             return $epoch_time;
 4627:         }
 4628:     }
 4629:     return POSIX::mktime(
 4630:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 4631:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 4632: }
 4633: 
 4634: #########################################
 4635: 
 4636: sub findallcourses {
 4637:     my ($roles,$uname,$udom) = @_;
 4638:     my %roles;
 4639:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 4640:     my %courses;
 4641:     my $now=time;
 4642:     if (!defined($uname)) {
 4643:         $uname = $env{'user.name'};
 4644:     }
 4645:     if (!defined($udom)) {
 4646:         $udom = $env{'user.domain'};
 4647:     }
 4648:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 4649:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 4650:         if (!%roles) {
 4651:             %roles = (
 4652:                        cc => 1,
 4653:                        co => 1,
 4654:                        in => 1,
 4655:                        ep => 1,
 4656:                        ta => 1,
 4657:                        cr => 1,
 4658:                        st => 1,
 4659:              );
 4660:         }
 4661:         foreach my $entry (keys(%roleshash)) {
 4662:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 4663:             if ($trole =~ /^cr/) { 
 4664:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 4665:             } else {
 4666:                 next if (!exists($roles{$trole}));
 4667:             }
 4668:             if ($tend) {
 4669:                 next if ($tend < $now);
 4670:             }
 4671:             if ($tstart) {
 4672:                 next if ($tstart > $now);
 4673:             }
 4674:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 4675:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 4676:             my $value = $trole.'/'.$cdom.'/';
 4677:             if ($secpart eq '') {
 4678:                 ($cnum,$role) = split(/_/,$cnumpart); 
 4679:                 $sec = 'none';
 4680:                 $value .= $cnum.'/';
 4681:             } else {
 4682:                 $cnum = $cnumpart;
 4683:                 ($sec,$role) = split(/_/,$secpart);
 4684:                 $value .= $cnum.'/'.$sec;
 4685:             }
 4686:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4687:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4688:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4689:                 }
 4690:             } else {
 4691:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4692:             }
 4693:         }
 4694:     } else {
 4695:         foreach my $key (keys(%env)) {
 4696: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 4697:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 4698: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 4699: 	        next if ($role eq 'ca' || $role eq 'aa');
 4700: 	        next if (%roles && !exists($roles{$role}));
 4701: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 4702:                 my $active=1;
 4703:                 if ($starttime) {
 4704: 		    if ($now<$starttime) { $active=0; }
 4705:                 }
 4706:                 if ($endtime) {
 4707:                     if ($now>$endtime) { $active=0; }
 4708:                 }
 4709:                 if ($active) {
 4710:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 4711:                     if ($sec eq '') {
 4712:                         $sec = 'none';
 4713:                     } else {
 4714:                         $value .= $sec;
 4715:                     }
 4716:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4717:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4718:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4719:                         }
 4720:                     } else {
 4721:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4722:                     }
 4723:                 }
 4724:             }
 4725:         }
 4726:     }
 4727:     return %courses;
 4728: }
 4729: 
 4730: ###############################################
 4731: 
 4732: sub blockcheck {
 4733:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
 4734: 
 4735:     unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
 4736:         my ($has_evb,$check_ipaccess);
 4737:         my $dom = $env{'user.domain'};
 4738:         if ($env{'request.course.id'}) {
 4739:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4740:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4741:             my $checkrole = "cm./$cdom/$cnum";
 4742:             my $sec = $env{'request.course.sec'};
 4743:             if ($sec ne '') {
 4744:                 $checkrole .= "/$sec";
 4745:             }
 4746:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 4747:                 ($env{'request.role'} !~ /^st/)) {
 4748:                 $has_evb = 1;
 4749:             }
 4750:             unless ($has_evb) {
 4751:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
 4752:                     ($activity eq 'boards') || ($activity eq 'groups') || ($activity eq 'chat')) {
 4753:                     if ($udom eq $cdom) {
 4754:                         $check_ipaccess = 1;
 4755:                     }
 4756:                 }
 4757:             }
 4758:         } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
 4759:                 ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
 4760:             my $checkrole;
 4761:             if ($env{'request.role.domain'} eq '') {
 4762:                 $checkrole = "cm./$env{'user.domain'}/";
 4763:             } else {
 4764:                 $checkrole = "cm./$env{'request.role.domain'}/";
 4765:             }
 4766:             if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
 4767:                 $has_evb = 1;
 4768:             }
 4769:         }
 4770:         unless ($has_evb || $check_ipaccess) {
 4771:             my @machinedoms = &Apache::lonnet::current_machine_domains();
 4772:             if (($dom eq 'public') && ($activity eq 'port')) {
 4773:                 $dom = $udom;
 4774:             }
 4775:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
 4776:                 $check_ipaccess = 1;
 4777:             } else {
 4778:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 4779:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
 4780:                 my $prim = &Apache::lonnet::domain($dom,'primary');
 4781:                 my $intdom = &Apache::lonnet::internet_dom($prim);
 4782:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
 4783:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
 4784:                         $check_ipaccess = 1;
 4785:                     }
 4786:                 }
 4787:             }
 4788:         }
 4789:         if ($check_ipaccess) {
 4790:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
 4791:             unless (defined($cached)) {
 4792:                 my %domconfig =
 4793:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
 4794:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
 4795:             }
 4796:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
 4797:                 foreach my $id (keys(%{$ipaccessref})) {
 4798:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
 4799:                         my $range = $ipaccessref->{$id}->{'ip'};
 4800:                         if ($range) {
 4801:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
 4802:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
 4803:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
 4804:                                         return ('','','',$id,$dom);
 4805:                                         last;
 4806:                                     }
 4807:                                 }
 4808:                             }
 4809:                         }
 4810:                     }
 4811:                 }
 4812:             }
 4813:         }
 4814:         if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
 4815:             return ();
 4816:         }
 4817:     }
 4818:     if (defined($udom) && defined($uname)) {
 4819:         # If uname and udom are for a course, check for blocks in the course.
 4820:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
 4821:             my ($startblock,$endblock,$triggerblock) =
 4822:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
 4823:             return ($startblock,$endblock,$triggerblock);
 4824:         }
 4825:     } else {
 4826:         $udom = $env{'user.domain'};
 4827:         $uname = $env{'user.name'};
 4828:     }
 4829: 
 4830:     my $startblock = 0;
 4831:     my $endblock = 0;
 4832:     my $triggerblock = '';
 4833:     my %live_courses;
 4834:     unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
 4835:         %live_courses = &findallcourses(undef,$uname,$udom);
 4836:     }
 4837: 
 4838:     # If uname is for a user, and activity is course-specific, i.e.,
 4839:     # boards, chat or groups, check for blocking in current course only.
 4840: 
 4841:     if (($activity eq 'boards' || $activity eq 'chat' ||
 4842:          $activity eq 'groups' || $activity eq 'printout' ||
 4843:          $activity eq 'search' || $activity eq 'reinit' ||
 4844:          $activity eq 'alert') && ($env{'request.course.id'})) {
 4845:         foreach my $key (keys(%live_courses)) {
 4846:             if ($key ne $env{'request.course.id'}) {
 4847:                 delete($live_courses{$key});
 4848:             }
 4849:         }
 4850:     }
 4851: 
 4852:     my $otheruser = 0;
 4853:     my %own_courses;
 4854:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 4855:         # Resource belongs to user other than current user.
 4856:         $otheruser = 1;
 4857:         # Gather courses for current user
 4858:         %own_courses = 
 4859:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 4860:     }
 4861: 
 4862:     # Gather active course roles - course coordinator, instructor, 
 4863:     # exam proctor, ta, student, or custom role.
 4864: 
 4865:     foreach my $course (keys(%live_courses)) {
 4866:         my ($cdom,$cnum);
 4867:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 4868:             $cdom = $env{'course.'.$course.'.domain'};
 4869:             $cnum = $env{'course.'.$course.'.num'};
 4870:         } else {
 4871:             ($cdom,$cnum) = split(/_/,$course); 
 4872:         }
 4873:         my $no_ownblock = 0;
 4874:         my $no_userblock = 0;
 4875:         if ($otheruser && $activity ne 'com') {
 4876:             # Check if current user has 'evb' priv for this
 4877:             if (defined($own_courses{$course})) {
 4878:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 4879:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4880:                     if ($sec ne 'none') {
 4881:                         $checkrole .= '/'.$sec;
 4882:                     }
 4883:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4884:                         $no_ownblock = 1;
 4885:                         last;
 4886:                     }
 4887:                 }
 4888:             }
 4889:             # if they have 'evb' priv and are currently not playing student
 4890:             next if (($no_ownblock) &&
 4891:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 4892:         }
 4893:         foreach my $sec (keys(%{$live_courses{$course}})) {
 4894:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4895:             if ($sec ne 'none') {
 4896:                 $checkrole .= '/'.$sec;
 4897:             }
 4898:             if ($otheruser) {
 4899:                 # Resource belongs to user other than current user.
 4900:                 # Assemble privs for that user, and check for 'evb' priv.
 4901:                 my (%allroles,%userroles);
 4902:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 4903:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 4904:                         my ($trole,$tdom,$tnum,$tsec);
 4905:                         if ($entry =~ /^cr/) {
 4906:                             ($trole,$tdom,$tnum,$tsec) = 
 4907:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 4908:                         } else {
 4909:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 4910:                         }
 4911:                         my ($spec,$area,$trest);
 4912:                         $area = '/'.$tdom.'/'.$tnum;
 4913:                         $trest = $tnum;
 4914:                         if ($tsec ne '') {
 4915:                             $area .= '/'.$tsec;
 4916:                             $trest .= '/'.$tsec;
 4917:                         }
 4918:                         $spec = $trole.'.'.$area;
 4919:                         if ($trole =~ /^cr/) {
 4920:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 4921:                                                               $tdom,$spec,$trest,$area);
 4922:                         } else {
 4923:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 4924:                                                                 $tdom,$spec,$trest,$area);
 4925:                         }
 4926:                     }
 4927:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 4928:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 4929:                         if ($1) {
 4930:                             $no_userblock = 1;
 4931:                             last;
 4932:                         }
 4933:                     }
 4934:                 }
 4935:             } else {
 4936:                 # Resource belongs to current user
 4937:                 # Check for 'evb' priv via lonnet::allowed().
 4938:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4939:                     $no_ownblock = 1;
 4940:                     last;
 4941:                 }
 4942:             }
 4943:         }
 4944:         # if they have the evb priv and are currently not playing student
 4945:         next if (($no_ownblock) &&
 4946:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 4947:         next if ($no_userblock);
 4948: 
 4949:         # Retrieve blocking times and identity of blocker for course
 4950:         # of specified user, unless user has 'evb' privilege.
 4951:         
 4952:         my ($start,$end,$trigger) = 
 4953:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
 4954:         if (($start != 0) && 
 4955:             (($startblock == 0) || ($startblock > $start))) {
 4956:             $startblock = $start;
 4957:             if ($trigger ne '') {
 4958:                 $triggerblock = $trigger;
 4959:             }
 4960:         }
 4961:         if (($end != 0)  &&
 4962:             (($endblock == 0) || ($endblock < $end))) {
 4963:             $endblock = $end;
 4964:             if ($trigger ne '') {
 4965:                 $triggerblock = $trigger;
 4966:             }
 4967:         }
 4968:     }
 4969:     return ($startblock,$endblock,$triggerblock);
 4970: }
 4971: 
 4972: sub get_blocks {
 4973:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
 4974:     my $startblock = 0;
 4975:     my $endblock = 0;
 4976:     my $triggerblock = '';
 4977:     my $course = $cdom.'_'.$cnum;
 4978:     $setters->{$course} = {};
 4979:     $setters->{$course}{'staff'} = [];
 4980:     $setters->{$course}{'times'} = [];
 4981:     $setters->{$course}{'triggers'} = [];
 4982:     my (@blockers,%triggered);
 4983:     my $now = time;
 4984:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 4985:     if ($activity eq 'docs') {
 4986:         my ($blocked,$nosymbcache,$noenccheck);
 4987:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
 4988:             $blocked = 1;
 4989:             $nosymbcache = 1;
 4990:             $noenccheck = 1;
 4991:         }
 4992:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
 4993:         foreach my $block (@blockers) {
 4994:             if ($block =~ /^firstaccess____(.+)$/) {
 4995:                 my $item = $1;
 4996:                 my $type = 'map';
 4997:                 my $timersymb = $item;
 4998:                 if ($item eq 'course') {
 4999:                     $type = 'course';
 5000:                 } elsif ($item =~ /___\d+___/) {
 5001:                     $type = 'resource';
 5002:                 } else {
 5003:                     $timersymb = &Apache::lonnet::symbread($item);
 5004:                 }
 5005:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5006:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 5007:                 $triggered{$block} = {
 5008:                                        start => $start,
 5009:                                        end   => $end,
 5010:                                        type  => $type,
 5011:                                      };
 5012:             }
 5013:         }
 5014:     } else {
 5015:         foreach my $block (keys(%commblocks)) {
 5016:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 5017:                 my ($start,$end) = ($1,$2);
 5018:                 if ($start <= time && $end >= time) {
 5019:                     if (ref($commblocks{$block}) eq 'HASH') {
 5020:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5021:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5022:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 5023:                                     push(@blockers,$block);
 5024:                                 }
 5025:                             }
 5026:                         }
 5027:                     }
 5028:                 }
 5029:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 5030:                 my $item = $1;
 5031:                 my $timersymb = $item; 
 5032:                 my $type = 'map';
 5033:                 if ($item eq 'course') {
 5034:                     $type = 'course';
 5035:                 } elsif ($item =~ /___\d+___/) {
 5036:                     $type = 'resource';
 5037:                 } else {
 5038:                     $timersymb = &Apache::lonnet::symbread($item);
 5039:                 }
 5040:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5041:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 5042:                 if ($start && $end) {
 5043:                     if (($start <= time) && ($end >= time)) {
 5044:                         if (ref($commblocks{$block}) eq 'HASH') {
 5045:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5046:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5047:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
 5048:                                         push(@blockers,$block);
 5049:                                         $triggered{$block} = {
 5050:                                                                start => $start,
 5051:                                                                end   => $end,
 5052:                                                                type  => $type,
 5053:                                                              };
 5054:                                     }
 5055:                                 }
 5056:                             }
 5057:                         }
 5058:                     }
 5059:                 }
 5060:             }
 5061:         }
 5062:     }
 5063:     foreach my $blocker (@blockers) {
 5064:         my ($staff_name,$staff_dom,$title,$blocks) =
 5065:             &parse_block_record($commblocks{$blocker});
 5066:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 5067:         my ($start,$end,$triggertype);
 5068:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 5069:             ($start,$end) = ($1,$2);
 5070:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 5071:             $start = $triggered{$blocker}{'start'};
 5072:             $end = $triggered{$blocker}{'end'};
 5073:             $triggertype = $triggered{$blocker}{'type'};
 5074:         }
 5075:         if ($start) {
 5076:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 5077:             if ($triggertype) {
 5078:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 5079:             } else {
 5080:                 push(@{$$setters{$course}{'triggers'}},0);
 5081:             }
 5082:             if ( ($startblock == 0) || ($startblock > $start) ) {
 5083:                 $startblock = $start;
 5084:                 if ($triggertype) {
 5085:                     $triggerblock = $blocker;
 5086:                 }
 5087:             }
 5088:             if ( ($endblock == 0) || ($endblock < $end) ) {
 5089:                $endblock = $end;
 5090:                if ($triggertype) {
 5091:                    $triggerblock = $blocker;
 5092:                }
 5093:             }
 5094:         }
 5095:     }
 5096:     return ($startblock,$endblock,$triggerblock);
 5097: }
 5098: 
 5099: sub parse_block_record {
 5100:     my ($record) = @_;
 5101:     my ($setuname,$setudom,$title,$blocks);
 5102:     if (ref($record) eq 'HASH') {
 5103:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 5104:         $title = &unescape($record->{'event'});
 5105:         $blocks = $record->{'blocks'};
 5106:     } else {
 5107:         my @data = split(/:/,$record,3);
 5108:         if (scalar(@data) eq 2) {
 5109:             $title = $data[1];
 5110:             ($setuname,$setudom) = split(/@/,$data[0]);
 5111:         } else {
 5112:             ($setuname,$setudom,$title) = @data;
 5113:         }
 5114:         $blocks = { 'com' => 'on' };
 5115:     }
 5116:     return ($setuname,$setudom,$title,$blocks);
 5117: }
 5118: 
 5119: sub blocking_status {
 5120:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
 5121:     my %setters;
 5122: 
 5123: # check for active blocking
 5124:     if ($clientip eq '') {
 5125:         $clientip = &Apache::lonnet::get_requestor_ip();
 5126:     }
 5127:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
 5128:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
 5129:     my $blocked = 0;
 5130:     if (($startblock && $endblock) || ($by_ip)) {
 5131:         $blocked = 1;
 5132:     }
 5133: 
 5134: # caller just wants to know whether a block is active
 5135:     if (!wantarray) { return $blocked; }
 5136: 
 5137: # build a link to a popup window containing the details
 5138:     my $querystring  = "?activity=$activity";
 5139: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
 5140:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
 5141:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/);
 5142:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
 5143:     } elsif ($activity eq 'docs') {
 5144:         my $showurl = &Apache::lonenc::check_encrypt($url);
 5145:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
 5146:         if ($symb) {
 5147:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
 5148:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
 5149:         }
 5150:     }
 5151: 
 5152:     my $output .= <<'END_MYBLOCK';
 5153: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 5154:     var options = "width=" + w + ",height=" + h + ",";
 5155:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 5156:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 5157:     var newWin = window.open(url, wdwName, options);
 5158:     newWin.focus();
 5159: }
 5160: END_MYBLOCK
 5161: 
 5162:     $output = Apache::lonhtmlcommon::scripttag($output);
 5163:   
 5164:     my $popupUrl = "/adm/blockingstatus/$querystring";
 5165:     my $text = &mt('Communication Blocked');
 5166:     my $class = 'LC_comblock';
 5167:     if ($activity eq 'docs') {
 5168:         $text = &mt('Content Access Blocked');
 5169:         $class = '';
 5170:     } elsif ($activity eq 'printout') {
 5171:         $text = &mt('Printing Blocked');
 5172:     } elsif ($activity eq 'passwd') {
 5173:         $text = &mt('Password Changing Blocked');
 5174:     } elsif ($activity eq 'grades') {
 5175:         $text = &mt('Gradebook Blocked');
 5176:     } elsif ($activity eq 'search') {
 5177:         $text = &mt('Search Blocked');
 5178:     } elsif ($activity eq 'alert') {
 5179:         $text = &mt('Checking Critical Messages Blocked');
 5180:     } elsif ($activity eq 'reinit') {
 5181:         $text = &mt('Checking Course Update Blocked');
 5182:     } elsif ($activity eq 'about') {
 5183:         $text = &mt('Access to User Information Pages Blocked');
 5184:     } elsif ($activity eq 'wishlist') {
 5185:         $text = &mt('Access to Stored Links Blocked');
 5186:     } elsif ($activity eq 'annotate') {
 5187:         $text = &mt('Access to Annotations Blocked');
 5188:     }
 5189:     $output .= <<"END_BLOCK";
 5190: <div class='$class'>
 5191:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 5192:   title='$text'>
 5193:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 5194:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 5195:   title='$text'>$text</a>
 5196: </div>
 5197: 
 5198: END_BLOCK
 5199: 
 5200:     return ($blocked, $output);
 5201: }
 5202: 
 5203: ###############################################
 5204: 
 5205: sub check_ip_acc {
 5206:     my ($acc,$clientip)=@_;
 5207:     &Apache::lonxml::debug("acc is $acc");
 5208:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 5209:         return 1;
 5210:     }
 5211:     my $allowed=0;
 5212:     my $ip;
 5213:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
 5214:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
 5215:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
 5216:     } else {
 5217:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
 5218:         $ip = $remote_ip || $env{'request.host'} || $clientip;
 5219:     }
 5220: 
 5221:     my $name;
 5222:     my %access = (
 5223:                      allowfrom => 1,
 5224:                      denyfrom  => 0,
 5225:                  );
 5226:     my @allows;
 5227:     my @denies;
 5228:     foreach my $item (split(',',$acc)) {
 5229:         $item =~ s/^\s*//;
 5230:         $item =~ s/\s*$//;
 5231:         if ($item =~ /^\!(.+)$/) {
 5232:             push(@denies,$1);
 5233:         } else {
 5234:             push(@allows,$item);
 5235:         }
 5236:     }
 5237:     my $numdenies = scalar(@denies);
 5238:     my $numallows = scalar(@allows);
 5239:     my $count = 0;
 5240:     foreach my $pattern (@denies,@allows) {
 5241:         $count ++;
 5242:         my $acctype = 'allowfrom';
 5243:         if ($count <= $numdenies) {
 5244:             $acctype = 'denyfrom';
 5245:         }
 5246:         if ($pattern =~ /\*$/) {
 5247:             #35.8.*
 5248:             $pattern=~s/\*//;
 5249:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 5250:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 5251:             #35.8.3.[34-56]
 5252:             my $low=$2;
 5253:             my $high=$3;
 5254:             $pattern=$1;
 5255:             if ($ip =~ /^\Q$pattern\E/) {
 5256:                 my $last=(split(/\./,$ip))[3];
 5257:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
 5258:             }
 5259:         } elsif ($pattern =~ /^\*/) {
 5260:             #*.msu.edu
 5261:             $pattern=~s/\*//;
 5262:             if (!defined($name)) {
 5263:                 use Socket;
 5264:                 my $netaddr=inet_aton($ip);
 5265:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5266:             }
 5267:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5268:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 5269:             #127.0.0.1
 5270:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 5271:         } else {
 5272:             #some.name.com
 5273:             if (!defined($name)) {
 5274:                 use Socket;
 5275:                 my $netaddr=inet_aton($ip);
 5276:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5277:             }
 5278:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5279:         }
 5280:         if ($allowed =~ /^(0|1)$/) { last; }
 5281:     }
 5282:     if ($allowed eq '') {
 5283:         if ($numdenies && !$numallows) {
 5284:             $allowed = 1;
 5285:         } else {
 5286:             $allowed = 0;
 5287:         }
 5288:     }
 5289:     return $allowed;
 5290: }
 5291: 
 5292: ###############################################
 5293: 
 5294: =pod
 5295: 
 5296: =head1 Domain Template Functions
 5297: 
 5298: =over 4
 5299: 
 5300: =item * &determinedomain()
 5301: 
 5302: Inputs: $domain (usually will be undef)
 5303: 
 5304: Returns: Determines which domain should be used for designs
 5305: 
 5306: =cut
 5307: 
 5308: ###############################################
 5309: sub determinedomain {
 5310:     my $domain=shift;
 5311:     if (! $domain) {
 5312:         # Determine domain if we have not been given one
 5313:         $domain = &Apache::lonnet::default_login_domain();
 5314:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 5315:         if ($env{'request.role.domain'}) { 
 5316:             $domain=$env{'request.role.domain'}; 
 5317:         }
 5318:     }
 5319:     return $domain;
 5320: }
 5321: ###############################################
 5322: 
 5323: sub devalidate_domconfig_cache {
 5324:     my ($udom)=@_;
 5325:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 5326: }
 5327: 
 5328: # ---------------------- Get domain configuration for a domain
 5329: sub get_domainconf {
 5330:     my ($udom) = @_;
 5331:     my $cachetime=1800;
 5332:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 5333:     if (defined($cached)) { return %{$result}; }
 5334: 
 5335:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 5336: 					     ['login','rolecolors','autoenroll'],$udom);
 5337:     my (%designhash,%legacy);
 5338:     if (keys(%domconfig) > 0) {
 5339:         if (ref($domconfig{'login'}) eq 'HASH') {
 5340:             if (keys(%{$domconfig{'login'}})) {
 5341:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 5342:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5343:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
 5344:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5345:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
 5346:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
 5347:                                         if ($key eq 'loginvia') {
 5348:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 5349:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 5350:                                                 $designhash{$udom.'.login.loginvia'} = $server;
 5351:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 5352:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 5353:                                                 } else {
 5354:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 5355:                                                 }
 5356:                                             }
 5357:                                         } elsif ($key eq 'headtag') {
 5358:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
 5359:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
 5360:                                             }
 5361:                                         }
 5362:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
 5363:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
 5364:                                         }
 5365:                                     }
 5366:                                 }
 5367:                             }
 5368:                         } elsif ($key eq 'saml') {
 5369:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5370:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
 5371:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
 5372:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
 5373:                                         foreach my $item ('text','img','alt','url','title','notsso') {
 5374:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
 5375:                                         }
 5376:                                     }
 5377:                                 }
 5378:                             }
 5379:                         } else {
 5380:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 5381:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 5382:                                     $domconfig{'login'}{$key}{$img};
 5383:                             }
 5384:                         }
 5385:                     } else {
 5386:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 5387:                     }
 5388:                 }
 5389:             } else {
 5390:                 $legacy{'login'} = 1;
 5391:             }
 5392:         } else {
 5393:             $legacy{'login'} = 1;
 5394:         }
 5395:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 5396:             if (keys(%{$domconfig{'rolecolors'}})) {
 5397:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 5398:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 5399:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 5400:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 5401:                         }
 5402:                     }
 5403:                 }
 5404:             } else {
 5405:                 $legacy{'rolecolors'} = 1;
 5406:             }
 5407:         } else {
 5408:             $legacy{'rolecolors'} = 1;
 5409:         }
 5410:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5411:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 5412:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 5413:             }
 5414:         }
 5415:         if (keys(%legacy) > 0) {
 5416:             my %legacyhash = &get_legacy_domconf($udom);
 5417:             foreach my $item (keys(%legacyhash)) {
 5418:                 if ($item =~ /^\Q$udom\E\.login/) {
 5419:                     if ($legacy{'login'}) { 
 5420:                         $designhash{$item} = $legacyhash{$item};
 5421:                     }
 5422:                 } else {
 5423:                     if ($legacy{'rolecolors'}) {
 5424:                         $designhash{$item} = $legacyhash{$item};
 5425:                     }
 5426:                 }
 5427:             }
 5428:         }
 5429:     } else {
 5430:         %designhash = &get_legacy_domconf($udom); 
 5431:     }
 5432:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 5433: 				  $cachetime);
 5434:     return %designhash;
 5435: }
 5436: 
 5437: sub get_legacy_domconf {
 5438:     my ($udom) = @_;
 5439:     my %legacyhash;
 5440:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 5441:     my $designfile =  $designdir.'/'.$udom.'.tab';
 5442:     if (-e $designfile) {
 5443:         if ( open (my $fh,'<',$designfile) ) {
 5444:             while (my $line = <$fh>) {
 5445:                 next if ($line =~ /^\#/);
 5446:                 chomp($line);
 5447:                 my ($key,$val)=(split(/\=/,$line));
 5448:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 5449:             }
 5450:             close($fh);
 5451:         }
 5452:     }
 5453:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 5454:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 5455:     }
 5456:     return %legacyhash;
 5457: }
 5458: 
 5459: =pod
 5460: 
 5461: =item * &domainlogo()
 5462: 
 5463: Inputs: $domain (usually will be undef)
 5464: 
 5465: Returns: A link to a domain logo, if the domain logo exists.
 5466: If the domain logo does not exist, a description of the domain.
 5467: 
 5468: =cut
 5469: 
 5470: ###############################################
 5471: sub domainlogo {
 5472:     my $domain = &determinedomain(shift);
 5473:     my %designhash = &get_domainconf($domain);    
 5474:     # See if there is a logo
 5475:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 5476:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 5477:         if ($imgsrc =~ m{^/(adm|res)/}) {
 5478: 	    if ($imgsrc =~ m{^/res/}) {
 5479: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 5480: 		&Apache::lonnet::repcopy($local_name);
 5481: 	    }
 5482: 	   $imgsrc = &lonhttpdurl($imgsrc);
 5483:         }
 5484:         my $alttext = $domain;
 5485:         if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
 5486:             $alttext = $designhash{$domain.'.login.alttext_domlogo'};
 5487:         }
 5488:         return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
 5489:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 5490:         return &Apache::lonnet::domain($domain,'description');
 5491:     } else {
 5492:         return '';
 5493:     }
 5494: }
 5495: ##############################################
 5496: 
 5497: =pod
 5498: 
 5499: =item * &designparm()
 5500: 
 5501: Inputs: $which parameter; $domain (usually will be undef)
 5502: 
 5503: Returns: value of designparamter $which
 5504: 
 5505: =cut
 5506: 
 5507: 
 5508: ##############################################
 5509: sub designparm {
 5510:     my ($which,$domain)=@_;
 5511:     if (exists($env{'environment.color.'.$which})) {
 5512:         return $env{'environment.color.'.$which};
 5513:     }
 5514:     $domain=&determinedomain($domain);
 5515:     my %domdesign;
 5516:     unless ($domain eq 'public') {
 5517:         %domdesign = &get_domainconf($domain);
 5518:     }
 5519:     my $output;
 5520:     if ($domdesign{$domain.'.'.$which} ne '') {
 5521:         $output = $domdesign{$domain.'.'.$which};
 5522:     } else {
 5523:         $output = $defaultdesign{$which};
 5524:     }
 5525:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 5526:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 5527:         if ($output =~ m{^/(adm|res)/}) {
 5528:             if ($output =~ m{^/res/}) {
 5529:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 5530:                 &Apache::lonnet::repcopy($local_name);
 5531:             }
 5532:             $output = &lonhttpdurl($output);
 5533:         }
 5534:     }
 5535:     return $output;
 5536: }
 5537: 
 5538: ##############################################
 5539: =pod
 5540: 
 5541: =item * &authorspace()
 5542: 
 5543: Inputs: $url (usually will be undef).
 5544: 
 5545: Returns: Path to Authoring Space containing the resource or 
 5546:          directory being viewed (or for which action is being taken). 
 5547:          If $url is provided, and begins /priv/<domain>/<uname>
 5548:          the path will be that portion of the $context argument.
 5549:          Otherwise the path will be for the author space of the current
 5550:          user when the current role is author, or for that of the 
 5551:          co-author/assistant co-author space when the current role 
 5552:          is co-author or assistant co-author.
 5553: 
 5554: =cut
 5555: 
 5556: sub authorspace {
 5557:     my ($url) = @_;
 5558:     if ($url ne '') {
 5559:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 5560:            return $1;
 5561:         }
 5562:     }
 5563:     my $caname = '';
 5564:     my $cadom = '';
 5565:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 5566:         ($cadom,$caname) =
 5567:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 5568:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 5569:         $caname = $env{'user.name'};
 5570:         $cadom = $env{'user.domain'};
 5571:     }
 5572:     if (($caname ne '') && ($cadom ne '')) {
 5573:         return "/priv/$cadom/$caname/";
 5574:     }
 5575:     return;
 5576: }
 5577: 
 5578: ##############################################
 5579: =pod
 5580: 
 5581: =item * &head_subbox()
 5582: 
 5583: Inputs: $content (contains HTML code with page functions, etc.)
 5584: 
 5585: Returns: HTML div with $content
 5586:          To be included in page header
 5587: 
 5588: =cut
 5589: 
 5590: sub head_subbox {
 5591:     my ($content)=@_;
 5592:     my $output =
 5593:         '<div class="LC_head_subbox">'
 5594:        .$content
 5595:        .'</div>'
 5596: }
 5597: 
 5598: ##############################################
 5599: =pod
 5600: 
 5601: =item * &CSTR_pageheader()
 5602: 
 5603: Input: (optional) filename from which breadcrumb trail is built.
 5604:        In most cases no input as needed, as $env{'request.filename'}
 5605:        is appropriate for use in building the breadcrumb trail.
 5606: 
 5607: Returns: HTML div with CSTR path and recent box
 5608:          To be included on Authoring Space pages
 5609: 
 5610: =cut
 5611: 
 5612: sub CSTR_pageheader {
 5613:     my ($trailfile) = @_;
 5614:     if ($trailfile eq '') {
 5615:         $trailfile = $env{'request.filename'};
 5616:     }
 5617: 
 5618: # this is for resources; directories have customtitle, and crumbs
 5619: # and select recent are created in lonpubdir.pm
 5620: 
 5621:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 5622:     my ($udom,$uname,$thisdisfn)=
 5623:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 5624:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 5625:     $formaction =~ s{/+}{/}g;
 5626: 
 5627:     my $parentpath = '';
 5628:     my $lastitem = '';
 5629:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 5630:         $parentpath = $1;
 5631:         $lastitem = $2;
 5632:     } else {
 5633:         $lastitem = $thisdisfn;
 5634:     }
 5635: 
 5636:     my $output =
 5637:          '<div>'
 5638:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 5639:         .'<b>'.&mt('Authoring Space:').'</b> '
 5640:         .'<form name="dirs" method="post" action="'.$formaction
 5641:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
 5642:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
 5643: 
 5644:     if ($lastitem) {
 5645:         $output .=
 5646:              '<span class="LC_filename">'
 5647:             .$lastitem
 5648:             .'</span>';
 5649:     }
 5650:     $output .=
 5651:          '<br />'
 5652:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 5653:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 5654:         .'</form>'
 5655:         .&Apache::lonmenu::constspaceform()
 5656:         .'</div>';
 5657: 
 5658:     return $output;
 5659: }
 5660: 
 5661: ###############################################
 5662: ###############################################
 5663: 
 5664: =pod
 5665: 
 5666: =back
 5667: 
 5668: =head1 HTML Helpers
 5669: 
 5670: =over 4
 5671: 
 5672: =item * &bodytag()
 5673: 
 5674: Returns a uniform header for LON-CAPA web pages.
 5675: 
 5676: Inputs: 
 5677: 
 5678: =over 4
 5679: 
 5680: =item * $title, A title to be displayed on the page.
 5681: 
 5682: =item * $function, the current role (can be undef).
 5683: 
 5684: =item * $addentries, extra parameters for the <body> tag.
 5685: 
 5686: =item * $bodyonly, if defined, only return the <body> tag.
 5687: 
 5688: =item * $domain, if defined, force a given domain.
 5689: 
 5690: =item * $forcereg, if page should register as content page (relevant for 
 5691:             text interface only)
 5692: 
 5693: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 5694:                      navigational links
 5695: 
 5696: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 5697: 
 5698: =item * $no_inline_link, if true and in remote mode, don't show the
 5699:          'Switch To Inline Menu' link
 5700: 
 5701: =item * $args, optional argument valid values are
 5702:             no_auto_mt_title -> prevents &mt()ing the title arg
 5703:             use_absolute     -> for external resource or syllabus, this will
 5704:                                 contain https://<hostname> if server uses
 5705:                                 https (as per hosts.tab), but request is for http
 5706:             hostname         -> hostname, from $r->hostname().
 5707: 
 5708: =item * $advtoolsref, optional argument, ref to an array containing
 5709:             inlineremote items to be added in "Functions" menu below
 5710:             breadcrumbs.
 5711: 
 5712: =item * $ltiscope, optional argument, will be one of: resource, map or
 5713:             course, if LON-CAPA is in LTI Provider context. Value is
 5714:             the scope of use, i.e., launch was for access to a single, a map
 5715:             or the entire course.
 5716: 
 5717: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
 5718:             context, this will contain the URL for the landing item in
 5719:             the course, after launch from an LTI Consumer
 5720: 
 5721: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
 5722:             context, this will contain a reference to hash of items
 5723:             to be included in the page header and/or inline menu.
 5724: 
 5725: =back
 5726: 
 5727: Returns: A uniform header for LON-CAPA web pages.  
 5728: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 5729: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 5730: other decorations will be returned.
 5731: 
 5732: =cut
 5733: 
 5734: sub bodytag {
 5735:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 5736:         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref,
 5737:         $ltiscope,$ltiuri,$ltimenu,$menucoll,$menuref)=@_;
 5738: 
 5739:     my $public;
 5740:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 5741:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 5742:         $public = 1;
 5743:     }
 5744:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5745:     my $httphost = $args->{'use_absolute'};
 5746:     my $hostname = $args->{'hostname'};
 5747: 
 5748:     $function = &get_users_function() if (!$function);
 5749:     my $img =    &designparm($function.'.img',$domain);
 5750:     my $font =   &designparm($function.'.font',$domain);
 5751:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 5752: 
 5753:     my %design = ( 'style'   => 'margin-top: 0',
 5754: 		   'bgcolor' => $pgbg,
 5755: 		   'text'    => $font,
 5756:                    'alink'   => &designparm($function.'.alink',$domain),
 5757: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 5758: 		   'link'    => &designparm($function.'.link',$domain),);
 5759:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 5760: 
 5761:  # role and realm
 5762:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
 5763:     if ($realm) {
 5764:         $realm = '/'.$realm;
 5765:     }
 5766:     if ($role eq 'ca') {
 5767:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 5768:         $realm = &plainname($rname,$rdom);
 5769:     } 
 5770: # realm
 5771:     my ($cid,$sec);
 5772:     if ($env{'request.course.id'}) {
 5773:         $cid = $env{'request.course.id'};
 5774:         if ($env{'request.course.sec'}) {
 5775:             $sec = $env{'request.course.sec'};
 5776:         }
 5777:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
 5778:         if (&Apache::lonnet::is_course($1,$2)) {
 5779:             $cid = $1.'_'.$2;
 5780:             $sec = $3;
 5781:         }
 5782:     }
 5783:     if ($cid) {
 5784:         if ($env{'request.role'} !~ /^cr/) {
 5785:             $role = &Apache::lonnet::plaintext($role,&course_type());
 5786:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
 5787:             if ($env{'request.role.desc'}) {
 5788:                 $role = $env{'request.role.desc'};
 5789:             } else {
 5790:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
 5791:             }
 5792:         } else {
 5793:             $role = (split(/\//,$role,4))[-1];
 5794:         }
 5795:         if ($sec) {
 5796:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
 5797:         }   
 5798: 	$realm = $env{'course.'.$cid.'.description'};
 5799:     } else {
 5800:         $role = &Apache::lonnet::plaintext($role);
 5801:     }
 5802: 
 5803:     if (!$realm) { $realm='&nbsp;'; }
 5804: 
 5805:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 5806: 
 5807: # construct main body tag
 5808:     my $bodytag = "<body $extra_body_attr>".
 5809: 	&Apache::lontexconvert::init_math_support();
 5810: 
 5811:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 5812: 
 5813:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 5814:         return $bodytag;
 5815:     }
 5816: 
 5817:     if ($public) {
 5818: 	undef($role);
 5819:     }
 5820: 
 5821:     my $showcrstitle = 1;
 5822:     if (($cid) && ($env{'request.lti.login'})) {
 5823:         if (ref($ltimenu) eq 'HASH') {
 5824:             unless ($ltimenu->{'role'}) {
 5825:                 undef($role);
 5826:             }
 5827:             unless ($ltimenu->{'coursetitle'}) {
 5828:                 $realm='&nbsp;';
 5829:                 $showcrstitle = 0;
 5830:             }
 5831:         }
 5832:     } elsif (($cid) && ($menucoll)) {
 5833:         if (ref($menuref) eq 'HASH') {
 5834:             unless ($menuref->{'role'}) {
 5835:                 undef($role);
 5836:             }
 5837:             unless ($menuref->{'crs'}) {
 5838:                 $realm='&nbsp;';
 5839:                 $showcrstitle = 0;
 5840:             }
 5841:         }
 5842:     }
 5843: 
 5844:     my $titleinfo = '<h1>'.$title.'</h1>';
 5845:     #
 5846:     # Extra info if you are the DC
 5847:     my $dc_info = '';
 5848:     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
 5849:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
 5850:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 5851:         $dc_info =~ s/\s+$//;
 5852:     }
 5853: 
 5854:     my $crstype;
 5855:     if ($cid) {
 5856:         $crstype = $env{'course.'.$cid.'.type'};
 5857:     } elsif ($args->{'crstype'}) {
 5858:         $crstype = $args->{'crstype'};
 5859:     }
 5860: 
 5861:     $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
 5862: 
 5863:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 5864: 
 5865: 
 5866: 
 5867:     my $funclist;
 5868:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
 5869:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
 5870:                     Apache::lonmenu::serverform();
 5871:         my $forbodytag;
 5872:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5873:                                             $forcereg,$args->{'group'},
 5874:                                             $args->{'bread_crumbs'},
 5875:                                             $advtoolsref,'','',\$forbodytag);
 5876:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 5877:             $funclist = $forbodytag;
 5878:         }
 5879:     } else {
 5880: 
 5881:         #    if ($env{'request.state'} eq 'construct') {
 5882:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 5883:         #    }
 5884: 
 5885:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 5886:             Apache::lonmenu::utilityfunctions($httphost), 'start');
 5887: 
 5888:         unless ($args->{'no_primary_menu'}) {
 5889:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
 5890:                                                               $args->{'links_disabled'});
 5891:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 5892:                 if ($dc_info) {
 5893:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 5894:                 }
 5895:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 5896:                                <em>$realm</em> $dc_info</div>|;
 5897:                 return $bodytag;
 5898:             }
 5899: 
 5900:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 5901:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 5902:             }
 5903: 
 5904:             $bodytag .= $right;
 5905: 
 5906:             if ($dc_info) {
 5907:                 $dc_info = &dc_courseid_toggle($dc_info);
 5908:             }
 5909:             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 5910:         }
 5911: 
 5912:         #if directed to not display the secondary menu, don't.
 5913:         if ($args->{'no_secondary_menu'}) {
 5914:             return $bodytag;
 5915:         }
 5916:         #don't show menus for public users
 5917:         if (!$public){
 5918:             unless ($args->{'no_inline_menu'}) {
 5919:                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
 5920:                                                             $args->{'no_primary_menu'},
 5921:                                                             $menucoll,$menuref,
 5922:                                                             $args->{'links_disabled'});
 5923:             }
 5924:             $bodytag .= Apache::lonmenu::serverform();
 5925:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 5926:             if ($env{'request.state'} eq 'construct') {
 5927:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 5928:                                 $args->{'bread_crumbs'},'','',$hostname,$ltiscope,$ltiuri);
 5929:             } elsif ($forcereg) {
 5930:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 5931:                                                             $args->{'group'},
 5932:                                                             $args->{'hide_buttons'},
 5933:                                                             $hostname,$ltiscope,$ltiuri);
 5934:             } else {
 5935:                 my $forbodytag;
 5936:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5937:                                                     $forcereg,$args->{'group'},
 5938:                                                     $args->{'bread_crumbs'},
 5939:                                                     $advtoolsref,'',$hostname,
 5940:                                                     \$forbodytag);
 5941:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 5942:                     $bodytag .= $forbodytag;
 5943:                 }
 5944:             }
 5945:         }else{
 5946:             # this is to seperate menu from content when there's no secondary
 5947:             # menu. Especially needed for public accessible ressources.
 5948:             $bodytag .= '<hr style="clear:both" />';
 5949:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 5950:         }
 5951: 
 5952:         return $bodytag;
 5953:     }
 5954: 
 5955: #
 5956: # Top frame rendering, Remote is up
 5957: #
 5958: 
 5959:     my $imgsrc = $img;
 5960:     if ($img =~ /^\/adm/) {
 5961:         $imgsrc = &lonhttpdurl($img);
 5962:     }
 5963:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 5964: 
 5965:     my $help=($no_inline_link?''
 5966:               :&Apache::loncommon::top_nav_help('Help'));
 5967: 
 5968:     # Explicit link to get inline menu
 5969:     my $menu= ($no_inline_link?''
 5970:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
 5971: 
 5972:     if ($dc_info) {
 5973:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
 5974:     }
 5975: 
 5976:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 5977:     unless ($public) {
 5978:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
 5979:                                 undef,'LC_menubuttons_link');
 5980:     }
 5981: 
 5982:     unless ($env{'form.inhibitmenu'}) {
 5983:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
 5984:                        <ol class="LC_primary_menu LC_floatright LC_right">
 5985:                        <li>$help</li>
 5986:                        <li>$menu</li>
 5987:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
 5988:     }
 5989:     if ($env{'request.state'} eq 'construct') {
 5990:         if (!$public){
 5991:             if ($env{'request.state'} eq 'construct') {
 5992:                 $funclist = &Apache::lonhtmlcommon::scripttag(
 5993:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
 5994:                             &Apache::lonhtmlcommon::scripttag('','end').
 5995:                             &Apache::lonmenu::innerregister($forcereg,
 5996:                                                             $args->{'bread_crumbs'});
 5997:             }
 5998:         }
 5999:     }
 6000:     return $bodytag."\n".$funclist;
 6001: }
 6002: 
 6003: sub dc_courseid_toggle {
 6004:     my ($dc_info) = @_;
 6005:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 6006:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 6007:            &mt('(More ...)').'</a></span>'.
 6008:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 6009: }
 6010: 
 6011: sub make_attr_string {
 6012:     my ($register,$attr_ref) = @_;
 6013: 
 6014:     if ($attr_ref && !ref($attr_ref)) {
 6015: 	die("addentries Must be a hash ref ".
 6016: 	    join(':',caller(1))." ".
 6017: 	    join(':',caller(0))." ");
 6018:     }
 6019: 
 6020:     if ($register) {
 6021: 	my ($on_load,$on_unload);
 6022: 	foreach my $key (keys(%{$attr_ref})) {
 6023: 	    if      (lc($key) eq 'onload') {
 6024: 		$on_load.=$attr_ref->{$key}.';';
 6025: 		delete($attr_ref->{$key});
 6026: 
 6027: 	    } elsif (lc($key) eq 'onunload') {
 6028: 		$on_unload.=$attr_ref->{$key}.';';
 6029: 		delete($attr_ref->{$key});
 6030: 	    }
 6031: 	}
 6032:         if ($env{'environment.remote'} eq 'on') {
 6033:             $attr_ref->{'onload'}  =
 6034:                 &Apache::lonmenu::loadevents().  $on_load;
 6035:             $attr_ref->{'onunload'}=
 6036:                 &Apache::lonmenu::unloadevents().$on_unload;
 6037:         } else {  
 6038: 	    $attr_ref->{'onload'}  = $on_load;
 6039: 	    $attr_ref->{'onunload'}= $on_unload;
 6040:         }
 6041:     }
 6042: 
 6043:     my $attr_string;
 6044:     foreach my $attr (sort(keys(%$attr_ref))) {
 6045: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 6046:     }
 6047:     return $attr_string;
 6048: }
 6049: 
 6050: 
 6051: ###############################################
 6052: ###############################################
 6053: 
 6054: =pod
 6055: 
 6056: =item * &endbodytag()
 6057: 
 6058: Returns a uniform footer for LON-CAPA web pages.
 6059: 
 6060: Inputs: 1 - optional reference to an args hash
 6061: If in the hash, key for noredirectlink has a value which evaluates to true,
 6062: a 'Continue' link is not displayed if the page contains an
 6063: internal redirect in the <head></head> section,
 6064: i.e., $env{'internal.head.redirect'} exists   
 6065: 
 6066: =cut
 6067: 
 6068: sub endbodytag {
 6069:     my ($args) = @_;
 6070:     my $endbodytag;
 6071:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 6072:         $endbodytag='</body>';
 6073:     }
 6074:     if ( exists( $env{'internal.head.redirect'} ) ) {
 6075:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 6076: 	    $endbodytag=
 6077: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 6078: 	        &mt('Continue').'</a>'.
 6079: 	        $endbodytag;
 6080:         }
 6081:     }
 6082:     return $endbodytag;
 6083: }
 6084: 
 6085: =pod
 6086: 
 6087: =item * &standard_css()
 6088: 
 6089: Returns a style sheet
 6090: 
 6091: Inputs: (all optional)
 6092:             domain         -> force to color decorate a page for a specific
 6093:                                domain
 6094:             function       -> force usage of a specific rolish color scheme
 6095:             bgcolor        -> override the default page bgcolor
 6096: 
 6097: =cut
 6098: 
 6099: sub standard_css {
 6100:     my ($function,$domain,$bgcolor) = @_;
 6101:     $function  = &get_users_function() if (!$function);
 6102:     my $img    = &designparm($function.'.img',   $domain);
 6103:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 6104:     my $font   = &designparm($function.'.font',  $domain);
 6105:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 6106: #second colour for later usage
 6107:     my $sidebg = &designparm($function.'.sidebg',$domain);
 6108:     my $pgbg_or_bgcolor =
 6109: 	         $bgcolor ||
 6110: 	         &designparm($function.'.pgbg',  $domain);
 6111:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 6112:     my $alink  = &designparm($function.'.alink', $domain);
 6113:     my $vlink  = &designparm($function.'.vlink', $domain);
 6114:     my $link   = &designparm($function.'.link',  $domain);
 6115: 
 6116:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 6117:     my $mono                 = 'monospace';
 6118:     my $data_table_head      = $sidebg;
 6119:     my $data_table_light     = '#FAFAFA';
 6120:     my $data_table_dark      = '#E0E0E0';
 6121:     my $data_table_darker    = '#CCCCCC';
 6122:     my $data_table_highlight = '#FFFF00';
 6123:     my $mail_new             = '#FFBB77';
 6124:     my $mail_new_hover       = '#DD9955';
 6125:     my $mail_read            = '#BBBB77';
 6126:     my $mail_read_hover      = '#999944';
 6127:     my $mail_replied         = '#AAAA88';
 6128:     my $mail_replied_hover   = '#888855';
 6129:     my $mail_other           = '#99BBBB';
 6130:     my $mail_other_hover     = '#669999';
 6131:     my $table_header         = '#DDDDDD';
 6132:     my $feedback_link_bg     = '#BBBBBB';
 6133:     my $lg_border_color      = '#C8C8C8';
 6134:     my $button_hover         = '#BF2317';
 6135: 
 6136:     my $border = ($env{'browser.type'} eq 'explorer' ||
 6137:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 6138:                                              : '0 3px 0 4px';
 6139: 
 6140: 
 6141:     return <<END;
 6142: 
 6143: /* needed for iframe to allow 100% height in FF */
 6144: body, html { 
 6145:     margin: 0;
 6146:     padding: 0 0.5%;
 6147:     height: 99%; /* to avoid scrollbars */
 6148: }
 6149: 
 6150: body {
 6151:   font-family: $sans;
 6152:   line-height:130%;
 6153:   font-size:0.83em;
 6154:   color:$font;
 6155: }
 6156: 
 6157: a:focus,
 6158: a:focus img {
 6159:   color: red;
 6160: }
 6161: 
 6162: form, .inline {
 6163:   display: inline;
 6164: }
 6165: 
 6166: .LC_right {
 6167:   text-align:right;
 6168: }
 6169: 
 6170: .LC_middle {
 6171:   vertical-align:middle;
 6172: }
 6173: 
 6174: .LC_floatleft {
 6175:   float: left;
 6176: }
 6177: 
 6178: .LC_floatright {
 6179:   float: right;
 6180: }
 6181: 
 6182: .LC_400Box {
 6183:   width:400px;
 6184: }
 6185: 
 6186: .LC_iframecontainer {
 6187:     width: 98%;
 6188:     margin: 0;
 6189:     position: fixed;
 6190:     top: 8.5em;
 6191:     bottom: 0;
 6192: }
 6193: 
 6194: .LC_iframecontainer iframe{
 6195:     border: none;
 6196:     width: 100%;
 6197:     height: 100%;
 6198: }
 6199: 
 6200: .LC_filename {
 6201:   font-family: $mono;
 6202:   white-space:pre;
 6203:   font-size: 120%;
 6204: }
 6205: 
 6206: .LC_fileicon {
 6207:   border: none;
 6208:   height: 1.3em;
 6209:   vertical-align: text-bottom;
 6210:   margin-right: 0.3em;
 6211:   text-decoration:none;
 6212: }
 6213: 
 6214: .LC_setting {
 6215:   text-decoration:underline;
 6216: }
 6217: 
 6218: .LC_error {
 6219:   color: red;
 6220: }
 6221: 
 6222: .LC_warning {
 6223:   color: darkorange;
 6224: }
 6225: 
 6226: .LC_diff_removed {
 6227:   color: red;
 6228: }
 6229: 
 6230: .LC_info,
 6231: .LC_success,
 6232: .LC_diff_added {
 6233:   color: green;
 6234: }
 6235: 
 6236: div.LC_confirm_box {
 6237:   background-color: #FAFAFA;
 6238:   border: 1px solid $lg_border_color;
 6239:   margin-right: 0;
 6240:   padding: 5px;
 6241: }
 6242: 
 6243: div.LC_confirm_box .LC_error img,
 6244: div.LC_confirm_box .LC_success img {
 6245:   vertical-align: middle;
 6246: }
 6247: 
 6248: .LC_maxwidth {
 6249:   max-width: 100%;
 6250:   height: auto;
 6251: }
 6252: 
 6253: .LC_textsize_mobile {
 6254:   \@media only screen and (max-device-width: 480px) {
 6255:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
 6256:   }
 6257: }
 6258: 
 6259: .LC_icon {
 6260:   border: none;
 6261:   vertical-align: middle;
 6262: }
 6263: 
 6264: .LC_docs_spacer {
 6265:   width: 25px;
 6266:   height: 1px;
 6267:   border: none;
 6268: }
 6269: 
 6270: .LC_internal_info {
 6271:   color: #999999;
 6272: }
 6273: 
 6274: .LC_discussion {
 6275:   background: $data_table_dark;
 6276:   border: 1px solid black;
 6277:   margin: 2px;
 6278: }
 6279: 
 6280: .LC_disc_action_left {
 6281:   background: $sidebg;
 6282:   text-align: left;
 6283:   padding: 4px;
 6284:   margin: 2px;
 6285: }
 6286: 
 6287: .LC_disc_action_right {
 6288:   background: $sidebg;
 6289:   text-align: right;
 6290:   padding: 4px;
 6291:   margin: 2px;
 6292: }
 6293: 
 6294: .LC_disc_new_item {
 6295:   background: white;
 6296:   border: 2px solid red;
 6297:   margin: 4px;
 6298:   padding: 4px;
 6299: }
 6300: 
 6301: .LC_disc_old_item {
 6302:   background: white;
 6303:   margin: 4px;
 6304:   padding: 4px;
 6305: }
 6306: 
 6307: table.LC_pastsubmission {
 6308:   border: 1px solid black;
 6309:   margin: 2px;
 6310: }
 6311: 
 6312: table#LC_menubuttons {
 6313:   width: 100%;
 6314:   background: $pgbg;
 6315:   border: 2px;
 6316:   border-collapse: separate;
 6317:   padding: 0;
 6318: }
 6319: 
 6320: table#LC_title_bar a {
 6321:   color: $fontmenu;
 6322: }
 6323: 
 6324: table#LC_title_bar {
 6325:   clear: both;
 6326:   display: none;
 6327: }
 6328: 
 6329: table#LC_title_bar,
 6330: table.LC_breadcrumbs, /* obsolete? */
 6331: table#LC_title_bar.LC_with_remote {
 6332:   width: 100%;
 6333:   border-color: $pgbg;
 6334:   border-style: solid;
 6335:   border-width: $border;
 6336:   background: $pgbg;
 6337:   color: $fontmenu;
 6338:   border-collapse: collapse;
 6339:   padding: 0;
 6340:   margin: 0;
 6341: }
 6342: 
 6343: ul.LC_breadcrumb_tools_outerlist {
 6344:     margin: 0;
 6345:     padding: 0;
 6346:     position: relative;
 6347:     list-style: none;
 6348: }
 6349: ul.LC_breadcrumb_tools_outerlist li {
 6350:     display: inline;
 6351: }
 6352: 
 6353: .LC_breadcrumb_tools_navigation {
 6354:     padding: 0;
 6355:     margin: 0;
 6356:     float: left;
 6357: }
 6358: .LC_breadcrumb_tools_tools {
 6359:     padding: 0;
 6360:     margin: 0;
 6361:     float: right;
 6362: }
 6363: 
 6364: table#LC_title_bar td {
 6365:   background: $tabbg;
 6366: }
 6367: 
 6368: table#LC_menubuttons img {
 6369:   border: none;
 6370: }
 6371: 
 6372: .LC_breadcrumbs_component {
 6373:   float: right;
 6374:   margin: 0 1em;
 6375: }
 6376: .LC_breadcrumbs_component img {
 6377:   vertical-align: middle;
 6378: }
 6379: 
 6380: .LC_breadcrumbs_hoverable {
 6381:   background: $sidebg;
 6382: }
 6383: 
 6384: td.LC_table_cell_checkbox {
 6385:   text-align: center;
 6386: }
 6387: 
 6388: .LC_fontsize_small {
 6389:   font-size: 70%;
 6390: }
 6391: 
 6392: #LC_breadcrumbs {
 6393:   clear:both;
 6394:   background: $sidebg;
 6395:   border-bottom: 1px solid $lg_border_color;
 6396:   line-height: 2.5em;
 6397:   overflow: hidden;
 6398:   margin: 0;
 6399:   padding: 0;
 6400:   text-align: left;
 6401: }
 6402: 
 6403: .LC_head_subbox, .LC_actionbox {
 6404:   clear:both;
 6405:   background: #F8F8F8; /* $sidebg; */
 6406:   border: 1px solid $sidebg;
 6407:   margin: 0 0 10px 0;
 6408:   padding: 3px;
 6409:   text-align: left;
 6410: }
 6411: 
 6412: .LC_fontsize_medium {
 6413:   font-size: 85%;
 6414: }
 6415: 
 6416: .LC_fontsize_large {
 6417:   font-size: 120%;
 6418: }
 6419: 
 6420: .LC_menubuttons_inline_text {
 6421:   color: $font;
 6422:   font-size: 90%;
 6423:   padding-left:3px;
 6424: }
 6425: 
 6426: .LC_menubuttons_inline_text img{
 6427:   vertical-align: middle;
 6428: }
 6429: 
 6430: li.LC_menubuttons_inline_text img {
 6431:   cursor:pointer;
 6432:   text-decoration: none;
 6433: }
 6434: 
 6435: .LC_menubuttons_link {
 6436:   text-decoration: none;
 6437: }
 6438: 
 6439: .LC_menubuttons_category {
 6440:   color: $font;
 6441:   background: $pgbg;
 6442:   font-size: larger;
 6443:   font-weight: bold;
 6444: }
 6445: 
 6446: td.LC_menubuttons_text {
 6447:   color: $font;
 6448: }
 6449: 
 6450: .LC_current_location {
 6451:   background: $tabbg;
 6452: }
 6453: 
 6454: td.LC_zero_height {
 6455:   line-height: 0;
 6456:   cellpadding: 0;
 6457: }
 6458: 
 6459: table.LC_data_table {
 6460:   border: 1px solid #000000;
 6461:   border-collapse: separate;
 6462:   border-spacing: 1px;
 6463:   background: $pgbg;
 6464: }
 6465: 
 6466: .LC_data_table_dense {
 6467:   font-size: small;
 6468: }
 6469: 
 6470: table.LC_nested_outer {
 6471:   border: 1px solid #000000;
 6472:   border-collapse: collapse;
 6473:   border-spacing: 0;
 6474:   width: 100%;
 6475: }
 6476: 
 6477: table.LC_innerpickbox,
 6478: table.LC_nested {
 6479:   border: none;
 6480:   border-collapse: collapse;
 6481:   border-spacing: 0;
 6482:   width: 100%;
 6483: }
 6484: 
 6485: table.LC_data_table tr th,
 6486: table.LC_calendar tr th,
 6487: table.LC_prior_tries tr th,
 6488: table.LC_innerpickbox tr th {
 6489:   font-weight: bold;
 6490:   background-color: $data_table_head;
 6491:   color:$fontmenu;
 6492:   font-size:90%;
 6493: }
 6494: 
 6495: table.LC_innerpickbox tr th,
 6496: table.LC_innerpickbox tr td {
 6497:   vertical-align: top;
 6498: }
 6499: 
 6500: table.LC_data_table tr.LC_info_row > td {
 6501:   background-color: #CCCCCC;
 6502:   font-weight: bold;
 6503:   text-align: left;
 6504: }
 6505: 
 6506: table.LC_data_table tr.LC_odd_row > td {
 6507:   background-color: $data_table_light;
 6508:   padding: 2px;
 6509:   vertical-align: top;
 6510: }
 6511: 
 6512: table.LC_pick_box tr > td.LC_odd_row {
 6513:   background-color: $data_table_light;
 6514:   vertical-align: top;
 6515: }
 6516: 
 6517: table.LC_data_table tr.LC_even_row > td {
 6518:   background-color: $data_table_dark;
 6519:   padding: 2px;
 6520:   vertical-align: top;
 6521: }
 6522: 
 6523: table.LC_pick_box tr > td.LC_even_row {
 6524:   background-color: $data_table_dark;
 6525:   vertical-align: top;
 6526: }
 6527: 
 6528: table.LC_data_table tr.LC_data_table_highlight td {
 6529:   background-color: $data_table_darker;
 6530: }
 6531: 
 6532: table.LC_data_table tr td.LC_leftcol_header {
 6533:   background-color: $data_table_head;
 6534:   font-weight: bold;
 6535: }
 6536: 
 6537: table.LC_data_table tr.LC_empty_row td,
 6538: table.LC_nested tr.LC_empty_row td {
 6539:   font-weight: bold;
 6540:   font-style: italic;
 6541:   text-align: center;
 6542:   padding: 8px;
 6543: }
 6544: 
 6545: table.LC_data_table tr.LC_empty_row td,
 6546: table.LC_data_table tr.LC_footer_row td {
 6547:   background-color: $sidebg;
 6548: }
 6549: 
 6550: table.LC_nested tr.LC_empty_row td {
 6551:   background-color: #FFFFFF;
 6552: }
 6553: 
 6554: table.LC_caption {
 6555: }
 6556: 
 6557: table.LC_nested tr.LC_empty_row td {
 6558:   padding: 4ex
 6559: }
 6560: 
 6561: table.LC_nested_outer tr th {
 6562:   font-weight: bold;
 6563:   color:$fontmenu;
 6564:   background-color: $data_table_head;
 6565:   font-size: small;
 6566:   border-bottom: 1px solid #000000;
 6567: }
 6568: 
 6569: table.LC_nested_outer tr td.LC_subheader {
 6570:   background-color: $data_table_head;
 6571:   font-weight: bold;
 6572:   font-size: small;
 6573:   border-bottom: 1px solid #000000;
 6574:   text-align: right;
 6575: }
 6576: 
 6577: table.LC_nested tr.LC_info_row td {
 6578:   background-color: #CCCCCC;
 6579:   font-weight: bold;
 6580:   font-size: small;
 6581:   text-align: center;
 6582: }
 6583: 
 6584: table.LC_nested tr.LC_info_row td.LC_left_item,
 6585: table.LC_nested_outer tr th.LC_left_item {
 6586:   text-align: left;
 6587: }
 6588: 
 6589: table.LC_nested td {
 6590:   background-color: #FFFFFF;
 6591:   font-size: small;
 6592: }
 6593: 
 6594: table.LC_nested_outer tr th.LC_right_item,
 6595: table.LC_nested tr.LC_info_row td.LC_right_item,
 6596: table.LC_nested tr.LC_odd_row td.LC_right_item,
 6597: table.LC_nested tr td.LC_right_item {
 6598:   text-align: right;
 6599: }
 6600: 
 6601: table.LC_nested tr.LC_odd_row td {
 6602:   background-color: #EEEEEE;
 6603: }
 6604: 
 6605: table.LC_createuser {
 6606: }
 6607: 
 6608: table.LC_createuser tr.LC_section_row td {
 6609:   font-size: small;
 6610: }
 6611: 
 6612: table.LC_createuser tr.LC_info_row td  {
 6613:   background-color: #CCCCCC;
 6614:   font-weight: bold;
 6615:   text-align: center;
 6616: }
 6617: 
 6618: table.LC_calendar {
 6619:   border: 1px solid #000000;
 6620:   border-collapse: collapse;
 6621:   width: 98%;
 6622: }
 6623: 
 6624: table.LC_calendar_pickdate {
 6625:   font-size: xx-small;
 6626: }
 6627: 
 6628: table.LC_calendar tr td {
 6629:   border: 1px solid #000000;
 6630:   vertical-align: top;
 6631:   width: 14%;
 6632: }
 6633: 
 6634: table.LC_calendar tr td.LC_calendar_day_empty {
 6635:   background-color: $data_table_dark;
 6636: }
 6637: 
 6638: table.LC_calendar tr td.LC_calendar_day_current {
 6639:   background-color: $data_table_highlight;
 6640: }
 6641: 
 6642: table.LC_data_table tr td.LC_mail_new {
 6643:   background-color: $mail_new;
 6644: }
 6645: 
 6646: table.LC_data_table tr.LC_mail_new:hover {
 6647:   background-color: $mail_new_hover;
 6648: }
 6649: 
 6650: table.LC_data_table tr td.LC_mail_read {
 6651:   background-color: $mail_read;
 6652: }
 6653: 
 6654: /*
 6655: table.LC_data_table tr.LC_mail_read:hover {
 6656:   background-color: $mail_read_hover;
 6657: }
 6658: */
 6659: 
 6660: table.LC_data_table tr td.LC_mail_replied {
 6661:   background-color: $mail_replied;
 6662: }
 6663: 
 6664: /*
 6665: table.LC_data_table tr.LC_mail_replied:hover {
 6666:   background-color: $mail_replied_hover;
 6667: }
 6668: */
 6669: 
 6670: table.LC_data_table tr td.LC_mail_other {
 6671:   background-color: $mail_other;
 6672: }
 6673: 
 6674: /*
 6675: table.LC_data_table tr.LC_mail_other:hover {
 6676:   background-color: $mail_other_hover;
 6677: }
 6678: */
 6679: 
 6680: table.LC_data_table tr > td.LC_browser_file,
 6681: table.LC_data_table tr > td.LC_browser_file_published {
 6682:   background: #AAEE77;
 6683: }
 6684: 
 6685: table.LC_data_table tr > td.LC_browser_file_locked,
 6686: table.LC_data_table tr > td.LC_browser_file_unpublished {
 6687:   background: #FFAA99;
 6688: }
 6689: 
 6690: table.LC_data_table tr > td.LC_browser_file_obsolete {
 6691:   background: #888888;
 6692: }
 6693: 
 6694: table.LC_data_table tr > td.LC_browser_file_modified,
 6695: table.LC_data_table tr > td.LC_browser_file_metamodified {
 6696:   background: #F8F866;
 6697: }
 6698: 
 6699: table.LC_data_table tr.LC_browser_folder > td {
 6700:   background: #E0E8FF;
 6701: }
 6702: 
 6703: table.LC_data_table tr > td.LC_roles_is {
 6704:   /* background: #77FF77; */
 6705: }
 6706: 
 6707: table.LC_data_table tr > td.LC_roles_future {
 6708:   border-right: 8px solid #FFFF77;
 6709: }
 6710: 
 6711: table.LC_data_table tr > td.LC_roles_will {
 6712:   border-right: 8px solid #FFAA77;
 6713: }
 6714: 
 6715: table.LC_data_table tr > td.LC_roles_expired {
 6716:   border-right: 8px solid #FF7777;
 6717: }
 6718: 
 6719: table.LC_data_table tr > td.LC_roles_will_not {
 6720:   border-right: 8px solid #AAFF77;
 6721: }
 6722: 
 6723: table.LC_data_table tr > td.LC_roles_selected {
 6724:   border-right: 8px solid #11CC55;
 6725: }
 6726: 
 6727: span.LC_current_location {
 6728:   font-size:larger;
 6729:   background: $pgbg;
 6730: }
 6731: 
 6732: span.LC_current_nav_location {
 6733:   font-weight:bold;
 6734:   background: $sidebg;
 6735: }
 6736: 
 6737: span.LC_parm_menu_item {
 6738:   font-size: larger;
 6739: }
 6740: 
 6741: span.LC_parm_scope_all {
 6742:   color: red;
 6743: }
 6744: 
 6745: span.LC_parm_scope_folder {
 6746:   color: green;
 6747: }
 6748: 
 6749: span.LC_parm_scope_resource {
 6750:   color: orange;
 6751: }
 6752: 
 6753: span.LC_parm_part {
 6754:   color: blue;
 6755: }
 6756: 
 6757: span.LC_parm_folder,
 6758: span.LC_parm_symb {
 6759:   font-size: x-small;
 6760:   font-family: $mono;
 6761:   color: #AAAAAA;
 6762: }
 6763: 
 6764: ul.LC_parm_parmlist li {
 6765:   display: inline-block;
 6766:   padding: 0.3em 0.8em;
 6767:   vertical-align: top;
 6768:   width: 150px;
 6769:   border-top:1px solid $lg_border_color;
 6770: }
 6771: 
 6772: td.LC_parm_overview_level_menu,
 6773: td.LC_parm_overview_map_menu,
 6774: td.LC_parm_overview_parm_selectors,
 6775: td.LC_parm_overview_restrictions  {
 6776:   border: 1px solid black;
 6777:   border-collapse: collapse;
 6778: }
 6779: 
 6780: table.LC_parm_overview_restrictions td {
 6781:   border-width: 1px 4px 1px 4px;
 6782:   border-style: solid;
 6783:   border-color: $pgbg;
 6784:   text-align: center;
 6785: }
 6786: 
 6787: table.LC_parm_overview_restrictions th {
 6788:   background: $tabbg;
 6789:   border-width: 1px 4px 1px 4px;
 6790:   border-style: solid;
 6791:   border-color: $pgbg;
 6792: }
 6793: 
 6794: table#LC_helpmenu {
 6795:   border: none;
 6796:   height: 55px;
 6797:   border-spacing: 0;
 6798: }
 6799: 
 6800: table#LC_helpmenu fieldset legend {
 6801:   font-size: larger;
 6802: }
 6803: 
 6804: table#LC_helpmenu_links {
 6805:   width: 100%;
 6806:   border: 1px solid black;
 6807:   background: $pgbg;
 6808:   padding: 0;
 6809:   border-spacing: 1px;
 6810: }
 6811: 
 6812: table#LC_helpmenu_links tr td {
 6813:   padding: 1px;
 6814:   background: $tabbg;
 6815:   text-align: center;
 6816:   font-weight: bold;
 6817: }
 6818: 
 6819: table#LC_helpmenu_links a:link,
 6820: table#LC_helpmenu_links a:visited,
 6821: table#LC_helpmenu_links a:active {
 6822:   text-decoration: none;
 6823:   color: $font;
 6824: }
 6825: 
 6826: table#LC_helpmenu_links a:hover {
 6827:   text-decoration: underline;
 6828:   color: $vlink;
 6829: }
 6830: 
 6831: .LC_chrt_popup_exists {
 6832:   border: 1px solid #339933;
 6833:   margin: -1px;
 6834: }
 6835: 
 6836: .LC_chrt_popup_up {
 6837:   border: 1px solid yellow;
 6838:   margin: -1px;
 6839: }
 6840: 
 6841: .LC_chrt_popup {
 6842:   border: 1px solid #8888FF;
 6843:   background: #CCCCFF;
 6844: }
 6845: 
 6846: table.LC_pick_box {
 6847:   border-collapse: separate;
 6848:   background: white;
 6849:   border: 1px solid black;
 6850:   border-spacing: 1px;
 6851: }
 6852: 
 6853: table.LC_pick_box td.LC_pick_box_title {
 6854:   background: $sidebg;
 6855:   font-weight: bold;
 6856:   text-align: left;
 6857:   vertical-align: top;
 6858:   width: 184px;
 6859:   padding: 8px;
 6860: }
 6861: 
 6862: table.LC_pick_box td.LC_pick_box_value {
 6863:   text-align: left;
 6864:   padding: 8px;
 6865: }
 6866: 
 6867: table.LC_pick_box td.LC_pick_box_select {
 6868:   text-align: left;
 6869:   padding: 8px;
 6870: }
 6871: 
 6872: table.LC_pick_box td.LC_pick_box_separator {
 6873:   padding: 0;
 6874:   height: 1px;
 6875:   background: black;
 6876: }
 6877: 
 6878: table.LC_pick_box td.LC_pick_box_submit {
 6879:   text-align: right;
 6880: }
 6881: 
 6882: table.LC_pick_box td.LC_evenrow_value {
 6883:   text-align: left;
 6884:   padding: 8px;
 6885:   background-color: $data_table_light;
 6886: }
 6887: 
 6888: table.LC_pick_box td.LC_oddrow_value {
 6889:   text-align: left;
 6890:   padding: 8px;
 6891:   background-color: $data_table_light;
 6892: }
 6893: 
 6894: span.LC_helpform_receipt_cat {
 6895:   font-weight: bold;
 6896: }
 6897: 
 6898: table.LC_group_priv_box {
 6899:   background: white;
 6900:   border: 1px solid black;
 6901:   border-spacing: 1px;
 6902: }
 6903: 
 6904: table.LC_group_priv_box td.LC_pick_box_title {
 6905:   background: $tabbg;
 6906:   font-weight: bold;
 6907:   text-align: right;
 6908:   width: 184px;
 6909: }
 6910: 
 6911: table.LC_group_priv_box td.LC_groups_fixed {
 6912:   background: $data_table_light;
 6913:   text-align: center;
 6914: }
 6915: 
 6916: table.LC_group_priv_box td.LC_groups_optional {
 6917:   background: $data_table_dark;
 6918:   text-align: center;
 6919: }
 6920: 
 6921: table.LC_group_priv_box td.LC_groups_functionality {
 6922:   background: $data_table_darker;
 6923:   text-align: center;
 6924:   font-weight: bold;
 6925: }
 6926: 
 6927: table.LC_group_priv td {
 6928:   text-align: left;
 6929:   padding: 0;
 6930: }
 6931: 
 6932: .LC_navbuttons {
 6933:   margin: 2ex 0ex 2ex 0ex;
 6934: }
 6935: 
 6936: .LC_topic_bar {
 6937:   font-weight: bold;
 6938:   background: $tabbg;
 6939:   margin: 1em 0em 1em 2em;
 6940:   padding: 3px;
 6941:   font-size: 1.2em;
 6942: }
 6943: 
 6944: .LC_topic_bar span {
 6945:   left: 0.5em;
 6946:   position: absolute;
 6947:   vertical-align: middle;
 6948:   font-size: 1.2em;
 6949: }
 6950: 
 6951: table.LC_course_group_status {
 6952:   margin: 20px;
 6953: }
 6954: 
 6955: table.LC_status_selector td {
 6956:   vertical-align: top;
 6957:   text-align: center;
 6958:   padding: 4px;
 6959: }
 6960: 
 6961: div.LC_feedback_link {
 6962:   clear: both;
 6963:   background: $sidebg;
 6964:   width: 100%;
 6965:   padding-bottom: 10px;
 6966:   border: 1px $tabbg solid;
 6967:   height: 22px;
 6968:   line-height: 22px;
 6969:   padding-top: 5px;
 6970: }
 6971: 
 6972: div.LC_feedback_link img {
 6973:   height: 22px;
 6974:   vertical-align:middle;
 6975: }
 6976: 
 6977: div.LC_feedback_link a {
 6978:   text-decoration: none;
 6979: }
 6980: 
 6981: div.LC_comblock {
 6982:   display:inline;
 6983:   color:$font;
 6984:   font-size:90%;
 6985: }
 6986: 
 6987: div.LC_feedback_link div.LC_comblock {
 6988:   padding-left:5px;
 6989: }
 6990: 
 6991: div.LC_feedback_link div.LC_comblock a {
 6992:   color:$font;
 6993: }
 6994: 
 6995: span.LC_feedback_link {
 6996:   /* background: $feedback_link_bg; */
 6997:   font-size: larger;
 6998: }
 6999: 
 7000: span.LC_message_link {
 7001:   /* background: $feedback_link_bg; */
 7002:   font-size: larger;
 7003:   position: absolute;
 7004:   right: 1em;
 7005: }
 7006: 
 7007: table.LC_prior_tries {
 7008:   border: 1px solid #000000;
 7009:   border-collapse: separate;
 7010:   border-spacing: 1px;
 7011: }
 7012: 
 7013: table.LC_prior_tries td {
 7014:   padding: 2px;
 7015: }
 7016: 
 7017: .LC_answer_correct {
 7018:   background: lightgreen;
 7019:   color: darkgreen;
 7020:   padding: 6px;
 7021: }
 7022: 
 7023: .LC_answer_charged_try {
 7024:   background: #FFAAAA;
 7025:   color: darkred;
 7026:   padding: 6px;
 7027: }
 7028: 
 7029: .LC_answer_not_charged_try,
 7030: .LC_answer_no_grade,
 7031: .LC_answer_late {
 7032:   background: lightyellow;
 7033:   color: black;
 7034:   padding: 6px;
 7035: }
 7036: 
 7037: .LC_answer_previous {
 7038:   background: lightblue;
 7039:   color: darkblue;
 7040:   padding: 6px;
 7041: }
 7042: 
 7043: .LC_answer_no_message {
 7044:   background: #FFFFFF;
 7045:   color: black;
 7046:   padding: 6px;
 7047: }
 7048: 
 7049: .LC_answer_unknown,
 7050: .LC_answer_warning {
 7051:   background: orange;
 7052:   color: black;
 7053:   padding: 6px;
 7054: }
 7055: 
 7056: span.LC_prior_numerical,
 7057: span.LC_prior_string,
 7058: span.LC_prior_custom,
 7059: span.LC_prior_reaction,
 7060: span.LC_prior_math {
 7061:   font-family: $mono;
 7062:   white-space: pre;
 7063: }
 7064: 
 7065: span.LC_prior_string {
 7066:   font-family: $mono;
 7067:   white-space: pre;
 7068: }
 7069: 
 7070: table.LC_prior_option {
 7071:   width: 100%;
 7072:   border-collapse: collapse;
 7073: }
 7074: 
 7075: table.LC_prior_rank,
 7076: table.LC_prior_match {
 7077:   border-collapse: collapse;
 7078: }
 7079: 
 7080: table.LC_prior_option tr td,
 7081: table.LC_prior_rank tr td,
 7082: table.LC_prior_match tr td {
 7083:   border: 1px solid #000000;
 7084: }
 7085: 
 7086: .LC_nobreak {
 7087:   white-space: nowrap;
 7088: }
 7089: 
 7090: span.LC_cusr_emph {
 7091:   font-style: italic;
 7092: }
 7093: 
 7094: span.LC_cusr_subheading {
 7095:   font-weight: normal;
 7096:   font-size: 85%;
 7097: }
 7098: 
 7099: div.LC_docs_entry_move {
 7100:   border: 1px solid #BBBBBB;
 7101:   background: #DDDDDD;
 7102:   width: 22px;
 7103:   padding: 1px;
 7104:   margin: 0;
 7105: }
 7106: 
 7107: table.LC_data_table tr > td.LC_docs_entry_commands,
 7108: table.LC_data_table tr > td.LC_docs_entry_parameter {
 7109:   font-size: x-small;
 7110: }
 7111: 
 7112: .LC_docs_entry_parameter {
 7113:   white-space: nowrap;
 7114: }
 7115: 
 7116: .LC_docs_copy {
 7117:   color: #000099;
 7118: }
 7119: 
 7120: .LC_docs_cut {
 7121:   color: #550044;
 7122: }
 7123: 
 7124: .LC_docs_rename {
 7125:   color: #009900;
 7126: }
 7127: 
 7128: .LC_docs_remove {
 7129:   color: #990000;
 7130: }
 7131: 
 7132: .LC_domprefs_email,
 7133: .LC_docs_reinit_warn,
 7134: .LC_docs_ext_edit {
 7135:   font-size: x-small;
 7136: }
 7137: 
 7138: table.LC_docs_adddocs td,
 7139: table.LC_docs_adddocs th {
 7140:   border: 1px solid #BBBBBB;
 7141:   padding: 4px;
 7142:   background: #DDDDDD;
 7143: }
 7144: 
 7145: table.LC_sty_begin {
 7146:   background: #BBFFBB;
 7147: }
 7148: 
 7149: table.LC_sty_end {
 7150:   background: #FFBBBB;
 7151: }
 7152: 
 7153: table.LC_double_column {
 7154:   border-width: 0;
 7155:   border-collapse: collapse;
 7156:   width: 100%;
 7157:   padding: 2px;
 7158: }
 7159: 
 7160: table.LC_double_column tr td.LC_left_col {
 7161:   top: 2px;
 7162:   left: 2px;
 7163:   width: 47%;
 7164:   vertical-align: top;
 7165: }
 7166: 
 7167: table.LC_double_column tr td.LC_right_col {
 7168:   top: 2px;
 7169:   right: 2px;
 7170:   width: 47%;
 7171:   vertical-align: top;
 7172: }
 7173: 
 7174: div.LC_left_float {
 7175:   float: left;
 7176:   padding-right: 5%;
 7177:   padding-bottom: 4px;
 7178: }
 7179: 
 7180: div.LC_clear_float_header {
 7181:   padding-bottom: 2px;
 7182: }
 7183: 
 7184: div.LC_clear_float_footer {
 7185:   padding-top: 10px;
 7186:   clear: both;
 7187: }
 7188: 
 7189: div.LC_grade_show_user {
 7190: /*  border-left: 5px solid $sidebg; */
 7191:   border-top: 5px solid #000000;
 7192:   margin: 50px 0 0 0;
 7193:   padding: 15px 0 5px 10px;
 7194: }
 7195: 
 7196: div.LC_grade_show_user_odd_row {
 7197: /*  border-left: 5px solid #000000; */
 7198: }
 7199: 
 7200: div.LC_grade_show_user div.LC_Box {
 7201:   margin-right: 50px;
 7202: }
 7203: 
 7204: div.LC_grade_submissions,
 7205: div.LC_grade_message_center,
 7206: div.LC_grade_info_links {
 7207:   margin: 5px;
 7208:   width: 99%;
 7209:   background: #FFFFFF;
 7210: }
 7211: 
 7212: div.LC_grade_submissions_header,
 7213: div.LC_grade_message_center_header {
 7214:   font-weight: bold;
 7215:   font-size: large;
 7216: }
 7217: 
 7218: div.LC_grade_submissions_body,
 7219: div.LC_grade_message_center_body {
 7220:   border: 1px solid black;
 7221:   width: 99%;
 7222:   background: #FFFFFF;
 7223: }
 7224: 
 7225: table.LC_scantron_action {
 7226:   width: 100%;
 7227: }
 7228: 
 7229: table.LC_scantron_action tr th {
 7230:   font-weight:bold;
 7231:   font-style:normal;
 7232: }
 7233: 
 7234: .LC_edit_problem_header,
 7235: div.LC_edit_problem_footer {
 7236:   font-weight: normal;
 7237:   font-size:  medium;
 7238:   margin: 2px;
 7239:   background-color: $sidebg;
 7240: }
 7241: 
 7242: div.LC_edit_problem_header,
 7243: div.LC_edit_problem_header div,
 7244: div.LC_edit_problem_footer,
 7245: div.LC_edit_problem_footer div,
 7246: div.LC_edit_problem_editxml_header,
 7247: div.LC_edit_problem_editxml_header div {
 7248:   z-index: 100;
 7249: }
 7250: 
 7251: div.LC_edit_problem_header_title {
 7252:   font-weight: bold;
 7253:   font-size: larger;
 7254:   background: $tabbg;
 7255:   padding: 3px;
 7256:   margin: 0 0 5px 0;
 7257: }
 7258: 
 7259: table.LC_edit_problem_header_title {
 7260:   width: 100%;
 7261:   background: $tabbg;
 7262: }
 7263: 
 7264: div.LC_edit_actionbar {
 7265:     background-color: $sidebg;
 7266:     margin: 0;
 7267:     padding: 0;
 7268:     line-height: 200%;
 7269: }
 7270: 
 7271: div.LC_edit_actionbar div{
 7272:     padding: 0;
 7273:     margin: 0;
 7274:     display: inline-block;
 7275: }
 7276: 
 7277: .LC_edit_opt {
 7278:   padding-left: 1em;
 7279:   white-space: nowrap;
 7280: }
 7281: 
 7282: .LC_edit_problem_latexhelper{
 7283:     text-align: right;
 7284: }
 7285: 
 7286: #LC_edit_problem_colorful div{
 7287:     margin-left: 40px;
 7288: }
 7289: 
 7290: #LC_edit_problem_codemirror div{
 7291:     margin-left: 0px;
 7292: }
 7293: 
 7294: img.stift {
 7295:   border-width: 0;
 7296:   vertical-align: middle;
 7297: }
 7298: 
 7299: table td.LC_mainmenu_col_fieldset {
 7300:   vertical-align: top;
 7301: }
 7302: 
 7303: div.LC_createcourse {
 7304:   margin: 10px 10px 10px 10px;
 7305: }
 7306: 
 7307: .LC_dccid {
 7308:   float: right;
 7309:   margin: 0.2em 0 0 0;
 7310:   padding: 0;
 7311:   font-size: 90%;
 7312:   display:none;
 7313: }
 7314: 
 7315: ol.LC_primary_menu a:hover,
 7316: ol#LC_MenuBreadcrumbs a:hover,
 7317: ol#LC_PathBreadcrumbs a:hover,
 7318: ul#LC_secondary_menu a:hover,
 7319: .LC_FormSectionClearButton input:hover
 7320: ul.LC_TabContent   li:hover a {
 7321:   color:$button_hover;
 7322:   text-decoration:none;
 7323: }
 7324: 
 7325: h1 {
 7326:   padding: 0;
 7327:   line-height:130%;
 7328: }
 7329: 
 7330: h2,
 7331: h3,
 7332: h4,
 7333: h5,
 7334: h6 {
 7335:   margin: 5px 0 5px 0;
 7336:   padding: 0;
 7337:   line-height:130%;
 7338: }
 7339: 
 7340: .LC_hcell {
 7341:   padding:3px 15px 3px 15px;
 7342:   margin: 0;
 7343:   background-color:$tabbg;
 7344:   color:$fontmenu;
 7345:   border-bottom:solid 1px $lg_border_color;
 7346: }
 7347: 
 7348: .LC_Box > .LC_hcell {
 7349:   margin: 0 -10px 10px -10px;
 7350: }
 7351: 
 7352: .LC_noBorder {
 7353:   border: 0;
 7354: }
 7355: 
 7356: .LC_FormSectionClearButton input {
 7357:   background-color:transparent;
 7358:   border: none;
 7359:   cursor:pointer;
 7360:   text-decoration:underline;
 7361: }
 7362: 
 7363: .LC_help_open_topic {
 7364:   color: #FFFFFF;
 7365:   background-color: #EEEEFF;
 7366:   margin: 1px;
 7367:   padding: 4px;
 7368:   border: 1px solid #000033;
 7369:   white-space: nowrap;
 7370:   /* vertical-align: middle; */
 7371: }
 7372: 
 7373: dl,
 7374: ul,
 7375: div,
 7376: fieldset {
 7377:   margin: 10px 10px 10px 0;
 7378:   /* overflow: hidden; */
 7379: }
 7380: 
 7381: article.geogebraweb div {
 7382:     margin: 0;
 7383: }
 7384: 
 7385: fieldset > legend {
 7386:   font-weight: bold;
 7387:   padding: 0 5px 0 5px;
 7388: }
 7389: 
 7390: #LC_nav_bar {
 7391:   float: left;
 7392:   background-color: $pgbg_or_bgcolor;
 7393:   margin: 0 0 2px 0;
 7394: }
 7395: 
 7396: #LC_realm {
 7397:   margin: 0.2em 0 0 0;
 7398:   padding: 0;
 7399:   font-weight: bold;
 7400:   text-align: center;
 7401:   background-color: $pgbg_or_bgcolor;
 7402: }
 7403: 
 7404: #LC_nav_bar em {
 7405:   font-weight: bold;
 7406:   font-style: normal;
 7407: }
 7408: 
 7409: ol.LC_primary_menu {
 7410:   margin: 0;
 7411:   padding: 0;
 7412: }
 7413: 
 7414: ol#LC_PathBreadcrumbs {
 7415:   margin: 0;
 7416: }
 7417: 
 7418: ol.LC_primary_menu li {
 7419:   color: RGB(80, 80, 80);
 7420:   vertical-align: middle;
 7421:   text-align: left;
 7422:   list-style: none;
 7423:   position: relative;
 7424:   float: left;
 7425:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
 7426:   line-height: 1.5em;
 7427: }
 7428: 
 7429: ol.LC_primary_menu li a, 
 7430: ol.LC_primary_menu li p {
 7431:   display: block;
 7432:   margin: 0;
 7433:   padding: 0 5px 0 10px;
 7434:   text-decoration: none;
 7435: }
 7436: 
 7437: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
 7438:   display: inline-block;
 7439:   width: 95%;
 7440:   text-align: left;
 7441: }
 7442: 
 7443: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
 7444:   display: inline-block;
 7445:   width: 5%;
 7446:   float: right;
 7447:   text-align: right;
 7448:   font-size: 70%;
 7449: }
 7450: 
 7451: ol.LC_primary_menu ul {
 7452:   display: none;
 7453:   width: 15em;
 7454:   background-color: $data_table_light;
 7455:   position: absolute;
 7456:   top: 100%;
 7457: }
 7458: 
 7459: ol.LC_primary_menu ul ul {
 7460:   left: 100%;
 7461:   top: 0;
 7462: }
 7463: 
 7464: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
 7465:   display: block;
 7466:   position: absolute;
 7467:   margin: 0;
 7468:   padding: 0;
 7469:   z-index: 2;
 7470: }
 7471: 
 7472: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 7473: /* First Submenu -> size should be smaller than the menu title of the whole menu */
 7474:   font-size: 90%;
 7475:   vertical-align: top;
 7476:   float: none;
 7477:   border-left: 1px solid black;
 7478:   border-right: 1px solid black;
 7479: /* A dark bottom border to visualize different menu options;
 7480: overwritten in the create_submenu routine for the last border-bottom of the menu */
 7481:   border-bottom: 1px solid $data_table_dark;
 7482: }
 7483: 
 7484: ol.LC_primary_menu li li p:hover {
 7485:   color:$button_hover;
 7486:   text-decoration:none;
 7487:   background-color:$data_table_dark;
 7488: }
 7489: 
 7490: ol.LC_primary_menu li li a:hover {
 7491:    color:$button_hover;
 7492:    background-color:$data_table_dark;
 7493: }
 7494: 
 7495: /* Font-size equal to the size of the predecessors*/
 7496: ol.LC_primary_menu li:hover li li {
 7497:   font-size: 100%;
 7498: }
 7499: 
 7500: ol.LC_primary_menu li img {
 7501:   vertical-align: bottom;
 7502:   height: 1.1em;
 7503:   margin: 0.2em 0 0 0;
 7504: }
 7505: 
 7506: ol.LC_primary_menu a {
 7507:   color: RGB(80, 80, 80);
 7508:   text-decoration: none;
 7509: }
 7510: 
 7511: ol.LC_primary_menu a.LC_new_message {
 7512:   font-weight:bold;
 7513:   color: darkred;
 7514: }
 7515: 
 7516: ol.LC_docs_parameters {
 7517:   margin-left: 0;
 7518:   padding: 0;
 7519:   list-style: none;
 7520: }
 7521: 
 7522: ol.LC_docs_parameters li {
 7523:   margin: 0;
 7524:   padding-right: 20px;
 7525:   display: inline;
 7526: }
 7527: 
 7528: ol.LC_docs_parameters li:before {
 7529:   content: "\\002022 \\0020";
 7530: }
 7531: 
 7532: li.LC_docs_parameters_title {
 7533:   font-weight: bold;
 7534: }
 7535: 
 7536: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 7537:   content: "";
 7538: }
 7539: 
 7540: ul#LC_secondary_menu {
 7541:   clear: right;
 7542:   color: $fontmenu;
 7543:   background: $tabbg;
 7544:   list-style: none;
 7545:   padding: 0;
 7546:   margin: 0;
 7547:   width: 100%;
 7548:   text-align: left;
 7549:   float: left;
 7550: }
 7551: 
 7552: ul#LC_secondary_menu li {
 7553:   font-weight: bold;
 7554:   line-height: 1.8em;
 7555:   border-right: 1px solid black;
 7556:   float: left;
 7557: }
 7558: 
 7559: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 7560:   background-color: $data_table_light;
 7561: }
 7562: 
 7563: ul#LC_secondary_menu li a {
 7564:   padding: 0 0.8em;
 7565: }
 7566: 
 7567: ul#LC_secondary_menu li ul {
 7568:   display: none;
 7569: }
 7570: 
 7571: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 7572:   display: block;
 7573:   position: absolute;
 7574:   margin: 0;
 7575:   padding: 0;
 7576:   list-style:none;
 7577:   float: none;
 7578:   background-color: $data_table_light;
 7579:   z-index: 2;
 7580:   margin-left: -1px;
 7581: }
 7582: 
 7583: ul#LC_secondary_menu li ul li {
 7584:   font-size: 90%;
 7585:   vertical-align: top;
 7586:   border-left: 1px solid black;
 7587:   border-right: 1px solid black;
 7588:   background-color: $data_table_light;
 7589:   list-style:none;
 7590:   float: none;
 7591: }
 7592: 
 7593: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 7594:   background-color: $data_table_dark;
 7595: }
 7596: 
 7597: ul.LC_TabContent {
 7598:   display:block;
 7599:   background: $sidebg;
 7600:   border-bottom: solid 1px $lg_border_color;
 7601:   list-style:none;
 7602:   margin: -1px -10px 0 -10px;
 7603:   padding: 0;
 7604: }
 7605: 
 7606: ul.LC_TabContent li,
 7607: ul.LC_TabContentBigger li {
 7608:   float:left;
 7609: }
 7610: 
 7611: ul#LC_secondary_menu li a {
 7612:   color: $fontmenu;
 7613:   text-decoration: none;
 7614: }
 7615: 
 7616: ul.LC_TabContent {
 7617:   min-height:20px;
 7618: }
 7619: 
 7620: ul.LC_TabContent li {
 7621:   vertical-align:middle;
 7622:   padding: 0 16px 0 10px;
 7623:   background-color:$tabbg;
 7624:   border-bottom:solid 1px $lg_border_color;
 7625:   border-left: solid 1px $font;
 7626: }
 7627: 
 7628: ul.LC_TabContent .right {
 7629:   float:right;
 7630: }
 7631: 
 7632: ul.LC_TabContent li a,
 7633: ul.LC_TabContent li {
 7634:   color:rgb(47,47,47);
 7635:   text-decoration:none;
 7636:   font-size:95%;
 7637:   font-weight:bold;
 7638:   min-height:20px;
 7639: }
 7640: 
 7641: ul.LC_TabContent li a:hover,
 7642: ul.LC_TabContent li a:focus {
 7643:   color: $button_hover;
 7644:   background:none;
 7645:   outline:none;
 7646: }
 7647: 
 7648: ul.LC_TabContent li:hover {
 7649:   color: $button_hover;
 7650:   cursor:pointer;
 7651: }
 7652: 
 7653: ul.LC_TabContent li.active {
 7654:   color: $font;
 7655:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 7656:   border-bottom:solid 1px #FFFFFF;
 7657:   cursor: default;
 7658: }
 7659: 
 7660: ul.LC_TabContent li.active a {
 7661:   color:$font;
 7662:   background:#FFFFFF;
 7663:   outline: none;
 7664: }
 7665: 
 7666: ul.LC_TabContent li.goback {
 7667:   float: left;
 7668:   border-left: none;
 7669: }
 7670: 
 7671: #maincoursedoc {
 7672:   clear:both;
 7673: }
 7674: 
 7675: ul.LC_TabContentBigger {
 7676:   display:block;
 7677:   list-style:none;
 7678:   padding: 0;
 7679: }
 7680: 
 7681: ul.LC_TabContentBigger li {
 7682:   vertical-align:bottom;
 7683:   height: 30px;
 7684:   font-size:110%;
 7685:   font-weight:bold;
 7686:   color: #737373;
 7687: }
 7688: 
 7689: ul.LC_TabContentBigger li.active {
 7690:   position: relative;
 7691:   top: 1px;
 7692: }
 7693: 
 7694: ul.LC_TabContentBigger li a {
 7695:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 7696:   height: 30px;
 7697:   line-height: 30px;
 7698:   text-align: center;
 7699:   display: block;
 7700:   text-decoration: none;
 7701:   outline: none;  
 7702: }
 7703: 
 7704: ul.LC_TabContentBigger li.active a {
 7705:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 7706:   color:$font;
 7707: }
 7708: 
 7709: ul.LC_TabContentBigger li b {
 7710:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 7711:   display: block;
 7712:   float: left;
 7713:   padding: 0 30px;
 7714:   border-bottom: 1px solid $lg_border_color;
 7715: }
 7716: 
 7717: ul.LC_TabContentBigger li:hover b {
 7718:   color:$button_hover;
 7719: }
 7720: 
 7721: ul.LC_TabContentBigger li.active b {
 7722:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 7723:   color:$font;
 7724:   border: 0;
 7725: }
 7726: 
 7727: 
 7728: ul.LC_CourseBreadcrumbs {
 7729:   background: $sidebg;
 7730:   height: 2em;
 7731:   padding-left: 10px;
 7732:   margin: 0;
 7733:   list-style-position: inside;
 7734: }
 7735: 
 7736: ol#LC_MenuBreadcrumbs,
 7737: ol#LC_PathBreadcrumbs {
 7738:   padding-left: 10px;
 7739:   margin: 0;
 7740:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 7741: }
 7742: 
 7743: ol#LC_MenuBreadcrumbs li,
 7744: ol#LC_PathBreadcrumbs li,
 7745: ul.LC_CourseBreadcrumbs li {
 7746:   display: inline;
 7747:   white-space: normal;  
 7748: }
 7749: 
 7750: ol#LC_MenuBreadcrumbs li a,
 7751: ul.LC_CourseBreadcrumbs li a {
 7752:   text-decoration: none;
 7753:   font-size:90%;
 7754: }
 7755: 
 7756: ol#LC_MenuBreadcrumbs h1 {
 7757:   display: inline;
 7758:   font-size: 90%;
 7759:   line-height: 2.5em;
 7760:   margin: 0;
 7761:   padding: 0;
 7762: }
 7763: 
 7764: ol#LC_PathBreadcrumbs li a {
 7765:   text-decoration:none;
 7766:   font-size:100%;
 7767:   font-weight:bold;
 7768: }
 7769: 
 7770: .LC_Box {
 7771:   border: solid 1px $lg_border_color;
 7772:   padding: 0 10px 10px 10px;
 7773: }
 7774: 
 7775: .LC_DocsBox {
 7776:   border: solid 1px $lg_border_color;
 7777:   padding: 0 0 10px 10px;
 7778: }
 7779: 
 7780: .LC_AboutMe_Image {
 7781:   float:left;
 7782:   margin-right:10px;
 7783: }
 7784: 
 7785: .LC_Clear_AboutMe_Image {
 7786:   clear:left;
 7787: }
 7788: 
 7789: dl.LC_ListStyleClean dt {
 7790:   padding-right: 5px;
 7791:   display: table-header-group;
 7792: }
 7793: 
 7794: dl.LC_ListStyleClean dd {
 7795:   display: table-row;
 7796: }
 7797: 
 7798: .LC_ListStyleClean,
 7799: .LC_ListStyleSimple,
 7800: .LC_ListStyleNormal,
 7801: .LC_ListStyleSpecial {
 7802:   /* display:block; */
 7803:   list-style-position: inside;
 7804:   list-style-type: none;
 7805:   overflow: hidden;
 7806:   padding: 0;
 7807: }
 7808: 
 7809: .LC_ListStyleSimple li,
 7810: .LC_ListStyleSimple dd,
 7811: .LC_ListStyleNormal li,
 7812: .LC_ListStyleNormal dd,
 7813: .LC_ListStyleSpecial li,
 7814: .LC_ListStyleSpecial dd {
 7815:   margin: 0;
 7816:   padding: 5px 5px 5px 10px;
 7817:   clear: both;
 7818: }
 7819: 
 7820: .LC_ListStyleClean li,
 7821: .LC_ListStyleClean dd {
 7822:   padding-top: 0;
 7823:   padding-bottom: 0;
 7824: }
 7825: 
 7826: .LC_ListStyleSimple dd,
 7827: .LC_ListStyleSimple li {
 7828:   border-bottom: solid 1px $lg_border_color;
 7829: }
 7830: 
 7831: .LC_ListStyleSpecial li,
 7832: .LC_ListStyleSpecial dd {
 7833:   list-style-type: none;
 7834:   background-color: RGB(220, 220, 220);
 7835:   margin-bottom: 4px;
 7836: }
 7837: 
 7838: table.LC_SimpleTable {
 7839:   margin:5px;
 7840:   border:solid 1px $lg_border_color;
 7841: }
 7842: 
 7843: table.LC_SimpleTable tr {
 7844:   padding: 0;
 7845:   border:solid 1px $lg_border_color;
 7846: }
 7847: 
 7848: table.LC_SimpleTable thead {
 7849:   background:rgb(220,220,220);
 7850: }
 7851: 
 7852: div.LC_columnSection {
 7853:   display: block;
 7854:   clear: both;
 7855:   overflow: hidden;
 7856:   margin: 0;
 7857: }
 7858: 
 7859: div.LC_columnSection>* {
 7860:   float: left;
 7861:   margin: 10px 20px 10px 0;
 7862:   overflow:hidden;
 7863: }
 7864: 
 7865: table em {
 7866:   font-weight: bold;
 7867:   font-style: normal;
 7868: }
 7869: 
 7870: table.LC_tableBrowseRes,
 7871: table.LC_tableOfContent {
 7872:   border:none;
 7873:   border-spacing: 1px;
 7874:   padding: 3px;
 7875:   background-color: #FFFFFF;
 7876:   font-size: 90%;
 7877: }
 7878: 
 7879: table.LC_tableOfContent {
 7880:   border-collapse: collapse;
 7881: }
 7882: 
 7883: table.LC_tableBrowseRes a,
 7884: table.LC_tableOfContent a {
 7885:   background-color: transparent;
 7886:   text-decoration: none;
 7887: }
 7888: 
 7889: table.LC_tableOfContent img {
 7890:   border: none;
 7891:   height: 1.3em;
 7892:   vertical-align: text-bottom;
 7893:   margin-right: 0.3em;
 7894: }
 7895: 
 7896: a#LC_content_toolbar_firsthomework {
 7897:   background-image:url(/res/adm/pages/open-first-problem.gif);
 7898: }
 7899: 
 7900: a#LC_content_toolbar_everything {
 7901:   background-image:url(/res/adm/pages/show-all.gif);
 7902: }
 7903: 
 7904: a#LC_content_toolbar_uncompleted {
 7905:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 7906: }
 7907: 
 7908: #LC_content_toolbar_clearbubbles {
 7909:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 7910: }
 7911: 
 7912: a#LC_content_toolbar_changefolder {
 7913:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 7914: }
 7915: 
 7916: a#LC_content_toolbar_changefolder_toggled {
 7917:   background-image:url(/res/adm/pages/open-all-folders.gif);
 7918: }
 7919: 
 7920: a#LC_content_toolbar_edittoplevel {
 7921:   background-image:url(/res/adm/pages/edittoplevel.gif);
 7922: }
 7923: 
 7924: ul#LC_toolbar li a:hover {
 7925:   background-position: bottom center;
 7926: }
 7927: 
 7928: ul#LC_toolbar {
 7929:   padding: 0;
 7930:   margin: 2px;
 7931:   list-style:none;
 7932:   position:relative;
 7933:   background-color:white;
 7934:   overflow: auto;
 7935: }
 7936: 
 7937: ul#LC_toolbar li {
 7938:   border:1px solid white;
 7939:   padding: 0;
 7940:   margin: 0;
 7941:   float: left;
 7942:   display:inline;
 7943:   vertical-align:middle;
 7944:   white-space: nowrap;
 7945: }
 7946: 
 7947: 
 7948: a.LC_toolbarItem {
 7949:   display:block;
 7950:   padding: 0;
 7951:   margin: 0;
 7952:   height: 32px;
 7953:   width: 32px;
 7954:   color:white;
 7955:   border: none;
 7956:   background-repeat:no-repeat;
 7957:   background-color:transparent;
 7958: }
 7959: 
 7960: ul.LC_funclist {
 7961:     margin: 0;
 7962:     padding: 0.5em 1em 0.5em 0;
 7963: }
 7964: 
 7965: ul.LC_funclist > li:first-child {
 7966:     font-weight:bold; 
 7967:     margin-left:0.8em;
 7968: }
 7969: 
 7970: ul.LC_funclist + ul.LC_funclist {
 7971:     /* 
 7972:        left border as a seperator if we have more than
 7973:        one list 
 7974:     */
 7975:     border-left: 1px solid $sidebg;
 7976:     /* 
 7977:        this hides the left border behind the border of the 
 7978:        outer box if element is wrapped to the next 'line' 
 7979:     */
 7980:     margin-left: -1px;
 7981: }
 7982: 
 7983: ul.LC_funclist li {
 7984:   display: inline;
 7985:   white-space: nowrap;
 7986:   margin: 0 0 0 25px;
 7987:   line-height: 150%;
 7988: }
 7989: 
 7990: .LC_hidden {
 7991:   display: none;
 7992: }
 7993: 
 7994: .LCmodal-overlay {
 7995: 		position:fixed;
 7996: 		top:0;
 7997: 		right:0;
 7998: 		bottom:0;
 7999: 		left:0;
 8000: 		height:100%;
 8001: 		width:100%;
 8002: 		margin:0;
 8003: 		padding:0;
 8004: 		background:#999;
 8005: 		opacity:.75;
 8006: 		filter: alpha(opacity=75);
 8007: 		-moz-opacity: 0.75;
 8008: 		z-index:101;
 8009: }
 8010: 
 8011: * html .LCmodal-overlay {   
 8012: 		position: absolute;
 8013: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 8014: }
 8015: 
 8016: .LCmodal-window {
 8017: 		position:fixed;
 8018: 		top:50%;
 8019: 		left:50%;
 8020: 		margin:0;
 8021: 		padding:0;
 8022: 		z-index:102;
 8023: 	}
 8024: 
 8025: * html .LCmodal-window {
 8026: 		position:absolute;
 8027: }
 8028: 
 8029: .LCclose-window {
 8030: 		position:absolute;
 8031: 		width:32px;
 8032: 		height:32px;
 8033: 		right:8px;
 8034: 		top:8px;
 8035: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 8036: 		text-indent:-99999px;
 8037: 		overflow:hidden;
 8038: 		cursor:pointer;
 8039: }
 8040: 
 8041: .LCisDisabled {
 8042:   cursor: not-allowed;
 8043:   opacity: 0.5;
 8044: }
 8045: 
 8046: a[aria-disabled="true"] {
 8047:   color: currentColor;
 8048:   display: inline-block;  /* For IE11/ MS Edge bug */
 8049:   pointer-events: none;
 8050:   text-decoration: none;
 8051: }
 8052: 
 8053: pre.LC_wordwrap {
 8054:   white-space: pre-wrap;
 8055:   white-space: -moz-pre-wrap;
 8056:   white-space: -pre-wrap;
 8057:   white-space: -o-pre-wrap;
 8058:   word-wrap: break-word;
 8059: }
 8060: 
 8061: /*
 8062:   styles used by TTH when "Default set of options to pass to tth/m
 8063:   when converting TeX" in course settings has been set
 8064: 
 8065:   option passed: -t
 8066: 
 8067: */
 8068: 
 8069: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 8070: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 8071: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 8072: td div.norm {line-height:normal;}
 8073: 
 8074: /*
 8075:   option passed -y3
 8076: */
 8077: 
 8078: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 8079: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 8080: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 8081: 
 8082: #LC_minitab_header {
 8083:   float:left;
 8084:   width:100%;
 8085:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
 8086:   font-size:93%;
 8087:   line-height:normal;
 8088:   margin: 0.5em 0 0.5em 0;
 8089: }
 8090: #LC_minitab_header ul {
 8091:   margin:0;
 8092:   padding:10px 10px 0;
 8093:   list-style:none;
 8094: }
 8095: #LC_minitab_header li {
 8096:   float:left;
 8097:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
 8098:   margin:0;
 8099:   padding:0 0 0 9px;
 8100: }
 8101: #LC_minitab_header a {
 8102:   display:block;
 8103:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
 8104:   padding:5px 15px 4px 6px;
 8105: }
 8106: #LC_minitab_header #LC_current_minitab {
 8107:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
 8108: }
 8109: #LC_minitab_header #LC_current_minitab a {
 8110:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
 8111:   padding-bottom:5px;
 8112: }
 8113: 
 8114: 
 8115: END
 8116: }
 8117: 
 8118: =pod
 8119: 
 8120: =item * &headtag()
 8121: 
 8122: Returns a uniform footer for LON-CAPA web pages.
 8123: 
 8124: Inputs: $title - optional title for the head
 8125:         $head_extra - optional extra HTML to put inside the <head>
 8126:         $args - optional arguments
 8127:             force_register - if is true call registerurl so the remote is 
 8128:                              informed
 8129:             redirect       -> array ref of
 8130:                                    1- seconds before redirect occurs
 8131:                                    2- url to redirect to
 8132:                                    3- whether the side effect should occur
 8133:                            (side effect of setting 
 8134:                                $env{'internal.head.redirect'} to the url 
 8135:                                redirected too)
 8136:             domain         -> force to color decorate a page for a specific
 8137:                                domain
 8138:             function       -> force usage of a specific rolish color scheme
 8139:             bgcolor        -> override the default page bgcolor
 8140:             no_auto_mt_title
 8141:                            -> prevent &mt()ing the title arg
 8142: 
 8143: =cut
 8144: 
 8145: sub headtag {
 8146:     my ($title,$head_extra,$args) = @_;
 8147:     
 8148:     my $function = $args->{'function'} || &get_users_function();
 8149:     my $domain   = $args->{'domain'}   || &determinedomain();
 8150:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 8151:     my $httphost = $args->{'use_absolute'};
 8152:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 8153: 		   $Apache::lonnet::perlvar{'lonVersion'},
 8154: 		   #time(),
 8155: 		   $env{'environment.color.timestamp'},
 8156: 		   $function,$domain,$bgcolor);
 8157: 
 8158:     $url = '/adm/css/'.&escape($url).'.css';
 8159: 
 8160:     my $result =
 8161: 	'<head>'.
 8162: 	&font_settings($args);
 8163: 
 8164:     my $inhibitprint;
 8165:     if ($args->{'print_suppress'}) {
 8166:         $inhibitprint = &print_suppression();
 8167:     }
 8168: 
 8169:     if (!$args->{'frameset'}) {
 8170: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 8171:     }
 8172:     if ($args->{'force_register'}) {
 8173:         $result .= &Apache::lonmenu::registerurl(1);
 8174:     }
 8175:     if (!$args->{'no_nav_bar'} 
 8176: 	&& !$args->{'only_body'}
 8177: 	&& !$args->{'frameset'}) {
 8178: 	$result .= &help_menu_js($httphost);
 8179:         $result.=&modal_window();
 8180:         $result.=&togglebox_script();
 8181:         $result.=&wishlist_window();
 8182:         $result.=&LCprogressbarUpdate_script();
 8183:     } else {
 8184:         if ($args->{'add_modal'}) {
 8185:            $result.=&modal_window();
 8186:         }
 8187:         if ($args->{'add_wishlist'}) {
 8188:            $result.=&wishlist_window();
 8189:         }
 8190:         if ($args->{'add_togglebox'}) {
 8191:            $result.=&togglebox_script();
 8192:         }
 8193:         if ($args->{'add_progressbar'}) {
 8194:            $result.=&LCprogressbarUpdate_script();
 8195:         }
 8196:     }
 8197:     if (ref($args->{'redirect'})) {
 8198: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 8199: 	$url = &Apache::lonenc::check_encrypt($url);
 8200: 	if (!$inhibit_continue) {
 8201: 	    $env{'internal.head.redirect'} = $url;
 8202: 	}
 8203: 	$result.=<<ADDMETA
 8204: <meta http-equiv="pragma" content="no-cache" />
 8205: <meta http-equiv="Refresh" content="$time; url=$url" />
 8206: ADDMETA
 8207:     } else {
 8208:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
 8209:             my $requrl = $env{'request.uri'};
 8210:             if ($requrl eq '') {
 8211:                 $requrl = $ENV{'REQUEST_URI'};
 8212:                 $requrl =~ s/\?.+$//;
 8213:             }
 8214:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
 8215:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
 8216:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
 8217:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
 8218:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
 8219:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
 8220:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 8221:                     my ($offload,$offloadoth);
 8222:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
 8223:                         if ($domdefs{'offloadnow'}{$lonhost}) {
 8224:                             $offload = 1;
 8225:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
 8226:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
 8227:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
 8228:                                     $offloadoth = 1;
 8229:                                     $dom_in_use = $env{'user.domain'};
 8230:                                 }
 8231:                             }
 8232:                         }
 8233:                     }
 8234:                     unless ($offload) {
 8235:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
 8236:                             if ($domdefs{'offloadoth'}{$lonhost}) {
 8237:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
 8238:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
 8239:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
 8240:                                         $offload = 1;
 8241:                                         $offloadoth = 1;
 8242:                                         $dom_in_use = $env{'user.domain'};
 8243:                                     }
 8244:                                 }
 8245:                             }
 8246:                         }
 8247:                     }
 8248:                     if ($offload) {
 8249:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
 8250:                         if (($newserver eq '') && ($offloadoth)) {
 8251:                             my @domains = &Apache::lonnet::current_machine_domains();
 8252:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) {
 8253:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
 8254:                             }
 8255:                         }
 8256:                         if (($newserver) && ($newserver ne $lonhost)) {
 8257:                             my $numsec = 5;
 8258:                             my $timeout = $numsec * 1000;
 8259:                             my ($newurl,$locknum,%locks,$msg);
 8260:                             if ($env{'request.role.adv'}) {
 8261:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
 8262:                             }
 8263:                             my $disable_submit = 0;
 8264:                             if ($requrl =~ /$LONCAPA::assess_re/) {
 8265:                                 $disable_submit = 1;
 8266:                             }
 8267:                             if ($locknum) {
 8268:                                 my @lockinfo = sort(values(%locks));
 8269:                                 $msg = &mt('Once the following tasks are complete:')." \n".
 8270:                                        join(", ",sort(values(%locks)))."\n";
 8271:                                 if (&show_course()) {
 8272:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
 8273:                                 } else {
 8274:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
 8275:                                 }
 8276:                             } else {
 8277:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
 8278:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
 8279:                                 }
 8280:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
 8281:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
 8282:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
 8283:                                     $newurl .= '&role='.$env{'request.role'};
 8284:                                 }
 8285:                                 if ($env{'request.symb'}) {
 8286:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
 8287:                                     if ($shownsymb =~ m{^/enc/}) {
 8288:                                         my $reqdmajor = 2;
 8289:                                         my $reqdminor = 11;
 8290:                                         my $reqdsubminor = 3;
 8291:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
 8292:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
 8293:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
 8294:                                         if (($major eq '' && $minor eq '') ||
 8295:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
 8296:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
 8297:                                              ($reqdsubminor > $subminor))))) {
 8298:                                             undef($shownsymb);
 8299:                                         }
 8300:                                     }
 8301:                                     if ($shownsymb) {
 8302:                                         &js_escape(\$shownsymb);
 8303:                                         $newurl .= '&symb='.$shownsymb;
 8304:                                     }
 8305:                                 } else {
 8306:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
 8307:                                     &js_escape(\$shownurl);
 8308:                                     $newurl .= '&origurl='.$shownurl;
 8309:                                 }
 8310:                             }
 8311:                             &js_escape(\$msg);
 8312:                             $result.=<<OFFLOAD
 8313: <meta http-equiv="pragma" content="no-cache" />
 8314: <script type="text/javascript">
 8315: // <![CDATA[
 8316: function LC_Offload_Now() {
 8317:     var dest = "$newurl";
 8318:     if (dest != '') {
 8319:         window.location.href="$newurl";
 8320:     }
 8321: }
 8322: \$(document).ready(function () {
 8323:     window.alert('$msg');
 8324:     if ($disable_submit) {
 8325:         \$(".LC_hwk_submit").prop("disabled", true);
 8326:         \$( ".LC_textline" ).prop( "readonly", "readonly");
 8327:     }
 8328:     setTimeout('LC_Offload_Now()', $timeout);
 8329: });
 8330: // ]]>
 8331: </script>
 8332: OFFLOAD
 8333:                         }
 8334:                     }
 8335:                 }
 8336:             }
 8337:         }
 8338:     }
 8339:     if (!defined($title)) {
 8340: 	$title = 'The LearningOnline Network with CAPA';
 8341:     }
 8342:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 8343:     $result .= '<title> LON-CAPA '.$title.'</title>'
 8344: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
 8345:     if (!$args->{'frameset'}) {
 8346:         $result .= ' /';
 8347:     }
 8348:     $result .= '>'
 8349:         .$inhibitprint
 8350: 	.$head_extra;
 8351:     my $clientmobile;
 8352:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 8353:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
 8354:     } else {
 8355:         $clientmobile = $env{'browser.mobile'};
 8356:     }
 8357:     if ($clientmobile) {
 8358:         $result .= '
 8359: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 8360: <meta name="apple-mobile-web-app-capable" content="yes" />';
 8361:     }
 8362:     $result .= '<meta name="google" content="notranslate" />'."\n";
 8363:     return $result.'</head>';
 8364: }
 8365: 
 8366: =pod
 8367: 
 8368: =item * &font_settings()
 8369: 
 8370: Returns neccessary <meta> to set the proper encoding
 8371: 
 8372: Inputs: optional reference to HASH -- $args passed to &headtag()
 8373: 
 8374: =cut
 8375: 
 8376: sub font_settings {
 8377:     my ($args) = @_;
 8378:     my $headerstring='';
 8379:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
 8380:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
 8381: 	$headerstring.=
 8382: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
 8383:         if (!$args->{'frameset'}) {
 8384:             $headerstring.= ' /';
 8385:         }
 8386:         $headerstring .= '>'."\n";
 8387:     }
 8388:     return $headerstring;
 8389: }
 8390: 
 8391: =pod
 8392: 
 8393: =item * &print_suppression()
 8394: 
 8395: In course context returns css which causes the body to be blank when media="print",
 8396: if printout generation is unavailable for the current resource.
 8397: 
 8398: This could be because:
 8399: 
 8400: (a) printstartdate is in the future
 8401: 
 8402: (b) printenddate is in the past
 8403: 
 8404: (c) there is an active exam block with "printout"
 8405: functionality blocked
 8406: 
 8407: Users with pav, pfo or evb privileges are exempt.
 8408: 
 8409: Inputs: none
 8410: 
 8411: =cut
 8412: 
 8413: 
 8414: sub print_suppression {
 8415:     my $noprint;
 8416:     if ($env{'request.course.id'}) {
 8417:         my $scope = $env{'request.course.id'};
 8418:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8419:             (&Apache::lonnet::allowed('pfo',$scope))) {
 8420:             return;
 8421:         }
 8422:         if ($env{'request.course.sec'} ne '') {
 8423:             $scope .= "/$env{'request.course.sec'}";
 8424:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8425:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 8426:                 return;
 8427:             }
 8428:         }
 8429:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8430:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8431:         my $clientip = &Apache::lonnet::get_requestor_ip();
 8432:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
 8433:         if ($blocked) {
 8434:             my $checkrole = "cm./$cdom/$cnum";
 8435:             if ($env{'request.course.sec'} ne '') {
 8436:                 $checkrole .= "/$env{'request.course.sec'}";
 8437:             }
 8438:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 8439:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 8440:                 $noprint = 1;
 8441:             }
 8442:         }
 8443:         unless ($noprint) {
 8444:             my $symb = &Apache::lonnet::symbread();
 8445:             if ($symb ne '') {
 8446:                 my $navmap = Apache::lonnavmaps::navmap->new();
 8447:                 if (ref($navmap)) {
 8448:                     my $res = $navmap->getBySymb($symb);
 8449:                     if (ref($res)) {
 8450:                         if (!$res->resprintable()) {
 8451:                             $noprint = 1;
 8452:                         }
 8453:                     }
 8454:                 }
 8455:             }
 8456:         }
 8457:         if ($noprint) {
 8458:             return <<"ENDSTYLE";
 8459: <style type="text/css" media="print">
 8460:     body { display:none }
 8461: </style>
 8462: ENDSTYLE
 8463:         }
 8464:     }
 8465:     return;
 8466: }
 8467: 
 8468: =pod
 8469: 
 8470: =item * &xml_begin()
 8471: 
 8472: Returns the needed doctype and <html>
 8473: 
 8474: Inputs: none
 8475: 
 8476: =cut
 8477: 
 8478: sub xml_begin {
 8479:     my ($is_frameset) = @_;
 8480:     my $output='';
 8481: 
 8482:     if ($env{'browser.mathml'}) {
 8483: 	$output='<?xml version="1.0"?>'
 8484:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 8485: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 8486:             
 8487: #	    .'<!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">] >'
 8488: 	    .'<!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">'
 8489:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 8490: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 8491:     } elsif ($is_frameset) {
 8492:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
 8493:                 '<html>'."\n";
 8494:     } else {
 8495: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
 8496:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
 8497:     }
 8498:     return $output;
 8499: }
 8500: 
 8501: =pod
 8502: 
 8503: =item * &start_page()
 8504: 
 8505: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 8506: 
 8507: Inputs:
 8508: 
 8509: =over 4
 8510: 
 8511: $title - optional title for the page
 8512: 
 8513: $head_extra - optional extra HTML to incude inside the <head>
 8514: 
 8515: $args - additional optional args supported are:
 8516: 
 8517: =over 8
 8518: 
 8519:              only_body      -> is true will set &bodytag() onlybodytag
 8520:                                     arg on
 8521:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 8522:              add_entries    -> additional attributes to add to the  <body>
 8523:              domain         -> force to color decorate a page for a 
 8524:                                     specific domain
 8525:              function       -> force usage of a specific rolish color
 8526:                                     scheme
 8527:              redirect       -> see &headtag()
 8528:              bgcolor        -> override the default page bg color
 8529:              js_ready       -> return a string ready for being used in 
 8530:                                     a javascript writeln
 8531:              html_encode    -> return a string ready for being used in 
 8532:                                     a html attribute
 8533:              force_register -> if is true will turn on the &bodytag()
 8534:                                     $forcereg arg
 8535:              frameset       -> if true will start with a <frameset>
 8536:                                     rather than <body>
 8537:              skip_phases    -> hash ref of 
 8538:                                     head -> skip the <html><head> generation
 8539:                                     body -> skip all <body> generation
 8540:              no_inline_link -> if true and in remote mode, don't show the
 8541:                                     'Switch To Inline Menu' link
 8542:              no_auto_mt_title -> prevent &mt()ing the title arg
 8543:              bread_crumbs ->             Array containing breadcrumbs
 8544:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 8545:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
 8546:                                     to lonhtmlcommon::breadcrumbs
 8547:              group          -> includes the current group, if page is for a
 8548:                                specific group
 8549:              use_absolute   -> for request for external resource or syllabus, this
 8550:                                will contain https://<hostname> if server uses
 8551:                                https (as per hosts.tab), but request is for http
 8552:              hostname       -> hostname, originally from $r->hostname(), (optional).
 8553:              links_disabled -> Links in primary and secondary menus are disabled
 8554:                                (Can enable them once page has loaded - see lonroles.pm
 8555:                                for an example).
 8556: 
 8557: =back
 8558: 
 8559: =back
 8560: 
 8561: =cut
 8562: 
 8563: sub start_page {
 8564:     my ($title,$head_extra,$args) = @_;
 8565:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 8566: 
 8567:     $env{'internal.start_page'}++;
 8568:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
 8569: 
 8570:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 8571:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
 8572:     }
 8573: 
 8574:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
 8575:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
 8576:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
 8577:                 $args->{'no_primary_menu'} = 1;
 8578:             }
 8579:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
 8580:                 $args->{'no_inline_menu'} = 1;
 8581:             }
 8582:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
 8583:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
 8584:             }
 8585:         } else {
 8586:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8587:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
 8588:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
 8589:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
 8590:                     $args->{'no_primary_menu'} = 1;
 8591:                 }
 8592:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
 8593:                     $args->{'no_inline_menu'} = 1;
 8594:                 }
 8595:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
 8596:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
 8597:                 }
 8598:             }
 8599:         }
 8600:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
 8601:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
 8602:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
 8603:     } elsif ($env{'request.course.id'}) {
 8604:         my $expiretime=600;
 8605:         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
 8606:             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
 8607:         }
 8608:         my ($deeplinkmenu,$menuref);
 8609:         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
 8610:         if ($menucoll) {
 8611:             if (ref($menuref) eq 'HASH') {
 8612:                 %menu = %{$menuref};
 8613:             }
 8614:             if ($menu{'top'} eq 'n') {
 8615:                 $args->{'no_primary_menu'} = 1;
 8616:             }
 8617:             if ($menu{'inline'} eq 'n') {
 8618:                 unless (&Apache::lonnet::allowed('opa')) {
 8619:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8620:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8621:                     my $crstype = &course_type();
 8622:                     my $now = time;
 8623:                     my $ccrole;
 8624:                     if ($crstype eq 'Community') {
 8625:                         $ccrole = 'co';
 8626:                     } else {
 8627:                         $ccrole = 'cc';
 8628:                     }
 8629:                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
 8630:                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
 8631:                         if ((($start) && ($start<0)) ||
 8632:                             (($end) && ($end<$now))  ||
 8633:                             (($start) && ($now<$start))) {
 8634:                             $args->{'no_inline_menu'} = 1;
 8635:                         }
 8636:                     } else {
 8637:                         $args->{'no_inline_menu'} = 1;
 8638:                     }
 8639:                 }
 8640:             }
 8641:         }
 8642:     }
 8643: 
 8644:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 8645: 	if ($args->{'frameset'}) {
 8646: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 8647: 						$args->{'add_entries'});
 8648: 	    $result .= "\n<frameset $attr_string>\n";
 8649:         } else {
 8650:             $result .=
 8651:                 &bodytag($title, 
 8652:                          $args->{'function'},       $args->{'add_entries'},
 8653:                          $args->{'only_body'},      $args->{'domain'},
 8654:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 8655:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
 8656:                          $args,                     \@advtools,
 8657:                          $ltiscope,$ltiuri,\%ltimenu,$menucoll,\%menu);
 8658:         }
 8659:     }
 8660: 
 8661:     if ($args->{'js_ready'}) {
 8662: 		$result = &js_ready($result);
 8663:     }
 8664:     if ($args->{'html_encode'}) {
 8665: 		$result = &html_encode($result);
 8666:     }
 8667: 
 8668:     # Preparation for new and consistent functionlist at top of screen
 8669:     # if ($args->{'functionlist'}) {
 8670:     #            $result .= &build_functionlist();
 8671:     #}
 8672: 
 8673:     # Don't add anything more if only_body wanted or in const space
 8674:     return $result if    $args->{'only_body'} 
 8675:                       || $env{'request.state'} eq 'construct';
 8676: 
 8677:     #Breadcrumbs
 8678:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 8679: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 8680: 		#if any br links exists, add them to the breadcrumbs
 8681: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 8682: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 8683: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 8684: 			}
 8685: 		}
 8686:                 # if @advtools array contains items add then to the breadcrumbs
 8687:                 if (@advtools > 0) {
 8688:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 8689:                 }
 8690:                 my $menulink;
 8691:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
 8692:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
 8693:                     ($ltiscope eq 'map') || ($ltiscope eq 'resource')) {
 8694:                     $menulink = 0;
 8695:                 } else {
 8696:                     undef($menulink);
 8697:                 }
 8698: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 8699: 		if(exists($args->{'bread_crumbs_component'})){
 8700: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
 8701: 		} else {
 8702: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
 8703: 		}
 8704:     } elsif (($env{'environment.remote'} eq 'on') &&
 8705:              ($env{'form.inhibitmenu'} ne 'yes') &&
 8706:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
 8707:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
 8708:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
 8709:     }
 8710:     return $result;
 8711: }
 8712: 
 8713: sub end_page {
 8714:     my ($args) = @_;
 8715:     $env{'internal.end_page'}++;
 8716:     my $result;
 8717:     if ($args->{'discussion'}) {
 8718: 	my ($target,$parser);
 8719: 	if (ref($args->{'discussion'})) {
 8720: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 8721: 				$args->{'discussion'}{'parser'});
 8722: 	}
 8723: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 8724:     }
 8725:     if ($args->{'frameset'}) {
 8726: 	$result .= '</frameset>';
 8727:     } else {
 8728: 	$result .= &endbodytag($args);
 8729:     }
 8730:     unless ($args->{'notbody'}) {
 8731:         $result .= "\n</html>";
 8732:     }
 8733: 
 8734:     if ($args->{'js_ready'}) {
 8735: 	$result = &js_ready($result);
 8736:     }
 8737: 
 8738:     if ($args->{'html_encode'}) {
 8739: 	$result = &html_encode($result);
 8740:     }
 8741: 
 8742:     return $result;
 8743: }
 8744: 
 8745: sub menucoll_in_effect {
 8746:     my ($menucoll,$deeplinkmenu,%menu);
 8747:     if ($env{'request.course.id'}) {
 8748:         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
 8749:         if ($env{'request.deeplink.login'}) {
 8750:             my ($deeplink_symb,$deeplink,$check_login_symb);
 8751:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8752:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8753:             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
 8754:                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
 8755:                     my $navmap = Apache::lonnavmaps::navmap->new();
 8756:                     if (ref($navmap)) {
 8757:                         $deeplink = $navmap->get_mapparam(undef,
 8758:                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
 8759:                                                           '0.deeplink');
 8760:                     } else {
 8761:                         $check_login_symb = 1;
 8762:                     }
 8763:                 } else {
 8764:                     my $symb=&Apache::lonnet::symbread();
 8765:                     if ($symb) {
 8766:                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
 8767:                     } else {
 8768:                         $check_login_symb = 1;
 8769:                     }
 8770:                 }
 8771:             } else {
 8772:                 $check_login_symb = 1;
 8773:             }
 8774:             if ($check_login_symb) {
 8775:                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
 8776:                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
 8777:                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
 8778:                     my $navmap = Apache::lonnavmaps::navmap->new();
 8779:                     if (ref($navmap)) {
 8780:                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
 8781:                     }
 8782:                 } else {
 8783:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
 8784:                 }
 8785:             }
 8786:             if ($deeplink ne '') {
 8787:                 my ($state,$others,$listed,$scope,$protect,$display) = split(/,/,$deeplink);
 8788:                 if ($display =~ /^\d+$/) {
 8789:                     $deeplinkmenu = 1;
 8790:                     $menucoll = $display;
 8791:                 }
 8792:             }
 8793:         }
 8794:         if ($menucoll) {
 8795:             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
 8796:         }
 8797:     }
 8798:     return ($menucoll,$deeplinkmenu,\%menu);
 8799: }
 8800: 
 8801: sub deeplink_login_symb {
 8802:     my ($cnum,$cdom) = @_;
 8803:     my $login_symb;
 8804:     if ($env{'request.deeplink.login'}) {
 8805:         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
 8806:     }
 8807:     return $login_symb;
 8808: }
 8809: 
 8810: sub symb_from_tinyurl {
 8811:     my ($url,$cnum,$cdom) = @_;
 8812:     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
 8813:         my $key = $1;
 8814:         my ($tinyurl,$login);
 8815:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
 8816:         if (defined($cached)) {
 8817:             $tinyurl = $result;
 8818:         } else {
 8819:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
 8820:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
 8821:             if ($currtiny{$key} ne '') {
 8822:                 $tinyurl = $currtiny{$key};
 8823:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
 8824:             }
 8825:         }
 8826:         if ($tinyurl ne '') {
 8827:             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
 8828:             if (wantarray) {
 8829:                 return ($cnumreq,$symb);
 8830:             } elsif ($cnumreq eq $cnum) {
 8831:                 return $symb;
 8832:             }
 8833:         }
 8834:     }
 8835:     if (wantarray) {
 8836:         return ();
 8837:     } else {
 8838:         return;
 8839:     }
 8840: }
 8841: 
 8842: sub wishlist_window {
 8843:     return(<<'ENDWISHLIST');
 8844: <script type="text/javascript">
 8845: // <![CDATA[
 8846: // <!-- BEGIN LON-CAPA Internal
 8847: function set_wishlistlink(title, path) {
 8848:     if (!title) {
 8849:         title = document.title;
 8850:         title = title.replace(/^LON-CAPA /,'');
 8851:     }
 8852:     title = encodeURIComponent(title);
 8853:     title = title.replace("'","\\\'");
 8854:     if (!path) {
 8855:         path = location.pathname;
 8856:     }
 8857:     path = encodeURIComponent(path);
 8858:     path = path.replace("'","\\\'");
 8859:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 8860:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 8861: }
 8862: // END LON-CAPA Internal -->
 8863: // ]]>
 8864: </script>
 8865: ENDWISHLIST
 8866: }
 8867: 
 8868: sub modal_window {
 8869:     return(<<'ENDMODAL');
 8870: <script type="text/javascript">
 8871: // <![CDATA[
 8872: // <!-- BEGIN LON-CAPA Internal
 8873: var modalWindow = {
 8874: 	parent:"body",
 8875: 	windowId:null,
 8876: 	content:null,
 8877: 	width:null,
 8878: 	height:null,
 8879: 	close:function()
 8880: 	{
 8881: 	        $(".LCmodal-window").remove();
 8882: 	        $(".LCmodal-overlay").remove();
 8883: 	},
 8884: 	open:function()
 8885: 	{
 8886: 		var modal = "";
 8887: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 8888: 		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;\">";
 8889: 		modal += this.content;
 8890: 		modal += "</div>";	
 8891: 
 8892: 		$(this.parent).append(modal);
 8893: 
 8894: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 8895: 		$(".LCclose-window").click(function(){modalWindow.close();});
 8896: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 8897: 	}
 8898: };
 8899: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
 8900: 	{
 8901:                 source = source.replace(/'/g,"&#39;");
 8902: 		modalWindow.windowId = "myModal";
 8903: 		modalWindow.width = width;
 8904: 		modalWindow.height = height;
 8905: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
 8906: 		modalWindow.open();
 8907: 	};
 8908: // END LON-CAPA Internal -->
 8909: // ]]>
 8910: </script>
 8911: ENDMODAL
 8912: }
 8913: 
 8914: sub modal_link {
 8915:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
 8916:     unless ($width) { $width=480; }
 8917:     unless ($height) { $height=400; }
 8918:     unless ($scrolling) { $scrolling='yes'; }
 8919:     unless ($transparency) { $transparency='true'; }
 8920: 
 8921:     my $target_attr;
 8922:     if (defined($target)) {
 8923:         $target_attr = 'target="'.$target.'"';
 8924:     }
 8925:     return <<"ENDLINK";
 8926: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
 8927: ENDLINK
 8928: }
 8929: 
 8930: sub modal_adhoc_script {
 8931:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
 8932:     my $mathjax;
 8933:     if ($possmathjax) {
 8934:         $mathjax = <<'ENDJAX';
 8935:                if (typeof MathJax == 'object') {
 8936:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
 8937:                }
 8938: ENDJAX
 8939:     }
 8940:     return (<<ENDADHOC);
 8941: <script type="text/javascript">
 8942: // <![CDATA[
 8943:         var $funcname = function()
 8944:         {
 8945:                 modalWindow.windowId = "myModal";
 8946:                 modalWindow.width = $width;
 8947:                 modalWindow.height = $height;
 8948:                 modalWindow.content = '$content';
 8949:                 modalWindow.open();
 8950:                 $mathjax
 8951:         };  
 8952: // ]]>
 8953: </script>
 8954: ENDADHOC
 8955: }
 8956: 
 8957: sub modal_adhoc_inner {
 8958:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
 8959:     my $innerwidth=$width-20;
 8960:     $content=&js_ready(
 8961:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 8962:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
 8963:                  $content.
 8964:                  &end_scrollbox().
 8965:                  &end_page()
 8966:              );
 8967:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
 8968: }
 8969: 
 8970: sub modal_adhoc_window {
 8971:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
 8972:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
 8973:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 8974: }
 8975: 
 8976: sub modal_adhoc_launch {
 8977:     my ($funcname,$width,$height,$content)=@_;
 8978:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 8979: <script type="text/javascript">
 8980: // <![CDATA[
 8981: $funcname();
 8982: // ]]>
 8983: </script>
 8984: ENDLAUNCH
 8985: }
 8986: 
 8987: sub modal_adhoc_close {
 8988:     return (<<ENDCLOSE);
 8989: <script type="text/javascript">
 8990: // <![CDATA[
 8991: modalWindow.close();
 8992: // ]]>
 8993: </script>
 8994: ENDCLOSE
 8995: }
 8996: 
 8997: sub togglebox_script {
 8998:    return(<<ENDTOGGLE);
 8999: <script type="text/javascript"> 
 9000: // <![CDATA[
 9001: function LCtoggleDisplay(id,hidetext,showtext) {
 9002:    link = document.getElementById(id + "link").childNodes[0];
 9003:    with (document.getElementById(id).style) {
 9004:       if (display == "none" ) {
 9005:           display = "inline";
 9006:           link.nodeValue = hidetext;
 9007:         } else {
 9008:           display = "none";
 9009:           link.nodeValue = showtext;
 9010:        }
 9011:    }
 9012: }
 9013: // ]]>
 9014: </script>
 9015: ENDTOGGLE
 9016: }
 9017: 
 9018: sub start_togglebox {
 9019:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 9020:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 9021:     unless ($showtext) { $showtext=&mt('show'); }
 9022:     unless ($hidetext) { $hidetext=&mt('hide'); }
 9023:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 9024:     return &start_data_table().
 9025:            &start_data_table_header_row().
 9026:            '<td bgcolor="'.$headerbg.'">'.$heading.
 9027:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 9028:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 9029:            &end_data_table_header_row().
 9030:            '<tr id="'.$id.'" style="display:none""><td>';
 9031: }
 9032: 
 9033: sub end_togglebox {
 9034:     return '</td></tr>'.&end_data_table();
 9035: }
 9036: 
 9037: sub LCprogressbar_script {
 9038:    my ($id,$number_to_do)=@_;
 9039:    if ($number_to_do) {
 9040:        return(<<ENDPROGRESS);
 9041: <script type="text/javascript">
 9042: // <![CDATA[
 9043: \$('#progressbar$id').progressbar({
 9044:   value: 0,
 9045:   change: function(event, ui) {
 9046:     var newVal = \$(this).progressbar('option', 'value');
 9047:     \$('.pblabel', this).text(LCprogressTxt);
 9048:   }
 9049: });
 9050: // ]]>
 9051: </script>
 9052: ENDPROGRESS
 9053:    } else {
 9054:        return(<<ENDPROGRESS);
 9055: <script type="text/javascript">
 9056: // <![CDATA[
 9057: \$('#progressbar$id').progressbar({
 9058:   value: false,
 9059:   create: function(event, ui) {
 9060:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
 9061:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
 9062:   }
 9063: });
 9064: // ]]>
 9065: </script>
 9066: ENDPROGRESS
 9067:    }
 9068: }
 9069: 
 9070: sub LCprogressbarUpdate_script {
 9071:    return(<<ENDPROGRESSUPDATE);
 9072: <style type="text/css">
 9073: .ui-progressbar { position:relative; }
 9074: .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%; }
 9075: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 9076: </style>
 9077: <script type="text/javascript">
 9078: // <![CDATA[
 9079: var LCprogressTxt='---';
 9080: 
 9081: function LCupdateProgress(percent,progresstext,id,maxnum) {
 9082:    LCprogressTxt=progresstext;
 9083:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
 9084:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
 9085:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
 9086:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
 9087:    } else {
 9088:        \$('#progressbar'+id).progressbar('value',percent);
 9089:    }
 9090: }
 9091: // ]]>
 9092: </script>
 9093: ENDPROGRESSUPDATE
 9094: }
 9095: 
 9096: my $LClastpercent;
 9097: my $LCidcnt;
 9098: my $LCcurrentid;
 9099: 
 9100: sub LCprogressbar {
 9101:     my ($r,$number_to_do,$preamble)=@_;
 9102:     $LClastpercent=0;
 9103:     $LCidcnt++;
 9104:     $LCcurrentid=$$.'_'.$LCidcnt;
 9105:     my ($starting,$content);
 9106:     if ($number_to_do) {
 9107:         $starting=&mt('Starting');
 9108:         $content=(<<ENDPROGBAR);
 9109: $preamble
 9110:   <div id="progressbar$LCcurrentid">
 9111:     <span class="pblabel">$starting</span>
 9112:   </div>
 9113: ENDPROGBAR
 9114:     } else {
 9115:         $starting=&mt('Loading...');
 9116:         $LClastpercent='false';
 9117:         $content=(<<ENDPROGBAR);
 9118: $preamble
 9119:   <div id="progressbar$LCcurrentid">
 9120:       <div class="progress-label">$starting</div>
 9121:   </div>
 9122: ENDPROGBAR
 9123:     }
 9124:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
 9125: }
 9126: 
 9127: sub LCprogressbarUpdate {
 9128:     my ($r,$val,$text,$number_to_do)=@_;
 9129:     if ($number_to_do) {
 9130:         unless ($val) { 
 9131:             if ($LClastpercent) {
 9132:                 $val=$LClastpercent;
 9133:             } else {
 9134:                 $val=0;
 9135:             }
 9136:         }
 9137:         if ($val<0) { $val=0; }
 9138:         if ($val>100) { $val=0; }
 9139:         $LClastpercent=$val;
 9140:         unless ($text) { $text=$val.'%'; }
 9141:     } else {
 9142:         $val = 'false';
 9143:     }
 9144:     $text=&js_ready($text);
 9145:     &r_print($r,<<ENDUPDATE);
 9146: <script type="text/javascript">
 9147: // <![CDATA[
 9148: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
 9149: // ]]>
 9150: </script>
 9151: ENDUPDATE
 9152: }
 9153: 
 9154: sub LCprogressbarClose {
 9155:     my ($r)=@_;
 9156:     $LClastpercent=0;
 9157:     &r_print($r,<<ENDCLOSE);
 9158: <script type="text/javascript">
 9159: // <![CDATA[
 9160: \$("#progressbar$LCcurrentid").hide('slow'); 
 9161: // ]]>
 9162: </script>
 9163: ENDCLOSE
 9164: }
 9165: 
 9166: sub r_print {
 9167:     my ($r,$to_print)=@_;
 9168:     if ($r) {
 9169:       $r->print($to_print);
 9170:       $r->rflush();
 9171:     } else {
 9172:       print($to_print);
 9173:     }
 9174: }
 9175: 
 9176: sub html_encode {
 9177:     my ($result) = @_;
 9178: 
 9179:     $result = &HTML::Entities::encode($result,'<>&"');
 9180:     
 9181:     return $result;
 9182: }
 9183: 
 9184: sub js_ready {
 9185:     my ($result) = @_;
 9186: 
 9187:     $result =~ s/[\n\r]/ /xmsg;
 9188:     $result =~ s/\\/\\\\/xmsg;
 9189:     $result =~ s/'/\\'/xmsg;
 9190:     $result =~ s{</}{<\\/}xmsg;
 9191:     
 9192:     return $result;
 9193: }
 9194: 
 9195: sub validate_page {
 9196:     if (  exists($env{'internal.start_page'})
 9197: 	  &&     $env{'internal.start_page'} > 1) {
 9198: 	&Apache::lonnet::logthis('start_page called multiple times '.
 9199: 				 $env{'internal.start_page'}.' '.
 9200: 				 $ENV{'request.filename'});
 9201:     }
 9202:     if (  exists($env{'internal.end_page'})
 9203: 	  &&     $env{'internal.end_page'} > 1) {
 9204: 	&Apache::lonnet::logthis('end_page called multiple times '.
 9205: 				 $env{'internal.end_page'}.' '.
 9206: 				 $env{'request.filename'});
 9207:     }
 9208:     if (     exists($env{'internal.start_page'})
 9209: 	&& ! exists($env{'internal.end_page'})) {
 9210: 	&Apache::lonnet::logthis('start_page called without end_page '.
 9211: 				 $env{'request.filename'});
 9212:     }
 9213:     if (   ! exists($env{'internal.start_page'})
 9214: 	&&   exists($env{'internal.end_page'})) {
 9215: 	&Apache::lonnet::logthis('end_page called without start_page'.
 9216: 				 $env{'request.filename'});
 9217:     }
 9218: }
 9219: 
 9220: 
 9221: sub start_scrollbox {
 9222:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
 9223:     unless ($outerwidth) { $outerwidth='520px'; }
 9224:     unless ($width) { $width='500px'; }
 9225:     unless ($height) { $height='200px'; }
 9226:     my ($table_id,$div_id,$tdcol);
 9227:     if ($id ne '') {
 9228:         $table_id = ' id="table_'.$id.'"';
 9229:         $div_id = ' id="div_'.$id.'"';
 9230:     }
 9231:     if ($bgcolor ne '') {
 9232:         $tdcol = "background-color: $bgcolor;";
 9233:     }
 9234:     my $nicescroll_js;
 9235:     if ($env{'browser.mobile'}) {
 9236:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
 9237:     }
 9238:     return <<"END";
 9239: $nicescroll_js
 9240: 
 9241: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
 9242: <div style="overflow:auto; width:$width; height:$height;"$div_id>
 9243: END
 9244: }
 9245: 
 9246: sub end_scrollbox {
 9247:     return '</div></td></tr></table>';
 9248: }
 9249: 
 9250: sub nicescroll_javascript {
 9251:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
 9252:     my %options;
 9253:     if (ref($cursor) eq 'HASH') {
 9254:         %options = %{$cursor};
 9255:     }
 9256:     unless ($options{'railalign'} =~ /^left|right$/) {
 9257:         $options{'railalign'} = 'left';
 9258:     }
 9259:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 9260:         my $function  = &get_users_function();
 9261:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
 9262:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 9263:             $options{'cursorcolor'} = '#00F';
 9264:         }
 9265:     }
 9266:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
 9267:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
 9268:             $options{'cursoropacity'}='1.0';
 9269:         }
 9270:     } else {
 9271:         $options{'cursoropacity'}='1.0';
 9272:     }
 9273:     if ($options{'cursorfixedheight'} eq 'none') {
 9274:         delete($options{'cursorfixedheight'});
 9275:     } else {
 9276:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
 9277:     }
 9278:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
 9279:         delete($options{'railoffset'});
 9280:     }
 9281:     my @niceoptions;
 9282:     while (my($key,$value) = each(%options)) {
 9283:         if ($value =~ /^\{.+\}$/) {
 9284:             push(@niceoptions,$key.':'.$value);
 9285:         } else {
 9286:             push(@niceoptions,$key.':"'.$value.'"');
 9287:         }
 9288:     }
 9289:     my $nicescroll_js = '
 9290: $(document).ready(
 9291:       function() {
 9292:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
 9293:       }
 9294: );
 9295: ';
 9296:     if ($framecheck) {
 9297:         $nicescroll_js .= '
 9298: function expand_div(caller) {
 9299:     if (top === self) {
 9300:         document.getElementById("'.$id.'").style.width = "auto";
 9301:         document.getElementById("'.$id.'").style.height = "auto";
 9302:     } else {
 9303:         try {
 9304:             if (parent.frames) {
 9305:                 if (parent.frames.length > 1) {
 9306:                     var framesrc = parent.frames[1].location.href;
 9307:                     var currsrc = framesrc.replace(/\#.*$/,"");
 9308:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
 9309:                         document.getElementById("'.$id.'").style.width = "auto";
 9310:                         document.getElementById("'.$id.'").style.height = "auto";
 9311:                     }
 9312:                 }
 9313:             }
 9314:         } catch (e) {
 9315:             return;
 9316:         }
 9317:     }
 9318:     return;
 9319: }
 9320: ';
 9321:     }
 9322:     if ($needjsready) {
 9323:         $nicescroll_js = '
 9324: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
 9325:     } else {
 9326:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
 9327:     }
 9328:     return $nicescroll_js;
 9329: }
 9330: 
 9331: sub simple_error_page {
 9332:     my ($r,$title,$msg,$args) = @_;
 9333:     my %displayargs;
 9334:     if (ref($args) eq 'HASH') {
 9335:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
 9336:         if ($args->{'only_body'}) {
 9337:             $displayargs{'only_body'} = 1;
 9338:         }
 9339:         if ($args->{'no_nav_bar'}) {
 9340:             $displayargs{'no_nav_bar'} = 1;
 9341:         }
 9342:     } else {
 9343:         $msg = &mt($msg);
 9344:     }
 9345: 
 9346:     my $page =
 9347: 	&Apache::loncommon::start_page($title,'',\%displayargs).
 9348: 	'<p class="LC_error">'.$msg.'</p>'.
 9349: 	&Apache::loncommon::end_page();
 9350:     if (ref($r)) {
 9351: 	$r->print($page);
 9352: 	return;
 9353:     }
 9354:     return $page;
 9355: }
 9356: 
 9357: {
 9358:     my @row_count;
 9359: 
 9360:     sub start_data_table_count {
 9361:         unshift(@row_count, 0);
 9362:         return;
 9363:     }
 9364: 
 9365:     sub end_data_table_count {
 9366:         shift(@row_count);
 9367:         return;
 9368:     }
 9369: 
 9370:     sub start_data_table {
 9371: 	my ($add_class,$id) = @_;
 9372: 	my $css_class = (join(' ','LC_data_table',$add_class));
 9373:         my $table_id;
 9374:         if (defined($id)) {
 9375:             $table_id = ' id="'.$id.'"';
 9376:         }
 9377: 	&start_data_table_count();
 9378: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 9379:     }
 9380: 
 9381:     sub end_data_table {
 9382: 	&end_data_table_count();
 9383: 	return '</table>'."\n";;
 9384:     }
 9385: 
 9386:     sub start_data_table_row {
 9387: 	my ($add_class, $id) = @_;
 9388: 	$row_count[0]++;
 9389: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 9390: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 9391:         $id = (' id="'.$id.'"') unless ($id eq '');
 9392:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 9393:     }
 9394:     
 9395:     sub continue_data_table_row {
 9396: 	my ($add_class, $id) = @_;
 9397: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 9398: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 9399:         $id = (' id="'.$id.'"') unless ($id eq '');
 9400:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 9401:     }
 9402: 
 9403:     sub end_data_table_row {
 9404: 	return '</tr>'."\n";;
 9405:     }
 9406: 
 9407:     sub start_data_table_empty_row {
 9408: #	$row_count[0]++;
 9409: 	return  '<tr class="LC_empty_row" >'."\n";;
 9410:     }
 9411: 
 9412:     sub end_data_table_empty_row {
 9413: 	return '</tr>'."\n";;
 9414:     }
 9415: 
 9416:     sub start_data_table_header_row {
 9417: 	return  '<tr class="LC_header_row">'."\n";;
 9418:     }
 9419: 
 9420:     sub end_data_table_header_row {
 9421: 	return '</tr>'."\n";;
 9422:     }
 9423: 
 9424:     sub data_table_caption {
 9425:         my $caption = shift;
 9426:         return "<caption class=\"LC_caption\">$caption</caption>";
 9427:     }
 9428: }
 9429: 
 9430: =pod
 9431: 
 9432: =item * &inhibit_menu_check($arg)
 9433: 
 9434: Checks for a inhibitmenu state and generates output to preserve it
 9435: 
 9436: Inputs:         $arg - can be any of
 9437:                      - undef - in which case the return value is a string 
 9438:                                to add  into arguments list of a uri
 9439:                      - 'input' - in which case the return value is a HTML
 9440:                                  <form> <input> field of type hidden to
 9441:                                  preserve the value
 9442:                      - a url - in which case the return value is the url with
 9443:                                the neccesary cgi args added to preserve the
 9444:                                inhibitmenu state
 9445:                      - a ref to a url - no return value, but the string is
 9446:                                         updated to include the neccessary cgi
 9447:                                         args to preserve the inhibitmenu state
 9448: 
 9449: =cut
 9450: 
 9451: sub inhibit_menu_check {
 9452:     my ($arg) = @_;
 9453:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 9454:     if ($arg eq 'input') {
 9455: 	if ($env{'form.inhibitmenu'}) {
 9456: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 9457: 	} else {
 9458: 	    return
 9459: 	}
 9460:     }
 9461:     if ($env{'form.inhibitmenu'}) {
 9462: 	if (ref($arg)) {
 9463: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 9464: 	} elsif ($arg eq '') {
 9465: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 9466: 	} else {
 9467: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 9468: 	}
 9469:     }
 9470:     if (!ref($arg)) {
 9471: 	return $arg;
 9472:     }
 9473: }
 9474: 
 9475: ###############################################
 9476: 
 9477: =pod
 9478: 
 9479: =back
 9480: 
 9481: =head1 User Information Routines
 9482: 
 9483: =over 4
 9484: 
 9485: =item * &get_users_function()
 9486: 
 9487: Used by &bodytag to determine the current users primary role.
 9488: Returns either 'student','coordinator','admin', or 'author'.
 9489: 
 9490: =cut
 9491: 
 9492: ###############################################
 9493: sub get_users_function {
 9494:     my $function = 'norole';
 9495:     if ($env{'request.role'}=~/^(st)/) {
 9496:         $function='student';
 9497:     }
 9498:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 9499:         $function='coordinator';
 9500:     }
 9501:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 9502:         $function='admin';
 9503:     }
 9504:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 9505:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 9506:         $function='author';
 9507:     }
 9508:     return $function;
 9509: }
 9510: 
 9511: ###############################################
 9512: 
 9513: =pod
 9514: 
 9515: =item * &show_course()
 9516: 
 9517: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 9518: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 9519: 
 9520: Inputs:
 9521: None
 9522: 
 9523: Outputs:
 9524: Scalar: 1 if 'Course' to be used, 0 otherwise.
 9525: 
 9526: =cut
 9527: 
 9528: ###############################################
 9529: sub show_course {
 9530:     my $course = !$env{'user.adv'};
 9531:     if (!$env{'user.adv'}) {
 9532:         foreach my $env (keys(%env)) {
 9533:             next if ($env !~ m/^user\.priv\./);
 9534:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 9535:                 $course = 0;
 9536:                 last;
 9537:             }
 9538:         }
 9539:     }
 9540:     return $course;
 9541: }
 9542: 
 9543: ###############################################
 9544: 
 9545: =pod
 9546: 
 9547: =item * &check_user_status()
 9548: 
 9549: Determines current status of supplied role for a
 9550: specific user. Roles can be active, previous or future.
 9551: 
 9552: Inputs: 
 9553: user's domain, user's username, course's domain,
 9554: course's number, optional section ID.
 9555: 
 9556: Outputs:
 9557: role status: active, previous or future. 
 9558: 
 9559: =cut
 9560: 
 9561: sub check_user_status {
 9562:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 9563:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 9564:     my @uroles = keys(%userinfo);
 9565:     my $srchstr;
 9566:     my $active_chk = 'none';
 9567:     my $now = time;
 9568:     if (@uroles > 0) {
 9569:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 9570:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 9571:         } else {
 9572:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 9573:         }
 9574:         if (grep/^\Q$srchstr\E$/,@uroles) {
 9575:             my $role_end = 0;
 9576:             my $role_start = 0;
 9577:             $active_chk = 'active';
 9578:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 9579:                 $role_end = $1;
 9580:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 9581:                     $role_start = $1;
 9582:                 }
 9583:             }
 9584:             if ($role_start > 0) {
 9585:                 if ($now < $role_start) {
 9586:                     $active_chk = 'future';
 9587:                 }
 9588:             }
 9589:             if ($role_end > 0) {
 9590:                 if ($now > $role_end) {
 9591:                     $active_chk = 'previous';
 9592:                 }
 9593:             }
 9594:         }
 9595:     }
 9596:     return $active_chk;
 9597: }
 9598: 
 9599: ###############################################
 9600: 
 9601: =pod
 9602: 
 9603: =item * &get_sections()
 9604: 
 9605: Determines all the sections for a course including
 9606: sections with students and sections containing other roles.
 9607: Incoming parameters: 
 9608: 
 9609: 1. domain
 9610: 2. course number 
 9611: 3. reference to array containing roles for which sections should 
 9612: be gathered (optional).
 9613: 4. reference to array containing status types for which sections 
 9614: should be gathered (optional).
 9615: 
 9616: If the third argument is undefined, sections are gathered for any role. 
 9617: If the fourth argument is undefined, sections are gathered for any status.
 9618: Permissible values are 'active' or 'future' or 'previous'.
 9619:  
 9620: Returns section hash (keys are section IDs, values are
 9621: number of users in each section), subject to the
 9622: optional roles filter, optional status filter 
 9623: 
 9624: =cut
 9625: 
 9626: ###############################################
 9627: sub get_sections {
 9628:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 9629:     if (!defined($cdom) || !defined($cnum)) {
 9630:         my $cid =  $env{'request.course.id'};
 9631: 
 9632: 	return if (!defined($cid));
 9633: 
 9634:         $cdom = $env{'course.'.$cid.'.domain'};
 9635:         $cnum = $env{'course.'.$cid.'.num'};
 9636:     }
 9637: 
 9638:     my %sectioncount;
 9639:     my $now = time;
 9640: 
 9641:     my $check_students = 1;
 9642:     my $only_students = 0;
 9643:     if (ref($possible_roles) eq 'ARRAY') {
 9644:         if (grep(/^st$/,@{$possible_roles})) {
 9645:             if (@{$possible_roles} == 1) {
 9646:                 $only_students = 1;
 9647:             }
 9648:         } else {
 9649:             $check_students = 0;
 9650:         }
 9651:     }
 9652: 
 9653:     if ($check_students) {
 9654: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 9655: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 9656: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 9657:         my $start_index = &Apache::loncoursedata::CL_START();
 9658:         my $end_index = &Apache::loncoursedata::CL_END();
 9659:         my $status;
 9660: 	while (my ($student,$data) = each(%$classlist)) {
 9661: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 9662: 				                     $data->[$status_index],
 9663:                                                      $data->[$start_index],
 9664:                                                      $data->[$end_index]);
 9665:             if ($stu_status eq 'Active') {
 9666:                 $status = 'active';
 9667:             } elsif ($end < $now) {
 9668:                 $status = 'previous';
 9669:             } elsif ($start > $now) {
 9670:                 $status = 'future';
 9671:             } 
 9672: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 9673:                 if ((!defined($possible_status)) || (($status ne '') && 
 9674:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 9675: 		    $sectioncount{$section}++;
 9676:                 }
 9677: 	    }
 9678: 	}
 9679:     }
 9680:     if ($only_students) {
 9681:         return %sectioncount;
 9682:     }
 9683:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9684:     foreach my $user (sort(keys(%courseroles))) {
 9685: 	if ($user !~ /^(\w{2})/) { next; }
 9686: 	my ($role) = ($user =~ /^(\w{2})/);
 9687: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 9688: 	my ($section,$status);
 9689: 	if ($role eq 'cr' &&
 9690: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 9691: 	    $section=$1;
 9692: 	}
 9693: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 9694: 	if (!defined($section) || $section eq '-1') { next; }
 9695:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 9696:         if ($end == -1 && $start == -1) {
 9697:             next; #deleted role
 9698:         }
 9699:         if (!defined($possible_status)) { 
 9700:             $sectioncount{$section}++;
 9701:         } else {
 9702:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 9703:                 $status = 'active';
 9704:             } elsif ($end < $now) {
 9705:                 $status = 'future';
 9706:             } elsif ($start > $now) {
 9707:                 $status = 'previous';
 9708:             }
 9709:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 9710:                 $sectioncount{$section}++;
 9711:             }
 9712:         }
 9713:     }
 9714:     return %sectioncount;
 9715: }
 9716: 
 9717: ###############################################
 9718: 
 9719: =pod
 9720: 
 9721: =item * &get_course_users()
 9722: 
 9723: Retrieves usernames:domains for users in the specified course
 9724: with specific role(s), and access status. 
 9725: 
 9726: Incoming parameters:
 9727: 1. course domain
 9728: 2. course number
 9729: 3. access status: users must have - either active, 
 9730: previous, future, or all.
 9731: 4. reference to array of permissible roles
 9732: 5. reference to array of section restrictions (optional)
 9733: 6. reference to results object (hash of hashes).
 9734: 7. reference to optional userdata hash
 9735: 8. reference to optional statushash
 9736: 9. flag if privileged users (except those set to unhide in
 9737:    course settings) should be excluded    
 9738: Keys of top level results hash are roles.
 9739: Keys of inner hashes are username:domain, with 
 9740: values set to access type.
 9741: Optional userdata hash returns an array with arguments in the 
 9742: same order as loncoursedata::get_classlist() for student data.
 9743: 
 9744: Optional statushash returns
 9745: 
 9746: Entries for end, start, section and status are blank because
 9747: of the possibility of multiple values for non-student roles.
 9748: 
 9749: =cut
 9750: 
 9751: ###############################################
 9752: 
 9753: sub get_course_users {
 9754:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 9755:     my %idx = ();
 9756:     my %seclists;
 9757: 
 9758:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 9759:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 9760:     $idx{end} = &Apache::loncoursedata::CL_END();
 9761:     $idx{start} = &Apache::loncoursedata::CL_START();
 9762:     $idx{id} = &Apache::loncoursedata::CL_ID();
 9763:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 9764:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 9765:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 9766: 
 9767:     if (grep(/^st$/,@{$roles})) {
 9768:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 9769:         my $now = time;
 9770:         foreach my $student (keys(%{$classlist})) {
 9771:             my $match = 0;
 9772:             my $secmatch = 0;
 9773:             my $section = $$classlist{$student}[$idx{section}];
 9774:             my $status = $$classlist{$student}[$idx{status}];
 9775:             if ($section eq '') {
 9776:                 $section = 'none';
 9777:             }
 9778:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 9779:                 if (grep(/^all$/,@{$sections})) {
 9780:                     $secmatch = 1;
 9781:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 9782:                     if (grep(/^none$/,@{$sections})) {
 9783:                         $secmatch = 1;
 9784:                     }
 9785:                 } else {  
 9786: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 9787: 		        $secmatch = 1;
 9788:                     }
 9789: 		}
 9790:                 if (!$secmatch) {
 9791:                     next;
 9792:                 }
 9793:             }
 9794:             if (defined($$types{'active'})) {
 9795:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 9796:                     push(@{$$users{st}{$student}},'active');
 9797:                     $match = 1;
 9798:                 }
 9799:             }
 9800:             if (defined($$types{'previous'})) {
 9801:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 9802:                     push(@{$$users{st}{$student}},'previous');
 9803:                     $match = 1;
 9804:                 }
 9805:             }
 9806:             if (defined($$types{'future'})) {
 9807:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 9808:                     push(@{$$users{st}{$student}},'future');
 9809:                     $match = 1;
 9810:                 }
 9811:             }
 9812:             if ($match) {
 9813:                 push(@{$seclists{$student}},$section);
 9814:                 if (ref($userdata) eq 'HASH') {
 9815:                     $$userdata{$student} = $$classlist{$student};
 9816:                 }
 9817:                 if (ref($statushash) eq 'HASH') {
 9818:                     $statushash->{$student}{'st'}{$section} = $status;
 9819:                 }
 9820:             }
 9821:         }
 9822:     }
 9823:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 9824:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9825:         my $now = time;
 9826:         my %displaystatus = ( previous => 'Expired',
 9827:                               active   => 'Active',
 9828:                               future   => 'Future',
 9829:                             );
 9830:         my (%nothide,@possdoms);
 9831:         if ($hidepriv) {
 9832:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 9833:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 9834:                 if ($user !~ /:/) {
 9835:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 9836:                 } else {
 9837:                     $nothide{$user} = 1;
 9838:                 }
 9839:             }
 9840:             my @possdoms = ($cdom);
 9841:             if ($coursehash{'checkforpriv'}) {
 9842:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 9843:             }
 9844:         }
 9845:         foreach my $person (sort(keys(%coursepersonnel))) {
 9846:             my $match = 0;
 9847:             my $secmatch = 0;
 9848:             my $status;
 9849:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 9850:             $user =~ s/:$//;
 9851:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 9852:             if ($end == -1 || $start == -1) {
 9853:                 next;
 9854:             }
 9855:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 9856:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 9857:                 my ($uname,$udom) = split(/:/,$user);
 9858:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 9859:                     if (grep(/^all$/,@{$sections})) {
 9860:                         $secmatch = 1;
 9861:                     } elsif ($usec eq '') {
 9862:                         if (grep(/^none$/,@{$sections})) {
 9863:                             $secmatch = 1;
 9864:                         }
 9865:                     } else {
 9866:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 9867:                             $secmatch = 1;
 9868:                         }
 9869:                     }
 9870:                     if (!$secmatch) {
 9871:                         next;
 9872:                     }
 9873:                 }
 9874:                 if ($usec eq '') {
 9875:                     $usec = 'none';
 9876:                 }
 9877:                 if ($uname ne '' && $udom ne '') {
 9878:                     if ($hidepriv) {
 9879:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
 9880:                             (!$nothide{$uname.':'.$udom})) {
 9881:                             next;
 9882:                         }
 9883:                     }
 9884:                     if ($end > 0 && $end < $now) {
 9885:                         $status = 'previous';
 9886:                     } elsif ($start > $now) {
 9887:                         $status = 'future';
 9888:                     } else {
 9889:                         $status = 'active';
 9890:                     }
 9891:                     foreach my $type (keys(%{$types})) { 
 9892:                         if ($status eq $type) {
 9893:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 9894:                                 push(@{$$users{$role}{$user}},$type);
 9895:                             }
 9896:                             $match = 1;
 9897:                         }
 9898:                     }
 9899:                     if (($match) && (ref($userdata) eq 'HASH')) {
 9900:                         if (!exists($$userdata{$uname.':'.$udom})) {
 9901: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 9902:                         }
 9903:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 9904:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 9905:                         }
 9906:                         if (ref($statushash) eq 'HASH') {
 9907:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 9908:                         }
 9909:                     }
 9910:                 }
 9911:             }
 9912:         }
 9913:         if (grep(/^ow$/,@{$roles})) {
 9914:             if ((defined($cdom)) && (defined($cnum))) {
 9915:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 9916:                 if ( defined($csettings{'internal.courseowner'}) ) {
 9917:                     my $owner = $csettings{'internal.courseowner'};
 9918:                     next if ($owner eq '');
 9919:                     my ($ownername,$ownerdom);
 9920:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 9921:                         $ownername = $1;
 9922:                         $ownerdom = $2;
 9923:                     } else {
 9924:                         $ownername = $owner;
 9925:                         $ownerdom = $cdom;
 9926:                         $owner = $ownername.':'.$ownerdom;
 9927:                     }
 9928:                     @{$$users{'ow'}{$owner}} = 'any';
 9929:                     if (defined($userdata) && 
 9930: 			!exists($$userdata{$owner})) {
 9931: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 9932:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 9933:                             push(@{$seclists{$owner}},'none');
 9934:                         }
 9935:                         if (ref($statushash) eq 'HASH') {
 9936:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 9937:                         }
 9938: 		    }
 9939:                 }
 9940:             }
 9941:         }
 9942:         foreach my $user (keys(%seclists)) {
 9943:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 9944:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 9945:         }
 9946:     }
 9947:     return;
 9948: }
 9949: 
 9950: sub get_user_info {
 9951:     my ($udom,$uname,$idx,$userdata) = @_;
 9952:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 9953: 	&plainname($uname,$udom,'lastname');
 9954:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 9955:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 9956:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 9957:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 9958:     return;
 9959: }
 9960: 
 9961: ###############################################
 9962: 
 9963: =pod
 9964: 
 9965: =item * &get_user_quota()
 9966: 
 9967: Retrieves quota assigned for storage of user files.
 9968: Default is to report quota for portfolio files.
 9969: 
 9970: Incoming parameters:
 9971: 1. user's username
 9972: 2. user's domain
 9973: 3. quota name - portfolio, author, or course
 9974:    (if no quota name provided, defaults to portfolio).
 9975: 4. crstype - official, unofficial, textbook or community, if quota name is
 9976:    course
 9977: 
 9978: Returns:
 9979: 1. Disk quota (in MB) assigned to student.
 9980: 2. (Optional) Type of setting: custom or default
 9981:    (individually assigned or default for user's 
 9982:    institutional status).
 9983: 3. (Optional) - User's institutional status (e.g., faculty, staff
 9984:    or student - types as defined in localenroll::inst_usertypes 
 9985:    for user's domain, which determines default quota for user.
 9986: 4. (Optional) - Default quota which would apply to the user.
 9987: 
 9988: If a value has been stored in the user's environment, 
 9989: it will return that, otherwise it returns the maximal default
 9990: defined for the user's institutional status(es) in the domain.
 9991: 
 9992: =cut
 9993: 
 9994: ###############################################
 9995: 
 9996: 
 9997: sub get_user_quota {
 9998:     my ($uname,$udom,$quotaname,$crstype) = @_;
 9999:     my ($quota,$quotatype,$settingstatus,$defquota);
10000:     if (!defined($udom)) {
10001:         $udom = $env{'user.domain'};
10002:     }
10003:     if (!defined($uname)) {
10004:         $uname = $env{'user.name'};
10005:     }
10006:     if (($udom eq '' || $uname eq '') ||
10007:         ($udom eq 'public') && ($uname eq 'public')) {
10008:         $quota = 0;
10009:         $quotatype = 'default';
10010:         $defquota = 0; 
10011:     } else {
10012:         my $inststatus;
10013:         if ($quotaname eq 'course') {
10014:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
10015:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
10016:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
10017:             } else {
10018:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
10019:                 $quota = $cenv{'internal.uploadquota'};
10020:             }
10021:         } else {
10022:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
10023:                 if ($quotaname eq 'author') {
10024:                     $quota = $env{'environment.authorquota'};
10025:                 } else {
10026:                     $quota = $env{'environment.portfolioquota'};
10027:                 }
10028:                 $inststatus = $env{'environment.inststatus'};
10029:             } else {
10030:                 my %userenv = 
10031:                     &Apache::lonnet::get('environment',['portfolioquota',
10032:                                          'authorquota','inststatus'],$udom,$uname);
10033:                 my ($tmp) = keys(%userenv);
10034:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10035:                     if ($quotaname eq 'author') {
10036:                         $quota = $userenv{'authorquota'};
10037:                     } else {
10038:                         $quota = $userenv{'portfolioquota'};
10039:                     }
10040:                     $inststatus = $userenv{'inststatus'};
10041:                 } else {
10042:                     undef(%userenv);
10043:                 }
10044:             }
10045:         }
10046:         if ($quota eq '' || wantarray) {
10047:             if ($quotaname eq 'course') {
10048:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
10049:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
10050:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
10051:                     $defquota = $domdefs{$crstype.'quota'};
10052:                 }
10053:                 if ($defquota eq '') {
10054:                     $defquota = 500;
10055:                 }
10056:             } else {
10057:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
10058:             }
10059:             if ($quota eq '') {
10060:                 $quota = $defquota;
10061:                 $quotatype = 'default';
10062:             } else {
10063:                 $quotatype = 'custom';
10064:             }
10065:         }
10066:     }
10067:     if (wantarray) {
10068:         return ($quota,$quotatype,$settingstatus,$defquota);
10069:     } else {
10070:         return $quota;
10071:     }
10072: }
10073: 
10074: ###############################################
10075: 
10076: =pod
10077: 
10078: =item * &default_quota()
10079: 
10080: Retrieves default quota assigned for storage of user portfolio files,
10081: given an (optional) user's institutional status.
10082: 
10083: Incoming parameters:
10084: 
10085: 1. domain
10086: 2. (Optional) institutional status(es).  This is a : separated list of 
10087:    status types (e.g., faculty, staff, student etc.)
10088:    which apply to the user for whom the default is being retrieved.
10089:    If the institutional status string in undefined, the domain
10090:    default quota will be returned.
10091: 3.  quota name - portfolio, author, or course
10092:    (if no quota name provided, defaults to portfolio).
10093: 
10094: Returns:
10095: 
10096: 1. Default disk quota (in MB) for user portfolios in the domain.
10097: 2. (Optional) institutional type which determined the value of the
10098:    default quota.
10099: 
10100: If a value has been stored in the domain's configuration db,
10101: it will return that, otherwise it returns 20 (for backwards 
10102: compatibility with domains which have not set up a configuration
10103: db file; the original statically defined portfolio quota was 20 MB). 
10104: 
10105: If the user's status includes multiple types (e.g., staff and student),
10106: the largest default quota which applies to the user determines the
10107: default quota returned.
10108: 
10109: =cut
10110: 
10111: ###############################################
10112: 
10113: 
10114: sub default_quota {
10115:     my ($udom,$inststatus,$quotaname) = @_;
10116:     my ($defquota,$settingstatus);
10117:     my %quotahash = &Apache::lonnet::get_dom('configuration',
10118:                                             ['quotas'],$udom);
10119:     my $key = 'defaultquota';
10120:     if ($quotaname eq 'author') {
10121:         $key = 'authorquota';
10122:     }
10123:     if (ref($quotahash{'quotas'}) eq 'HASH') {
10124:         if ($inststatus ne '') {
10125:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
10126:             foreach my $item (@statuses) {
10127:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
10128:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
10129:                         if ($defquota eq '') {
10130:                             $defquota = $quotahash{'quotas'}{$key}{$item};
10131:                             $settingstatus = $item;
10132:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
10133:                             $defquota = $quotahash{'quotas'}{$key}{$item};
10134:                             $settingstatus = $item;
10135:                         }
10136:                     }
10137:                 } elsif ($key eq 'defaultquota') {
10138:                     if ($quotahash{'quotas'}{$item} ne '') {
10139:                         if ($defquota eq '') {
10140:                             $defquota = $quotahash{'quotas'}{$item};
10141:                             $settingstatus = $item;
10142:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
10143:                             $defquota = $quotahash{'quotas'}{$item};
10144:                             $settingstatus = $item;
10145:                         }
10146:                     }
10147:                 }
10148:             }
10149:         }
10150:         if ($defquota eq '') {
10151:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
10152:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
10153:             } elsif ($key eq 'defaultquota') {
10154:                 $defquota = $quotahash{'quotas'}{'default'};
10155:             }
10156:             $settingstatus = 'default';
10157:             if ($defquota eq '') {
10158:                 if ($quotaname eq 'author') {
10159:                     $defquota = 500;
10160:                 }
10161:             }
10162:         }
10163:     } else {
10164:         $settingstatus = 'default';
10165:         if ($quotaname eq 'author') {
10166:             $defquota = 500;
10167:         } else {
10168:             $defquota = 20;
10169:         }
10170:     }
10171:     if (wantarray) {
10172:         return ($defquota,$settingstatus);
10173:     } else {
10174:         return $defquota;
10175:     }
10176: }
10177: 
10178: ###############################################
10179: 
10180: =pod
10181: 
10182: =item * &excess_filesize_warning()
10183: 
10184: Returns warning message if upload of file to authoring space, or copying
10185: of existing file within authoring space will cause quota for the authoring
10186: space to be exceeded.
10187: 
10188: Same, if upload of a file directly to a course/community via Course Editor
10189: will cause quota for uploaded content for the course to be exceeded.
10190: 
10191: Inputs: 7 
10192: 1. username or coursenum
10193: 2. domain
10194: 3. context ('author' or 'course')
10195: 4. filename of file for which action is being requested
10196: 5. filesize (kB) of file
10197: 6. action being taken: copy or upload.
10198: 7. quotatype (in course context -- official, unofficial, community or textbook).
10199: 
10200: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
10201:          otherwise return null.
10202: 
10203: =back
10204: 
10205: =cut
10206: 
10207: sub excess_filesize_warning {
10208:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
10209:     my $current_disk_usage = 0;
10210:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
10211:     if ($context eq 'author') {
10212:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
10213:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
10214:     } else {
10215:         foreach my $subdir ('docs','supplemental') {
10216:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
10217:         }
10218:     }
10219:     $disk_quota = int($disk_quota * 1000);
10220:     if (($current_disk_usage + $filesize) > $disk_quota) {
10221:         return '<p class="LC_warning">'.
10222:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
10223:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
10224:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
10225:                             $disk_quota,$current_disk_usage).
10226:                '</p>';
10227:     }
10228:     return;
10229: }
10230: 
10231: ###############################################
10232: 
10233: 
10234: sub get_secgrprole_info {
10235:     my ($cdom,$cnum,$needroles,$type)  = @_;
10236:     my %sections_count = &get_sections($cdom,$cnum);
10237:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
10238:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
10239:     my @groups = sort(keys(%curr_groups));
10240:     my $allroles = [];
10241:     my $rolehash;
10242:     my $accesshash = {
10243:                      active => 'Currently has access',
10244:                      future => 'Will have future access',
10245:                      previous => 'Previously had access',
10246:                   };
10247:     if ($needroles) {
10248:         $rolehash = {'all' => 'all'};
10249:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10250: 	if (&Apache::lonnet::error(%user_roles)) {
10251: 	    undef(%user_roles);
10252: 	}
10253:         foreach my $item (keys(%user_roles)) {
10254:             my ($role)=split(/\:/,$item,2);
10255:             if ($role eq 'cr') { next; }
10256:             if ($role =~ /^cr/) {
10257:                 $$rolehash{$role} = (split('/',$role))[3];
10258:             } else {
10259:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
10260:             }
10261:         }
10262:         foreach my $key (sort(keys(%{$rolehash}))) {
10263:             push(@{$allroles},$key);
10264:         }
10265:         push (@{$allroles},'st');
10266:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
10267:     }
10268:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
10269: }
10270: 
10271: sub user_picker {
10272:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
10273:     my $currdom = $dom;
10274:     my @alldoms = &Apache::lonnet::all_domains();
10275:     if (@alldoms == 1) {
10276:         my %domsrch = &Apache::lonnet::get_dom('configuration',
10277:                                                ['directorysrch'],$alldoms[0]);
10278:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
10279:         my $showdom = $domdesc;
10280:         if ($showdom eq '') {
10281:             $showdom = $dom;
10282:         }
10283:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
10284:             if ((!$domsrch{'directorysrch'}{'available'}) &&
10285:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
10286:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
10287:             }
10288:         }
10289:     }
10290:     my %curr_selected = (
10291:                         srchin => 'dom',
10292:                         srchby => 'lastname',
10293:                       );
10294:     my $srchterm;
10295:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
10296:         if ($srch->{'srchby'} ne '') {
10297:             $curr_selected{'srchby'} = $srch->{'srchby'};
10298:         }
10299:         if ($srch->{'srchin'} ne '') {
10300:             $curr_selected{'srchin'} = $srch->{'srchin'};
10301:         }
10302:         if ($srch->{'srchtype'} ne '') {
10303:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
10304:         }
10305:         if ($srch->{'srchdomain'} ne '') {
10306:             $currdom = $srch->{'srchdomain'};
10307:         }
10308:         $srchterm = $srch->{'srchterm'};
10309:     }
10310:     my %html_lt=&Apache::lonlocal::texthash(
10311:                     'usr'       => 'Search criteria',
10312:                     'doma'      => 'Domain/institution to search',
10313:                     'uname'     => 'username',
10314:                     'lastname'  => 'last name',
10315:                     'lastfirst' => 'last name, first name',
10316:                     'crs'       => 'in this course',
10317:                     'dom'       => 'in selected LON-CAPA domain', 
10318:                     'alc'       => 'all LON-CAPA',
10319:                     'instd'     => 'in institutional directory for selected domain',
10320:                     'exact'     => 'is',
10321:                     'contains'  => 'contains',
10322:                     'begins'    => 'begins with',
10323:                                        );
10324:     my %js_lt=&Apache::lonlocal::texthash(
10325:                     'youm'      => "You must include some text to search for.",
10326:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
10327:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
10328:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
10329:                     'ymcd'      => "You must choose a domain when using a domain search.",
10330:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
10331:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
10332:                      'thfo'     => "The following need to be corrected before the search can be run:",
10333:                                        );
10334:     &html_escape(\%html_lt);
10335:     &js_escape(\%js_lt);
10336:     my $domform;
10337:     my $allow_blank = 1;
10338:     if ($fixeddom) {
10339:         $allow_blank = 0;
10340:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
10341:     } else {
10342:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1);
10343:     }
10344:     my $srchinsel = ' <select name="srchin">';
10345: 
10346:     my @srchins = ('crs','dom','alc','instd');
10347: 
10348:     foreach my $option (@srchins) {
10349:         # FIXME 'alc' option unavailable until 
10350:         #       loncreateuser::print_user_query_page()
10351:         #       has been completed.
10352:         next if ($option eq 'alc');
10353:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
10354:         next if ($option eq 'crs' && !$env{'request.course.id'});
10355:         next if (($option eq 'instd') && ($noinstd));
10356:         if ($curr_selected{'srchin'} eq $option) {
10357:             $srchinsel .= ' 
10358:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10359:         } else {
10360:             $srchinsel .= '
10361:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10362:         }
10363:     }
10364:     $srchinsel .= "\n  </select>\n";
10365: 
10366:     my $srchbysel =  ' <select name="srchby">';
10367:     foreach my $option ('lastname','lastfirst','uname') {
10368:         if ($curr_selected{'srchby'} eq $option) {
10369:             $srchbysel .= '
10370:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10371:         } else {
10372:             $srchbysel .= '
10373:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10374:          }
10375:     }
10376:     $srchbysel .= "\n  </select>\n";
10377: 
10378:     my $srchtypesel = ' <select name="srchtype">';
10379:     foreach my $option ('begins','contains','exact') {
10380:         if ($curr_selected{'srchtype'} eq $option) {
10381:             $srchtypesel .= '
10382:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10383:         } else {
10384:             $srchtypesel .= '
10385:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10386:         }
10387:     }
10388:     $srchtypesel .= "\n  </select>\n";
10389: 
10390:     my ($newuserscript,$new_user_create);
10391:     my $context_dom = $env{'request.role.domain'};
10392:     if ($context eq 'requestcrs') {
10393:         if ($env{'form.coursedom'} ne '') { 
10394:             $context_dom = $env{'form.coursedom'};
10395:         }
10396:     }
10397:     if ($forcenewuser) {
10398:         if (ref($srch) eq 'HASH') {
10399:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
10400:                 if ($cancreate) {
10401:                     $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>';
10402:                 } else {
10403:                     my $helplink = 'javascript:helpMenu('."'display'".')';
10404:                     my %usertypetext = (
10405:                         official   => 'institutional',
10406:                         unofficial => 'non-institutional',
10407:                     );
10408:                     $new_user_create = '<p class="LC_warning">'
10409:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
10410:                                       .' '
10411:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
10412:                                           ,'<a href="'.$helplink.'">','</a>')
10413:                                       .'</p><br />';
10414:                 }
10415:             }
10416:         }
10417: 
10418:         $newuserscript = <<"ENDSCRIPT";
10419: 
10420: function setSearch(createnew,callingForm) {
10421:     if (createnew == 1) {
10422:         for (var i=0; i<callingForm.srchby.length; i++) {
10423:             if (callingForm.srchby.options[i].value == 'uname') {
10424:                 callingForm.srchby.selectedIndex = i;
10425:             }
10426:         }
10427:         for (var i=0; i<callingForm.srchin.length; i++) {
10428:             if ( callingForm.srchin.options[i].value == 'dom') {
10429: 		callingForm.srchin.selectedIndex = i;
10430:             }
10431:         }
10432:         for (var i=0; i<callingForm.srchtype.length; i++) {
10433:             if (callingForm.srchtype.options[i].value == 'exact') {
10434:                 callingForm.srchtype.selectedIndex = i;
10435:             }
10436:         }
10437:         for (var i=0; i<callingForm.srchdomain.length; i++) {
10438:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
10439:                 callingForm.srchdomain.selectedIndex = i;
10440:             }
10441:         }
10442:     }
10443: }
10444: ENDSCRIPT
10445: 
10446:     }
10447: 
10448:     my $output = <<"END_BLOCK";
10449: <script type="text/javascript">
10450: // <![CDATA[
10451: function validateEntry(callingForm) {
10452: 
10453:     var checkok = 1;
10454:     var srchin;
10455:     for (var i=0; i<callingForm.srchin.length; i++) {
10456: 	if ( callingForm.srchin[i].checked ) {
10457: 	    srchin = callingForm.srchin[i].value;
10458: 	}
10459:     }
10460: 
10461:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
10462:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
10463:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
10464:     var srchterm =  callingForm.srchterm.value;
10465:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
10466:     var msg = "";
10467: 
10468:     if (srchterm == "") {
10469:         checkok = 0;
10470:         msg += "$js_lt{'youm'}\\n";
10471:     }
10472: 
10473:     if (srchtype== 'begins') {
10474:         if (srchterm.length < 2) {
10475:             checkok = 0;
10476:             msg += "$js_lt{'thte'}\\n";
10477:         }
10478:     }
10479: 
10480:     if (srchtype== 'contains') {
10481:         if (srchterm.length < 3) {
10482:             checkok = 0;
10483:             msg += "$js_lt{'thet'}\\n";
10484:         }
10485:     }
10486:     if (srchin == 'instd') {
10487:         if (srchdomain == '') {
10488:             checkok = 0;
10489:             msg += "$js_lt{'yomc'}\\n";
10490:         }
10491:     }
10492:     if (srchin == 'dom') {
10493:         if (srchdomain == '') {
10494:             checkok = 0;
10495:             msg += "$js_lt{'ymcd'}\\n";
10496:         }
10497:     }
10498:     if (srchby == 'lastfirst') {
10499:         if (srchterm.indexOf(",") == -1) {
10500:             checkok = 0;
10501:             msg += "$js_lt{'whus'}\\n";
10502:         }
10503:         if (srchterm.indexOf(",") == srchterm.length -1) {
10504:             checkok = 0;
10505:             msg += "$js_lt{'whse'}\\n";
10506:         }
10507:     }
10508:     if (checkok == 0) {
10509:         alert("$js_lt{'thfo'}\\n"+msg);
10510:         return;
10511:     }
10512:     if (checkok == 1) {
10513:         callingForm.submit();
10514:     }
10515: }
10516: 
10517: $newuserscript
10518: 
10519: // ]]>
10520: </script>
10521: 
10522: $new_user_create
10523: 
10524: END_BLOCK
10525: 
10526:     $output .= &Apache::lonhtmlcommon::start_pick_box().
10527:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
10528:                $domform.
10529:                &Apache::lonhtmlcommon::row_closure().
10530:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
10531:                $srchbysel.
10532:                $srchtypesel. 
10533:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
10534:                $srchinsel.
10535:                &Apache::lonhtmlcommon::row_closure(1). 
10536:                &Apache::lonhtmlcommon::end_pick_box().
10537:                '<br />';
10538:     return ($output,1);
10539: }
10540: 
10541: sub user_rule_check {
10542:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
10543:     my ($response,%inst_response);
10544:     if (ref($usershash) eq 'HASH') {
10545:         if (keys(%{$usershash}) > 1) {
10546:             my (%by_username,%by_id,%userdoms);
10547:             my $checkid;
10548:             if (ref($checks) eq 'HASH') {
10549:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
10550:                     $checkid = 1;
10551:                 }
10552:             }
10553:             foreach my $user (keys(%{$usershash})) {
10554:                 my ($uname,$udom) = split(/:/,$user);
10555:                 if ($checkid) {
10556:                     if (ref($usershash->{$user}) eq 'HASH') {
10557:                         if ($usershash->{$user}->{'id'} ne '') {
10558:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
10559:                             $userdoms{$udom} = 1;
10560:                             if (ref($inst_results) eq 'HASH') {
10561:                                 $inst_results->{$uname.':'.$udom} = {};
10562:                             }
10563:                         }
10564:                     }
10565:                 } else {
10566:                     $by_username{$udom}{$uname} = 1;
10567:                     $userdoms{$udom} = 1;
10568:                     if (ref($inst_results) eq 'HASH') {
10569:                         $inst_results->{$uname.':'.$udom} = {};
10570:                     }
10571:                 }
10572:             }
10573:             foreach my $udom (keys(%userdoms)) {
10574:                 if (!$got_rules->{$udom}) {
10575:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
10576:                                                              ['usercreation'],$udom);
10577:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
10578:                         foreach my $item ('username','id') {
10579:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10580:                                 $$curr_rules{$udom}{$item} =
10581:                                     $domconfig{'usercreation'}{$item.'_rule'};
10582:                             }
10583:                         }
10584:                     }
10585:                     $got_rules->{$udom} = 1;
10586:                 }
10587:             }
10588:             if ($checkid) {
10589:                 foreach my $udom (keys(%by_id)) {
10590:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
10591:                     if ($outcome eq 'ok') {
10592:                         foreach my $id (keys(%{$by_id{$udom}})) {
10593:                             my $uname = $by_id{$udom}{$id};
10594:                             $inst_response{$uname.':'.$udom} = $outcome;
10595:                         }
10596:                         if (ref($results) eq 'HASH') {
10597:                             foreach my $uname (keys(%{$results})) {
10598:                                 if (exists($inst_response{$uname.':'.$udom})) {
10599:                                     $inst_response{$uname.':'.$udom} = $outcome;
10600:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
10601:                                 }
10602:                             }
10603:                         }
10604:                     }
10605:                 }
10606:             } else {
10607:                 foreach my $udom (keys(%by_username)) {
10608:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
10609:                     if ($outcome eq 'ok') {
10610:                         foreach my $uname (keys(%{$by_username{$udom}})) {
10611:                             $inst_response{$uname.':'.$udom} = $outcome;
10612:                         }
10613:                         if (ref($results) eq 'HASH') {
10614:                             foreach my $uname (keys(%{$results})) {
10615:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
10616:                             }
10617:                         }
10618:                     }
10619:                 }
10620:             }
10621:         } elsif (keys(%{$usershash}) == 1) {
10622:             my $user = (keys(%{$usershash}))[0];
10623:             my ($uname,$udom) = split(/:/,$user);
10624:             if (($udom ne '') && ($uname ne '')) {
10625:                 if (ref($usershash->{$user}) eq 'HASH') {
10626:                     if (ref($checks) eq 'HASH') {
10627:                         if (defined($checks->{'username'})) {
10628:                             ($inst_response{$user},%{$inst_results->{$user}}) =
10629:                                 &Apache::lonnet::get_instuser($udom,$uname);
10630:                         } elsif (defined($checks->{'id'})) {
10631:                             if ($usershash->{$user}->{'id'} ne '') {
10632:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
10633:                                     &Apache::lonnet::get_instuser($udom,undef,
10634:                                                                   $usershash->{$user}->{'id'});
10635:                             } else {
10636:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
10637:                                     &Apache::lonnet::get_instuser($udom,$uname);
10638:                             }
10639:                         }
10640:                     } else {
10641:                        ($inst_response{$user},%{$inst_results->{$user}}) =
10642:                             &Apache::lonnet::get_instuser($udom,$uname);
10643:                        return;
10644:                     }
10645:                     if (!$got_rules->{$udom}) {
10646:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
10647:                                                                  ['usercreation'],$udom);
10648:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
10649:                             foreach my $item ('username','id') {
10650:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10651:                                    $$curr_rules{$udom}{$item} =
10652:                                        $domconfig{'usercreation'}{$item.'_rule'};
10653:                                 }
10654:                             }
10655:                         }
10656:                         $got_rules->{$udom} = 1;
10657:                     }
10658:                 }
10659:             } else {
10660:                 return;
10661:             }
10662:         } else {
10663:             return;
10664:         }
10665:         foreach my $user (keys(%{$usershash})) {
10666:             my ($uname,$udom) = split(/:/,$user);
10667:             next if (($udom eq '') || ($uname eq ''));
10668:             my $id;
10669:             if (ref($inst_results) eq 'HASH') {
10670:                 if (ref($inst_results->{$user}) eq 'HASH') {
10671:                     $id = $inst_results->{$user}->{'id'};
10672:                 }
10673:             }
10674:             if ($id eq '') {
10675:                 if (ref($usershash->{$user})) {
10676:                     $id = $usershash->{$user}->{'id'};
10677:                 }
10678:             }
10679:             foreach my $item (keys(%{$checks})) {
10680:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
10681:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
10682:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
10683:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
10684:                                                                              $$curr_rules{$udom}{$item});
10685:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
10686:                                 if ($rule_check{$rule}) {
10687:                                     $$rulematch{$user}{$item} = $rule;
10688:                                     if ($inst_response{$user} eq 'ok') {
10689:                                         if (ref($inst_results) eq 'HASH') {
10690:                                             if (ref($inst_results->{$user}) eq 'HASH') {
10691:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
10692:                                                     $$alerts{$item}{$udom}{$uname} = 1;
10693:                                                 } elsif ($item eq 'id') {
10694:                                                     if ($inst_results->{$user}->{'id'} eq '') {
10695:                                                         $$alerts{$item}{$udom}{$uname} = 1;
10696:                                                     }
10697:                                                 }
10698:                                             }
10699:                                         }
10700:                                     }
10701:                                     last;
10702:                                 }
10703:                             }
10704:                         }
10705:                     }
10706:                 }
10707:             }
10708:         }
10709:     }
10710:     return;
10711: }
10712: 
10713: sub user_rule_formats {
10714:     my ($domain,$domdesc,$curr_rules,$check) = @_;
10715:     my %text = ( 
10716:                  'username' => 'Usernames',
10717:                  'id'       => 'IDs',
10718:                );
10719:     my $output;
10720:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
10721:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
10722:         if (@{$ruleorder} > 0) {
10723:             $output = '<br />'.
10724:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
10725:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
10726:                       ' <ul>';
10727:             foreach my $rule (@{$ruleorder}) {
10728:                 if (ref($curr_rules) eq 'ARRAY') {
10729:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
10730:                         if (ref($rules->{$rule}) eq 'HASH') {
10731:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
10732:                                         $rules->{$rule}{'desc'}.'</li>';
10733:                         }
10734:                     }
10735:                 }
10736:             }
10737:             $output .= '</ul>';
10738:         }
10739:     }
10740:     return $output;
10741: }
10742: 
10743: sub instrule_disallow_msg {
10744:     my ($checkitem,$domdesc,$count,$mode) = @_;
10745:     my $response;
10746:     my %text = (
10747:                   item   => 'username',
10748:                   items  => 'usernames',
10749:                   match  => 'matches',
10750:                   do     => 'does',
10751:                   action => 'a username',
10752:                   one    => 'one',
10753:                );
10754:     if ($count > 1) {
10755:         $text{'item'} = 'usernames';
10756:         $text{'match'} ='match';
10757:         $text{'do'} = 'do';
10758:         $text{'action'} = 'usernames',
10759:         $text{'one'} = 'ones';
10760:     }
10761:     if ($checkitem eq 'id') {
10762:         $text{'items'} = 'IDs';
10763:         $text{'item'} = 'ID';
10764:         $text{'action'} = 'an ID';
10765:         if ($count > 1) {
10766:             $text{'item'} = 'IDs';
10767:             $text{'action'} = 'IDs';
10768:         }
10769:     }
10770:     $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 />';
10771:     if ($mode eq 'upload') {
10772:         if ($checkitem eq 'username') {
10773:             $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'}.");
10774:         } elsif ($checkitem eq 'id') {
10775:             $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.");
10776:         }
10777:     } elsif ($mode eq 'selfcreate') {
10778:         if ($checkitem eq 'id') {
10779:             $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.");
10780:         }
10781:     } else {
10782:         if ($checkitem eq 'username') {
10783:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
10784:         } elsif ($checkitem eq 'id') {
10785:             $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.");
10786:         }
10787:     }
10788:     return $response;
10789: }
10790: 
10791: sub personal_data_fieldtitles {
10792:     my %fieldtitles = &Apache::lonlocal::texthash (
10793:                         id => 'Student/Employee ID',
10794:                         permanentemail => 'E-mail address',
10795:                         lastname => 'Last Name',
10796:                         firstname => 'First Name',
10797:                         middlename => 'Middle Name',
10798:                         generation => 'Generation',
10799:                         gen => 'Generation',
10800:                         inststatus => 'Affiliation',
10801:                    );
10802:     return %fieldtitles;
10803: }
10804: 
10805: sub sorted_inst_types {
10806:     my ($dom) = @_;
10807:     my ($usertypes,$order);
10808:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
10809:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
10810:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
10811:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
10812:     } else {
10813:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
10814:     }
10815:     my $othertitle = &mt('All users');
10816:     if ($env{'request.course.id'}) {
10817:         $othertitle  = &mt('Any users');
10818:     }
10819:     my @types;
10820:     if (ref($order) eq 'ARRAY') {
10821:         @types = @{$order};
10822:     }
10823:     if (@types == 0) {
10824:         if (ref($usertypes) eq 'HASH') {
10825:             @types = sort(keys(%{$usertypes}));
10826:         }
10827:     }
10828:     if (keys(%{$usertypes}) > 0) {
10829:         $othertitle = &mt('Other users');
10830:     }
10831:     return ($othertitle,$usertypes,\@types);
10832: }
10833: 
10834: sub get_institutional_codes {
10835:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
10836: # Get complete list of course sections to update
10837:     my @currsections = ();
10838:     my @currxlists = ();
10839:     my (%unclutteredsec,%unclutteredlcsec);
10840:     my $coursecode = $$settings{'internal.coursecode'};
10841:     my $crskey = $crs.':'.$coursecode;
10842:     @{$unclutteredsec{$crskey}} = ();
10843:     @{$unclutteredlcsec{$crskey}} = ();
10844: 
10845:     if ($$settings{'internal.sectionnums'} ne '') {
10846:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
10847:     }
10848: 
10849:     if ($$settings{'internal.crosslistings'} ne '') {
10850:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
10851:     }
10852: 
10853:     if (@currxlists > 0) {
10854:         foreach my $xl (@currxlists) {
10855:             if ($xl =~ /^([^:]+):(\w*)$/) {
10856:                 unless (grep/^$1$/,@{$allcourses}) {
10857:                     push(@{$allcourses},$1);
10858:                     $$LC_code{$1} = $2;
10859:                 }
10860:             }
10861:         }
10862:     }
10863: 
10864:     if (@currsections > 0) {
10865:         foreach my $sec (@currsections) {
10866:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
10867:                 my $instsec = $1;
10868:                 my $lc_sec = $2;
10869:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
10870:                     push(@{$unclutteredsec{$crskey}},$instsec);
10871:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
10872:                 }
10873:             }
10874:         }
10875:     }
10876: 
10877:     if (@{$unclutteredsec{$crskey}} > 0) {
10878:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
10879:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
10880:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
10881:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
10882:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
10883:                     push(@{$allcourses},$sec);
10884:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
10885:                 }
10886:             }
10887:         }
10888:     }
10889:     return;
10890: }
10891: 
10892: sub get_standard_codeitems {
10893:     return ('Year','Semester','Department','Number','Section');
10894: }
10895: 
10896: =pod
10897: 
10898: =head1 Slot Helpers
10899: 
10900: =over 4
10901: 
10902: =item * sorted_slots()
10903: 
10904: Sorts an array of slot names in order of an optional sort key,
10905: default sort is by slot start time (earliest first). 
10906: 
10907: Inputs:
10908: 
10909: =over 4
10910: 
10911: slotsarr  - Reference to array of unsorted slot names.
10912: 
10913: slots     - Reference to hash of hash, where outer hash keys are slot names.
10914: 
10915: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
10916: 
10917: =back
10918: 
10919: Returns:
10920: 
10921: =over 4
10922: 
10923: sorted   - An array of slot names sorted by a specified sort key 
10924:            (default sort key is start time of the slot).
10925: 
10926: =back
10927: 
10928: =cut
10929: 
10930: 
10931: sub sorted_slots {
10932:     my ($slotsarr,$slots,$sortkey) = @_;
10933:     if ($sortkey eq '') {
10934:         $sortkey = 'starttime';
10935:     }
10936:     my @sorted;
10937:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
10938:         @sorted =
10939:             sort {
10940:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
10941:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
10942:                      }
10943:                      if (ref($slots->{$a})) { return -1;}
10944:                      if (ref($slots->{$b})) { return 1;}
10945:                      return 0;
10946:                  } @{$slotsarr};
10947:     }
10948:     return @sorted;
10949: }
10950: 
10951: =pod
10952: 
10953: =item * get_future_slots()
10954: 
10955: Inputs:
10956: 
10957: =over 4
10958: 
10959: cnum - course number
10960: 
10961: cdom - course domain
10962: 
10963: now - current UNIX time
10964: 
10965: symb - optional symb
10966: 
10967: =back
10968: 
10969: Returns:
10970: 
10971: =over 4
10972: 
10973: sorted_reservable - ref to array of student_schedulable slots currently 
10974:                     reservable, ordered by end date of reservation period.
10975: 
10976: reservable_now - ref to hash of student_schedulable slots currently
10977:                  reservable.
10978: 
10979:     Keys in inner hash are:
10980:     (a) symb: either blank or symb to which slot use is restricted.
10981:     (b) endreserve: end date of reservation period.
10982:     (c) uniqueperiod: start,end dates when slot is to be uniquely
10983:         selected.
10984: 
10985: sorted_future - ref to array of student_schedulable slots reservable in
10986:                 the future, ordered by start date of reservation period.
10987: 
10988: future_reservable - ref to hash of student_schedulable slots reservable
10989:                     in the future.
10990: 
10991:     Keys in inner hash are:
10992:     (a) symb: either blank or symb to which slot use is restricted.
10993:     (b) startreserve:  start date of reservation period.
10994:     (c) uniqueperiod: start,end dates when slot is to be uniquely
10995:         selected.
10996: 
10997: =back
10998: 
10999: =cut
11000: 
11001: sub get_future_slots {
11002:     my ($cnum,$cdom,$now,$symb) = @_;
11003:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
11004:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
11005:     foreach my $slot (keys(%slots)) {
11006:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
11007:         if ($symb) {
11008:             next if (($slots{$slot}->{'symb'} ne '') && 
11009:                      ($slots{$slot}->{'symb'} ne $symb));
11010:         }
11011:         if (($slots{$slot}->{'starttime'} > $now) &&
11012:             ($slots{$slot}->{'endtime'} > $now)) {
11013:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
11014:                 my $userallowed = 0;
11015:                 if ($slots{$slot}->{'allowedsections'}) {
11016:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
11017:                     if (!defined($env{'request.role.sec'})
11018:                         && grep(/^No section assigned$/,@allowed_sec)) {
11019:                         $userallowed=1;
11020:                     } else {
11021:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
11022:                             $userallowed=1;
11023:                         }
11024:                     }
11025:                     unless ($userallowed) {
11026:                         if (defined($env{'request.course.groups'})) {
11027:                             my @groups = split(/:/,$env{'request.course.groups'});
11028:                             foreach my $group (@groups) {
11029:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
11030:                                     $userallowed=1;
11031:                                     last;
11032:                                 }
11033:                             }
11034:                         }
11035:                     }
11036:                 }
11037:                 if ($slots{$slot}->{'allowedusers'}) {
11038:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
11039:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
11040:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
11041:                         $userallowed = 1;
11042:                     }
11043:                 }
11044:                 next unless($userallowed);
11045:             }
11046:             my $startreserve = $slots{$slot}->{'startreserve'};
11047:             my $endreserve = $slots{$slot}->{'endreserve'};
11048:             my $symb = $slots{$slot}->{'symb'};
11049:             my $uniqueperiod;
11050:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
11051:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
11052:             }
11053:             if (($startreserve < $now) &&
11054:                 (!$endreserve || $endreserve > $now)) {
11055:                 my $lastres = $endreserve;
11056:                 if (!$lastres) {
11057:                     $lastres = $slots{$slot}->{'starttime'};
11058:                 }
11059:                 $reservable_now{$slot} = {
11060:                                            symb       => $symb,
11061:                                            endreserve => $lastres,
11062:                                            uniqueperiod => $uniqueperiod,   
11063:                                          };
11064:             } elsif (($startreserve > $now) &&
11065:                      (!$endreserve || $endreserve > $startreserve)) {
11066:                 $future_reservable{$slot} = {
11067:                                               symb         => $symb,
11068:                                               startreserve => $startreserve,
11069:                                               uniqueperiod => $uniqueperiod,
11070:                                             };
11071:             }
11072:         }
11073:     }
11074:     my @unsorted_reservable = keys(%reservable_now);
11075:     if (@unsorted_reservable > 0) {
11076:         @sorted_reservable = 
11077:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
11078:     }
11079:     my @unsorted_future = keys(%future_reservable);
11080:     if (@unsorted_future > 0) {
11081:         @sorted_future =
11082:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
11083:     }
11084:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
11085: }
11086: 
11087: =pod
11088: 
11089: =back
11090: 
11091: =head1 HTTP Helpers
11092: 
11093: =over 4
11094: 
11095: =item * &get_unprocessed_cgi($query,$possible_names)
11096: 
11097: Modify the %env hash to contain unprocessed CGI form parameters held in
11098: $query.  The parameters listed in $possible_names (an array reference),
11099: will be set in $env{'form.name'} if they do not already exist.
11100: 
11101: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
11102: $possible_names is an ref to an array of form element names.  As an example:
11103: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
11104: will result in $env{'form.uname'} and $env{'form.udom'} being set.
11105: 
11106: =cut
11107: 
11108: sub get_unprocessed_cgi {
11109:   my ($query,$possible_names)= @_;
11110:   # $Apache::lonxml::debug=1;
11111:   foreach my $pair (split(/&/,$query)) {
11112:     my ($name, $value) = split(/=/,$pair);
11113:     $name = &unescape($name);
11114:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
11115:       $value =~ tr/+/ /;
11116:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
11117:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
11118:     }
11119:   }
11120: }
11121: 
11122: =pod
11123: 
11124: =item * &cacheheader() 
11125: 
11126: returns cache-controlling header code
11127: 
11128: =cut
11129: 
11130: sub cacheheader {
11131:     unless ($env{'request.method'} eq 'GET') { return ''; }
11132:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
11133:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
11134:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
11135:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
11136:     return $output;
11137: }
11138: 
11139: =pod
11140: 
11141: =item * &no_cache($r) 
11142: 
11143: specifies header code to not have cache
11144: 
11145: =cut
11146: 
11147: sub no_cache {
11148:     my ($r) = @_;
11149:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
11150: 	$env{'request.method'} ne 'GET') { return ''; }
11151:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
11152:     $r->no_cache(1);
11153:     $r->header_out("Expires" => $date);
11154:     $r->header_out("Pragma" => "no-cache");
11155: }
11156: 
11157: sub content_type {
11158:     my ($r,$type,$charset) = @_;
11159:     if ($r) {
11160: 	#  Note that printout.pl calls this with undef for $r.
11161: 	&no_cache($r);
11162:     }
11163:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
11164:     unless ($charset) {
11165: 	$charset=&Apache::lonlocal::current_encoding;
11166:     }
11167:     if ($charset) { $type.='; charset='.$charset; }
11168:     if ($r) {
11169: 	$r->content_type($type);
11170:     } else {
11171: 	print("Content-type: $type\n\n");
11172:     }
11173: }
11174: 
11175: =pod
11176: 
11177: =item * &add_to_env($name,$value) 
11178: 
11179: adds $name to the %env hash with value
11180: $value, if $name already exists, the entry is converted to an array
11181: reference and $value is added to the array.
11182: 
11183: =cut
11184: 
11185: sub add_to_env {
11186:   my ($name,$value)=@_;
11187:   if (defined($env{$name})) {
11188:     if (ref($env{$name})) {
11189:       #already have multiple values
11190:       push(@{ $env{$name} },$value);
11191:     } else {
11192:       #first time seeing multiple values, convert hash entry to an arrayref
11193:       my $first=$env{$name};
11194:       undef($env{$name});
11195:       push(@{ $env{$name} },$first,$value);
11196:     }
11197:   } else {
11198:     $env{$name}=$value;
11199:   }
11200: }
11201: 
11202: =pod
11203: 
11204: =item * &get_env_multiple($name) 
11205: 
11206: gets $name from the %env hash, it seemlessly handles the cases where multiple
11207: values may be defined and end up as an array ref.
11208: 
11209: returns an array of values
11210: 
11211: =cut
11212: 
11213: sub get_env_multiple {
11214:     my ($name) = @_;
11215:     my @values;
11216:     if (defined($env{$name})) {
11217:         # exists is it an array
11218:         if (ref($env{$name})) {
11219:             @values=@{ $env{$name} };
11220:         } else {
11221:             $values[0]=$env{$name};
11222:         }
11223:     }
11224:     return(@values);
11225: }
11226: 
11227: sub ask_for_embedded_content {
11228:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
11229:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
11230:         %currsubfile,%unused,$rem);
11231:     my $counter = 0;
11232:     my $numnew = 0;
11233:     my $numremref = 0;
11234:     my $numinvalid = 0;
11235:     my $numpathchg = 0;
11236:     my $numexisting = 0;
11237:     my $numunused = 0;
11238:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
11239:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
11240:     my $heading = &mt('Upload embedded files');
11241:     my $buttontext = &mt('Upload');
11242: 
11243:     if ($env{'request.course.id'}) {
11244:         if ($actionurl eq '/adm/dependencies') {
11245:             $navmap = Apache::lonnavmaps::navmap->new();
11246:         }
11247:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11248:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11249:     }
11250:     if (($actionurl eq '/adm/portfolio') ||
11251:         ($actionurl eq '/adm/coursegrp_portfolio')) {
11252:         my $current_path='/';
11253:         if ($env{'form.currentpath'}) {
11254:             $current_path = $env{'form.currentpath'};
11255:         }
11256:         if ($actionurl eq '/adm/coursegrp_portfolio') {
11257:             $udom = $cdom;
11258:             $uname = $cnum;
11259:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
11260:         } else {
11261:             $udom = $env{'user.domain'};
11262:             $uname = $env{'user.name'};
11263:             $url = '/userfiles/portfolio';
11264:         }
11265:         $toplevel = $url.'/';
11266:         $url .= $current_path;
11267:         $getpropath = 1;
11268:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
11269:              ($actionurl eq '/adm/imsimport')) { 
11270:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
11271:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
11272:         $toplevel = $url;
11273:         if ($rest ne '') {
11274:             $url .= $rest;
11275:         }
11276:     } elsif ($actionurl eq '/adm/coursedocs') {
11277:         if (ref($args) eq 'HASH') {
11278:             $url = $args->{'docs_url'};
11279:             $toplevel = $url;
11280:             if ($args->{'context'} eq 'paste') {
11281:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
11282:                 ($path) =
11283:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
11284:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
11285:                 $fileloc =~ s{^/}{};
11286:             }
11287:         }
11288:     } elsif ($actionurl eq '/adm/dependencies') {
11289:         if ($env{'request.course.id'} ne '') {
11290:             if (ref($args) eq 'HASH') {
11291:                 $url = $args->{'docs_url'};
11292:                 $title = $args->{'docs_title'};
11293:                 $toplevel = $url;
11294:                 unless ($toplevel =~ m{^/}) {
11295:                     $toplevel = "/$url";
11296:                 }
11297:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
11298:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
11299:                     $path = $1;
11300:                 } else {
11301:                     ($path) =
11302:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
11303:                 }
11304:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
11305:                     $fileloc = $toplevel;
11306:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
11307:                     my ($udom,$uname,$fname) =
11308:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
11309:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
11310:                 } else {
11311:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
11312:                 }
11313:                 $fileloc =~ s{^/}{};
11314:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
11315:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
11316:             }
11317:         }
11318:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
11319:         $udom = $cdom;
11320:         $uname = $cnum;
11321:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
11322:         $toplevel = $url;
11323:         $path = $url;
11324:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
11325:         $fileloc =~ s{^/}{};
11326:     }
11327:     foreach my $file (keys(%{$allfiles})) {
11328:         my $embed_file;
11329:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
11330:             $embed_file = $1;
11331:         } else {
11332:             $embed_file = $file;
11333:         }
11334:         my ($absolutepath,$cleaned_file);
11335:         if ($embed_file =~ m{^\w+://}) {
11336:             $cleaned_file = $embed_file;
11337:             $newfiles{$cleaned_file} = 1;
11338:             $mapping{$cleaned_file} = $embed_file;
11339:         } else {
11340:             $cleaned_file = &clean_path($embed_file);
11341:             if ($embed_file =~ m{^/}) {
11342:                 $absolutepath = $embed_file;
11343:             }
11344:             if ($cleaned_file =~ m{/}) {
11345:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
11346:                 $path = &check_for_traversal($path,$url,$toplevel);
11347:                 my $item = $fname;
11348:                 if ($path ne '') {
11349:                     $item = $path.'/'.$fname;
11350:                     $subdependencies{$path}{$fname} = 1;
11351:                 } else {
11352:                     $dependencies{$item} = 1;
11353:                 }
11354:                 if ($absolutepath) {
11355:                     $mapping{$item} = $absolutepath;
11356:                 } else {
11357:                     $mapping{$item} = $embed_file;
11358:                 }
11359:             } else {
11360:                 $dependencies{$embed_file} = 1;
11361:                 if ($absolutepath) {
11362:                     $mapping{$cleaned_file} = $absolutepath;
11363:                 } else {
11364:                     $mapping{$cleaned_file} = $embed_file;
11365:                 }
11366:             }
11367:         }
11368:     }
11369:     my $dirptr = 16384;
11370:     foreach my $path (keys(%subdependencies)) {
11371:         $currsubfile{$path} = {};
11372:         if (($actionurl eq '/adm/portfolio') ||
11373:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
11374:             my ($sublistref,$listerror) =
11375:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
11376:             if (ref($sublistref) eq 'ARRAY') {
11377:                 foreach my $line (@{$sublistref}) {
11378:                     my ($file_name,$rest) = split(/\&/,$line,2);
11379:                     $currsubfile{$path}{$file_name} = 1;
11380:                 }
11381:             }
11382:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11383:             if (opendir(my $dir,$url.'/'.$path)) {
11384:                 my @subdir_list = grep(!/^\./,readdir($dir));
11385:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
11386:             }
11387:         } elsif (($actionurl eq '/adm/dependencies') ||
11388:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11389:                   ($args->{'context'} eq 'paste')) ||
11390:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
11391:             if ($env{'request.course.id'} ne '') {
11392:                 my $dir;
11393:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
11394:                     $dir = $fileloc;
11395:                 } else {
11396:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
11397:                 }
11398:                 if ($dir ne '') {
11399:                     my ($sublistref,$listerror) =
11400:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
11401:                     if (ref($sublistref) eq 'ARRAY') {
11402:                         foreach my $line (@{$sublistref}) {
11403:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
11404:                                 undef,$mtime)=split(/\&/,$line,12);
11405:                             unless (($testdir&$dirptr) ||
11406:                                     ($file_name =~ /^\.\.?$/)) {
11407:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
11408:                             }
11409:                         }
11410:                     }
11411:                 }
11412:             }
11413:         }
11414:         foreach my $file (keys(%{$subdependencies{$path}})) {
11415:             if (exists($currsubfile{$path}{$file})) {
11416:                 my $item = $path.'/'.$file;
11417:                 unless ($mapping{$item} eq $item) {
11418:                     $pathchanges{$item} = 1;
11419:                 }
11420:                 $existing{$item} = 1;
11421:                 $numexisting ++;
11422:             } else {
11423:                 $newfiles{$path.'/'.$file} = 1;
11424:             }
11425:         }
11426:         if ($actionurl eq '/adm/dependencies') {
11427:             foreach my $path (keys(%currsubfile)) {
11428:                 if (ref($currsubfile{$path}) eq 'HASH') {
11429:                     foreach my $file (keys(%{$currsubfile{$path}})) {
11430:                          unless ($subdependencies{$path}{$file}) {
11431:                              next if (($rem ne '') &&
11432:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
11433:                                        (ref($navmap) &&
11434:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
11435:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
11436:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
11437:                              $unused{$path.'/'.$file} = 1; 
11438:                          }
11439:                     }
11440:                 }
11441:             }
11442:         }
11443:     }
11444:     my %currfile;
11445:     if (($actionurl eq '/adm/portfolio') ||
11446:         ($actionurl eq '/adm/coursegrp_portfolio')) {
11447:         my ($dirlistref,$listerror) =
11448:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
11449:         if (ref($dirlistref) eq 'ARRAY') {
11450:             foreach my $line (@{$dirlistref}) {
11451:                 my ($file_name,$rest) = split(/\&/,$line,2);
11452:                 $currfile{$file_name} = 1;
11453:             }
11454:         }
11455:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11456:         if (opendir(my $dir,$url)) {
11457:             my @dir_list = grep(!/^\./,readdir($dir));
11458:             map {$currfile{$_} = 1;} @dir_list;
11459:         }
11460:     } elsif (($actionurl eq '/adm/dependencies') ||
11461:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11462:               ($args->{'context'} eq 'paste')) ||
11463:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
11464:         if ($env{'request.course.id'} ne '') {
11465:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
11466:             if ($dir ne '') {
11467:                 my ($dirlistref,$listerror) =
11468:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
11469:                 if (ref($dirlistref) eq 'ARRAY') {
11470:                     foreach my $line (@{$dirlistref}) {
11471:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
11472:                             $size,undef,$mtime)=split(/\&/,$line,12);
11473:                         unless (($testdir&$dirptr) ||
11474:                                 ($file_name =~ /^\.\.?$/)) {
11475:                             $currfile{$file_name} = [$size,$mtime];
11476:                         }
11477:                     }
11478:                 }
11479:             }
11480:         }
11481:     }
11482:     foreach my $file (keys(%dependencies)) {
11483:         if (exists($currfile{$file})) {
11484:             unless ($mapping{$file} eq $file) {
11485:                 $pathchanges{$file} = 1;
11486:             }
11487:             $existing{$file} = 1;
11488:             $numexisting ++;
11489:         } else {
11490:             $newfiles{$file} = 1;
11491:         }
11492:     }
11493:     foreach my $file (keys(%currfile)) {
11494:         unless (($file eq $filename) ||
11495:                 ($file eq $filename.'.bak') ||
11496:                 ($dependencies{$file})) {
11497:             if ($actionurl eq '/adm/dependencies') {
11498:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
11499:                     next if (($rem ne '') &&
11500:                              (($env{"httpref.$rem".$file} ne '') ||
11501:                               (ref($navmap) &&
11502:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
11503:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
11504:                                 ($navmap->getResourceByUrl($rem.$1)))))));
11505:                 }
11506:             }
11507:             $unused{$file} = 1;
11508:         }
11509:     }
11510:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11511:         ($args->{'context'} eq 'paste')) {
11512:         $counter = scalar(keys(%existing));
11513:         $numpathchg = scalar(keys(%pathchanges));
11514:         return ($output,$counter,$numpathchg,\%existing);
11515:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
11516:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
11517:         $counter = scalar(keys(%existing));
11518:         $numpathchg = scalar(keys(%pathchanges));
11519:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
11520:     }
11521:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
11522:         if ($actionurl eq '/adm/dependencies') {
11523:             next if ($embed_file =~ m{^\w+://});
11524:         }
11525:         $upload_output .= &start_data_table_row().
11526:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
11527:                           '<span class="LC_filename">'.$embed_file.'</span>';
11528:         unless ($mapping{$embed_file} eq $embed_file) {
11529:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
11530:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
11531:         }
11532:         $upload_output .= '</td>';
11533:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
11534:             $upload_output.='<td align="right">'.
11535:                             '<span class="LC_info LC_fontsize_medium">'.
11536:                             &mt("URL points to web address").'</span>';
11537:             $numremref++;
11538:         } elsif ($args->{'error_on_invalid_names'}
11539:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
11540:             $upload_output.='<td align="right"><span class="LC_warning">'.
11541:                             &mt('Invalid characters').'</span>';
11542:             $numinvalid++;
11543:         } else {
11544:             $upload_output .= '<td>'.
11545:                               &embedded_file_element('upload_embedded',$counter,
11546:                                                      $embed_file,\%mapping,
11547:                                                      $allfiles,$codebase,'upload');
11548:             $counter ++;
11549:             $numnew ++;
11550:         }
11551:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
11552:     }
11553:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
11554:         if ($actionurl eq '/adm/dependencies') {
11555:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
11556:             $modify_output .= &start_data_table_row().
11557:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
11558:                               '<img src="'.&icon($embed_file).'" border="0" />'.
11559:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
11560:                               '<td>'.$size.'</td>'.
11561:                               '<td>'.$mtime.'</td>'.
11562:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
11563:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
11564:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
11565:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
11566:                               &embedded_file_element('upload_embedded',$counter,
11567:                                                      $embed_file,\%mapping,
11568:                                                      $allfiles,$codebase,'modify').
11569:                               '</div></td>'.
11570:                               &end_data_table_row()."\n";
11571:             $counter ++;
11572:         } else {
11573:             $upload_output .= &start_data_table_row().
11574:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
11575:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
11576:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
11577:                               &Apache::loncommon::end_data_table_row()."\n";
11578:         }
11579:     }
11580:     my $delidx = $counter;
11581:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
11582:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
11583:         $delete_output .= &start_data_table_row().
11584:                           '<td><img src="'.&icon($oldfile).'" />'.
11585:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
11586:                           '<td>'.$size.'</td>'.
11587:                           '<td>'.$mtime.'</td>'.
11588:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
11589:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
11590:                           &embedded_file_element('upload_embedded',$delidx,
11591:                                                  $oldfile,\%mapping,$allfiles,
11592:                                                  $codebase,'delete').'</td>'.
11593:                           &end_data_table_row()."\n"; 
11594:         $numunused ++;
11595:         $delidx ++;
11596:     }
11597:     if ($upload_output) {
11598:         $upload_output = &start_data_table().
11599:                          $upload_output.
11600:                          &end_data_table()."\n";
11601:     }
11602:     if ($modify_output) {
11603:         $modify_output = &start_data_table().
11604:                          &start_data_table_header_row().
11605:                          '<th>'.&mt('File').'</th>'.
11606:                          '<th>'.&mt('Size (KB)').'</th>'.
11607:                          '<th>'.&mt('Modified').'</th>'.
11608:                          '<th>'.&mt('Upload replacement?').'</th>'.
11609:                          &end_data_table_header_row().
11610:                          $modify_output.
11611:                          &end_data_table()."\n";
11612:     }
11613:     if ($delete_output) {
11614:         $delete_output = &start_data_table().
11615:                          &start_data_table_header_row().
11616:                          '<th>'.&mt('File').'</th>'.
11617:                          '<th>'.&mt('Size (KB)').'</th>'.
11618:                          '<th>'.&mt('Modified').'</th>'.
11619:                          '<th>'.&mt('Delete?').'</th>'.
11620:                          &end_data_table_header_row().
11621:                          $delete_output.
11622:                          &end_data_table()."\n";
11623:     }
11624:     my $applies = 0;
11625:     if ($numremref) {
11626:         $applies ++;
11627:     }
11628:     if ($numinvalid) {
11629:         $applies ++;
11630:     }
11631:     if ($numexisting) {
11632:         $applies ++;
11633:     }
11634:     if ($counter || $numunused) {
11635:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
11636:                   ' method="post" enctype="multipart/form-data">'."\n".
11637:                   $state.'<h3>'.$heading.'</h3>'; 
11638:         if ($actionurl eq '/adm/dependencies') {
11639:             if ($numnew) {
11640:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
11641:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
11642:                            $upload_output.'<br />'."\n";
11643:             }
11644:             if ($numexisting) {
11645:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
11646:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
11647:                            $modify_output.'<br />'."\n";
11648:                            $buttontext = &mt('Save changes');
11649:             }
11650:             if ($numunused) {
11651:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
11652:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
11653:                            $delete_output.'<br />'."\n";
11654:                            $buttontext = &mt('Save changes');
11655:             }
11656:         } else {
11657:             $output .= $upload_output.'<br />'."\n";
11658:         }
11659:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
11660:                    $counter.'" />'."\n";
11661:         if ($actionurl eq '/adm/dependencies') { 
11662:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
11663:                        $numnew.'" />'."\n";
11664:         } elsif ($actionurl eq '') {
11665:             $output .=  '<input type="hidden" name="phase" value="three" />';
11666:         }
11667:     } elsif ($applies) {
11668:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
11669:         if ($applies > 1) {
11670:             $output .=  
11671:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
11672:             if ($numremref) {
11673:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
11674:             }
11675:             if ($numinvalid) {
11676:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
11677:             }
11678:             if ($numexisting) {
11679:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
11680:             }
11681:             $output .= '</ul><br />';
11682:         } elsif ($numremref) {
11683:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
11684:         } elsif ($numinvalid) {
11685:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
11686:         } elsif ($numexisting) {
11687:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
11688:         }
11689:         $output .= $upload_output.'<br />';
11690:     }
11691:     my ($pathchange_output,$chgcount);
11692:     $chgcount = $counter;
11693:     if (keys(%pathchanges) > 0) {
11694:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
11695:             if ($counter) {
11696:                 $output .= &embedded_file_element('pathchange',$chgcount,
11697:                                                   $embed_file,\%mapping,
11698:                                                   $allfiles,$codebase,'change');
11699:             } else {
11700:                 $pathchange_output .= 
11701:                     &start_data_table_row().
11702:                     '<td><input type ="checkbox" name="namechange" value="'.
11703:                     $chgcount.'" checked="checked" /></td>'.
11704:                     '<td>'.$mapping{$embed_file}.'</td>'.
11705:                     '<td>'.$embed_file.
11706:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
11707:                                            \%mapping,$allfiles,$codebase,'change').
11708:                     '</td>'.&end_data_table_row();
11709:             }
11710:             $numpathchg ++;
11711:             $chgcount ++;
11712:         }
11713:     }
11714:     if (($counter) || ($numunused)) {
11715:         if ($numpathchg) {
11716:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
11717:                        $numpathchg.'" />'."\n";
11718:         }
11719:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
11720:             ($actionurl eq '/adm/imsimport')) {
11721:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
11722:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
11723:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
11724:         } elsif ($actionurl eq '/adm/dependencies') {
11725:             $output .= '<input type="hidden" name="action" value="process_changes" />';
11726:         }
11727:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
11728:     } elsif ($numpathchg) {
11729:         my %pathchange = ();
11730:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
11731:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11732:             $output .= '<p>'.&mt('or').'</p>'; 
11733:         }
11734:     }
11735:     return ($output,$counter,$numpathchg);
11736: }
11737: 
11738: =pod
11739: 
11740: =item * clean_path($name)
11741: 
11742: Performs clean-up of directories, subdirectories and filename in an
11743: embedded object, referenced in an HTML file which is being uploaded
11744: to a course or portfolio, where
11745: "Upload embedded images/multimedia files if HTML file" checkbox was
11746: checked.
11747: 
11748: Clean-up is similar to replacements in lonnet::clean_filename()
11749: except each / between sub-directory and next level is preserved.
11750: 
11751: =cut
11752: 
11753: sub clean_path {
11754:     my ($embed_file) = @_;
11755:     $embed_file =~s{^/+}{};
11756:     my @contents;
11757:     if ($embed_file =~ m{/}) {
11758:         @contents = split(/\//,$embed_file);
11759:     } else {
11760:         @contents = ($embed_file);
11761:     }
11762:     my $lastidx = scalar(@contents)-1;
11763:     for (my $i=0; $i<=$lastidx; $i++) {
11764:         $contents[$i]=~s{\\}{/}g;
11765:         $contents[$i]=~s/\s+/\_/g;
11766:         $contents[$i]=~s{[^/\w\.\-]}{}g;
11767:         if ($i == $lastidx) {
11768:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
11769:         }
11770:     }
11771:     if ($lastidx > 0) {
11772:         return join('/',@contents);
11773:     } else {
11774:         return $contents[0];
11775:     }
11776: }
11777: 
11778: sub embedded_file_element {
11779:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
11780:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
11781:                    (ref($codebase) eq 'HASH'));
11782:     my $output;
11783:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
11784:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
11785:     }
11786:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
11787:                &escape($embed_file).'" />';
11788:     unless (($context eq 'upload_embedded') && 
11789:             ($mapping->{$embed_file} eq $embed_file)) {
11790:         $output .='
11791:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
11792:     }
11793:     my $attrib;
11794:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
11795:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
11796:     }
11797:     $output .=
11798:         "\n\t\t".
11799:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
11800:         $attrib.'" />';
11801:     if (exists($codebase->{$mapping->{$embed_file}})) {
11802:         $output .=
11803:             "\n\t\t".
11804:             '<input name="codebase_'.$num.'" type="hidden" value="'.
11805:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
11806:     }
11807:     return $output;
11808: }
11809: 
11810: sub get_dependency_details {
11811:     my ($currfile,$currsubfile,$embed_file) = @_;
11812:     my ($size,$mtime,$showsize,$showmtime);
11813:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
11814:         if ($embed_file =~ m{/}) {
11815:             my ($path,$fname) = split(/\//,$embed_file);
11816:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
11817:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
11818:             }
11819:         } else {
11820:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
11821:                 ($size,$mtime) = @{$currfile->{$embed_file}};
11822:             }
11823:         }
11824:         $showsize = $size/1024.0;
11825:         $showsize = sprintf("%.1f",$showsize);
11826:         if ($mtime > 0) {
11827:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
11828:         }
11829:     }
11830:     return ($showsize,$showmtime);
11831: }
11832: 
11833: sub ask_embedded_js {
11834:     return <<"END";
11835: <script type="text/javascript"">
11836: // <![CDATA[
11837: function toggleBrowse(counter) {
11838:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
11839:     var fileid = document.getElementById('embedded_item_'+counter);
11840:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
11841:     if (chkboxid.checked == true) {
11842:         uploaddivid.style.display='block';
11843:     } else {
11844:         uploaddivid.style.display='none';
11845:         fileid.value = '';
11846:     }
11847: }
11848: // ]]>
11849: </script>
11850: 
11851: END
11852: }
11853: 
11854: sub upload_embedded {
11855:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
11856:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
11857:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
11858:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
11859:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
11860:         my $orig_uploaded_filename =
11861:             $env{'form.embedded_item_'.$i.'.filename'};
11862:         foreach my $type ('orig','ref','attrib','codebase') {
11863:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
11864:                 $env{'form.embedded_'.$type.'_'.$i} =
11865:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
11866:             }
11867:         }
11868:         my ($path,$fname) =
11869:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
11870:         # no path, whole string is fname
11871:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
11872:         $fname = &Apache::lonnet::clean_filename($fname);
11873:         # See if there is anything left
11874:         next if ($fname eq '');
11875: 
11876:         # Check if file already exists as a file or directory.
11877:         my ($state,$msg);
11878:         if ($context eq 'portfolio') {
11879:             my $port_path = $dirpath;
11880:             if ($group ne '') {
11881:                 $port_path = "groups/$group/$port_path";
11882:             }
11883:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
11884:                                               $fname,$group,'embedded_item_'.$i,
11885:                                               $dir_root,$port_path,$disk_quota,
11886:                                               $current_disk_usage,$uname,$udom);
11887:             if ($state eq 'will_exceed_quota'
11888:                 || $state eq 'file_locked') {
11889:                 $output .= $msg;
11890:                 next;
11891:             }
11892:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
11893:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
11894:             if ($state eq 'exists') {
11895:                 $output .= $msg;
11896:                 next;
11897:             }
11898:         }
11899:         # Check if extension is valid
11900:         if (($fname =~ /\.(\w+)$/) &&
11901:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
11902:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
11903:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
11904:             next;
11905:         } elsif (($fname =~ /\.(\w+)$/) &&
11906:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
11907:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
11908:             next;
11909:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
11910:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
11911:             next;
11912:         }
11913:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
11914:         my $subdir = $path;
11915:         $subdir =~ s{/+$}{};
11916:         if ($context eq 'portfolio') {
11917:             my $result;
11918:             if ($state eq 'existingfile') {
11919:                 $result=
11920:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
11921:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
11922:             } else {
11923:                 $result=
11924:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
11925:                                                     $dirpath.
11926:                                                     $env{'form.currentpath'}.$subdir);
11927:                 if ($result !~ m|^/uploaded/|) {
11928:                     $output .= '<span class="LC_error">'
11929:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11930:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11931:                                .'</span><br />';
11932:                     next;
11933:                 } else {
11934:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11935:                                $path.$fname.'</span>').'<br />';     
11936:                 }
11937:             }
11938:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
11939:             my $extendedsubdir = $dirpath.'/'.$subdir;
11940:             $extendedsubdir =~ s{/+$}{};
11941:             my $result =
11942:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
11943:             if ($result !~ m|^/uploaded/|) {
11944:                 $output .= '<span class="LC_error">'
11945:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11946:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11947:                            .'</span><br />';
11948:                     next;
11949:             } else {
11950:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11951:                            $path.$fname.'</span>').'<br />';
11952:                 if ($context eq 'syllabus') {
11953:                     &Apache::lonnet::make_public_indefinitely($result);
11954:                 }
11955:             }
11956:         } else {
11957: # Save the file
11958:             my $target = $env{'form.embedded_item_'.$i};
11959:             my $fullpath = $dir_root.$dirpath.'/'.$path;
11960:             my $dest = $fullpath.$fname;
11961:             my $url = $url_root.$dirpath.'/'.$path.$fname;
11962:             my @parts=split(/\//,"$dirpath/$path");
11963:             my $count;
11964:             my $filepath = $dir_root;
11965:             foreach my $subdir (@parts) {
11966:                 $filepath .= "/$subdir";
11967:                 if (!-e $filepath) {
11968:                     mkdir($filepath,0770);
11969:                 }
11970:             }
11971:             my $fh;
11972:             if (!open($fh,'>'.$dest)) {
11973:                 &Apache::lonnet::logthis('Failed to create '.$dest);
11974:                 $output .= '<span class="LC_error">'.
11975:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
11976:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11977:                            '</span><br />';
11978:             } else {
11979:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
11980:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
11981:                     $output .= '<span class="LC_error">'.
11982:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
11983:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11984:                               '</span><br />';
11985:                 } else {
11986:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11987:                                $url.'</span>').'<br />';
11988:                     unless ($context eq 'testbank') {
11989:                         $footer .= &mt('View embedded file: [_1]',
11990:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
11991:                     }
11992:                 }
11993:                 close($fh);
11994:             }
11995:         }
11996:         if ($env{'form.embedded_ref_'.$i}) {
11997:             $pathchange{$i} = 1;
11998:         }
11999:     }
12000:     if ($output) {
12001:         $output = '<p>'.$output.'</p>';
12002:     }
12003:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
12004:     $returnflag = 'ok';
12005:     my $numpathchgs = scalar(keys(%pathchange));
12006:     if ($numpathchgs > 0) {
12007:         if ($context eq 'portfolio') {
12008:             $output .= '<p>'.&mt('or').'</p>';
12009:         } elsif ($context eq 'testbank') {
12010:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
12011:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
12012:             $returnflag = 'modify_orightml';
12013:         }
12014:     }
12015:     return ($output.$footer,$returnflag,$numpathchgs);
12016: }
12017: 
12018: sub modify_html_form {
12019:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
12020:     my $end = 0;
12021:     my $modifyform;
12022:     if ($context eq 'upload_embedded') {
12023:         return unless (ref($pathchange) eq 'HASH');
12024:         if ($env{'form.number_embedded_items'}) {
12025:             $end += $env{'form.number_embedded_items'};
12026:         }
12027:         if ($env{'form.number_pathchange_items'}) {
12028:             $end += $env{'form.number_pathchange_items'};
12029:         }
12030:         if ($end) {
12031:             for (my $i=0; $i<$end; $i++) {
12032:                 if ($i < $env{'form.number_embedded_items'}) {
12033:                     next unless($pathchange->{$i});
12034:                 }
12035:                 $modifyform .=
12036:                     &start_data_table_row().
12037:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
12038:                     'checked="checked" /></td>'.
12039:                     '<td>'.$env{'form.embedded_ref_'.$i}.
12040:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
12041:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
12042:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
12043:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
12044:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
12045:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
12046:                     '<td>'.$env{'form.embedded_orig_'.$i}.
12047:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
12048:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
12049:                     &end_data_table_row();
12050:             }
12051:         }
12052:     } else {
12053:         $modifyform = $pathchgtable;
12054:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12055:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
12056:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
12057:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
12058:         }
12059:     }
12060:     if ($modifyform) {
12061:         if ($actionurl eq '/adm/dependencies') {
12062:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
12063:         }
12064:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
12065:                '<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".
12066:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
12067:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
12068:                '</ol></p>'."\n".'<p>'.
12069:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
12070:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
12071:                &start_data_table()."\n".
12072:                &start_data_table_header_row().
12073:                '<th>'.&mt('Change?').'</th>'.
12074:                '<th>'.&mt('Current reference').'</th>'.
12075:                '<th>'.&mt('Required reference').'</th>'.
12076:                &end_data_table_header_row()."\n".
12077:                $modifyform.
12078:                &end_data_table().'<br />'."\n".$hiddenstate.
12079:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
12080:                '</form>'."\n";
12081:     }
12082:     return;
12083: }
12084: 
12085: sub modify_html_refs {
12086:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
12087:     my $container;
12088:     if ($context eq 'portfolio') {
12089:         $container = $env{'form.container'};
12090:     } elsif ($context eq 'coursedoc') {
12091:         $container = $env{'form.primaryurl'};
12092:     } elsif ($context eq 'manage_dependencies') {
12093:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
12094:         $container = "/$container";
12095:     } elsif ($context eq 'syllabus') {
12096:         $container = $url;
12097:     } else {
12098:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
12099:     }
12100:     my (%allfiles,%codebase,$output,$content);
12101:     my @changes = &get_env_multiple('form.namechange');
12102:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
12103:         if (wantarray) {
12104:             return ('',0,0); 
12105:         } else {
12106:             return;
12107:         }
12108:     }
12109:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
12110:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
12111:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
12112:             if (wantarray) {
12113:                 return ('',0,0);
12114:             } else {
12115:                 return;
12116:             }
12117:         } 
12118:         $content = &Apache::lonnet::getfile($container);
12119:         if ($content eq '-1') {
12120:             if (wantarray) {
12121:                 return ('',0,0);
12122:             } else {
12123:                 return;
12124:             }
12125:         }
12126:     } else {
12127:         unless ($container =~ /^\Q$dir_root\E/) {
12128:             if (wantarray) {
12129:                 return ('',0,0);
12130:             } else {
12131:                 return;
12132:             }
12133:         } 
12134:         if (open(my $fh,'<',$container)) {
12135:             $content = join('', <$fh>);
12136:             close($fh);
12137:         } else {
12138:             if (wantarray) {
12139:                 return ('',0,0);
12140:             } else {
12141:                 return;
12142:             }
12143:         }
12144:     }
12145:     my ($count,$codebasecount) = (0,0);
12146:     my $mm = new File::MMagic;
12147:     my $mime_type = $mm->checktype_contents($content);
12148:     if ($mime_type eq 'text/html') {
12149:         my $parse_result = 
12150:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
12151:                                                     \%codebase,\$content);
12152:         if ($parse_result eq 'ok') {
12153:             foreach my $i (@changes) {
12154:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
12155:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
12156:                 if ($allfiles{$ref}) {
12157:                     my $newname =  $orig;
12158:                     my ($attrib_regexp,$codebase);
12159:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
12160:                     if ($attrib_regexp =~ /:/) {
12161:                         $attrib_regexp =~ s/\:/|/g;
12162:                     }
12163:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
12164:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
12165:                         $count += $numchg;
12166:                         $allfiles{$newname} = $allfiles{$ref};
12167:                         delete($allfiles{$ref});
12168:                     }
12169:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
12170:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
12171:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
12172:                         $codebasecount ++;
12173:                     }
12174:                 }
12175:             }
12176:             my $skiprewrites;
12177:             if ($count || $codebasecount) {
12178:                 my $saveresult;
12179:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
12180:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
12181:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
12182:                     if ($url eq $container) {
12183:                         my ($fname) = ($container =~ m{/([^/]+)$});
12184:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
12185:                                             $count,'<span class="LC_filename">'.
12186:                                             $fname.'</span>').'</p>';
12187:                     } else {
12188:                          $output = '<p class="LC_error">'.
12189:                                    &mt('Error: update failed for: [_1].',
12190:                                    '<span class="LC_filename">'.
12191:                                    $container.'</span>').'</p>';
12192:                     }
12193:                     if ($context eq 'syllabus') {
12194:                         unless ($saveresult eq 'ok') {
12195:                             $skiprewrites = 1;
12196:                         }
12197:                     }
12198:                 } else {
12199:                     if (open(my $fh,'>',$container)) {
12200:                         print $fh $content;
12201:                         close($fh);
12202:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
12203:                                   $count,'<span class="LC_filename">'.
12204:                                   $container.'</span>').'</p>';
12205:                     } else {
12206:                          $output = '<p class="LC_error">'.
12207:                                    &mt('Error: could not update [_1].',
12208:                                    '<span class="LC_filename">'.
12209:                                    $container.'</span>').'</p>';
12210:                     }
12211:                 }
12212:             }
12213:             if (($context eq 'syllabus') && (!$skiprewrites)) {
12214:                 my ($actionurl,$state);
12215:                 $actionurl = "/public/$udom/$uname/syllabus";
12216:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
12217:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
12218:                                               \%codebase,
12219:                                               {'context' => 'rewrites',
12220:                                                'ignore_remote_references' => 1,});
12221:                 if (ref($mapping) eq 'HASH') {
12222:                     my $rewrites = 0;
12223:                     foreach my $key (keys(%{$mapping})) {
12224:                         next if ($key =~ m{^https?://});
12225:                         my $ref = $mapping->{$key};
12226:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
12227:                         my $attrib;
12228:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
12229:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
12230:                         }
12231:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
12232:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
12233:                             $rewrites += $numchg;
12234:                         }
12235:                     }
12236:                     if ($rewrites) {
12237:                         my $saveresult;
12238:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
12239:                         if ($url eq $container) {
12240:                             my ($fname) = ($container =~ m{/([^/]+)$});
12241:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
12242:                                             $count,'<span class="LC_filename">'.
12243:                                             $fname.'</span>').'</p>';
12244:                         } else {
12245:                             $output .= '<p class="LC_error">'.
12246:                                        &mt('Error: could not update links in [_1].',
12247:                                        '<span class="LC_filename">'.
12248:                                        $container.'</span>').'</p>';
12249: 
12250:                         }
12251:                     }
12252:                 }
12253:             }
12254:         } else {
12255:             &logthis('Failed to parse '.$container.
12256:                      ' to modify references: '.$parse_result);
12257:         }
12258:     }
12259:     if (wantarray) {
12260:         return ($output,$count,$codebasecount);
12261:     } else {
12262:         return $output;
12263:     }
12264: }
12265: 
12266: sub check_for_existing {
12267:     my ($path,$fname,$element) = @_;
12268:     my ($state,$msg);
12269:     if (-d $path.'/'.$fname) {
12270:         $state = 'exists';
12271:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
12272:     } elsif (-e $path.'/'.$fname) {
12273:         $state = 'exists';
12274:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
12275:     }
12276:     if ($state eq 'exists') {
12277:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
12278:     }
12279:     return ($state,$msg);
12280: }
12281: 
12282: sub check_for_upload {
12283:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
12284:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
12285:     my $filesize = length($env{'form.'.$element});
12286:     if (!$filesize) {
12287:         my $msg = '<span class="LC_error">'.
12288:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
12289:                       '<span class="LC_filename">'.$fname.'</span>',
12290:                       $filesize).'<br />'.
12291:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
12292:                   '</span>';
12293:         return ('zero_bytes',$msg);
12294:     }
12295:     $filesize =  $filesize/1000; #express in k (1024?)
12296:     my $getpropath = 1;
12297:     my ($dirlistref,$listerror) =
12298:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
12299:     my $found_file = 0;
12300:     my $locked_file = 0;
12301:     my @lockers;
12302:     my $navmap;
12303:     if ($env{'request.course.id'}) {
12304:         $navmap = Apache::lonnavmaps::navmap->new();
12305:     }
12306:     if (ref($dirlistref) eq 'ARRAY') {
12307:         foreach my $line (@{$dirlistref}) {
12308:             my ($file_name,$rest)=split(/\&/,$line,2);
12309:             if ($file_name eq $fname){
12310:                 $file_name = $path.$file_name;
12311:                 if ($group ne '') {
12312:                     $file_name = $group.$file_name;
12313:                 }
12314:                 $found_file = 1;
12315:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
12316:                     foreach my $lock (@lockers) {
12317:                         if (ref($lock) eq 'ARRAY') {
12318:                             my ($symb,$crsid) = @{$lock};
12319:                             if ($crsid eq $env{'request.course.id'}) {
12320:                                 if (ref($navmap)) {
12321:                                     my $res = $navmap->getBySymb($symb);
12322:                                     foreach my $part (@{$res->parts()}) { 
12323:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
12324:                                         unless (($slot_status == $res->RESERVED) ||
12325:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
12326:                                             $locked_file = 1;
12327:                                         }
12328:                                     }
12329:                                 } else {
12330:                                     $locked_file = 1;
12331:                                 }
12332:                             } else {
12333:                                 $locked_file = 1;
12334:                             }
12335:                         }
12336:                    }
12337:                 } else {
12338:                     my @info = split(/\&/,$rest);
12339:                     my $currsize = $info[6]/1000;
12340:                     if ($currsize < $filesize) {
12341:                         my $extra = $filesize - $currsize;
12342:                         if (($current_disk_usage + $extra) > $disk_quota) {
12343:                             my $msg = '<p class="LC_warning">'.
12344:                                       &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.',
12345:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
12346:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
12347:                                                    $disk_quota,$current_disk_usage).'</p>';
12348:                             return ('will_exceed_quota',$msg);
12349:                         }
12350:                     }
12351:                 }
12352:             }
12353:         }
12354:     }
12355:     if (($current_disk_usage + $filesize) > $disk_quota){
12356:         my $msg = '<p class="LC_warning">'.
12357:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
12358:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
12359:         return ('will_exceed_quota',$msg);
12360:     } elsif ($found_file) {
12361:         if ($locked_file) {
12362:             my $msg = '<p class="LC_warning">';
12363:             $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>');
12364:             $msg .= '</p>';
12365:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
12366:             return ('file_locked',$msg);
12367:         } else {
12368:             my $msg = '<p class="LC_error">';
12369:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
12370:             $msg .= '</p>';
12371:             return ('existingfile',$msg);
12372:         }
12373:     }
12374: }
12375: 
12376: sub check_for_traversal {
12377:     my ($path,$url,$toplevel) = @_;
12378:     my @parts=split(/\//,$path);
12379:     my $cleanpath;
12380:     my $fullpath = $url;
12381:     for (my $i=0;$i<@parts;$i++) {
12382:         next if ($parts[$i] eq '.');
12383:         if ($parts[$i] eq '..') {
12384:             $fullpath =~ s{([^/]+/)$}{};
12385:         } else {
12386:             $fullpath .= $parts[$i].'/';
12387:         }
12388:     }
12389:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
12390:         $cleanpath = $1;
12391:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
12392:         my $curr_toprel = $1;
12393:         my @parts = split(/\//,$curr_toprel);
12394:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
12395:         my @urlparts = split(/\//,$url_toprel);
12396:         my $doubledots;
12397:         my $startdiff = -1;
12398:         for (my $i=0; $i<@urlparts; $i++) {
12399:             if ($startdiff == -1) {
12400:                 unless ($urlparts[$i] eq $parts[$i]) {
12401:                     $startdiff = $i;
12402:                     $doubledots .= '../';
12403:                 }
12404:             } else {
12405:                 $doubledots .= '../';
12406:             }
12407:         }
12408:         if ($startdiff > -1) {
12409:             $cleanpath = $doubledots;
12410:             for (my $i=$startdiff; $i<@parts; $i++) {
12411:                 $cleanpath .= $parts[$i].'/';
12412:             }
12413:         }
12414:     }
12415:     $cleanpath =~ s{(/)$}{};
12416:     return $cleanpath;
12417: }
12418: 
12419: sub is_archive_file {
12420:     my ($mimetype) = @_;
12421:     if (($mimetype eq 'application/octet-stream') ||
12422:         ($mimetype eq 'application/x-stuffit') ||
12423:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
12424:         return 1;
12425:     }
12426:     return;
12427: }
12428: 
12429: sub decompress_form {
12430:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
12431:     my %lt = &Apache::lonlocal::texthash (
12432:         this => 'This file is an archive file.',
12433:         camt => 'This file is a Camtasia archive file.',
12434:         itsc => 'Its contents are as follows:',
12435:         youm => 'You may wish to extract its contents.',
12436:         extr => 'Extract contents',
12437:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
12438:         proa => 'Process automatically?',
12439:         yes  => 'Yes',
12440:         no   => 'No',
12441:         fold => 'Title for folder containing movie',
12442:         movi => 'Title for page containing embedded movie', 
12443:     );
12444:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
12445:     my ($is_camtasia,$topdir,%toplevel,@paths);
12446:     my $info = &list_archive_contents($fileloc,\@paths);
12447:     if (@paths) {
12448:         foreach my $path (@paths) {
12449:             $path =~ s{^/}{};
12450:             if ($path =~ m{^([^/]+)/$}) {
12451:                 $topdir = $1;
12452:             }
12453:             if ($path =~ m{^([^/]+)/}) {
12454:                 $toplevel{$1} = $path;
12455:             } else {
12456:                 $toplevel{$path} = $path;
12457:             }
12458:         }
12459:     }
12460:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
12461:         my @camtasia6 = ("$topdir/","$topdir/index.html",
12462:                         "$topdir/media/",
12463:                         "$topdir/media/$topdir.mp4",
12464:                         "$topdir/media/FirstFrame.png",
12465:                         "$topdir/media/player.swf",
12466:                         "$topdir/media/swfobject.js",
12467:                         "$topdir/media/expressInstall.swf");
12468:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
12469:                          "$topdir/$topdir.mp4",
12470:                          "$topdir/$topdir\_config.xml",
12471:                          "$topdir/$topdir\_controller.swf",
12472:                          "$topdir/$topdir\_embed.css",
12473:                          "$topdir/$topdir\_First_Frame.png",
12474:                          "$topdir/$topdir\_player.html",
12475:                          "$topdir/$topdir\_Thumbnails.png",
12476:                          "$topdir/playerProductInstall.swf",
12477:                          "$topdir/scripts/",
12478:                          "$topdir/scripts/config_xml.js",
12479:                          "$topdir/scripts/handlebars.js",
12480:                          "$topdir/scripts/jquery-1.7.1.min.js",
12481:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
12482:                          "$topdir/scripts/modernizr.js",
12483:                          "$topdir/scripts/player-min.js",
12484:                          "$topdir/scripts/swfobject.js",
12485:                          "$topdir/skins/",
12486:                          "$topdir/skins/configuration_express.xml",
12487:                          "$topdir/skins/express_show/",
12488:                          "$topdir/skins/express_show/player-min.css",
12489:                          "$topdir/skins/express_show/spritesheet.png");
12490:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
12491:                          "$topdir/$topdir.mp4",
12492:                          "$topdir/$topdir\_config.xml",
12493:                          "$topdir/$topdir\_controller.swf",
12494:                          "$topdir/$topdir\_embed.css",
12495:                          "$topdir/$topdir\_First_Frame.png",
12496:                          "$topdir/$topdir\_player.html",
12497:                          "$topdir/$topdir\_Thumbnails.png",
12498:                          "$topdir/playerProductInstall.swf",
12499:                          "$topdir/scripts/",
12500:                          "$topdir/scripts/config_xml.js",
12501:                          "$topdir/scripts/techsmith-smart-player.min.js",
12502:                          "$topdir/skins/",
12503:                          "$topdir/skins/configuration_express.xml",
12504:                          "$topdir/skins/express_show/",
12505:                          "$topdir/skins/express_show/spritesheet.min.css",
12506:                          "$topdir/skins/express_show/spritesheet.png",
12507:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
12508:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
12509:         if (@diffs == 0) {
12510:             $is_camtasia = 6;
12511:         } else {
12512:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
12513:             if (@diffs == 0) {
12514:                 $is_camtasia = 8;
12515:             } else {
12516:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
12517:                 if (@diffs == 0) {
12518:                     $is_camtasia = 8;
12519:                 }
12520:             }
12521:         }
12522:     }
12523:     my $output;
12524:     if ($is_camtasia) {
12525:         $output = <<"ENDCAM";
12526: <script type="text/javascript" language="Javascript">
12527: // <![CDATA[
12528: 
12529: function camtasiaToggle() {
12530:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
12531:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
12532:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
12533:                 document.getElementById('camtasia_titles').style.display='block';
12534:             } else {
12535:                 document.getElementById('camtasia_titles').style.display='none';
12536:             }
12537:         }
12538:     }
12539:     return;
12540: }
12541: 
12542: // ]]>
12543: </script>
12544: <p>$lt{'camt'}</p>
12545: ENDCAM
12546:     } else {
12547:         $output = '<p>'.$lt{'this'};
12548:         if ($info eq '') {
12549:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
12550:         } else {
12551:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
12552:                        '<div><pre>'.$info.'</pre></div>';
12553:         }
12554:     }
12555:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
12556:     my $duplicates;
12557:     my $num = 0;
12558:     if (ref($dirlist) eq 'ARRAY') {
12559:         foreach my $item (@{$dirlist}) {
12560:             if (ref($item) eq 'ARRAY') {
12561:                 if (exists($toplevel{$item->[0]})) {
12562:                     $duplicates .= 
12563:                         &start_data_table_row().
12564:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
12565:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
12566:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
12567:                         'value="1" />'.&mt('Yes').'</label>'.
12568:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
12569:                         '<td>'.$item->[0].'</td>';
12570:                     if ($item->[2]) {
12571:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
12572:                     } else {
12573:                         $duplicates .= '<td>'.&mt('File').'</td>';
12574:                     }
12575:                     $duplicates .= '<td>'.$item->[3].'</td>'.
12576:                                    '<td>'.
12577:                                    &Apache::lonlocal::locallocaltime($item->[4]).
12578:                                    '</td>'.
12579:                                    &end_data_table_row();
12580:                     $num ++;
12581:                 }
12582:             }
12583:         }
12584:     }
12585:     my $itemcount;
12586:     if (@paths > 0) {
12587:         $itemcount = scalar(@paths);
12588:     } else {
12589:         $itemcount = 1;
12590:     }
12591:     if ($is_camtasia) {
12592:         $output .= $lt{'auto'}.'<br />'.
12593:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
12594:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
12595:                    $lt{'yes'}.'</label>&nbsp;<label>'.
12596:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
12597:                    $lt{'no'}.'</label></span><br />'.
12598:                    '<div id="camtasia_titles" style="display:block">'.
12599:                    &Apache::lonhtmlcommon::start_pick_box().
12600:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
12601:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
12602:                    &Apache::lonhtmlcommon::row_closure().
12603:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
12604:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
12605:                    &Apache::lonhtmlcommon::row_closure(1).
12606:                    &Apache::lonhtmlcommon::end_pick_box().
12607:                    '</div>';
12608:     }
12609:     $output .= 
12610:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
12611:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
12612:         "\n";
12613:     if ($duplicates ne '') {
12614:         $output .= '<p><span class="LC_warning">'.
12615:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
12616:                    &start_data_table().
12617:                    &start_data_table_header_row().
12618:                    '<th>'.&mt('Overwrite?').'</th>'.
12619:                    '<th>'.&mt('Name').'</th>'.
12620:                    '<th>'.&mt('Type').'</th>'.
12621:                    '<th>'.&mt('Size').'</th>'.
12622:                    '<th>'.&mt('Last modified').'</th>'.
12623:                    &end_data_table_header_row().
12624:                    $duplicates.
12625:                    &end_data_table().
12626:                    '</p>';
12627:     }
12628:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
12629:     if (ref($hiddenelements) eq 'HASH') {
12630:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
12631:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
12632:         }
12633:     }
12634:     $output .= <<"END";
12635: <br />
12636: <input type="submit" name="decompress" value="$lt{'extr'}" />
12637: </form>
12638: $noextract
12639: END
12640:     return $output;
12641: }
12642: 
12643: sub decompression_utility {
12644:     my ($program) = @_;
12645:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
12646:     my $location;
12647:     if (grep(/^\Q$program\E$/,@utilities)) { 
12648:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
12649:                          '/usr/sbin/') {
12650:             if (-x $dir.$program) {
12651:                 $location = $dir.$program;
12652:                 last;
12653:             }
12654:         }
12655:     }
12656:     return $location;
12657: }
12658: 
12659: sub list_archive_contents {
12660:     my ($file,$pathsref) = @_;
12661:     my (@cmd,$output);
12662:     my $needsregexp;
12663:     if ($file =~ /\.zip$/) {
12664:         @cmd = (&decompression_utility('unzip'),"-l");
12665:         $needsregexp = 1;
12666:     } elsif (($file =~ m/\.tar\.gz$/) ||
12667:              ($file =~ /\.tgz$/)) {
12668:         @cmd = (&decompression_utility('tar'),"-ztf");
12669:     } elsif ($file =~ /\.tar\.bz2$/) {
12670:         @cmd = (&decompression_utility('tar'),"-jtf");
12671:     } elsif ($file =~ m|\.tar$|) {
12672:         @cmd = (&decompression_utility('tar'),"-tf");
12673:     }
12674:     if (@cmd) {
12675:         undef($!);
12676:         undef($@);
12677:         if (open(my $fh,"-|", @cmd, $file)) {
12678:             while (my $line = <$fh>) {
12679:                 $output .= $line;
12680:                 chomp($line);
12681:                 my $item;
12682:                 if ($needsregexp) {
12683:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
12684:                 } else {
12685:                     $item = $line;
12686:                 }
12687:                 if ($item ne '') {
12688:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
12689:                         push(@{$pathsref},$item);
12690:                     } 
12691:                 }
12692:             }
12693:             close($fh);
12694:         }
12695:     }
12696:     return $output;
12697: }
12698: 
12699: sub decompress_uploaded_file {
12700:     my ($file,$dir) = @_;
12701:     &Apache::lonnet::appenv({'cgi.file' => $file});
12702:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
12703:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
12704:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
12705:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
12706:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
12707:     my $decompressed = $env{'cgi.decompressed'};
12708:     &Apache::lonnet::delenv('cgi.file');
12709:     &Apache::lonnet::delenv('cgi.dir');
12710:     &Apache::lonnet::delenv('cgi.decompressed');
12711:     return ($decompressed,$result);
12712: }
12713: 
12714: sub process_decompression {
12715:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
12716:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
12717:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12718:                &mt('Unexpected file path.').'</p>'."\n";
12719:     }
12720:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
12721:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12722:                &mt('Unexpected course context.').'</p>'."\n";
12723:     }
12724:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
12725:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12726:                &mt('Filename contained unexpected characters.').'</p>'."\n";
12727:     }
12728:     my ($dir,$error,$warning,$output);
12729:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
12730:         $error = &mt('Filename not a supported archive file type.').
12731:                  '<br />'.&mt('Filename should end with one of: [_1].',
12732:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
12733:     } else {
12734:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
12735:         if ($docuhome eq 'no_host') {
12736:             $error = &mt('Could not determine home server for course.');
12737:         } else {
12738:             my @ids=&Apache::lonnet::current_machine_ids();
12739:             my $currdir = "$dir_root/$destination";
12740:             if (grep(/^\Q$docuhome\E$/,@ids)) {
12741:                 $dir = &LONCAPA::propath($docudom,$docuname).
12742:                        "$dir_root/$destination";
12743:             } else {
12744:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
12745:                        "$dir_root/$docudom/$docuname/$destination";
12746:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
12747:                     $error = &mt('Archive file not found.');
12748:                 }
12749:             }
12750:             my (@to_overwrite,@to_skip);
12751:             if ($env{'form.archive_overwrite_total'} > 0) {
12752:                 my $total = $env{'form.archive_overwrite_total'};
12753:                 for (my $i=0; $i<$total; $i++) {
12754:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
12755:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
12756:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
12757:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
12758:                     }
12759:                 }
12760:             }
12761:             my $numskip = scalar(@to_skip);
12762:             my $numoverwrite = scalar(@to_overwrite);
12763:             if (($numskip) && (!$numoverwrite)) {
12764:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
12765:             } elsif ($dir eq '') {
12766:                 $error = &mt('Directory containing archive file unavailable.');
12767:             } elsif (!$error) {
12768:                 my ($decompressed,$display);
12769:                 if (($numskip) || ($numoverwrite)) {
12770:                     my $tempdir = time.'_'.$$.int(rand(10000));
12771:                     mkdir("$dir/$tempdir",0755);
12772:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
12773:                         ($decompressed,$display) =
12774:                             &decompress_uploaded_file($file,"$dir/$tempdir");
12775:                         foreach my $item (@to_skip) {
12776:                             if (($item ne '') && ($item !~ /\.\./)) {
12777:                                 if (-f "$dir/$tempdir/$item") {
12778:                                     unlink("$dir/$tempdir/$item");
12779:                                 } elsif (-d "$dir/$tempdir/$item") {
12780:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
12781:                                 }
12782:                             }
12783:                         }
12784:                         foreach my $item (@to_overwrite) {
12785:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
12786:                                 if (($item ne '') && ($item !~ /\.\./)) {
12787:                                     if (-f "$dir/$item") {
12788:                                         unlink("$dir/$item");
12789:                                     } elsif (-d "$dir/$item") {
12790:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
12791:                                     }
12792:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
12793:                                 }
12794:                             }
12795:                         }
12796:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
12797:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
12798:                         }
12799:                     }
12800:                 } else {
12801:                     ($decompressed,$display) = 
12802:                         &decompress_uploaded_file($file,$dir);
12803:                 }
12804:                 if ($decompressed eq 'ok') {
12805:                     $output = '<p class="LC_info">'.
12806:                               &mt('Files extracted successfully from archive.').
12807:                               '</p>'."\n";
12808:                     my ($warning,$result,@contents);
12809:                     my ($newdirlistref,$newlisterror) =
12810:                         &Apache::lonnet::dirlist($currdir,$docudom,
12811:                                                  $docuname,1);
12812:                     my (%is_dir,%changes,@newitems);
12813:                     my $dirptr = 16384;
12814:                     if (ref($newdirlistref) eq 'ARRAY') {
12815:                         foreach my $dir_line (@{$newdirlistref}) {
12816:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12817:                             unless (($item =~ /^\.+$/) || ($item eq $file)) { 
12818:                                 push(@newitems,$item);
12819:                                 if ($dirptr&$testdir) {
12820:                                     $is_dir{$item} = 1;
12821:                                 }
12822:                                 $changes{$item} = 1;
12823:                             }
12824:                         }
12825:                     }
12826:                     if (keys(%changes) > 0) {
12827:                         foreach my $item (sort(@newitems)) {
12828:                             if ($changes{$item}) {
12829:                                 push(@contents,$item);
12830:                             }
12831:                         }
12832:                     }
12833:                     if (@contents > 0) {
12834:                         my $wantform;
12835:                         unless ($env{'form.autoextract_camtasia'}) {
12836:                             $wantform = 1;
12837:                         }
12838:                         my (%children,%parent,%dirorder,%titles);
12839:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
12840:                                                                 $currdir,\%is_dir,
12841:                                                                 \%children,\%parent,
12842:                                                                 \@contents,\%dirorder,
12843:                                                                 \%titles,$wantform);
12844:                         if ($datatable ne '') {
12845:                             $output .= &archive_options_form('decompressed',$datatable,
12846:                                                              $count,$hiddenelem);
12847:                             my $startcount = 6;
12848:                             $output .= &archive_javascript($startcount,$count,
12849:                                                            \%titles,\%children);
12850:                         }
12851:                         if ($env{'form.autoextract_camtasia'}) {
12852:                             my $version = $env{'form.autoextract_camtasia'};
12853:                             my %displayed;
12854:                             my $total = 1;
12855:                             $env{'form.archive_directory'} = [];
12856:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
12857:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
12858:                                 $path =~ s{/$}{};
12859:                                 my $item;
12860:                                 if ($path ne '') {
12861:                                     $item = "$path/$titles{$i}";
12862:                                 } else {
12863:                                     $item = $titles{$i};
12864:                                 }
12865:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
12866:                                 if ($item eq $contents[0]) {
12867:                                     push(@{$env{'form.archive_directory'}},$i);
12868:                                     $env{'form.archive_'.$i} = 'display';
12869:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
12870:                                     $displayed{'folder'} = $i;
12871:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
12872:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
12873:                                     $env{'form.archive_'.$i} = 'display';
12874:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
12875:                                     $displayed{'web'} = $i;
12876:                                 } else {
12877:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
12878:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
12879:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
12880:                                         push(@{$env{'form.archive_directory'}},$i);
12881:                                     }
12882:                                     $env{'form.archive_'.$i} = 'dependency';
12883:                                 }
12884:                                 $total ++;
12885:                             }
12886:                             for (my $i=1; $i<$total; $i++) {
12887:                                 next if ($i == $displayed{'web'});
12888:                                 next if ($i == $displayed{'folder'});
12889:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
12890:                             }
12891:                             $env{'form.phase'} = 'decompress_cleanup';
12892:                             $env{'form.archivedelete'} = 1;
12893:                             $env{'form.archive_count'} = $total-1;
12894:                             $output .=
12895:                                 &process_extracted_files('coursedocs',$docudom,
12896:                                                          $docuname,$destination,
12897:                                                          $dir_root,$hiddenelem);
12898:                         }
12899:                     } else {
12900:                         $warning = &mt('No new items extracted from archive file.');
12901:                     }
12902:                 } else {
12903:                     $output = $display;
12904:                     $error = &mt('An error occurred during extraction from the archive file.');
12905:                 }
12906:             }
12907:         }
12908:     }
12909:     if ($error) {
12910:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12911:                    $error.'</p>'."\n";
12912:     }
12913:     if ($warning) {
12914:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12915:     }
12916:     return $output;
12917: }
12918: 
12919: sub get_extracted {
12920:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
12921:         $titles,$wantform) = @_;
12922:     my $count = 0;
12923:     my $depth = 0;
12924:     my $datatable;
12925:     my @hierarchy;
12926:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
12927:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
12928:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
12929:     foreach my $item (@{$contents}) {
12930:         $count ++;
12931:         @{$dirorder->{$count}} = @hierarchy;
12932:         $titles->{$count} = $item;
12933:         &archive_hierarchy($depth,$count,$parent,$children);
12934:         if ($wantform) {
12935:             $datatable .= &archive_row($is_dir->{$item},$item,
12936:                                        $currdir,$depth,$count);
12937:         }
12938:         if ($is_dir->{$item}) {
12939:             $depth ++;
12940:             push(@hierarchy,$count);
12941:             $parent->{$depth} = $count;
12942:             $datatable .=
12943:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
12944:                                            \$depth,\$count,\@hierarchy,$dirorder,
12945:                                            $children,$parent,$titles,$wantform);
12946:             $depth --;
12947:             pop(@hierarchy);
12948:         }
12949:     }
12950:     return ($count,$datatable);
12951: }
12952: 
12953: sub recurse_extracted_archive {
12954:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
12955:         $children,$parent,$titles,$wantform) = @_;
12956:     my $result='';
12957:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
12958:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
12959:             (ref($dirorder) eq 'HASH')) {
12960:         return $result;
12961:     }
12962:     my $dirptr = 16384;
12963:     my ($newdirlistref,$newlisterror) =
12964:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
12965:     if (ref($newdirlistref) eq 'ARRAY') {
12966:         foreach my $dir_line (@{$newdirlistref}) {
12967:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12968:             unless ($item =~ /^\.+$/) {
12969:                 $$count ++;
12970:                 @{$dirorder->{$$count}} = @{$hierarchy};
12971:                 $titles->{$$count} = $item;
12972:                 &archive_hierarchy($$depth,$$count,$parent,$children);
12973: 
12974:                 my $is_dir;
12975:                 if ($dirptr&$testdir) {
12976:                     $is_dir = 1;
12977:                 }
12978:                 if ($wantform) {
12979:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
12980:                 }
12981:                 if ($is_dir) {
12982:                     $$depth ++;
12983:                     push(@{$hierarchy},$$count);
12984:                     $parent->{$$depth} = $$count;
12985:                     $result .=
12986:                         &recurse_extracted_archive("$currdir/$item",$docudom,
12987:                                                    $docuname,$depth,$count,
12988:                                                    $hierarchy,$dirorder,$children,
12989:                                                    $parent,$titles,$wantform);
12990:                     $$depth --;
12991:                     pop(@{$hierarchy});
12992:                 }
12993:             }
12994:         }
12995:     }
12996:     return $result;
12997: }
12998: 
12999: sub archive_hierarchy {
13000:     my ($depth,$count,$parent,$children) =@_;
13001:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
13002:         if (exists($parent->{$depth})) {
13003:              $children->{$parent->{$depth}} .= $count.':';
13004:         }
13005:     }
13006:     return;
13007: }
13008: 
13009: sub archive_row {
13010:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
13011:     my ($name) = ($item =~ m{([^/]+)$});
13012:     my %choices = &Apache::lonlocal::texthash (
13013:                                        'display'    => 'Add as file',
13014:                                        'dependency' => 'Include as dependency',
13015:                                        'discard'    => 'Discard',
13016:                                       );
13017:     if ($is_dir) {
13018:         $choices{'display'} = &mt('Add as folder'); 
13019:     }
13020:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
13021:     my $offset = 0;
13022:     foreach my $action ('display','dependency','discard') {
13023:         $offset ++;
13024:         if ($action ne 'display') {
13025:             $offset ++;
13026:         }  
13027:         $output .= '<td><span class="LC_nobreak">'.
13028:                    '<label><input type="radio" name="archive_'.$count.
13029:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
13030:         my $text = $choices{$action};
13031:         if ($is_dir) {
13032:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
13033:             if ($action eq 'display') {
13034:                 $text = &mt('Add as folder');
13035:             }
13036:         } else {
13037:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
13038: 
13039:         }
13040:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
13041:         if ($action eq 'dependency') {
13042:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
13043:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
13044:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
13045:                        '<option value=""></option>'."\n".
13046:                        '</select>'."\n".
13047:                        '</div>';
13048:         } elsif ($action eq 'display') {
13049:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
13050:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
13051:                        '</div>';
13052:         }
13053:         $output .= '</td>';
13054:     }
13055:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
13056:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
13057:     for (my $i=0; $i<$depth; $i++) {
13058:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
13059:     }
13060:     if ($is_dir) {
13061:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
13062:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
13063:     } else {
13064:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
13065:     }
13066:     $output .= '&nbsp;'.$name.'</td>'."\n".
13067:                &end_data_table_row();
13068:     return $output;
13069: }
13070: 
13071: sub archive_options_form {
13072:     my ($form,$display,$count,$hiddenelem) = @_;
13073:     my %lt = &Apache::lonlocal::texthash(
13074:                perm => 'Permanently remove archive file?',
13075:                hows => 'How should each extracted item be incorporated in the course?',
13076:                cont => 'Content actions for all',
13077:                addf => 'Add as folder/file',
13078:                incd => 'Include as dependency for a displayed file',
13079:                disc => 'Discard',
13080:                no   => 'No',
13081:                yes  => 'Yes',
13082:                save => 'Save',
13083:     );
13084:     my $output = <<"END";
13085: <form name="$form" method="post" action="">
13086: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
13087: <label>
13088:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
13089: </label>
13090: &nbsp;
13091: <label>
13092:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
13093: </span>
13094: </p>
13095: <input type="hidden" name="phase" value="decompress_cleanup" />
13096: <br />$lt{'hows'}
13097: <div class="LC_columnSection">
13098:   <fieldset>
13099:     <legend>$lt{'cont'}</legend>
13100:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
13101:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
13102:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
13103:   </fieldset>
13104: </div>
13105: END
13106:     return $output.
13107:            &start_data_table()."\n".
13108:            $display."\n".
13109:            &end_data_table()."\n".
13110:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
13111:            $hiddenelem.
13112:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
13113:            '</form>';
13114: }
13115: 
13116: sub archive_javascript {
13117:     my ($startcount,$numitems,$titles,$children) = @_;
13118:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
13119:     my $maintitle = $env{'form.comment'};
13120:     my $scripttag = <<START;
13121: <script type="text/javascript">
13122: // <![CDATA[
13123: 
13124: function checkAll(form,prefix) {
13125:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
13126:     for (var i=0; i < form.elements.length; i++) {
13127:         var id = form.elements[i].id;
13128:         if ((id != '') && (id != undefined)) {
13129:             if (idstr.test(id)) {
13130:                 if (form.elements[i].type == 'radio') {
13131:                     form.elements[i].checked = true;
13132:                     var nostart = i-$startcount;
13133:                     var offset = nostart%7;
13134:                     var count = (nostart-offset)/7;    
13135:                     dependencyCheck(form,count,offset);
13136:                 }
13137:             }
13138:         }
13139:     }
13140: }
13141: 
13142: function propagateCheck(form,count) {
13143:     if (count > 0) {
13144:         var startelement = $startcount + ((count-1) * 7);
13145:         for (var j=1; j<6; j++) {
13146:             if ((j != 2) && (j != 4)) {
13147:                 var item = startelement + j; 
13148:                 if (form.elements[item].type == 'radio') {
13149:                     if (form.elements[item].checked) {
13150:                         containerCheck(form,count,j);
13151:                         break;
13152:                     }
13153:                 }
13154:             }
13155:         }
13156:     }
13157: }
13158: 
13159: numitems = $numitems
13160: var titles = new Array(numitems);
13161: var parents = new Array(numitems);
13162: for (var i=0; i<numitems; i++) {
13163:     parents[i] = new Array;
13164: }
13165: var maintitle = '$maintitle';
13166: 
13167: START
13168: 
13169:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
13170:         my @contents = split(/:/,$children->{$container});
13171:         for (my $i=0; $i<@contents; $i ++) {
13172:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
13173:         }
13174:     }
13175: 
13176:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
13177:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
13178:     }
13179: 
13180:     $scripttag .= <<END;
13181: 
13182: function containerCheck(form,count,offset) {
13183:     if (count > 0) {
13184:         dependencyCheck(form,count,offset);
13185:         var item = (offset+$startcount)+7*(count-1);
13186:         form.elements[item].checked = true;
13187:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
13188:             if (parents[count].length > 0) {
13189:                 for (var j=0; j<parents[count].length; j++) {
13190:                     containerCheck(form,parents[count][j],offset);
13191:                 }
13192:             }
13193:         }
13194:     }
13195: }
13196: 
13197: function dependencyCheck(form,count,offset) {
13198:     if (count > 0) {
13199:         var chosen = (offset+$startcount)+7*(count-1);
13200:         var depitem = $startcount + ((count-1) * 7) + 4;
13201:         var currtype = form.elements[depitem].type;
13202:         if (form.elements[chosen].value == 'dependency') {
13203:             document.getElementById('arc_depon_'+count).style.display='block'; 
13204:             form.elements[depitem].options.length = 0;
13205:             form.elements[depitem].options[0] = new Option('Select','',true,true);
13206:             for (var i=1; i<=numitems; i++) {
13207:                 if (i == count) {
13208:                     continue;
13209:                 }
13210:                 var startelement = $startcount + (i-1) * 7;
13211:                 for (var j=1; j<6; j++) {
13212:                     if ((j != 2) && (j!= 4)) {
13213:                         var item = startelement + j;
13214:                         if (form.elements[item].type == 'radio') {
13215:                             if (form.elements[item].checked) {
13216:                                 if (form.elements[item].value == 'display') {
13217:                                     var n = form.elements[depitem].options.length;
13218:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
13219:                                 }
13220:                             }
13221:                         }
13222:                     }
13223:                 }
13224:             }
13225:         } else {
13226:             document.getElementById('arc_depon_'+count).style.display='none';
13227:             form.elements[depitem].options.length = 0;
13228:             form.elements[depitem].options[0] = new Option('Select','',true,true);
13229:         }
13230:         titleCheck(form,count,offset);
13231:     }
13232: }
13233: 
13234: function propagateSelect(form,count,offset) {
13235:     if (count > 0) {
13236:         var item = (1+offset+$startcount)+7*(count-1);
13237:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
13238:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
13239:             if (parents[count].length > 0) {
13240:                 for (var j=0; j<parents[count].length; j++) {
13241:                     containerSelect(form,parents[count][j],offset,picked);
13242:                 }
13243:             }
13244:         }
13245:     }
13246: }
13247: 
13248: function containerSelect(form,count,offset,picked) {
13249:     if (count > 0) {
13250:         var item = (offset+$startcount)+7*(count-1);
13251:         if (form.elements[item].type == 'radio') {
13252:             if (form.elements[item].value == 'dependency') {
13253:                 if (form.elements[item+1].type == 'select-one') {
13254:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
13255:                         if (form.elements[item+1].options[i].value == picked) {
13256:                             form.elements[item+1].selectedIndex = i;
13257:                             break;
13258:                         }
13259:                     }
13260:                 }
13261:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
13262:                     if (parents[count].length > 0) {
13263:                         for (var j=0; j<parents[count].length; j++) {
13264:                             containerSelect(form,parents[count][j],offset,picked);
13265:                         }
13266:                     }
13267:                 }
13268:             }
13269:         }
13270:     }
13271: }
13272: 
13273: function titleCheck(form,count,offset) {
13274:     if (count > 0) {
13275:         var chosen = (offset+$startcount)+7*(count-1);
13276:         var depitem = $startcount + ((count-1) * 7) + 2;
13277:         var currtype = form.elements[depitem].type;
13278:         if (form.elements[chosen].value == 'display') {
13279:             document.getElementById('arc_title_'+count).style.display='block';
13280:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
13281:                 document.getElementById('archive_title_'+count).value=maintitle;
13282:             }
13283:         } else {
13284:             document.getElementById('arc_title_'+count).style.display='none';
13285:             if (currtype == 'text') { 
13286:                 document.getElementById('archive_title_'+count).value='';
13287:             }
13288:         }
13289:     }
13290:     return;
13291: }
13292: 
13293: // ]]>
13294: </script>
13295: END
13296:     return $scripttag;
13297: }
13298: 
13299: sub process_extracted_files {
13300:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
13301:     my $numitems = $env{'form.archive_count'};
13302:     return if ((!$numitems) || ($numitems =~ /\D/));
13303:     my @ids=&Apache::lonnet::current_machine_ids();
13304:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
13305:         %folders,%containers,%mapinner,%prompttofetch);
13306:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
13307:     if (grep(/^\Q$docuhome\E$/,@ids)) {
13308:         $prefix = &LONCAPA::propath($docudom,$docuname);
13309:         $pathtocheck = "$dir_root/$destination";
13310:         $dir = $dir_root;
13311:         $ishome = 1;
13312:     } else {
13313:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
13314:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
13315:         $dir = "$dir_root/$docudom/$docuname";
13316:     }
13317:     my $currdir = "$dir_root/$destination";
13318:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
13319:     if ($env{'form.folderpath'}) {
13320:         my @items = split('&',$env{'form.folderpath'});
13321:         $folders{'0'} = $items[-2];
13322:         if ($env{'form.folderpath'} =~ /\:1$/) {
13323:             $containers{'0'}='page';
13324:         } else {
13325:             $containers{'0'}='sequence';
13326:         }
13327:     }
13328:     my @archdirs = &get_env_multiple('form.archive_directory');
13329:     if ($numitems) {
13330:         for (my $i=1; $i<=$numitems; $i++) {
13331:             my $path = $env{'form.archive_content_'.$i};
13332:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
13333:                 my $item = $1;
13334:                 $toplevelitems{$item} = $i;
13335:                 if (grep(/^\Q$i\E$/,@archdirs)) {
13336:                     $is_dir{$item} = 1;
13337:                 }
13338:             }
13339:         }
13340:     }
13341:     my ($output,%children,%parent,%titles,%dirorder,$result);
13342:     if (keys(%toplevelitems) > 0) {
13343:         my @contents = sort(keys(%toplevelitems));
13344:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
13345:                                            \%parent,\@contents,\%dirorder,\%titles);
13346:     }
13347:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
13348:     if ($numitems) {
13349:         for (my $i=1; $i<=$numitems; $i++) {
13350:             next if ($env{'form.archive_'.$i} eq 'dependency');
13351:             my $path = $env{'form.archive_content_'.$i};
13352:             if ($path =~ /^\Q$pathtocheck\E/) {
13353:                 if ($env{'form.archive_'.$i} eq 'discard') {
13354:                     if ($prefix ne '' && $path ne '') {
13355:                         if (-e $prefix.$path) {
13356:                             if ((@archdirs > 0) && 
13357:                                 (grep(/^\Q$i\E$/,@archdirs))) {
13358:                                 $todeletedir{$prefix.$path} = 1;
13359:                             } else {
13360:                                 $todelete{$prefix.$path} = 1;
13361:                             }
13362:                         }
13363:                     }
13364:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
13365:                     my ($docstitle,$title,$url,$outer);
13366:                     ($title) = ($path =~ m{/([^/]+)$});
13367:                     $docstitle = $env{'form.archive_title_'.$i};
13368:                     if ($docstitle eq '') {
13369:                         $docstitle = $title;
13370:                     }
13371:                     $outer = 0;
13372:                     if (ref($dirorder{$i}) eq 'ARRAY') {
13373:                         if (@{$dirorder{$i}} > 0) {
13374:                             foreach my $item (reverse(@{$dirorder{$i}})) {
13375:                                 if ($env{'form.archive_'.$item} eq 'display') {
13376:                                     $outer = $item;
13377:                                     last;
13378:                                 }
13379:                             }
13380:                         }
13381:                     }
13382:                     my ($errtext,$fatal) = 
13383:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
13384:                                                '/'.$folders{$outer}.'.'.
13385:                                                $containers{$outer});
13386:                     next if ($fatal);
13387:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
13388:                         if ($context eq 'coursedocs') {
13389:                             $mapinner{$i} = time;
13390:                             $folders{$i} = 'default_'.$mapinner{$i};
13391:                             $containers{$i} = 'sequence';
13392:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
13393:                                       $folders{$i}.'.'.$containers{$i};
13394:                             my $newidx = &LONCAPA::map::getresidx();
13395:                             $LONCAPA::map::resources[$newidx]=
13396:                                 $docstitle.':'.$url.':false:normal:res';
13397:                             push(@LONCAPA::map::order,$newidx);
13398:                             my ($outtext,$errtext) =
13399:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
13400:                                                         $docuname.'/'.$folders{$outer}.
13401:                                                         '.'.$containers{$outer},1,1);
13402:                             $newseqid{$i} = $newidx;
13403:                             unless ($errtext) {
13404:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
13405:                                                        &HTML::Entities::encode($docstitle,'<>&"'))..
13406:                                             '</li>'."\n";
13407:                             }
13408:                         }
13409:                     } else {
13410:                         if ($context eq 'coursedocs') {
13411:                             my $newidx=&LONCAPA::map::getresidx();
13412:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
13413:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
13414:                                       $title;
13415:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
13416:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
13417:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
13418:                                 }
13419:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
13420:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
13421:                                 }
13422:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
13423:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
13424:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
13425:                                         unless ($ishome) {
13426:                                             my $fetch = "$newdest{$i}/$title";
13427:                                             $fetch =~ s/^\Q$prefix$dir\E//;
13428:                                             $prompttofetch{$fetch} = 1;
13429:                                         }
13430:                                    }
13431:                                 }
13432:                                 $LONCAPA::map::resources[$newidx]=
13433:                                     $docstitle.':'.$url.':false:normal:res';
13434:                                 push(@LONCAPA::map::order, $newidx);
13435:                                 my ($outtext,$errtext)=
13436:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
13437:                                                             $docuname.'/'.$folders{$outer}.
13438:                                                             '.'.$containers{$outer},1,1);
13439:                                 unless ($errtext) {
13440:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
13441:                                         $result .= '<li>'.&mt('File: [_1] added to course',
13442:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
13443:                                                    '</li>'."\n";
13444:                                     }
13445:                                 }
13446:                             } else {
13447:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13448:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
13449:                             }
13450:                         }
13451:                     }
13452:                 }
13453:             } else {
13454:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13455:                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
13456:             }
13457:         }
13458:         for (my $i=1; $i<=$numitems; $i++) {
13459:             next unless ($env{'form.archive_'.$i} eq 'dependency');
13460:             my $path = $env{'form.archive_content_'.$i};
13461:             if ($path =~ /^\Q$pathtocheck\E/) {
13462:                 my ($title) = ($path =~ m{/([^/]+)$});
13463:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
13464:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
13465:                     if (ref($dirorder{$i}) eq 'ARRAY') {
13466:                         my ($itemidx,$fullpath,$relpath);
13467:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
13468:                             my $container = $dirorder{$referrer{$i}}->[-1];
13469:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
13470:                                 if ($dirorder{$i}->[$j] eq $container) {
13471:                                     $itemidx = $j;
13472:                                 }
13473:                             }
13474:                         }
13475:                         if ($itemidx eq '') {
13476:                             $itemidx =  0;
13477:                         }
13478:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
13479:                             if ($mapinner{$referrer{$i}}) {
13480:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
13481:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
13482:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
13483:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
13484:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
13485:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
13486:                                             if (!-e $fullpath) {
13487:                                                 mkdir($fullpath,0755);
13488:                                             }
13489:                                         }
13490:                                     } else {
13491:                                         last;
13492:                                     }
13493:                                 }
13494:                             }
13495:                         } elsif ($newdest{$referrer{$i}}) {
13496:                             $fullpath = $newdest{$referrer{$i}};
13497:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
13498:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
13499:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
13500:                                     last;
13501:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
13502:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
13503:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
13504:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
13505:                                         if (!-e $fullpath) {
13506:                                             mkdir($fullpath,0755);
13507:                                         }
13508:                                     }
13509:                                 } else {
13510:                                     last;
13511:                                 }
13512:                             }
13513:                         }
13514:                         if ($fullpath ne '') {
13515:                             if (-e "$prefix$path") {
13516:                                 unless (rename("$prefix$path","$fullpath/$title")) {
13517:                                      $warning .= &mt('Failed to rename dependency').'<br />';
13518:                                 }
13519:                             }
13520:                             if (-e "$fullpath/$title") {
13521:                                 my $showpath;
13522:                                 if ($relpath ne '') {
13523:                                     $showpath = "$relpath/$title";
13524:                                 } else {
13525:                                     $showpath = "/$title";
13526:                                 }
13527:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
13528:                                                       &HTML::Entities::encode($showpath,'<>&"')).
13529:                                            '</li>'."\n";
13530:                                 unless ($ishome) {
13531:                                     my $fetch = "$fullpath/$title";
13532:                                     $fetch =~ s/^\Q$prefix$dir\E//;
13533:                                     $prompttofetch{$fetch} = 1;
13534:                                 }
13535:                             }
13536:                         }
13537:                     }
13538:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
13539:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
13540:                                     &HTML::Entities::encode($path,'<>&"'),
13541:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
13542:                                 '<br />';
13543:                 }
13544:             } else {
13545:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13546:                                 &HTML::Entities::encode($path)).'<br />';
13547:             }
13548:         }
13549:         if (keys(%todelete)) {
13550:             foreach my $key (keys(%todelete)) {
13551:                 unlink($key);
13552:             }
13553:         }
13554:         if (keys(%todeletedir)) {
13555:             foreach my $key (keys(%todeletedir)) {
13556:                 rmdir($key);
13557:             }
13558:         }
13559:         foreach my $dir (sort(keys(%is_dir))) {
13560:             if (($pathtocheck ne '') && ($dir ne ''))  {
13561:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
13562:             }
13563:         }
13564:         if ($result ne '') {
13565:             $output .= '<ul>'."\n".
13566:                        $result."\n".
13567:                        '</ul>';
13568:         }
13569:         unless ($ishome) {
13570:             my $replicationfail;
13571:             foreach my $item (keys(%prompttofetch)) {
13572:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
13573:                 unless ($fetchresult eq 'ok') {
13574:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
13575:                 }
13576:             }
13577:             if ($replicationfail) {
13578:                 $output .= '<p class="LC_error">'.
13579:                            &mt('Course home server failed to retrieve:').'<ul>'.
13580:                            $replicationfail.
13581:                            '</ul></p>';
13582:             }
13583:         }
13584:     } else {
13585:         $warning = &mt('No items found in archive.');
13586:     }
13587:     if ($error) {
13588:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13589:                    $error.'</p>'."\n";
13590:     }
13591:     if ($warning) {
13592:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
13593:     }
13594:     return $output;
13595: }
13596: 
13597: sub cleanup_empty_dirs {
13598:     my ($path) = @_;
13599:     if (($path ne '') && (-d $path)) {
13600:         if (opendir(my $dirh,$path)) {
13601:             my @dircontents = grep(!/^\./,readdir($dirh));
13602:             my $numitems = 0;
13603:             foreach my $item (@dircontents) {
13604:                 if (-d "$path/$item") {
13605:                     &cleanup_empty_dirs("$path/$item");
13606:                     if (-e "$path/$item") {
13607:                         $numitems ++;
13608:                     }
13609:                 } else {
13610:                     $numitems ++;
13611:                 }
13612:             }
13613:             if ($numitems == 0) {
13614:                 rmdir($path);
13615:             }
13616:             closedir($dirh);
13617:         }
13618:     }
13619:     return;
13620: }
13621: 
13622: =pod
13623: 
13624: =item * &get_folder_hierarchy()
13625: 
13626: Provides hierarchy of names of folders/sub-folders containing the current
13627: item,
13628: 
13629: Inputs: 3
13630:      - $navmap - navmaps object
13631: 
13632:      - $map - url for map (either the trigger itself, or map containing
13633:                            the resource, which is the trigger).
13634: 
13635:      - $showitem - 1 => show title for map itself; 0 => do not show.
13636: 
13637: Outputs: 1 @pathitems - array of folder/subfolder names.
13638: 
13639: =cut
13640: 
13641: sub get_folder_hierarchy {
13642:     my ($navmap,$map,$showitem) = @_;
13643:     my @pathitems;
13644:     if (ref($navmap)) {
13645:         my $mapres = $navmap->getResourceByUrl($map);
13646:         if (ref($mapres)) {
13647:             my $pcslist = $mapres->map_hierarchy();
13648:             if ($pcslist ne '') {
13649:                 my @pcs = split(/,/,$pcslist);
13650:                 foreach my $pc (@pcs) {
13651:                     if ($pc == 1) {
13652:                         push(@pathitems,&mt('Main Content'));
13653:                     } else {
13654:                         my $res = $navmap->getByMapPc($pc);
13655:                         if (ref($res)) {
13656:                             my $title = $res->compTitle();
13657:                             $title =~ s/\W+/_/g;
13658:                             if ($title ne '') {
13659:                                 push(@pathitems,$title);
13660:                             }
13661:                         }
13662:                     }
13663:                 }
13664:             }
13665:             if ($showitem) {
13666:                 if ($mapres->{ID} eq '0.0') {
13667:                     push(@pathitems,&mt('Main Content'));
13668:                 } else {
13669:                     my $maptitle = $mapres->compTitle();
13670:                     $maptitle =~ s/\W+/_/g;
13671:                     if ($maptitle ne '') {
13672:                         push(@pathitems,$maptitle);
13673:                     }
13674:                 }
13675:             }
13676:         }
13677:     }
13678:     return @pathitems;
13679: }
13680: 
13681: =pod
13682: 
13683: =item * &get_turnedin_filepath()
13684: 
13685: Determines path in a user's portfolio file for storage of files uploaded
13686: to a specific essayresponse or dropbox item.
13687: 
13688: Inputs: 3 required + 1 optional.
13689: $symb is symb for resource, $uname and $udom are for current user (required).
13690: $caller is optional (can be "submission", if routine is called when storing
13691: an upoaded file when "Submit Answer" button was pressed).
13692: 
13693: Returns array containing $path and $multiresp. 
13694: $path is path in portfolio.  $multiresp is 1 if this resource contains more
13695: than one file upload item.  Callers of routine should append partid as a 
13696: subdirectory to $path in cases where $multiresp is 1.
13697: 
13698: Called by: homework/essayresponse.pm and homework/structuretags.pm
13699: 
13700: =cut
13701: 
13702: sub get_turnedin_filepath {
13703:     my ($symb,$uname,$udom,$caller) = @_;
13704:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
13705:     my $turnindir;
13706:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
13707:     $turnindir = $userhash{'turnindir'};
13708:     my ($path,$multiresp);
13709:     if ($turnindir eq '') {
13710:         if ($caller eq 'submission') {
13711:             $turnindir = &mt('turned in');
13712:             $turnindir =~ s/\W+/_/g;
13713:             my %newhash = (
13714:                             'turnindir' => $turnindir,
13715:                           );
13716:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
13717:         }
13718:     }
13719:     if ($turnindir ne '') {
13720:         $path = '/'.$turnindir.'/';
13721:         my ($multipart,$turnin,@pathitems);
13722:         my $navmap = Apache::lonnavmaps::navmap->new();
13723:         if (defined($navmap)) {
13724:             my $mapres = $navmap->getResourceByUrl($map);
13725:             if (ref($mapres)) {
13726:                 my $pcslist = $mapres->map_hierarchy();
13727:                 if ($pcslist ne '') {
13728:                     foreach my $pc (split(/,/,$pcslist)) {
13729:                         my $res = $navmap->getByMapPc($pc);
13730:                         if (ref($res)) {
13731:                             my $title = $res->compTitle();
13732:                             $title =~ s/\W+/_/g;
13733:                             if ($title ne '') {
13734:                                 if (($pc > 1) && (length($title) > 12)) {
13735:                                     $title = substr($title,0,12);
13736:                                 }
13737:                                 push(@pathitems,$title);
13738:                             }
13739:                         }
13740:                     }
13741:                 }
13742:                 my $maptitle = $mapres->compTitle();
13743:                 $maptitle =~ s/\W+/_/g;
13744:                 if ($maptitle ne '') {
13745:                     if (length($maptitle) > 12) {
13746:                         $maptitle = substr($maptitle,0,12);
13747:                     }
13748:                     push(@pathitems,$maptitle);
13749:                 }
13750:                 unless ($env{'request.state'} eq 'construct') {
13751:                     my $res = $navmap->getBySymb($symb);
13752:                     if (ref($res)) {
13753:                         my $partlist = $res->parts();
13754:                         my $totaluploads = 0;
13755:                         if (ref($partlist) eq 'ARRAY') {
13756:                             foreach my $part (@{$partlist}) {
13757:                                 my @types = $res->responseType($part);
13758:                                 my @ids = $res->responseIds($part);
13759:                                 for (my $i=0; $i < scalar(@ids); $i++) {
13760:                                     if ($types[$i] eq 'essay') {
13761:                                         my $partid = $part.'_'.$ids[$i];
13762:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
13763:                                             $totaluploads ++;
13764:                                         }
13765:                                     }
13766:                                 }
13767:                             }
13768:                             if ($totaluploads > 1) {
13769:                                 $multiresp = 1;
13770:                             }
13771:                         }
13772:                     }
13773:                 }
13774:             } else {
13775:                 return;
13776:             }
13777:         } else {
13778:             return;
13779:         }
13780:         my $restitle=&Apache::lonnet::gettitle($symb);
13781:         $restitle =~ s/\W+/_/g;
13782:         if ($restitle eq '') {
13783:             $restitle = ($resurl =~ m{/[^/]+$});
13784:             if ($restitle eq '') {
13785:                 $restitle = time;
13786:             }
13787:         }
13788:         if (length($restitle) > 12) {
13789:             $restitle = substr($restitle,0,12);
13790:         }
13791:         push(@pathitems,$restitle);
13792:         $path .= join('/',@pathitems);
13793:     }
13794:     return ($path,$multiresp);
13795: }
13796: 
13797: =pod
13798: 
13799: =back
13800: 
13801: =head1 CSV Upload/Handling functions
13802: 
13803: =over 4
13804: 
13805: =item * &upfile_store($r)
13806: 
13807: Store uploaded file, $r should be the HTTP Request object,
13808: needs $env{'form.upfile'}
13809: returns $datatoken to be put into hidden field
13810: 
13811: =cut
13812: 
13813: sub upfile_store {
13814:     my $r=shift;
13815:     $env{'form.upfile'}=~s/\r/\n/gs;
13816:     $env{'form.upfile'}=~s/\f/\n/gs;
13817:     $env{'form.upfile'}=~s/\n+/\n/gs;
13818:     $env{'form.upfile'}=~s/\n+$//gs;
13819: 
13820:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
13821:                                      '_enroll_'.$env{'request.course.id'}.'_'.
13822:                                      time.'_'.$$);
13823:     return if ($datatoken eq '');
13824: 
13825:     {
13826:         my $datafile = $r->dir_config('lonDaemons').
13827:                            '/tmp/'.$datatoken.'.tmp';
13828:         if ( open(my $fh,'>',$datafile) ) {
13829:             print $fh $env{'form.upfile'};
13830:             close($fh);
13831:         }
13832:     }
13833:     return $datatoken;
13834: }
13835: 
13836: =pod
13837: 
13838: =item * &load_tmp_file($r,$datatoken)
13839: 
13840: Load uploaded file from tmp, $r should be the HTTP Request object,
13841: $datatoken is the name to assign to the temporary file.
13842: sets $env{'form.upfile'} to the contents of the file
13843: 
13844: =cut
13845: 
13846: sub load_tmp_file {
13847:     my ($r,$datatoken) = @_;
13848:     return if ($datatoken eq '');
13849:     my @studentdata=();
13850:     {
13851:         my $studentfile = $r->dir_config('lonDaemons').
13852:                               '/tmp/'.$datatoken.'.tmp';
13853:         if ( open(my $fh,'<',$studentfile) ) {
13854:             @studentdata=<$fh>;
13855:             close($fh);
13856:         }
13857:     }
13858:     $env{'form.upfile'}=join('',@studentdata);
13859: }
13860: 
13861: sub valid_datatoken {
13862:     my ($datatoken) = @_;
13863:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
13864:         return $datatoken;
13865:     }
13866:     return;
13867: }
13868: 
13869: =pod
13870: 
13871: =item * &upfile_record_sep()
13872: 
13873: Separate uploaded file into records
13874: returns array of records,
13875: needs $env{'form.upfile'} and $env{'form.upfiletype'}
13876: 
13877: =cut
13878: 
13879: sub upfile_record_sep {
13880:     if ($env{'form.upfiletype'} eq 'xml') {
13881:     } else {
13882: 	my @records;
13883: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
13884: 	    if ($line=~/^\s*$/) { next; }
13885: 	    push(@records,$line);
13886: 	}
13887: 	return @records;
13888:     }
13889: }
13890: 
13891: =pod
13892: 
13893: =item * &record_sep($record)
13894: 
13895: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
13896: 
13897: =cut
13898: 
13899: sub takeleft {
13900:     my $index=shift;
13901:     return substr('0000'.$index,-4,4);
13902: }
13903: 
13904: sub record_sep {
13905:     my $record=shift;
13906:     my %components=();
13907:     if ($env{'form.upfiletype'} eq 'xml') {
13908:     } elsif ($env{'form.upfiletype'} eq 'space') {
13909:         my $i=0;
13910:         foreach my $field (split(/\s+/,$record)) {
13911:             $field=~s/^(\"|\')//;
13912:             $field=~s/(\"|\')$//;
13913:             $components{&takeleft($i)}=$field;
13914:             $i++;
13915:         }
13916:     } elsif ($env{'form.upfiletype'} eq 'tab') {
13917:         my $i=0;
13918:         foreach my $field (split(/\t/,$record)) {
13919:             $field=~s/^(\"|\')//;
13920:             $field=~s/(\"|\')$//;
13921:             $components{&takeleft($i)}=$field;
13922:             $i++;
13923:         }
13924:     } else {
13925:         my $separator=',';
13926:         if ($env{'form.upfiletype'} eq 'semisv') {
13927:             $separator=';';
13928:         }
13929:         my $i=0;
13930: # the character we are looking for to indicate the end of a quote or a record 
13931:         my $looking_for=$separator;
13932: # do not add the characters to the fields
13933:         my $ignore=0;
13934: # we just encountered a separator (or the beginning of the record)
13935:         my $just_found_separator=1;
13936: # store the field we are working on here
13937:         my $field='';
13938: # work our way through all characters in record
13939:         foreach my $character ($record=~/(.)/g) {
13940:             if ($character eq $looking_for) {
13941:                if ($character ne $separator) {
13942: # Found the end of a quote, again looking for separator
13943:                   $looking_for=$separator;
13944:                   $ignore=1;
13945:                } else {
13946: # Found a separator, store away what we got
13947:                   $components{&takeleft($i)}=$field;
13948: 	          $i++;
13949:                   $just_found_separator=1;
13950:                   $ignore=0;
13951:                   $field='';
13952:                }
13953:                next;
13954:             }
13955: # single or double quotation marks after a separator indicate beginning of a quote
13956: # we are now looking for the end of the quote and need to ignore separators
13957:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
13958:                $looking_for=$character;
13959:                next;
13960:             }
13961: # ignore would be true after we reached the end of a quote
13962:             if ($ignore) { next; }
13963:             if (($just_found_separator) && ($character=~/\s/)) { next; }
13964:             $field.=$character;
13965:             $just_found_separator=0; 
13966:         }
13967: # catch the very last entry, since we never encountered the separator
13968:         $components{&takeleft($i)}=$field;
13969:     }
13970:     return %components;
13971: }
13972: 
13973: ######################################################
13974: ######################################################
13975: 
13976: =pod
13977: 
13978: =item * &upfile_select_html()
13979: 
13980: Return HTML code to select a file from the users machine and specify 
13981: the file type.
13982: 
13983: =cut
13984: 
13985: ######################################################
13986: ######################################################
13987: sub upfile_select_html {
13988:     my %Types = (
13989:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
13990:                  semisv => &mt('Semicolon separated values'),
13991:                  space => &mt('Space separated'),
13992:                  tab   => &mt('Tabulator separated'),
13993: #                 xml   => &mt('HTML/XML'),
13994:                  );
13995:     my $Str = '<input type="file" name="upfile" size="50" />'.
13996:         '<br />'.&mt('Type').': <select name="upfiletype">';
13997:     foreach my $type (sort(keys(%Types))) {
13998:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
13999:     }
14000:     $Str .= "</select>\n";
14001:     return $Str;
14002: }
14003: 
14004: sub get_samples {
14005:     my ($records,$toget) = @_;
14006:     my @samples=({});
14007:     my $got=0;
14008:     foreach my $rec (@$records) {
14009: 	my %temp = &record_sep($rec);
14010: 	if (! grep(/\S/, values(%temp))) { next; }
14011: 	if (%temp) {
14012: 	    $samples[$got]=\%temp;
14013: 	    $got++;
14014: 	    if ($got == $toget) { last; }
14015: 	}
14016:     }
14017:     return \@samples;
14018: }
14019: 
14020: ######################################################
14021: ######################################################
14022: 
14023: =pod
14024: 
14025: =item * &csv_print_samples($r,$records)
14026: 
14027: Prints a table of sample values from each column uploaded $r is an
14028: Apache Request ref, $records is an arrayref from
14029: &Apache::loncommon::upfile_record_sep
14030: 
14031: =cut
14032: 
14033: ######################################################
14034: ######################################################
14035: sub csv_print_samples {
14036:     my ($r,$records) = @_;
14037:     my $samples = &get_samples($records,5);
14038: 
14039:     $r->print(&mt('Samples').'<br />'.&start_data_table().
14040:               &start_data_table_header_row());
14041:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
14042:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
14043:     $r->print(&end_data_table_header_row());
14044:     foreach my $hash (@$samples) {
14045: 	$r->print(&start_data_table_row());
14046: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
14047: 	    $r->print('<td>');
14048: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
14049: 	    $r->print('</td>');
14050: 	}
14051: 	$r->print(&end_data_table_row());
14052:     }
14053:     $r->print(&end_data_table().'<br />'."\n");
14054: }
14055: 
14056: ######################################################
14057: ######################################################
14058: 
14059: =pod
14060: 
14061: =item * &csv_print_select_table($r,$records,$d)
14062: 
14063: Prints a table to create associations between values and table columns.
14064: 
14065: $r is an Apache Request ref,
14066: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
14067: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
14068: 
14069: =cut
14070: 
14071: ######################################################
14072: ######################################################
14073: sub csv_print_select_table {
14074:     my ($r,$records,$d) = @_;
14075:     my $i=0;
14076:     my $samples = &get_samples($records,1);
14077:     $r->print(&mt('Associate columns with student attributes.')."\n".
14078: 	      &start_data_table().&start_data_table_header_row().
14079:               '<th>'.&mt('Attribute').'</th>'.
14080:               '<th>'.&mt('Column').'</th>'.
14081:               &end_data_table_header_row()."\n");
14082:     foreach my $array_ref (@$d) {
14083: 	my ($value,$display,$defaultcol)=@{ $array_ref };
14084: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
14085: 
14086: 	$r->print('<td><select name="f'.$i.'"'.
14087: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
14088: 	$r->print('<option value="none"></option>');
14089: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
14090: 	    $r->print('<option value="'.$sample.'"'.
14091:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
14092:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
14093: 	}
14094: 	$r->print('</select></td>'.&end_data_table_row()."\n");
14095: 	$i++;
14096:     }
14097:     $r->print(&end_data_table());
14098:     $i--;
14099:     return $i;
14100: }
14101: 
14102: ######################################################
14103: ######################################################
14104: 
14105: =pod
14106: 
14107: =item * &csv_samples_select_table($r,$records,$d)
14108: 
14109: Prints a table of sample values from the upload and can make associate samples to internal names.
14110: 
14111: $r is an Apache Request ref,
14112: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
14113: $d is an array of 2 element arrays (internal name, displayed name)
14114: 
14115: =cut
14116: 
14117: ######################################################
14118: ######################################################
14119: sub csv_samples_select_table {
14120:     my ($r,$records,$d) = @_;
14121:     my $i=0;
14122:     #
14123:     my $max_samples = 5;
14124:     my $samples = &get_samples($records,$max_samples);
14125:     $r->print(&start_data_table().
14126:               &start_data_table_header_row().'<th>'.
14127:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
14128:               &end_data_table_header_row());
14129: 
14130:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
14131: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
14132: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
14133: 	foreach my $option (@$d) {
14134: 	    my ($value,$display,$defaultcol)=@{ $option };
14135: 	    $r->print('<option value="'.$value.'"'.
14136:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
14137:                       $display.'</option>');
14138: 	}
14139: 	$r->print('</select></td><td>');
14140: 	foreach my $line (0..($max_samples-1)) {
14141: 	    if (defined($samples->[$line]{$key})) { 
14142: 		$r->print($samples->[$line]{$key}."<br />\n"); 
14143: 	    }
14144: 	}
14145: 	$r->print('</td>'.&end_data_table_row());
14146: 	$i++;
14147:     }
14148:     $r->print(&end_data_table());
14149:     $i--;
14150:     return($i);
14151: }
14152: 
14153: ######################################################
14154: ######################################################
14155: 
14156: =pod
14157: 
14158: =item * &clean_excel_name($name)
14159: 
14160: Returns a replacement for $name which does not contain any illegal characters.
14161: 
14162: =cut
14163: 
14164: ######################################################
14165: ######################################################
14166: sub clean_excel_name {
14167:     my ($name) = @_;
14168:     $name =~ s/[:\*\?\/\\]//g;
14169:     if (length($name) > 31) {
14170:         $name = substr($name,0,31);
14171:     }
14172:     return $name;
14173: }
14174: 
14175: =pod
14176: 
14177: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
14178: 
14179: Returns either 1 or undef
14180: 
14181: 1 if the part is to be hidden, undef if it is to be shown
14182: 
14183: Arguments are:
14184: 
14185: $id the id of the part to be checked
14186: $symb, optional the symb of the resource to check
14187: $udom, optional the domain of the user to check for
14188: $uname, optional the username of the user to check for
14189: 
14190: =cut
14191: 
14192: sub check_if_partid_hidden {
14193:     my ($id,$symb,$udom,$uname) = @_;
14194:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
14195: 					 $symb,$udom,$uname);
14196:     my $truth=1;
14197:     #if the string starts with !, then the list is the list to show not hide
14198:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
14199:     my @hiddenlist=split(/,/,$hiddenparts);
14200:     foreach my $checkid (@hiddenlist) {
14201: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
14202:     }
14203:     return !$truth;
14204: }
14205: 
14206: 
14207: ############################################################
14208: ############################################################
14209: 
14210: =pod
14211: 
14212: =back 
14213: 
14214: =head1 cgi-bin script and graphing routines
14215: 
14216: =over 4
14217: 
14218: =item * &get_cgi_id()
14219: 
14220: Inputs: none
14221: 
14222: Returns an id which can be used to pass environment variables
14223: to various cgi-bin scripts.  These environment variables will
14224: be removed from the users environment after a given time by
14225: the routine &Apache::lonnet::transfer_profile_to_env.
14226: 
14227: =cut
14228: 
14229: ############################################################
14230: ############################################################
14231: my $uniq=0;
14232: sub get_cgi_id {
14233:     $uniq=($uniq+1)%100000;
14234:     return (time.'_'.$$.'_'.$uniq);
14235: }
14236: 
14237: ############################################################
14238: ############################################################
14239: 
14240: =pod
14241: 
14242: =item * &DrawBarGraph()
14243: 
14244: Facilitates the plotting of data in a (stacked) bar graph.
14245: Puts plot definition data into the users environment in order for 
14246: graph.png to plot it.  Returns an <img> tag for the plot.
14247: The bars on the plot are labeled '1','2',...,'n'.
14248: 
14249: Inputs:
14250: 
14251: =over 4
14252: 
14253: =item $Title: string, the title of the plot
14254: 
14255: =item $xlabel: string, text describing the X-axis of the plot
14256: 
14257: =item $ylabel: string, text describing the Y-axis of the plot
14258: 
14259: =item $Max: scalar, the maximum Y value to use in the plot
14260: If $Max is < any data point, the graph will not be rendered.
14261: 
14262: =item $colors: array ref holding the colors to be used for the data sets when
14263: they are plotted.  If undefined, default values will be used.
14264: 
14265: =item $labels: array ref holding the labels to use on the x-axis for the bars.
14266: 
14267: =item @Values: An array of array references.  Each array reference holds data
14268: to be plotted in a stacked bar chart.
14269: 
14270: =item If the final element of @Values is a hash reference the key/value
14271: pairs will be added to the graph definition.
14272: 
14273: =back
14274: 
14275: Returns:
14276: 
14277: An <img> tag which references graph.png and the appropriate identifying
14278: information for the plot.
14279: 
14280: =cut
14281: 
14282: ############################################################
14283: ############################################################
14284: sub DrawBarGraph {
14285:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
14286:     #
14287:     if (! defined($colors)) {
14288:         $colors = ['#33ff00', 
14289:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
14290:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
14291:                   ]; 
14292:     }
14293:     my $extra_settings = {};
14294:     if (ref($Values[-1]) eq 'HASH') {
14295:         $extra_settings = pop(@Values);
14296:     }
14297:     #
14298:     my $identifier = &get_cgi_id();
14299:     my $id = 'cgi.'.$identifier;        
14300:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
14301:         return '';
14302:     }
14303:     #
14304:     my @Labels;
14305:     if (defined($labels)) {
14306:         @Labels = @$labels;
14307:     } else {
14308:         for (my $i=0;$i<@{$Values[0]};$i++) {
14309:             push(@Labels,$i+1);
14310:         }
14311:     }
14312:     #
14313:     my $NumBars = scalar(@{$Values[0]});
14314:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
14315:     my %ValuesHash;
14316:     my $NumSets=1;
14317:     foreach my $array (@Values) {
14318:         next if (! ref($array));
14319:         $ValuesHash{$id.'.data.'.$NumSets++} = 
14320:             join(',',@$array);
14321:     }
14322:     #
14323:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
14324:     if ($NumBars < 3) {
14325:         $width = 120+$NumBars*32;
14326:         $xskip = 1;
14327:         $bar_width = 30;
14328:     } elsif ($NumBars < 5) {
14329:         $width = 120+$NumBars*20;
14330:         $xskip = 1;
14331:         $bar_width = 20;
14332:     } elsif ($NumBars < 10) {
14333:         $width = 120+$NumBars*15;
14334:         $xskip = 1;
14335:         $bar_width = 15;
14336:     } elsif ($NumBars <= 25) {
14337:         $width = 120+$NumBars*11;
14338:         $xskip = 5;
14339:         $bar_width = 8;
14340:     } elsif ($NumBars <= 50) {
14341:         $width = 120+$NumBars*8;
14342:         $xskip = 5;
14343:         $bar_width = 4;
14344:     } else {
14345:         $width = 120+$NumBars*8;
14346:         $xskip = 5;
14347:         $bar_width = 4;
14348:     }
14349:     #
14350:     $Max = 1 if ($Max < 1);
14351:     if ( int($Max) < $Max ) {
14352:         $Max++;
14353:         $Max = int($Max);
14354:     }
14355:     $Title  = '' if (! defined($Title));
14356:     $xlabel = '' if (! defined($xlabel));
14357:     $ylabel = '' if (! defined($ylabel));
14358:     $ValuesHash{$id.'.title'}    = &escape($Title);
14359:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
14360:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
14361:     $ValuesHash{$id.'.y_max_value'} = $Max;
14362:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
14363:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
14364:     $ValuesHash{$id.'.PlotType'} = 'bar';
14365:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14366:     $ValuesHash{$id.'.height'}   = $height;
14367:     $ValuesHash{$id.'.width'}    = $width;
14368:     $ValuesHash{$id.'.xskip'}    = $xskip;
14369:     $ValuesHash{$id.'.bar_width'} = $bar_width;
14370:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
14371:     #
14372:     # Deal with other parameters
14373:     while (my ($key,$value) = each(%$extra_settings)) {
14374:         $ValuesHash{$id.'.'.$key} = $value;
14375:     }
14376:     #
14377:     &Apache::lonnet::appenv(\%ValuesHash);
14378:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14379: }
14380: 
14381: ############################################################
14382: ############################################################
14383: 
14384: =pod
14385: 
14386: =item * &DrawXYGraph()
14387: 
14388: Facilitates the plotting of data in an XY graph.
14389: Puts plot definition data into the users environment in order for 
14390: graph.png to plot it.  Returns an <img> tag for the plot.
14391: 
14392: Inputs:
14393: 
14394: =over 4
14395: 
14396: =item $Title: string, the title of the plot
14397: 
14398: =item $xlabel: string, text describing the X-axis of the plot
14399: 
14400: =item $ylabel: string, text describing the Y-axis of the plot
14401: 
14402: =item $Max: scalar, the maximum Y value to use in the plot
14403: If $Max is < any data point, the graph will not be rendered.
14404: 
14405: =item $colors: Array ref containing the hex color codes for the data to be 
14406: plotted in.  If undefined, default values will be used.
14407: 
14408: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
14409: 
14410: =item $Ydata: Array ref containing Array refs.  
14411: Each of the contained arrays will be plotted as a separate curve.
14412: 
14413: =item %Values: hash indicating or overriding any default values which are 
14414: passed to graph.png.  
14415: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
14416: 
14417: =back
14418: 
14419: Returns:
14420: 
14421: An <img> tag which references graph.png and the appropriate identifying
14422: information for the plot.
14423: 
14424: =cut
14425: 
14426: ############################################################
14427: ############################################################
14428: sub DrawXYGraph {
14429:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
14430:     #
14431:     # Create the identifier for the graph
14432:     my $identifier = &get_cgi_id();
14433:     my $id = 'cgi.'.$identifier;
14434:     #
14435:     $Title  = '' if (! defined($Title));
14436:     $xlabel = '' if (! defined($xlabel));
14437:     $ylabel = '' if (! defined($ylabel));
14438:     my %ValuesHash = 
14439:         (
14440:          $id.'.title'  => &escape($Title),
14441:          $id.'.xlabel' => &escape($xlabel),
14442:          $id.'.ylabel' => &escape($ylabel),
14443:          $id.'.y_max_value'=> $Max,
14444:          $id.'.labels'     => join(',',@$Xlabels),
14445:          $id.'.PlotType'   => 'XY',
14446:          );
14447:     #
14448:     if (defined($colors) && ref($colors) eq 'ARRAY') {
14449:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14450:     }
14451:     #
14452:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
14453:         return '';
14454:     }
14455:     my $NumSets=1;
14456:     foreach my $array (@{$Ydata}){
14457:         next if (! ref($array));
14458:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
14459:     }
14460:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
14461:     #
14462:     # Deal with other parameters
14463:     while (my ($key,$value) = each(%Values)) {
14464:         $ValuesHash{$id.'.'.$key} = $value;
14465:     }
14466:     #
14467:     &Apache::lonnet::appenv(\%ValuesHash);
14468:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14469: }
14470: 
14471: ############################################################
14472: ############################################################
14473: 
14474: =pod
14475: 
14476: =item * &DrawXYYGraph()
14477: 
14478: Facilitates the plotting of data in an XY graph with two Y axes.
14479: Puts plot definition data into the users environment in order for 
14480: graph.png to plot it.  Returns an <img> tag for the plot.
14481: 
14482: Inputs:
14483: 
14484: =over 4
14485: 
14486: =item $Title: string, the title of the plot
14487: 
14488: =item $xlabel: string, text describing the X-axis of the plot
14489: 
14490: =item $ylabel: string, text describing the Y-axis of the plot
14491: 
14492: =item $colors: Array ref containing the hex color codes for the data to be 
14493: plotted in.  If undefined, default values will be used.
14494: 
14495: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
14496: 
14497: =item $Ydata1: The first data set
14498: 
14499: =item $Min1: The minimum value of the left Y-axis
14500: 
14501: =item $Max1: The maximum value of the left Y-axis
14502: 
14503: =item $Ydata2: The second data set
14504: 
14505: =item $Min2: The minimum value of the right Y-axis
14506: 
14507: =item $Max2: The maximum value of the left Y-axis
14508: 
14509: =item %Values: hash indicating or overriding any default values which are 
14510: passed to graph.png.  
14511: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
14512: 
14513: =back
14514: 
14515: Returns:
14516: 
14517: An <img> tag which references graph.png and the appropriate identifying
14518: information for the plot.
14519: 
14520: =cut
14521: 
14522: ############################################################
14523: ############################################################
14524: sub DrawXYYGraph {
14525:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
14526:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
14527:     #
14528:     # Create the identifier for the graph
14529:     my $identifier = &get_cgi_id();
14530:     my $id = 'cgi.'.$identifier;
14531:     #
14532:     $Title  = '' if (! defined($Title));
14533:     $xlabel = '' if (! defined($xlabel));
14534:     $ylabel = '' if (! defined($ylabel));
14535:     my %ValuesHash = 
14536:         (
14537:          $id.'.title'  => &escape($Title),
14538:          $id.'.xlabel' => &escape($xlabel),
14539:          $id.'.ylabel' => &escape($ylabel),
14540:          $id.'.labels' => join(',',@$Xlabels),
14541:          $id.'.PlotType' => 'XY',
14542:          $id.'.NumSets' => 2,
14543:          $id.'.two_axes' => 1,
14544:          $id.'.y1_max_value' => $Max1,
14545:          $id.'.y1_min_value' => $Min1,
14546:          $id.'.y2_max_value' => $Max2,
14547:          $id.'.y2_min_value' => $Min2,
14548:          );
14549:     #
14550:     if (defined($colors) && ref($colors) eq 'ARRAY') {
14551:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14552:     }
14553:     #
14554:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
14555:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
14556:         return '';
14557:     }
14558:     my $NumSets=1;
14559:     foreach my $array ($Ydata1,$Ydata2){
14560:         next if (! ref($array));
14561:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
14562:     }
14563:     #
14564:     # Deal with other parameters
14565:     while (my ($key,$value) = each(%Values)) {
14566:         $ValuesHash{$id.'.'.$key} = $value;
14567:     }
14568:     #
14569:     &Apache::lonnet::appenv(\%ValuesHash);
14570:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14571: }
14572: 
14573: ############################################################
14574: ############################################################
14575: 
14576: =pod
14577: 
14578: =back 
14579: 
14580: =head1 Statistics helper routines?  
14581: 
14582: Bad place for them but what the hell.
14583: 
14584: =over 4
14585: 
14586: =item * &chartlink()
14587: 
14588: Returns a link to the chart for a specific student.  
14589: 
14590: Inputs:
14591: 
14592: =over 4
14593: 
14594: =item $linktext: The text of the link
14595: 
14596: =item $sname: The students username
14597: 
14598: =item $sdomain: The students domain
14599: 
14600: =back
14601: 
14602: =back
14603: 
14604: =cut
14605: 
14606: ############################################################
14607: ############################################################
14608: sub chartlink {
14609:     my ($linktext, $sname, $sdomain) = @_;
14610:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
14611:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
14612:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
14613:        '">'.$linktext.'</a>';
14614: }
14615: 
14616: #######################################################
14617: #######################################################
14618: 
14619: =pod
14620: 
14621: =head1 Course Environment Routines
14622: 
14623: =over 4
14624: 
14625: =item * &restore_course_settings()
14626: 
14627: =item * &store_course_settings()
14628: 
14629: Restores/Store indicated form parameters from the course environment.
14630: Will not overwrite existing values of the form parameters.
14631: 
14632: Inputs: 
14633: a scalar describing the data (e.g. 'chart', 'problem_analysis')
14634: 
14635: a hash ref describing the data to be stored.  For example:
14636:    
14637: %Save_Parameters = ('Status' => 'scalar',
14638:     'chartoutputmode' => 'scalar',
14639:     'chartoutputdata' => 'scalar',
14640:     'Section' => 'array',
14641:     'Group' => 'array',
14642:     'StudentData' => 'array',
14643:     'Maps' => 'array');
14644: 
14645: Returns: both routines return nothing
14646: 
14647: =back
14648: 
14649: =cut
14650: 
14651: #######################################################
14652: #######################################################
14653: sub store_course_settings {
14654:     return &store_settings($env{'request.course.id'},@_);
14655: }
14656: 
14657: sub store_settings {
14658:     # save to the environment
14659:     # appenv the same items, just to be safe
14660:     my $udom  = $env{'user.domain'};
14661:     my $uname = $env{'user.name'};
14662:     my ($context,$prefix,$Settings) = @_;
14663:     my %SaveHash;
14664:     my %AppHash;
14665:     while (my ($setting,$type) = each(%$Settings)) {
14666:         my $basename = join('.','internal',$context,$prefix,$setting);
14667:         my $envname = 'environment.'.$basename;
14668:         if (exists($env{'form.'.$setting})) {
14669:             # Save this value away
14670:             if ($type eq 'scalar' &&
14671:                 (! exists($env{$envname}) || 
14672:                  $env{$envname} ne $env{'form.'.$setting})) {
14673:                 $SaveHash{$basename} = $env{'form.'.$setting};
14674:                 $AppHash{$envname}   = $env{'form.'.$setting};
14675:             } elsif ($type eq 'array') {
14676:                 my $stored_form;
14677:                 if (ref($env{'form.'.$setting})) {
14678:                     $stored_form = join(',',
14679:                                         map {
14680:                                             &escape($_);
14681:                                         } sort(@{$env{'form.'.$setting}}));
14682:                 } else {
14683:                     $stored_form = 
14684:                         &escape($env{'form.'.$setting});
14685:                 }
14686:                 # Determine if the array contents are the same.
14687:                 if ($stored_form ne $env{$envname}) {
14688:                     $SaveHash{$basename} = $stored_form;
14689:                     $AppHash{$envname}   = $stored_form;
14690:                 }
14691:             }
14692:         }
14693:     }
14694:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
14695:                                           $udom,$uname);
14696:     if ($put_result !~ /^(ok|delayed)/) {
14697:         &Apache::lonnet::logthis('unable to save form parameters, '.
14698:                                  'got error:'.$put_result);
14699:     }
14700:     # Make sure these settings stick around in this session, too
14701:     &Apache::lonnet::appenv(\%AppHash);
14702:     return;
14703: }
14704: 
14705: sub restore_course_settings {
14706:     return &restore_settings($env{'request.course.id'},@_);
14707: }
14708: 
14709: sub restore_settings {
14710:     my ($context,$prefix,$Settings) = @_;
14711:     while (my ($setting,$type) = each(%$Settings)) {
14712:         next if (exists($env{'form.'.$setting}));
14713:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
14714:             '.'.$setting;
14715:         if (exists($env{$envname})) {
14716:             if ($type eq 'scalar') {
14717:                 $env{'form.'.$setting} = $env{$envname};
14718:             } elsif ($type eq 'array') {
14719:                 $env{'form.'.$setting} = [ 
14720:                                            map { 
14721:                                                &unescape($_); 
14722:                                            } split(',',$env{$envname})
14723:                                            ];
14724:             }
14725:         }
14726:     }
14727: }
14728: 
14729: #######################################################
14730: #######################################################
14731: 
14732: =pod
14733: 
14734: =head1 Domain E-mail Routines  
14735: 
14736: =over 4
14737: 
14738: =item * &build_recipient_list()
14739: 
14740: Build recipient lists for following types of e-mail:
14741: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
14742: (d) Help requests, (e) Course requests needing approval, (f) loncapa
14743: module change checking, student/employee ID conflict checks, as
14744: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
14745: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
14746: 
14747: Inputs:
14748: defmail (scalar - email address of default recipient),
14749: mailing type (scalar: errormail, packagesmail, helpdeskmail,
14750: requestsmail, updatesmail, or idconflictsmail).
14751: 
14752: defdom (domain for which to retrieve configuration settings),
14753: 
14754: origmail (scalar - email address of recipient from loncapa.conf,
14755: i.e., predates configuration by DC via domainprefs.pm
14756: 
14757: $requname username of requester (if mailing type is helpdeskmail)
14758: 
14759: $requdom domain of requester (if mailing type is helpdeskmail)
14760: 
14761: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
14762: 
14763: Returns: comma separated list of addresses to which to send e-mail.
14764: 
14765: =back
14766: 
14767: =cut
14768: 
14769: ############################################################
14770: ############################################################
14771: sub build_recipient_list {
14772:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
14773:     my @recipients;
14774:     my ($otheremails,$lastresort,$allbcc,$addtext);
14775:     my %domconfig =
14776:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
14777:     if (ref($domconfig{'contacts'}) eq 'HASH') {
14778:         if (exists($domconfig{'contacts'}{$mailing})) {
14779:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
14780:                 my @contacts = ('adminemail','supportemail');
14781:                 foreach my $item (@contacts) {
14782:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
14783:                         my $addr = $domconfig{'contacts'}{$item}; 
14784:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
14785:                             push(@recipients,$addr);
14786:                         }
14787:                     }
14788:                 }
14789:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
14790:                 if ($mailing eq 'helpdeskmail') {
14791:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
14792:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
14793:                         my @ok_bccs;
14794:                         foreach my $bcc (@bccs) {
14795:                             $bcc =~ s/^\s+//g;
14796:                             $bcc =~ s/\s+$//g;
14797:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14798:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14799:                                     push(@ok_bccs,$bcc);
14800:                                 }
14801:                             }
14802:                         }
14803:                         if (@ok_bccs > 0) {
14804:                             $allbcc = join(', ',@ok_bccs);
14805:                         }
14806:                     }
14807:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
14808:                 }
14809:             }
14810:         } elsif ($origmail ne '') {
14811:             $lastresort = $origmail;
14812:         }
14813:         if ($mailing eq 'helpdeskmail') {
14814:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
14815:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
14816:                 my ($inststatus,$inststatus_checked);
14817:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
14818:                     ($env{'user.domain'} ne 'public')) {
14819:                     $inststatus_checked = 1;
14820:                     $inststatus = $env{'environment.inststatus'};
14821:                 }
14822:                 unless ($inststatus_checked) {
14823:                     if (($requname ne '') && ($requdom ne '')) {
14824:                         if (($requname =~ /^$match_username$/) &&
14825:                             ($requdom =~ /^$match_domain$/) &&
14826:                             (&Apache::lonnet::domain($requdom))) {
14827:                             my $requhome = &Apache::lonnet::homeserver($requname,
14828:                                                                       $requdom);
14829:                             unless ($requhome eq 'no_host') {
14830:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
14831:                                 $inststatus = $userenv{'inststatus'};
14832:                                 $inststatus_checked = 1;
14833:                             }
14834:                         }
14835:                     }
14836:                 }
14837:                 unless ($inststatus_checked) {
14838:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
14839:                         my %srch = (srchby     => 'email',
14840:                                     srchdomain => $defdom,
14841:                                     srchterm   => $reqemail,
14842:                                     srchtype   => 'exact');
14843:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
14844:                         foreach my $uname (keys(%srch_results)) {
14845:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
14846:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
14847:                                 $inststatus_checked = 1;
14848:                                 last;
14849:                             }
14850:                         }
14851:                         unless ($inststatus_checked) {
14852:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
14853:                             if ($dirsrchres eq 'ok') {
14854:                                 foreach my $uname (keys(%srch_results)) {
14855:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
14856:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
14857:                                         $inststatus_checked = 1;
14858:                                         last;
14859:                                     }
14860:                                 }
14861:                             }
14862:                         }
14863:                     }
14864:                 }
14865:                 if ($inststatus ne '') {
14866:                     foreach my $status (split(/\:/,$inststatus)) {
14867:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
14868:                             my @contacts = ('adminemail','supportemail');
14869:                             foreach my $item (@contacts) {
14870:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
14871:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
14872:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
14873:                                         push(@recipients,$addr);
14874:                                     }
14875:                                 }
14876:                             }
14877:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
14878:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
14879:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
14880:                                 my @ok_bccs;
14881:                                 foreach my $bcc (@bccs) {
14882:                                     $bcc =~ s/^\s+//g;
14883:                                     $bcc =~ s/\s+$//g;
14884:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14885:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14886:                                             push(@ok_bccs,$bcc);
14887:                                         }
14888:                                     }
14889:                                 }
14890:                                 if (@ok_bccs > 0) {
14891:                                     $allbcc = join(', ',@ok_bccs);
14892:                                 }
14893:                             }
14894:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
14895:                             last;
14896:                         }
14897:                     }
14898:                 }
14899:             }
14900:         }
14901:     } elsif ($origmail ne '') {
14902:         $lastresort = $origmail;
14903:     }
14904:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
14905:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
14906:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
14907:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
14908:             my %what = (
14909:                           perlvar => 1,
14910:                        );
14911:             my $primary = &Apache::lonnet::domain($defdom,'primary');
14912:             if ($primary) {
14913:                 my $gotaddr;
14914:                 my ($result,$returnhash) =
14915:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
14916:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
14917:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
14918:                         $lastresort = $returnhash->{'lonSupportEMail'};
14919:                         $gotaddr = 1;
14920:                     }
14921:                 }
14922:                 unless ($gotaddr) {
14923:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
14924:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
14925:                     unless ($uintdom eq $intdom) {
14926:                         my %domconfig =
14927:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
14928:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
14929:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
14930:                                 my @contacts = ('adminemail','supportemail');
14931:                                 foreach my $item (@contacts) {
14932:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
14933:                                         my $addr = $domconfig{'contacts'}{$item};
14934:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
14935:                                             push(@recipients,$addr);
14936:                                         }
14937:                                     }
14938:                                 }
14939:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
14940:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
14941:                                 }
14942:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
14943:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
14944:                                     my @ok_bccs;
14945:                                     foreach my $bcc (@bccs) {
14946:                                         $bcc =~ s/^\s+//g;
14947:                                         $bcc =~ s/\s+$//g;
14948:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14949:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14950:                                                 push(@ok_bccs,$bcc);
14951:                                             }
14952:                                         }
14953:                                     }
14954:                                     if (@ok_bccs > 0) {
14955:                                         $allbcc = join(', ',@ok_bccs);
14956:                                     }
14957:                                 }
14958:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
14959:                             }
14960:                         }
14961:                     }
14962:                 }
14963:             }
14964:         }
14965:     }
14966:     if (defined($defmail)) {
14967:         if ($defmail ne '') {
14968:             push(@recipients,$defmail);
14969:         }
14970:     }
14971:     if ($otheremails) {
14972:         my @others;
14973:         if ($otheremails =~ /,/) {
14974:             @others = split(/,/,$otheremails);
14975:         } else {
14976:             push(@others,$otheremails);
14977:         }
14978:         foreach my $addr (@others) {
14979:             if (!grep(/^\Q$addr\E$/,@recipients)) {
14980:                 push(@recipients,$addr);
14981:             }
14982:         }
14983:     }
14984:     if ($mailing eq 'helpdeskmail') {
14985:         if ((!@recipients) && ($lastresort ne '')) {
14986:             push(@recipients,$lastresort);
14987:         }
14988:     } elsif ($lastresort ne '') {
14989:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
14990:             push(@recipients,$lastresort);
14991:         }
14992:     }
14993:     my $recipientlist = join(',',@recipients);
14994:     if (wantarray) {
14995:         return ($recipientlist,$allbcc,$addtext);
14996:     } else {
14997:         return $recipientlist;
14998:     }
14999: }
15000: 
15001: ############################################################
15002: ############################################################
15003: 
15004: =pod
15005: 
15006: =head1 Course Catalog Routines
15007: 
15008: =over 4
15009: 
15010: =item * &gather_categories()
15011: 
15012: Converts category definitions - keys of categories hash stored in  
15013: coursecategories in configuration.db on the primary library server in a 
15014: domain - to an array.  Also generates javascript and idx hash used to 
15015: generate Domain Coordinator interface for editing Course Categories.
15016: 
15017: Inputs:
15018: 
15019: categories (reference to hash of category definitions).
15020: 
15021: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15022:       categories and subcategories).
15023: 
15024: idx (reference to hash of counters used in Domain Coordinator interface for 
15025:       editing Course Categories).
15026: 
15027: jsarray (reference to array of categories used to create Javascript arrays for
15028:          Domain Coordinator interface for editing Course Categories).
15029: 
15030: Returns: nothing
15031: 
15032: Side effects: populates cats, idx and jsarray. 
15033: 
15034: =cut
15035: 
15036: sub gather_categories {
15037:     my ($categories,$cats,$idx,$jsarray) = @_;
15038:     my %counters;
15039:     my $num = 0;
15040:     foreach my $item (keys(%{$categories})) {
15041:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
15042:         if ($container eq '' && $depth == 0) {
15043:             $cats->[$depth][$categories->{$item}] = $cat;
15044:         } else {
15045:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
15046:         }
15047:         my ($escitem,$tail) = split(/:/,$item,2);
15048:         if ($counters{$tail} eq '') {
15049:             $counters{$tail} = $num;
15050:             $num ++;
15051:         }
15052:         if (ref($idx) eq 'HASH') {
15053:             $idx->{$item} = $counters{$tail};
15054:         }
15055:         if (ref($jsarray) eq 'ARRAY') {
15056:             push(@{$jsarray->[$counters{$tail}]},$item);
15057:         }
15058:     }
15059:     return;
15060: }
15061: 
15062: =pod
15063: 
15064: =item * &extract_categories()
15065: 
15066: Used to generate breadcrumb trails for course categories.
15067: 
15068: Inputs:
15069: 
15070: categories (reference to hash of category definitions).
15071: 
15072: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15073:       categories and subcategories).
15074: 
15075: trails (reference to array of breacrumb trails for each category).
15076: 
15077: allitems (reference to hash - key is category key 
15078:          (format: escaped(name):escaped(parent category):depth in hierarchy).
15079: 
15080: idx (reference to hash of counters used in Domain Coordinator interface for
15081:       editing Course Categories).
15082: 
15083: jsarray (reference to array of categories used to create Javascript arrays for
15084:          Domain Coordinator interface for editing Course Categories).
15085: 
15086: subcats (reference to hash of arrays containing all subcategories within each 
15087:          category, -recursive)
15088: 
15089: maxd (reference to hash used to hold max depth for all top-level categories).
15090: 
15091: Returns: nothing
15092: 
15093: Side effects: populates trails and allitems hash references.
15094: 
15095: =cut
15096: 
15097: sub extract_categories {
15098:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
15099:     if (ref($categories) eq 'HASH') {
15100:         &gather_categories($categories,$cats,$idx,$jsarray);
15101:         if (ref($cats->[0]) eq 'ARRAY') {
15102:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
15103:                 my $name = $cats->[0][$i];
15104:                 my $item = &escape($name).'::0';
15105:                 my $trailstr;
15106:                 if ($name eq 'instcode') {
15107:                     $trailstr = &mt('Official courses (with institutional codes)');
15108:                 } elsif ($name eq 'communities') {
15109:                     $trailstr = &mt('Communities');
15110:                 } else {
15111:                     $trailstr = $name;
15112:                 }
15113:                 if ($allitems->{$item} eq '') {
15114:                     push(@{$trails},$trailstr);
15115:                     $allitems->{$item} = scalar(@{$trails})-1;
15116:                 }
15117:                 my @parents = ($name);
15118:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
15119:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
15120:                         my $category = $cats->[1]{$name}[$j];
15121:                         if (ref($subcats) eq 'HASH') {
15122:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
15123:                         }
15124:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
15125:                     }
15126:                 } else {
15127:                     if (ref($subcats) eq 'HASH') {
15128:                         $subcats->{$item} = [];
15129:                     }
15130:                     if (ref($maxd) eq 'HASH') {
15131:                         $maxd->{$name} = 1;
15132:                     }
15133:                 }
15134:             }
15135:         }
15136:     }
15137:     return;
15138: }
15139: 
15140: =pod
15141: 
15142: =item * &recurse_categories()
15143: 
15144: Recursively used to generate breadcrumb trails for course categories.
15145: 
15146: Inputs:
15147: 
15148: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15149:       categories and subcategories).
15150: 
15151: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
15152: 
15153: category (current course category, for which breadcrumb trail is being generated).
15154: 
15155: trails (reference to array of breadcrumb trails for each category).
15156: 
15157: allitems (reference to hash - key is category key
15158:          (format: escaped(name):escaped(parent category):depth in hierarchy).
15159: 
15160: parents (array containing containers directories for current category, 
15161:          back to top level). 
15162: 
15163: Returns: nothing
15164: 
15165: Side effects: populates trails and allitems hash references
15166: 
15167: =cut
15168: 
15169: sub recurse_categories {
15170:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
15171:     my $shallower = $depth - 1;
15172:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
15173:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
15174:             my $name = $cats->[$depth]{$category}[$k];
15175:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
15176:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
15177:             if ($allitems->{$item} eq '') {
15178:                 push(@{$trails},$trailstr);
15179:                 $allitems->{$item} = scalar(@{$trails})-1;
15180:             }
15181:             my $deeper = $depth+1;
15182:             push(@{$parents},$category);
15183:             if (ref($subcats) eq 'HASH') {
15184:                 my $subcat = &escape($name).':'.$category.':'.$depth;
15185:                 for (my $j=@{$parents}; $j>=0; $j--) {
15186:                     my $higher;
15187:                     if ($j > 0) {
15188:                         $higher = &escape($parents->[$j]).':'.
15189:                                   &escape($parents->[$j-1]).':'.$j;
15190:                     } else {
15191:                         $higher = &escape($parents->[$j]).'::'.$j;
15192:                     }
15193:                     push(@{$subcats->{$higher}},$subcat);
15194:                 }
15195:             }
15196:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
15197:                                 $subcats,$maxd);
15198:             pop(@{$parents});
15199:         }
15200:     } else {
15201:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
15202:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
15203:         if ($allitems->{$item} eq '') {
15204:             push(@{$trails},$trailstr);
15205:             $allitems->{$item} = scalar(@{$trails})-1;
15206:         }
15207:         if (ref($maxd) eq 'HASH') {
15208:             if ($depth > $maxd->{$parents->[0]}) {
15209:                 $maxd->{$parents->[0]} = $depth;
15210:             }
15211:         }
15212:     }
15213:     return;
15214: }
15215: 
15216: =pod
15217: 
15218: =item * &assign_categories_table()
15219: 
15220: Create a datatable for display of hierarchical categories in a domain,
15221: with checkboxes to allow a course to be categorized. 
15222: 
15223: Inputs:
15224: 
15225: cathash - reference to hash of categories defined for the domain (from
15226:           configuration.db)
15227: 
15228: currcat - scalar with an & separated list of categories assigned to a course. 
15229: 
15230: type    - scalar contains course type (Course or Community).
15231: 
15232: disabled - scalar (optional) contains disabled="disabled" if input elements are
15233:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
15234: 
15235: Returns: $output (markup to be displayed) 
15236: 
15237: =cut
15238: 
15239: sub assign_categories_table {
15240:     my ($cathash,$currcat,$type,$disabled) = @_;
15241:     my $output;
15242:     if (ref($cathash) eq 'HASH') {
15243:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
15244:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
15245:         $maxdepth = scalar(@cats);
15246:         if (@cats > 0) {
15247:             my $itemcount = 0;
15248:             if (ref($cats[0]) eq 'ARRAY') {
15249:                 my @currcategories;
15250:                 if ($currcat ne '') {
15251:                     @currcategories = split('&',$currcat);
15252:                 }
15253:                 my $table;
15254:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
15255:                     my $parent = $cats[0][$i];
15256:                     next if ($parent eq 'instcode');
15257:                     if ($type eq 'Community') {
15258:                         next unless ($parent eq 'communities');
15259:                     } else {
15260:                         next if ($parent eq 'communities');
15261:                     }
15262:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
15263:                     my $item = &escape($parent).'::0';
15264:                     my $checked = '';
15265:                     if (@currcategories > 0) {
15266:                         if (grep(/^\Q$item\E$/,@currcategories)) {
15267:                             $checked = ' checked="checked"';
15268:                         }
15269:                     }
15270:                     my $parent_title = $parent;
15271:                     if ($parent eq 'communities') {
15272:                         $parent_title = &mt('Communities');
15273:                     }
15274:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
15275:                               '<input type="checkbox" name="usecategory" value="'.
15276:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
15277:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
15278:                     my $depth = 1;
15279:                     push(@path,$parent);
15280:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
15281:                     pop(@path);
15282:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
15283:                     $itemcount ++;
15284:                 }
15285:                 if ($itemcount) {
15286:                     $output = &Apache::loncommon::start_data_table().
15287:                               $table.
15288:                               &Apache::loncommon::end_data_table();
15289:                 }
15290:             }
15291:         }
15292:     }
15293:     return $output;
15294: }
15295: 
15296: =pod
15297: 
15298: =item * &assign_category_rows()
15299: 
15300: Create a datatable row for display of nested categories in a domain,
15301: with checkboxes to allow a course to be categorized,called recursively.
15302: 
15303: Inputs:
15304: 
15305: itemcount - track row number for alternating colors
15306: 
15307: cats - reference to array of arrays/hashes which encapsulates hierarchy of
15308:       categories and subcategories.
15309: 
15310: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
15311: 
15312: parent - parent of current category item
15313: 
15314: path - Array containing all categories back up through the hierarchy from the
15315:        current category to the top level.
15316: 
15317: currcategories - reference to array of current categories assigned to the course
15318: 
15319: disabled - scalar (optional) contains disabled="disabled" if input elements are
15320:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
15321: 
15322: Returns: $output (markup to be displayed).
15323: 
15324: =cut
15325: 
15326: sub assign_category_rows {
15327:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
15328:     my ($text,$name,$item,$chgstr);
15329:     if (ref($cats) eq 'ARRAY') {
15330:         my $maxdepth = scalar(@{$cats});
15331:         if (ref($cats->[$depth]) eq 'HASH') {
15332:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
15333:                 my $numchildren = @{$cats->[$depth]{$parent}};
15334:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
15335:                 $text .= '<td><table class="LC_data_table">';
15336:                 for (my $j=0; $j<$numchildren; $j++) {
15337:                     $name = $cats->[$depth]{$parent}[$j];
15338:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
15339:                     my $deeper = $depth+1;
15340:                     my $checked = '';
15341:                     if (ref($currcategories) eq 'ARRAY') {
15342:                         if (@{$currcategories} > 0) {
15343:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
15344:                                 $checked = ' checked="checked"';
15345:                             }
15346:                         }
15347:                     }
15348:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
15349:                              '<input type="checkbox" name="usecategory" value="'.
15350:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
15351:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
15352:                              '</td><td>';
15353:                     if (ref($path) eq 'ARRAY') {
15354:                         push(@{$path},$name);
15355:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
15356:                         pop(@{$path});
15357:                     }
15358:                     $text .= '</td></tr>';
15359:                 }
15360:                 $text .= '</table></td>';
15361:             }
15362:         }
15363:     }
15364:     return $text;
15365: }
15366: 
15367: =pod
15368: 
15369: =back
15370: 
15371: =cut
15372: 
15373: ############################################################
15374: ############################################################
15375: 
15376: 
15377: sub commit_customrole {
15378:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
15379:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
15380:                          ($start?', '.&mt('starting').' '.localtime($start):'').
15381:                          ($end?', ending '.localtime($end):'').': <b>'.
15382:               &Apache::lonnet::assigncustomrole(
15383:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
15384:                  '</b><br />';
15385:     return $output;
15386: }
15387: 
15388: sub commit_standardrole {
15389:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
15390:     my ($output,$logmsg,$linefeed);
15391:     if ($context eq 'auto') {
15392:         $linefeed = "\n";
15393:     } else {
15394:         $linefeed = "<br />\n";
15395:     }  
15396:     if ($three eq 'st') {
15397:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
15398:                                          $one,$two,$sec,$context,$credits);
15399:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
15400:             ($result eq 'unknown_course') || ($result eq 'refused')) {
15401:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
15402:         } else {
15403:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
15404:                ($start?', '.&mt('starting').' '.localtime($start):'').
15405:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
15406:             if ($context eq 'auto') {
15407:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
15408:             } else {
15409:                $output .= '<b>'.$result.'</b>'.$linefeed.
15410:                &mt('Add to classlist').': <b>ok</b>';
15411:             }
15412:             $output .= $linefeed;
15413:         }
15414:     } else {
15415:         $output = &mt('Assigning').' '.$three.' in '.$url.
15416:                ($start?', '.&mt('starting').' '.localtime($start):'').
15417:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
15418:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
15419:         if ($context eq 'auto') {
15420:             $output .= $result.$linefeed;
15421:         } else {
15422:             $output .= '<b>'.$result.'</b>'.$linefeed;
15423:         }
15424:     }
15425:     return $output;
15426: }
15427: 
15428: sub commit_studentrole {
15429:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
15430:         $credits) = @_;
15431:     my ($result,$linefeed,$oldsecurl,$newsecurl);
15432:     if ($context eq 'auto') {
15433:         $linefeed = "\n";
15434:     } else {
15435:         $linefeed = '<br />'."\n";
15436:     }
15437:     if (defined($one) && defined($two)) {
15438:         my $cid=$one.'_'.$two;
15439:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
15440:         my $secchange = 0;
15441:         my $expire_role_result;
15442:         my $modify_section_result;
15443:         if ($oldsec ne '-1') { 
15444:             if ($oldsec ne $sec) {
15445:                 $secchange = 1;
15446:                 my $now = time;
15447:                 my $uurl='/'.$cid;
15448:                 $uurl=~s/\_/\//g;
15449:                 if ($oldsec) {
15450:                     $uurl.='/'.$oldsec;
15451:                 }
15452:                 $oldsecurl = $uurl;
15453:                 $expire_role_result = 
15454:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
15455:                 if ($env{'request.course.sec'} ne '') { 
15456:                     if ($expire_role_result eq 'refused') {
15457:                         my @roles = ('st');
15458:                         my @statuses = ('previous');
15459:                         my @roledoms = ($one);
15460:                         my $withsec = 1;
15461:                         my %roleshash = 
15462:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
15463:                                               \@statuses,\@roles,\@roledoms,$withsec);
15464:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
15465:                             my ($oldstart,$oldend) = 
15466:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
15467:                             if ($oldend > 0 && $oldend <= $now) {
15468:                                 $expire_role_result = 'ok';
15469:                             }
15470:                         }
15471:                     }
15472:                 }
15473:                 $result = $expire_role_result;
15474:             }
15475:         }
15476:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
15477:             $modify_section_result = 
15478:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
15479:                                                            undef,undef,undef,$sec,
15480:                                                            $end,$start,'','',$cid,
15481:                                                            '',$context,$credits);
15482:             if ($modify_section_result =~ /^ok/) {
15483:                 if ($secchange == 1) {
15484:                     if ($sec eq '') {
15485:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
15486:                     } else {
15487:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
15488:                     }
15489:                 } elsif ($oldsec eq '-1') {
15490:                     if ($sec eq '') {
15491:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
15492:                     } else {
15493:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
15494:                     }
15495:                 } else {
15496:                     if ($sec eq '') {
15497:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
15498:                     } else {
15499:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
15500:                     }
15501:                 }
15502:             } else {
15503:                 if ($secchange) {       
15504:                     $$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;
15505:                 } else {
15506:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
15507:                 }
15508:             }
15509:             $result = $modify_section_result;
15510:         } elsif ($secchange == 1) {
15511:             if ($oldsec eq '') {
15512:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
15513:             } else {
15514:                 $$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;
15515:             }
15516:             if ($expire_role_result eq 'refused') {
15517:                 my $newsecurl = '/'.$cid;
15518:                 $newsecurl =~ s/\_/\//g;
15519:                 if ($sec ne '') {
15520:                     $newsecurl.='/'.$sec;
15521:                 }
15522:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
15523:                     if ($sec eq '') {
15524:                         $$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;
15525:                     } else {
15526:                         $$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;
15527:                     }
15528:                 }
15529:             }
15530:         }
15531:     } else {
15532:         $$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;
15533:         $result = "error: incomplete course id\n";
15534:     }
15535:     return $result;
15536: }
15537: 
15538: sub show_role_extent {
15539:     my ($scope,$context,$role) = @_;
15540:     $scope =~ s{^/}{};
15541:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
15542:     push(@courseroles,'co');
15543:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
15544:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
15545:         $scope =~ s{/}{_};
15546:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
15547:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
15548:         my ($audom,$auname) = split(/\//,$scope);
15549:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
15550:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
15551:     } else {
15552:         $scope =~ s{/$}{};
15553:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
15554:                    &Apache::lonnet::domain($scope,'description').'</span>');
15555:     }
15556: }
15557: 
15558: ############################################################
15559: ############################################################
15560: 
15561: sub check_clone {
15562:     my ($args,$linefeed) = @_;
15563:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
15564:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
15565:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
15566:     my $clonetitle;
15567:     my @clonemsg;
15568:     my $can_clone = 0;
15569:     my $lctype = lc($args->{'crstype'});
15570:     if ($lctype ne 'community') {
15571:         $lctype = 'course';
15572:     }
15573:     if ($clonehome eq 'no_host') {
15574:         if ($args->{'crstype'} eq 'Community') {
15575:             push(@clonemsg,({
15576:                               mt => 'No new community created.',
15577:                               args => [],
15578:                             },
15579:                             {
15580:                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
15581:                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
15582:                             }));
15583:         } else {
15584:             push(@clonemsg,({
15585:                               mt => 'No new course created.',
15586:                               args => [],
15587:                             },
15588:                             {
15589:                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
15590:                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
15591:                             }));
15592:         }
15593:     } else {
15594: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
15595:         $clonetitle = $clonedesc{'description'};
15596:         if ($args->{'crstype'} eq 'Community') {
15597:             if ($clonedesc{'type'} ne 'Community') {
15598:                 push(@clonemsg,({
15599:                                   mt => 'No new community created.',
15600:                                   args => [],
15601:                                 },
15602:                                 {
15603:                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
15604:                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
15605:                                 }));
15606:                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
15607:             }
15608:         }
15609: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
15610:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
15611: 	    $can_clone = 1;
15612: 	} else {
15613: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
15614: 						 $args->{'clonedomain'},$args->{'clonecourse'});
15615:             if ($clonehash{'cloners'} eq '') {
15616:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
15617:                 if ($domdefs{'canclone'}) {
15618:                     unless ($domdefs{'canclone'} eq 'none') {
15619:                         if ($domdefs{'canclone'} eq 'domain') {
15620:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
15621:                                 $can_clone = 1;
15622:                             }
15623:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
15624:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
15625:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
15626:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
15627:                                 $can_clone = 1;
15628:                             }
15629:                         }
15630:                     }
15631:                 }
15632:             } else {
15633: 	        my @cloners = split(/,/,$clonehash{'cloners'});
15634:                 if (grep(/^\*$/,@cloners)) {
15635:                     $can_clone = 1;
15636:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
15637:                     $can_clone = 1;
15638:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
15639:                     $can_clone = 1;
15640:                 }
15641:                 unless ($can_clone) {
15642:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
15643:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
15644:                         my (%gotdomdefaults,%gotcodedefaults);
15645:                         foreach my $cloner (@cloners) {
15646:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
15647:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
15648:                                 my (%codedefaults,@code_order);
15649:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
15650:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
15651:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
15652:                                     }
15653:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
15654:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
15655:                                     }
15656:                                 } else {
15657:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
15658:                                                                             \%codedefaults,
15659:                                                                             \@code_order);
15660:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
15661:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
15662:                                 }
15663:                                 if (@code_order > 0) {
15664:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
15665:                                                                                 $cloner,$clonehash{'internal.coursecode'},
15666:                                                                                 $args->{'crscode'})) {
15667:                                         $can_clone = 1;
15668:                                         last;
15669:                                     }
15670:                                 }
15671:                             }
15672:                         }
15673:                     }
15674:                 }
15675:             }
15676:             unless ($can_clone) {
15677:                 my $ccrole = 'cc';
15678:                 if ($args->{'crstype'} eq 'Community') {
15679:                     $ccrole = 'co';
15680:                 }
15681:                 my %roleshash =
15682:                     &Apache::lonnet::get_my_roles($args->{'ccuname'},
15683:                                                   $args->{'ccdomain'},
15684:                                                   'userroles',['active'],[$ccrole],
15685:                                                   [$args->{'clonedomain'}]);
15686:                 if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
15687:                     $can_clone = 1;
15688:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
15689:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
15690:                     $can_clone = 1;
15691:                 }
15692:             }
15693:             unless ($can_clone) {
15694:                 if ($args->{'crstype'} eq 'Community') {
15695:                     push(@clonemsg,({
15696:                                       mt => 'No new community created.',
15697:                                       args => [],
15698:                                     },
15699:                                     {
15700:                                       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]).',
15701:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
15702:                                     }));
15703:                 } else {
15704:                     push(@clonemsg,({
15705:                                       mt => 'No new course created.',
15706:                                       args => [],
15707:                                     },
15708:                                     {
15709:                                       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]).',
15710:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
15711:                                     }));
15712: 	        }
15713: 	    }
15714:         }
15715:     }
15716:     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
15717: }
15718: 
15719: sub construct_course {
15720:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
15721:         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
15722:     my ($outcome,$msgref,$clonemsgref);
15723:     my $linefeed =  '<br />'."\n";
15724:     if ($context eq 'auto') {
15725:         $linefeed = "\n";
15726:     }
15727: 
15728: #
15729: # Are we cloning?
15730: #
15731:     my ($can_clone,$cloneid,$clonehome,$clonetitle);
15732:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
15733: 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
15734:         if (!$can_clone) {
15735: 	    return (0,$outcome,$clonemsgref);
15736: 	}
15737:     }
15738: 
15739: #
15740: # Open course
15741: #
15742:     my $crstype = lc($args->{'crstype'});
15743:     my %cenv=();
15744:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
15745:                                              $args->{'cdescr'},
15746:                                              $args->{'curl'},
15747:                                              $args->{'course_home'},
15748:                                              $args->{'nonstandard'},
15749:                                              $args->{'crscode'},
15750:                                              $args->{'ccuname'}.':'.
15751:                                              $args->{'ccdomain'},
15752:                                              $args->{'crstype'},
15753:                                              $cnum,$context,$category,
15754:                                              $callercontext);
15755: 
15756:     # Note: The testing routines depend on this being output; see 
15757:     # Utils::Course. This needs to at least be output as a comment
15758:     # if anyone ever decides to not show this, and Utils::Course::new
15759:     # will need to be suitably modified.
15760:     if (($callercontext eq 'auto') && ($user_lh ne '')) {
15761:         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
15762:     } else {
15763:         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
15764:     }
15765:     if ($$courseid =~ /^error:/) {
15766:         return (0,$outcome,$clonemsgref);
15767:     }
15768: 
15769: #
15770: # Check if created correctly
15771: #
15772:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
15773:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
15774:     if ($crsuhome eq 'no_host') {
15775:         if (($callercontext eq 'auto') && ($user_lh ne '')) {
15776:             $outcome .= &mt_user($user_lh,
15777:                             'Course creation failed, unrecognized course home server.');
15778:         } else {
15779:             $outcome .= &mt('Course creation failed, unrecognized course home server.');
15780:         }
15781:         $outcome .= $linefeed;
15782:         return (0,$outcome,$clonemsgref);
15783:     }
15784:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
15785: 
15786: #
15787: # Do the cloning
15788: #
15789:     my @clonemsg;
15790:     if ($can_clone && $cloneid) {
15791:         push(@clonemsg,
15792:                       {
15793:                           mt => 'Created [_1] by cloning from [_2]',
15794:                           args => [$crstype,$clonetitle],
15795:                       });
15796: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
15797: # Copy all files
15798:         my @info =
15799:             &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
15800:                                                      $args->{'dateshift'},$args->{'crscode'},
15801:                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
15802:                                                      $args->{'tinyurls'});
15803:         if (@info) {
15804:             push(@clonemsg,@info);
15805:         }
15806: # Restore URL
15807: 	$cenv{'url'}=$oldcenv{'url'};
15808: # Restore title
15809: 	$cenv{'description'}=$oldcenv{'description'};
15810: # Restore creation date, creator and creation context.
15811:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
15812:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
15813:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
15814: # Mark as cloned
15815: 	$cenv{'clonedfrom'}=$cloneid;
15816: # Need to clone grading mode
15817:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
15818:         $cenv{'grading'}=$newenv{'grading'};
15819: # Do not clone these environment entries
15820:         &Apache::lonnet::del('environment',
15821:                   ['default_enrollment_start_date',
15822:                    'default_enrollment_end_date',
15823:                    'question.email',
15824:                    'policy.email',
15825:                    'comment.email',
15826:                    'pch.users.denied',
15827:                    'plc.users.denied',
15828:                    'hidefromcat',
15829:                    'checkforpriv',
15830:                    'categories'],
15831:                    $$crsudom,$$crsunum);
15832:         if ($args->{'textbook'}) {
15833:             $cenv{'internal.textbook'} = $args->{'textbook'};
15834:         }
15835:     }
15836: 
15837: #
15838: # Set environment (will override cloned, if existing)
15839: #
15840:     my @sections = ();
15841:     my @xlists = ();
15842:     if ($args->{'crstype'}) {
15843:         $cenv{'type'}=$args->{'crstype'};
15844:     }
15845:     if ($args->{'crsid'}) {
15846:         $cenv{'courseid'}=$args->{'crsid'};
15847:     }
15848:     if ($args->{'crscode'}) {
15849:         $cenv{'internal.coursecode'}=$args->{'crscode'};
15850:     }
15851:     if ($args->{'crsquota'} ne '') {
15852:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
15853:     } else {
15854:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
15855:     }
15856:     if ($args->{'ccuname'}) {
15857:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
15858:                                         ':'.$args->{'ccdomain'};
15859:     } else {
15860:         $cenv{'internal.courseowner'} = $args->{'curruser'};
15861:     }
15862:     if ($args->{'defaultcredits'}) {
15863:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
15864:     }
15865:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
15866:     if ($args->{'crssections'}) {
15867:         $cenv{'internal.sectionnums'} = '';
15868:         if ($args->{'crssections'} =~ m/,/) {
15869:             @sections = split/,/,$args->{'crssections'};
15870:         } else {
15871:             $sections[0] = $args->{'crssections'};
15872:         }
15873:         if (@sections > 0) {
15874:             foreach my $item (@sections) {
15875:                 my ($sec,$gp) = split/:/,$item;
15876:                 my $class = $args->{'crscode'}.$sec;
15877:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
15878:                 $cenv{'internal.sectionnums'} .= $item.',';
15879:                 unless ($addcheck eq 'ok') {
15880:                     push(@badclasses,$class);
15881:                 }
15882:             }
15883:             $cenv{'internal.sectionnums'} =~ s/,$//;
15884:         }
15885:     }
15886: # do not hide course coordinator from staff listing, 
15887: # even if privileged
15888:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15889: # add course coordinator's domain to domains to check for privileged users
15890: # if different to course domain
15891:     if ($$crsudom ne $args->{'ccdomain'}) {
15892:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
15893:     }
15894: # add crosslistings
15895:     if ($args->{'crsxlist'}) {
15896:         $cenv{'internal.crosslistings'}='';
15897:         if ($args->{'crsxlist'} =~ m/,/) {
15898:             @xlists = split/,/,$args->{'crsxlist'};
15899:         } else {
15900:             $xlists[0] = $args->{'crsxlist'};
15901:         }
15902:         if (@xlists > 0) {
15903:             foreach my $item (@xlists) {
15904:                 my ($xl,$gp) = split/:/,$item;
15905:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
15906:                 $cenv{'internal.crosslistings'} .= $item.',';
15907:                 unless ($addcheck eq 'ok') {
15908:                     push(@badclasses,$xl);
15909:                 }
15910:             }
15911:             $cenv{'internal.crosslistings'} =~ s/,$//;
15912:         }
15913:     }
15914:     if ($args->{'autoadds'}) {
15915:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
15916:     }
15917:     if ($args->{'autodrops'}) {
15918:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
15919:     }
15920: # check for notification of enrollment changes
15921:     my @notified = ();
15922:     if ($args->{'notify_owner'}) {
15923:         if ($args->{'ccuname'} ne '') {
15924:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
15925:         }
15926:     }
15927:     if ($args->{'notify_dc'}) {
15928:         if ($uname ne '') { 
15929:             push(@notified,$uname.':'.$udom);
15930:         }
15931:     }
15932:     if (@notified > 0) {
15933:         my $notifylist;
15934:         if (@notified > 1) {
15935:             $notifylist = join(',',@notified);
15936:         } else {
15937:             $notifylist = $notified[0];
15938:         }
15939:         $cenv{'internal.notifylist'} = $notifylist;
15940:     }
15941:     if (@badclasses > 0) {
15942:         my %lt=&Apache::lonlocal::texthash(
15943:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
15944:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
15945:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
15946:         );
15947:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
15948:                            &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'};
15949:         if ($context eq 'auto') {
15950:             $outcome .= $badclass_msg.$linefeed;
15951:         } else {
15952:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
15953:         }
15954:         foreach my $item (@badclasses) {
15955:             if ($context eq 'auto') {
15956:                 $outcome .= " - $item\n";
15957:             } else {
15958:                 $outcome .= "<li>$item</li>\n";
15959:             }
15960:         }
15961:         if ($context eq 'auto') {
15962:             $outcome .= $linefeed;
15963:         } else {
15964:             $outcome .= "</ul><br /><br /></div>\n";
15965:         }
15966:     }
15967:     if ($args->{'no_end_date'}) {
15968:         $args->{'endaccess'} = 0;
15969:     }
15970:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
15971:     $cenv{'internal.autoend'}=$args->{'enrollend'};
15972:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
15973:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
15974:     if ($args->{'showphotos'}) {
15975:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
15976:     }
15977:     $cenv{'internal.authtype'} = $args->{'authtype'};
15978:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
15979:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
15980:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
15981:             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'); 
15982:             if ($context eq 'auto') {
15983:                 $outcome .= $krb_msg;
15984:             } else {
15985:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
15986:             }
15987:             $outcome .= $linefeed;
15988:         }
15989:     }
15990:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
15991:        if ($args->{'setpolicy'}) {
15992:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15993:        }
15994:        if ($args->{'setcontent'}) {
15995:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15996:        }
15997:        if ($args->{'setcomment'}) {
15998:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15999:        }
16000:     }
16001:     if ($args->{'reshome'}) {
16002: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
16003: 	$cenv{'reshome'}=~s/\/+$/\//;
16004:     }
16005: #
16006: # course has keyed access
16007: #
16008:     if ($args->{'setkeys'}) {
16009:        $cenv{'keyaccess'}='yes';
16010:     }
16011: # if specified, key authority is not course, but user
16012: # only active if keyaccess is yes
16013:     if ($args->{'keyauth'}) {
16014: 	my ($user,$domain) = split(':',$args->{'keyauth'});
16015: 	$user = &LONCAPA::clean_username($user);
16016: 	$domain = &LONCAPA::clean_username($domain);
16017: 	if ($user ne '' && $domain ne '') {
16018: 	    $cenv{'keyauth'}=$user.':'.$domain;
16019: 	}
16020:     }
16021: 
16022: #
16023: #  generate and store uniquecode (available to course requester), if course should have one.
16024: #
16025:     if ($args->{'uniquecode'}) {
16026:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
16027:         if ($code) {
16028:             $cenv{'internal.uniquecode'} = $code;
16029:             my %crsinfo =
16030:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
16031:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
16032:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
16033:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
16034:             }
16035:             if (ref($coderef)) {
16036:                 $$coderef = $code;
16037:             }
16038:         }
16039:     }
16040: 
16041:     if ($args->{'disresdis'}) {
16042:         $cenv{'pch.roles.denied'}='st';
16043:     }
16044:     if ($args->{'disablechat'}) {
16045:         $cenv{'plc.roles.denied'}='st';
16046:     }
16047: 
16048:     # Record we've not yet viewed the Course Initialization Helper for this 
16049:     # course
16050:     $cenv{'course.helper.not.run'} = 1;
16051:     #
16052:     # Use new Randomseed
16053:     #
16054:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
16055:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
16056:     #
16057:     # The encryption code and receipt prefix for this course
16058:     #
16059:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
16060:     $cenv{'internal.encpref'}=100+int(9*rand(99));
16061:     #
16062:     # By default, use standard grading
16063:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
16064: 
16065:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
16066:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
16067: #
16068: # Open all assignments
16069: #
16070:     if ($args->{'openall'}) {
16071:        my $opendate = time;
16072:        if ($args->{'openallfrom'} =~ /^\d+$/) {
16073:            $opendate = $args->{'openallfrom'};
16074:        }
16075:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
16076:        my %storecontent = ($storeunder         => $opendate,
16077:                            $storeunder.'.type' => 'date_start');
16078:        $outcome .= &mt('All assignments open starting [_1]',
16079:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
16080:                    &Apache::lonnet::cput
16081:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
16082:    }
16083: #
16084: # Set first page
16085: #
16086:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
16087: 	    || ($cloneid)) {
16088: 	use LONCAPA::map;
16089: 	$outcome .= &mt('Setting first resource').': ';
16090: 
16091: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
16092:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
16093: 
16094:         $outcome .= ($fatal?$errtext:'read ok').' - ';
16095:         my $title; my $url;
16096:         if ($args->{'firstres'} eq 'syl') {
16097: 	    $title=&mt('Syllabus');
16098:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
16099:         } else {
16100:             $title=&mt('Table of Contents');
16101:             $url='/adm/navmaps';
16102:         }
16103: 
16104:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
16105: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
16106: 
16107: 	if ($errtext) { $fatal=2; }
16108:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
16109:     }
16110: 
16111:     return (1,$outcome,\@clonemsg);
16112: }
16113: 
16114: sub make_unique_code {
16115:     my ($cdom,$cnum) = @_;
16116:     # get lock on uniquecodes db
16117:     my $lockhash = {
16118:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
16119:                                                   ':'.$env{'user.domain'},
16120:                    };
16121:     my $tries = 0;
16122:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
16123:     my ($code,$error);
16124: 
16125:     while (($gotlock ne 'ok') && ($tries<3)) {
16126:         $tries ++;
16127:         sleep 1;
16128:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
16129:     }
16130:     if ($gotlock eq 'ok') {
16131:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
16132:         my $gotcode;
16133:         my $attempts = 0;
16134:         while ((!$gotcode) && ($attempts < 100)) {
16135:             $code = &generate_code();
16136:             if (!exists($currcodes{$code})) {
16137:                 $gotcode = 1;
16138:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
16139:                     $error = 'nostore';
16140:                 }
16141:             }
16142:             $attempts ++;
16143:         }
16144:         my @del_lock = ($cnum."\0".'uniquecodes');
16145:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
16146:     } else {
16147:         $error = 'nolock';
16148:     }
16149:     return ($code,$error);
16150: }
16151: 
16152: sub generate_code {
16153:     my $code;
16154:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
16155:     for (my $i=0; $i<6; $i++) {
16156:         my $lettnum = int (rand 2);
16157:         my $item = '';
16158:         if ($lettnum) {
16159:             $item = $letts[int( rand(18) )];
16160:         } else {
16161:             $item = 1+int( rand(8) );
16162:         }
16163:         $code .= $item;
16164:     }
16165:     return $code;
16166: }
16167: 
16168: ############################################################
16169: ############################################################
16170: 
16171: #SD
16172: # only Community and Course, or anything else?
16173: sub course_type {
16174:     my ($cid) = @_;
16175:     if (!defined($cid)) {
16176:         $cid = $env{'request.course.id'};
16177:     }
16178:     if (defined($env{'course.'.$cid.'.type'})) {
16179:         return $env{'course.'.$cid.'.type'};
16180:     } else {
16181:         return 'Course';
16182:     }
16183: }
16184: 
16185: sub group_term {
16186:     my $crstype = &course_type();
16187:     my %names = (
16188:                   'Course' => 'group',
16189:                   'Community' => 'group',
16190:                 );
16191:     return $names{$crstype};
16192: }
16193: 
16194: sub course_types {
16195:     my @types = ('official','unofficial','community','textbook');
16196:     my %typename = (
16197:                          official   => 'Official course',
16198:                          unofficial => 'Unofficial course',
16199:                          community  => 'Community',
16200:                          textbook   => 'Textbook course',
16201:                    );
16202:     return (\@types,\%typename);
16203: }
16204: 
16205: sub icon {
16206:     my ($file)=@_;
16207:     my $curfext = lc((split(/\./,$file))[-1]);
16208:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
16209:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
16210:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
16211: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
16212: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
16213: 	            $curfext.".gif") {
16214: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
16215: 		$curfext.".gif";
16216: 	}
16217:     }
16218:     return &lonhttpdurl($iconname);
16219: } 
16220: 
16221: sub lonhttpdurl {
16222: #
16223: # Had been used for "small fry" static images on separate port 8080.
16224: # Modify here if lightweight http functionality desired again.
16225: # Currently eliminated due to increasing firewall issues.
16226: #
16227:     my ($url)=@_;
16228:     return $url;
16229: }
16230: 
16231: sub connection_aborted {
16232:     my ($r)=@_;
16233:     $r->print(" ");$r->rflush();
16234:     my $c = $r->connection;
16235:     return $c->aborted();
16236: }
16237: 
16238: #    Escapes strings that may have embedded 's that will be put into
16239: #    strings as 'strings'.
16240: sub escape_single {
16241:     my ($input) = @_;
16242:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
16243:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
16244:     return $input;
16245: }
16246: 
16247: #  Same as escape_single, but escape's "'s  This 
16248: #  can be used for  "strings"
16249: sub escape_double {
16250:     my ($input) = @_;
16251:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
16252:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
16253:     return $input;
16254: }
16255:  
16256: #   Escapes the last element of a full URL.
16257: sub escape_url {
16258:     my ($url)   = @_;
16259:     my @urlslices = split(/\//, $url,-1);
16260:     my $lastitem = &escape(pop(@urlslices));
16261:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
16262: }
16263: 
16264: sub compare_arrays {
16265:     my ($arrayref1,$arrayref2) = @_;
16266:     my (@difference,%count);
16267:     @difference = ();
16268:     %count = ();
16269:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
16270:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
16271:         foreach my $element (keys(%count)) {
16272:             if ($count{$element} == 1) {
16273:                 push(@difference,$element);
16274:             }
16275:         }
16276:     }
16277:     return @difference;
16278: }
16279: 
16280: sub lon_status_items {
16281:     my %defaults = (
16282:                      E         => 100,
16283:                      W         => 4,
16284:                      N         => 1,
16285:                      U         => 5,
16286:                      threshold => 200,
16287:                      sysmail   => 2500,
16288:                    );
16289:     my %names = (
16290:                    E => 'Errors',
16291:                    W => 'Warnings',
16292:                    N => 'Notices',
16293:                    U => 'Unsent',
16294:                 );
16295:     return (\%defaults,\%names);
16296: }
16297: 
16298: # -------------------------------------------------------- Initialize user login
16299: sub init_user_environment {
16300:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
16301:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
16302: 
16303:     my $public=($username eq 'public' && $domain eq 'public');
16304: 
16305: # See if old ID present, if so, remove
16306: 
16307:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
16308:     my $now=time;
16309: 
16310:     if ($public) {
16311: 	my $max_public=100;
16312: 	my $oldest;
16313: 	my $oldest_time=0;
16314: 	for(my $next=1;$next<=$max_public;$next++) {
16315: 	    if (-e $lonids."/publicuser_$next.id") {
16316: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
16317: 		if ($mtime<$oldest_time || !$oldest_time) {
16318: 		    $oldest_time=$mtime;
16319: 		    $oldest=$next;
16320: 		}
16321: 	    } else {
16322: 		$cookie="publicuser_$next";
16323: 		last;
16324: 	    }
16325: 	}
16326: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
16327:     } else {
16328: 	# if this isn't a robot, kill any existing non-robot sessions
16329: 	if (!$args->{'robot'}) {
16330: 	    opendir(DIR,$lonids);
16331: 	    while ($filename=readdir(DIR)) {
16332: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
16333:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
16334:                             &GDBM_READER(),0640)) {
16335:                         my $linkedfile;
16336:                         if (exists($oldenv{'user.linkedenv'})) {
16337:                             $linkedfile = $oldenv{'user.linkedenv'};
16338:                         }
16339:                         untie(%oldenv);
16340:                         if (unlink("$lonids/$filename")) {
16341:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
16342:                                 if (-l "$lonids/$linkedfile.id") {
16343:                                     unlink("$lonids/$linkedfile.id");
16344:                                 }
16345:                             }
16346:                         }
16347:                     } else {
16348:                         unlink($lonids.'/'.$filename);
16349:                     }
16350: 		}
16351: 	    }
16352: 	    closedir(DIR);
16353: # If there is a undeleted lockfile for the user's paste buffer remove it.
16354:             my $namespace = 'nohist_courseeditor';
16355:             my $lockingkey = 'paste'."\0".'locked_num';
16356:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
16357:                                                 $domain,$username);
16358:             if (exists($lockhash{$lockingkey})) {
16359:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
16360:                 unless ($delresult eq 'ok') {
16361:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
16362:                 }
16363:             }
16364: 	}
16365: # Give them a new cookie
16366: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
16367: 		                   : $now.$$.int(rand(10000)));
16368: 	$cookie="$username\_$id\_$domain\_$authhost";
16369:     
16370: # Initialize roles
16371: 
16372: 	($userroles,$firstaccenv,$timerintenv) = 
16373:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
16374:     }
16375: # ------------------------------------ Check browser type and MathML capability
16376: 
16377:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
16378:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
16379: 
16380: # ------------------------------------------------------------- Get environment
16381: 
16382:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
16383:     my ($tmp) = keys(%userenv);
16384:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
16385:     } else {
16386: 	undef(%userenv);
16387:     }
16388:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
16389: 	$form->{'interface'}=$userenv{'interface'};
16390:     }
16391:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
16392: 
16393: # --------------- Do not trust query string to be put directly into environment
16394:     foreach my $option ('interface','localpath','localres') {
16395:         $form->{$option}=~s/[\n\r\=]//gs;
16396:     }
16397: # --------------------------------------------------------- Write first profile
16398: 
16399:     {
16400:         my $ip = &Apache::lonnet::get_requestor_ip();
16401: 	my %initial_env = 
16402: 	    ("user.name"          => $username,
16403: 	     "user.domain"        => $domain,
16404: 	     "user.home"          => $authhost,
16405: 	     "browser.type"       => $clientbrowser,
16406: 	     "browser.version"    => $clientversion,
16407: 	     "browser.mathml"     => $clientmathml,
16408: 	     "browser.unicode"    => $clientunicode,
16409: 	     "browser.os"         => $clientos,
16410:              "browser.mobile"     => $clientmobile,
16411:              "browser.info"       => $clientinfo,
16412:              "browser.osversion"  => $clientosversion,
16413: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
16414: 	     "request.course.fn"  => '',
16415: 	     "request.course.uri" => '',
16416: 	     "request.course.sec" => '',
16417: 	     "request.role"       => 'cm',
16418: 	     "request.role.adv"   => $env{'user.adv'},
16419: 	     "request.host"       => $ip,);
16420: 
16421:         if ($form->{'localpath'}) {
16422: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
16423: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
16424:         }
16425: 	
16426: 	if ($form->{'interface'}) {
16427: 	    $form->{'interface'}=~s/\W//gs;
16428: 	    $initial_env{"browser.interface"} = $form->{'interface'};
16429: 	    $env{'browser.interface'}=$form->{'interface'};
16430: 	}
16431: 
16432:         if ($form->{'iptoken'}) {
16433:             my $lonhost = $r->dir_config('lonHostID');
16434:             $initial_env{"user.noloadbalance"} = $lonhost;
16435:             $env{'user.noloadbalance'} = $lonhost;
16436:         }
16437: 
16438:         if ($form->{'noloadbalance'}) {
16439:             my @hosts = &Apache::lonnet::current_machine_ids();
16440:             my $hosthere = $form->{'noloadbalance'};
16441:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
16442:                 $initial_env{"user.noloadbalance"} = $hosthere;
16443:                 $env{'user.noloadbalance'} = $hosthere;
16444:             }
16445:         }
16446: 
16447:         unless ($domain eq 'public') {
16448:             my %is_adv = ( is_adv => $env{'user.adv'} );
16449:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
16450: 
16451:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
16452:                 $userenv{'availabletools.'.$tool} = 
16453:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
16454:                                                       undef,\%userenv,\%domdef,\%is_adv);
16455:             }
16456: 
16457:             foreach my $crstype ('official','unofficial','community','textbook') {
16458:                 $userenv{'canrequest.'.$crstype} =
16459:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
16460:                                                       'reload','requestcourses',
16461:                                                       \%userenv,\%domdef,\%is_adv);
16462:             }
16463: 
16464:             $userenv{'canrequest.author'} =
16465:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
16466:                                                   'reload','requestauthor',
16467:                                                   \%userenv,\%domdef,\%is_adv);
16468:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
16469:                                                  $domain,$username);
16470:             my $reqstatus = $reqauthor{'author_status'};
16471:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
16472:                 if (ref($reqauthor{'author'}) eq 'HASH') {
16473:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
16474:                                                       $reqauthor{'author'}{'timestamp'};
16475:                 }
16476:             }
16477:         }
16478: 
16479: 	$env{'user.environment'} = "$lonids/$cookie.id";
16480: 
16481: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
16482: 		 &GDBM_WRCREAT(),0640)) {
16483: 	    &_add_to_env(\%disk_env,\%initial_env);
16484: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
16485: 	    &_add_to_env(\%disk_env,$userroles);
16486:             if (ref($firstaccenv) eq 'HASH') {
16487:                 &_add_to_env(\%disk_env,$firstaccenv);
16488:             }
16489:             if (ref($timerintenv) eq 'HASH') {
16490:                 &_add_to_env(\%disk_env,$timerintenv);
16491:             }
16492: 	    if (ref($args->{'extra_env'})) {
16493: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
16494: 	    }
16495: 	    untie(%disk_env);
16496: 	} else {
16497: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
16498: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
16499: 	    return 'error: '.$!;
16500: 	}
16501:     }
16502:     $env{'request.role'}='cm';
16503:     $env{'request.role.adv'}=$env{'user.adv'};
16504:     $env{'browser.type'}=$clientbrowser;
16505: 
16506:     return $cookie;
16507: 
16508: }
16509: 
16510: sub _add_to_env {
16511:     my ($idf,$env_data,$prefix) = @_;
16512:     if (ref($env_data) eq 'HASH') {
16513:         while (my ($key,$value) = each(%$env_data)) {
16514: 	    $idf->{$prefix.$key} = $value;
16515: 	    $env{$prefix.$key}   = $value;
16516:         }
16517:     }
16518: }
16519: 
16520: # --- Get the symbolic name of a problem and the url
16521: sub get_symb {
16522:     my ($request,$silent) = @_;
16523:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
16524:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
16525:     if ($symb eq '') {
16526:         if (!$silent) {
16527:             if (ref($request)) { 
16528:                 $request->print("Unable to handle ambiguous references:$url:.");
16529:             }
16530:             return ();
16531:         }
16532:     }
16533:     &Apache::lonenc::check_decrypt(\$symb);
16534:     return ($symb);
16535: }
16536: 
16537: # --------------------------------------------------------------Get annotation
16538: 
16539: sub get_annotation {
16540:     my ($symb,$enc) = @_;
16541: 
16542:     my $key = $symb;
16543:     if (!$enc) {
16544:         $key =
16545:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
16546:     }
16547:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
16548:     return $annotation{$key};
16549: }
16550: 
16551: sub clean_symb {
16552:     my ($symb,$delete_enc) = @_;
16553: 
16554:     &Apache::lonenc::check_decrypt(\$symb);
16555:     my $enc = $env{'request.enc'};
16556:     if ($delete_enc) {
16557:         delete($env{'request.enc'});
16558:     }
16559: 
16560:     return ($symb,$enc);
16561: }
16562: 
16563: ############################################################
16564: ############################################################
16565: 
16566: =pod
16567: 
16568: =head1 Routines for building display used to search for courses
16569: 
16570: 
16571: =over 4
16572: 
16573: =item * &build_filters()
16574: 
16575: Create markup for a table used to set filters to use when selecting
16576: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
16577: and quotacheck.pl
16578: 
16579: 
16580: Inputs:
16581: 
16582: filterlist - anonymous array of fields to include as potential filters
16583: 
16584: crstype - course type
16585: 
16586: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
16587:               to pop-open a course selector (will contain "extra element").
16588: 
16589: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
16590: 
16591: filter - anonymous hash of criteria and their values
16592: 
16593: action - form action
16594: 
16595: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
16596: 
16597: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
16598: 
16599: cloneruname - username of owner of new course who wants to clone
16600: 
16601: clonerudom - domain of owner of new course who wants to clone
16602: 
16603: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
16604: 
16605: codetitlesref - reference to array of titles of components in institutional codes (official courses)
16606: 
16607: codedom - domain
16608: 
16609: formname - value of form element named "form".
16610: 
16611: fixeddom - domain, if fixed.
16612: 
16613: prevphase - value to assign to form element named "phase" when going back to the previous screen
16614: 
16615: cnameelement - name of form element in form on opener page which will receive title of selected course
16616: 
16617: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
16618: 
16619: cdomelement - name of form element in form on opener page which will receive domain of selected course
16620: 
16621: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
16622: 
16623: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
16624: 
16625: clonewarning - warning message about missing information for intended course owner when DC creates a course
16626: 
16627: 
16628: Returns: $output - HTML for display of search criteria, and hidden form elements.
16629: 
16630: 
16631: Side Effects: None
16632: 
16633: =cut
16634: 
16635: # ---------------------------------------------- search for courses based on last activity etc.
16636: 
16637: sub build_filters {
16638:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
16639:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
16640:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
16641:         $cnameelement,$cnumelement,$cdomelement,$setroles,
16642:         $clonetext,$clonewarning) = @_;
16643:     my ($list,$jscript);
16644:     my $onchange = 'javascript:updateFilters(this)';
16645:     my ($domainselectform,$sincefilterform,$createdfilterform,
16646:         $ownerdomselectform,$persondomselectform,$instcodeform,
16647:         $typeselectform,$instcodetitle);
16648:     if ($formname eq '') {
16649:         $formname = $caller;
16650:     }
16651:     foreach my $item (@{$filterlist}) {
16652:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
16653:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
16654:             if ($item eq 'domainfilter') {
16655:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
16656:             } elsif ($item eq 'coursefilter') {
16657:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
16658:             } elsif ($item eq 'ownerfilter') {
16659:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
16660:             } elsif ($item eq 'ownerdomfilter') {
16661:                 $filter->{'ownerdomfilter'} =
16662:                     &LONCAPA::clean_domain($filter->{$item});
16663:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
16664:                                                        'ownerdomfilter',1);
16665:             } elsif ($item eq 'personfilter') {
16666:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
16667:             } elsif ($item eq 'persondomfilter') {
16668:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
16669:                                                         'persondomfilter',1);
16670:             } else {
16671:                 $filter->{$item} =~ s/\W//g;
16672:             }
16673:             if (!$filter->{$item}) {
16674:                 $filter->{$item} = '';
16675:             }
16676:         }
16677:         if ($item eq 'domainfilter') {
16678:             my $allow_blank = 1;
16679:             if ($formname eq 'portform') {
16680:                 $allow_blank=0;
16681:             } elsif ($formname eq 'studentform') {
16682:                 $allow_blank=0;
16683:             }
16684:             if ($fixeddom) {
16685:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
16686:                                     ' value="'.$codedom.'" />'.
16687:                                     &Apache::lonnet::domain($codedom,'description');
16688:             } else {
16689:                 $domainselectform = &select_dom_form($filter->{$item},
16690:                                                      'domainfilter',
16691:                                                       $allow_blank,'',$onchange);
16692:             }
16693:         } else {
16694:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
16695:         }
16696:     }
16697: 
16698:     # last course activity filter and selection
16699:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
16700: 
16701:     # course created filter and selection
16702:     if (exists($filter->{'createdfilter'})) {
16703:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
16704:     }
16705: 
16706:     my %lt = &Apache::lonlocal::texthash(
16707:                 'cac' => "$crstype Activity",
16708:                 'ccr' => "$crstype Created",
16709:                 'cde' => "$crstype Title",
16710:                 'cdo' => "$crstype Domain",
16711:                 'ins' => 'Institutional Code',
16712:                 'inc' => 'Institutional Categorization',
16713:                 'cow' => "$crstype Owner/Co-owner",
16714:                 'cop' => "$crstype Personnel Includes",
16715:                 'cog' => 'Type',
16716:              );
16717: 
16718:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
16719:         my $typeval = 'Course';
16720:         if ($crstype eq 'Community') {
16721:             $typeval = 'Community';
16722:         }
16723:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
16724:     } else {
16725:         $typeselectform =  '<select name="type" size="1"';
16726:         if ($onchange) {
16727:             $typeselectform .= ' onchange="'.$onchange.'"';
16728:         }
16729:         $typeselectform .= '>'."\n";
16730:         foreach my $posstype ('Course','Community') {
16731:             $typeselectform.='<option value="'.$posstype.'"'.
16732:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
16733:         }
16734:         $typeselectform.="</select>";
16735:     }
16736: 
16737:     my ($cloneableonlyform,$cloneabletitle);
16738:     if (exists($filter->{'cloneableonly'})) {
16739:         my $cloneableon = '';
16740:         my $cloneableoff = ' checked="checked"';
16741:         if ($filter->{'cloneableonly'}) {
16742:             $cloneableon = $cloneableoff;
16743:             $cloneableoff = '';
16744:         }
16745:         $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>';
16746:         if ($formname eq 'ccrs') {
16747:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
16748:         } else {
16749:             $cloneabletitle = &mt('Cloneable by you');
16750:         }
16751:     }
16752:     my $officialjs;
16753:     if ($crstype eq 'Course') {
16754:         if (exists($filter->{'instcodefilter'})) {
16755: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
16756: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
16757:             if ($codedom) {
16758:                 $officialjs = 1;
16759:                 ($instcodeform,$jscript,$$numtitlesref) =
16760:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
16761:                                                                   $officialjs,$codetitlesref);
16762:                 if ($jscript) {
16763:                     $jscript = '<script type="text/javascript">'."\n".
16764:                                '// <![CDATA['."\n".
16765:                                $jscript."\n".
16766:                                '// ]]>'."\n".
16767:                                '</script>'."\n";
16768:                 }
16769:             }
16770:             if ($instcodeform eq '') {
16771:                 $instcodeform =
16772:                     '<input type="text" name="instcodefilter" size="10" value="'.
16773:                     $list->{'instcodefilter'}.'" />';
16774:                 $instcodetitle = $lt{'ins'};
16775:             } else {
16776:                 $instcodetitle = $lt{'inc'};
16777:             }
16778:             if ($fixeddom) {
16779:                 $instcodetitle .= '<br />('.$codedom.')';
16780:             }
16781:         }
16782:     }
16783:     my $output = qq|
16784: <form method="post" name="filterpicker" action="$action">
16785: <input type="hidden" name="form" value="$formname" />
16786: |;
16787:     if ($formname eq 'modifycourse') {
16788:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
16789:                    '<input type="hidden" name="prevphase" value="'.
16790:                    $prevphase.'" />'."\n";
16791:     } elsif ($formname eq 'quotacheck') {
16792:         $output .= qq|
16793: <input type="hidden" name="sortby" value="" />
16794: <input type="hidden" name="sortorder" value="" />
16795: |;
16796:     } else {
16797:         my $name_input;
16798:         if ($cnameelement ne '') {
16799:             $name_input = '<input type="hidden" name="cnameelement" value="'.
16800:                           $cnameelement.'" />';
16801:         }
16802:         $output .= qq|
16803: <input type="hidden" name="cnumelement" value="$cnumelement" />
16804: <input type="hidden" name="cdomelement" value="$cdomelement" />
16805: $name_input
16806: $roleelement
16807: $multelement
16808: $typeelement
16809: |;
16810:         if ($formname eq 'portform') {
16811:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
16812:         }
16813:     }
16814:     if ($fixeddom) {
16815:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
16816:     }
16817:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
16818:     if ($sincefilterform) {
16819:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
16820:                   .$sincefilterform
16821:                   .&Apache::lonhtmlcommon::row_closure();
16822:     }
16823:     if ($createdfilterform) {
16824:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
16825:                   .$createdfilterform
16826:                   .&Apache::lonhtmlcommon::row_closure();
16827:     }
16828:     if ($domainselectform) {
16829:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
16830:                   .$domainselectform
16831:                   .&Apache::lonhtmlcommon::row_closure();
16832:     }
16833:     if ($typeselectform) {
16834:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
16835:             $output .= $typeselectform;
16836:         } else {
16837:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
16838:                       .$typeselectform
16839:                       .&Apache::lonhtmlcommon::row_closure();
16840:         }
16841:     }
16842:     if ($instcodeform) {
16843:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
16844:                   .$instcodeform
16845:                   .&Apache::lonhtmlcommon::row_closure();
16846:     }
16847:     if (exists($filter->{'ownerfilter'})) {
16848:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
16849:                    '<table><tr><td>'.&mt('Username').'<br />'.
16850:                    '<input type="text" name="ownerfilter" size="20" value="'.
16851:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
16852:                    $ownerdomselectform.'</td></tr></table>'.
16853:                    &Apache::lonhtmlcommon::row_closure();
16854:     }
16855:     if (exists($filter->{'personfilter'})) {
16856:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
16857:                    '<table><tr><td>'.&mt('Username').'<br />'.
16858:                    '<input type="text" name="personfilter" size="20" value="'.
16859:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
16860:                    $persondomselectform.'</td></tr></table>'.
16861:                    &Apache::lonhtmlcommon::row_closure();
16862:     }
16863:     if (exists($filter->{'coursefilter'})) {
16864:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
16865:                   .'<input type="text" name="coursefilter" size="25" value="'
16866:                   .$list->{'coursefilter'}.'" />'
16867:                   .&Apache::lonhtmlcommon::row_closure();
16868:     }
16869:     if ($cloneableonlyform) {
16870:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
16871:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
16872:     }
16873:     if (exists($filter->{'descriptfilter'})) {
16874:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
16875:                   .'<input type="text" name="descriptfilter" size="40" value="'
16876:                   .$list->{'descriptfilter'}.'" />'
16877:                   .&Apache::lonhtmlcommon::row_closure(1);
16878:     }
16879:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
16880:                '<input type="hidden" name="updater" value="" />'."\n".
16881:                '<input type="submit" name="gosearch" value="'.
16882:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
16883:     return $jscript.$clonewarning.$output;
16884: }
16885: 
16886: =pod
16887: 
16888: =item * &timebased_select_form()
16889: 
16890: Create markup for a dropdown list used to select a time-based
16891: filter e.g., Course Activity, Course Created, when searching for courses
16892: or communities
16893: 
16894: Inputs:
16895: 
16896: item - name of form element (sincefilter or createdfilter)
16897: 
16898: filter - anonymous hash of criteria and their values
16899: 
16900: Returns: HTML for a select box contained a blank, then six time selections,
16901:          with value set in incoming form variables currently selected.
16902: 
16903: Side Effects: None
16904: 
16905: =cut
16906: 
16907: sub timebased_select_form {
16908:     my ($item,$filter) = @_;
16909:     if (ref($filter) eq 'HASH') {
16910:         $filter->{$item} =~ s/[^\d-]//g;
16911:         if (!$filter->{$item}) { $filter->{$item}=-1; }
16912:         return &select_form(
16913:                             $filter->{$item},
16914:                             $item,
16915:                             {      '-1' => '',
16916:                                 '86400' => &mt('today'),
16917:                                '604800' => &mt('last week'),
16918:                               '2592000' => &mt('last month'),
16919:                               '7776000' => &mt('last three months'),
16920:                              '15552000' => &mt('last six months'),
16921:                              '31104000' => &mt('last year'),
16922:                     'select_form_order' =>
16923:                            ['-1','86400','604800','2592000','7776000',
16924:                             '15552000','31104000']});
16925:     }
16926: }
16927: 
16928: =pod
16929: 
16930: =item * &js_changer()
16931: 
16932: Create script tag containing Javascript used to submit course search form
16933: when course type or domain is changed, and also to hide 'Searching ...' on
16934: page load completion for page showing search result.
16935: 
16936: Inputs: None
16937: 
16938: Returns: markup containing updateFilters() and hideSearching() javascript functions.
16939: 
16940: Side Effects: None
16941: 
16942: =cut
16943: 
16944: sub js_changer {
16945:     return <<ENDJS;
16946: <script type="text/javascript">
16947: // <![CDATA[
16948: function updateFilters(caller) {
16949:     if (typeof(caller) != "undefined") {
16950:         document.filterpicker.updater.value = caller.name;
16951:     }
16952:     document.filterpicker.submit();
16953: }
16954: 
16955: function hideSearching() {
16956:     if (document.getElementById('searching')) {
16957:         document.getElementById('searching').style.display = 'none';
16958:     }
16959:     return;
16960: }
16961: 
16962: // ]]>
16963: </script>
16964: 
16965: ENDJS
16966: }
16967: 
16968: =pod
16969: 
16970: =item * &search_courses()
16971: 
16972: Process selected filters form course search form and pass to lonnet::courseiddump
16973: to retrieve a hash for which keys are courseIDs which match the selected filters.
16974: 
16975: Inputs:
16976: 
16977: dom - domain being searched
16978: 
16979: type - course type ('Course' or 'Community' or '.' if any).
16980: 
16981: filter - anonymous hash of criteria and their values
16982: 
16983: numtitles - for institutional codes - number of categories
16984: 
16985: cloneruname - optional username of new course owner
16986: 
16987: clonerudom - optional domain of new course owner
16988: 
16989: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
16990:             (used when DC is using course creation form)
16991: 
16992: codetitles - reference to array of titles of components in institutional codes (official courses).
16993: 
16994: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
16995:            (and so can clone automatically)
16996: 
16997: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
16998: 
16999: reqinstcode - institutional code of new course, where search_courses is used to identify potential
17000:               courses to clone
17001: 
17002: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
17003: 
17004: 
17005: Side Effects: None
17006: 
17007: =cut
17008: 
17009: 
17010: sub search_courses {
17011:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
17012:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
17013:     my (%courses,%showcourses,$cloner);
17014:     if (($filter->{'ownerfilter'} ne '') ||
17015:         ($filter->{'ownerdomfilter'} ne '')) {
17016:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
17017:                                        $filter->{'ownerdomfilter'};
17018:     }
17019:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
17020:         if (!$filter->{$item}) {
17021:             $filter->{$item}='.';
17022:         }
17023:     }
17024:     my $now = time;
17025:     my $timefilter =
17026:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
17027:     my ($createdbefore,$createdafter);
17028:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
17029:         $createdbefore = $now;
17030:         $createdafter = $now-$filter->{'createdfilter'};
17031:     }
17032:     my ($instcodefilter,$regexpok);
17033:     if ($numtitles) {
17034:         if ($env{'form.official'} eq 'on') {
17035:             $instcodefilter =
17036:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
17037:             $regexpok = 1;
17038:         } elsif ($env{'form.official'} eq 'off') {
17039:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
17040:             unless ($instcodefilter eq '') {
17041:                 $regexpok = -1;
17042:             }
17043:         }
17044:     } else {
17045:         $instcodefilter = $filter->{'instcodefilter'};
17046:     }
17047:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
17048:     if ($type eq '') { $type = '.'; }
17049: 
17050:     if (($clonerudom ne '') && ($cloneruname ne '')) {
17051:         $cloner = $cloneruname.':'.$clonerudom;
17052:     }
17053:     %courses = &Apache::lonnet::courseiddump($dom,
17054:                                              $filter->{'descriptfilter'},
17055:                                              $timefilter,
17056:                                              $instcodefilter,
17057:                                              $filter->{'combownerfilter'},
17058:                                              $filter->{'coursefilter'},
17059:                                              undef,undef,$type,$regexpok,undef,undef,
17060:                                              undef,undef,$cloner,$cc_clone,
17061:                                              $filter->{'cloneableonly'},
17062:                                              $createdbefore,$createdafter,undef,
17063:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
17064:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
17065:         my $ccrole;
17066:         if ($type eq 'Community') {
17067:             $ccrole = 'co';
17068:         } else {
17069:             $ccrole = 'cc';
17070:         }
17071:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
17072:                                                      $filter->{'persondomfilter'},
17073:                                                      'userroles',undef,
17074:                                                      [$ccrole,'in','ad','ep','ta','cr'],
17075:                                                      $dom);
17076:         foreach my $role (keys(%rolehash)) {
17077:             my ($cnum,$cdom,$courserole) = split(':',$role);
17078:             my $cid = $cdom.'_'.$cnum;
17079:             if (exists($courses{$cid})) {
17080:                 if (ref($courses{$cid}) eq 'HASH') {
17081:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
17082:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
17083:                             push(@{$courses{$cid}{roles}},$courserole);
17084:                         }
17085:                     } else {
17086:                         $courses{$cid}{roles} = [$courserole];
17087:                     }
17088:                     $showcourses{$cid} = $courses{$cid};
17089:                 }
17090:             }
17091:         }
17092:         %courses = %showcourses;
17093:     }
17094:     return %courses;
17095: }
17096: 
17097: =pod
17098: 
17099: =back
17100: 
17101: =head1 Routines for version requirements for current course.
17102: 
17103: =over 4
17104: 
17105: =item * &check_release_required()
17106: 
17107: Compares required LON-CAPA version with version on server, and
17108: if required version is newer looks for a server with the required version.
17109: 
17110: Looks first at servers in user's owen domain; if none suitable, looks at
17111: servers in course's domain are permitted to host sessions for user's domain.
17112: 
17113: Inputs:
17114: 
17115: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
17116: 
17117: $courseid - Course ID of current course
17118: 
17119: $rolecode - User's current role in course (for switchserver query string).
17120: 
17121: $required - LON-CAPA version needed by course (format: Major.Minor).
17122: 
17123: 
17124: Returns:
17125: 
17126: $switchserver - query string tp append to /adm/switchserver call (if
17127:                 current server's LON-CAPA version is too old.
17128: 
17129: $warning - Message is displayed if no suitable server could be found.
17130: 
17131: =cut
17132: 
17133: sub check_release_required {
17134:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
17135:     my ($switchserver,$warning);
17136:     if ($required ne '') {
17137:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
17138:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
17139:         if ($reqdmajor ne '' && $reqdminor ne '') {
17140:             my $otherserver;
17141:             if (($major eq '' && $minor eq '') ||
17142:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
17143:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
17144:                 my $switchlcrev =
17145:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
17146:                                                            $userdomserver);
17147:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
17148:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
17149:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
17150:                     my $cdom = $env{'course.'.$courseid.'.domain'};
17151:                     if ($cdom ne $env{'user.domain'}) {
17152:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
17153:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
17154:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
17155:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
17156:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
17157:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
17158:                         my $canhost =
17159:                             &Apache::lonnet::can_host_session($env{'user.domain'},
17160:                                                               $coursedomserver,
17161:                                                               $remoterev,
17162:                                                               $udomdefaults{'remotesessions'},
17163:                                                               $defdomdefaults{'hostedsessions'});
17164: 
17165:                         if ($canhost) {
17166:                             $otherserver = $coursedomserver;
17167:                         } else {
17168:                             $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.");
17169:                         }
17170:                     } else {
17171:                         $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).");
17172:                     }
17173:                 } else {
17174:                     $otherserver = $userdomserver;
17175:                 }
17176:             }
17177:             if ($otherserver ne '') {
17178:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
17179:             }
17180:         }
17181:     }
17182:     return ($switchserver,$warning);
17183: }
17184: 
17185: =pod
17186: 
17187: =item * &check_release_result()
17188: 
17189: Inputs:
17190: 
17191: $switchwarning - Warning message if no suitable server found to host session.
17192: 
17193: $switchserver - query string to append to /adm/switchserver containing lonHostID
17194:                 and current role.
17195: 
17196: Returns: HTML to display with information about requirement to switch server.
17197:          Either displaying warning with link to Roles/Courses screen or
17198:          display link to switchserver.
17199: 
17200: =cut
17201: 
17202: sub check_release_result {
17203:     my ($switchwarning,$switchserver) = @_;
17204:     my $output = &start_page('Selected course unavailable on this server').
17205:                  '<p class="LC_warning">';
17206:     if ($switchwarning) {
17207:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
17208:         if (&show_course()) {
17209:             $output .= &mt('Display courses');
17210:         } else {
17211:             $output .= &mt('Display roles');
17212:         }
17213:         $output .= '</a>';
17214:     } elsif ($switchserver) {
17215:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
17216:                    '<br />'.
17217:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
17218:                    &mt('Switch Server').
17219:                    '</a>';
17220:     }
17221:     $output .= '</p>'.&end_page();
17222:     return $output;
17223: }
17224: 
17225: =pod
17226: 
17227: =item * &needs_coursereinit()
17228: 
17229: Determine if course contents stored for user's session needs to be
17230: refreshed, because content has changed since "Big Hash" last tied.
17231: 
17232: Check for change is made if time last checked is more than 10 minutes ago
17233: (by default).
17234: 
17235: Inputs:
17236: 
17237: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
17238: 
17239: $interval (optional) - Time which may elapse (in s) between last check for content
17240:                        change in current course. (default: 600 s).
17241: 
17242: Returns: an array; first element is:
17243: 
17244: =over 4
17245: 
17246: 'switch' - if content updates mean user's session
17247:            needs to be switched to a server running a newer LON-CAPA version
17248: 
17249: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
17250:            on current server hosting user's session
17251: 
17252: ''       - if no action required.
17253: 
17254: =back
17255: 
17256: If first item element is 'switch':
17257: 
17258: second item is $switchwarning - Warning message if no suitable server found to host session.
17259: 
17260: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
17261:                               and current role.
17262: 
17263: otherwise: no other elements returned.
17264: 
17265: =back
17266: 
17267: =cut
17268: 
17269: sub needs_coursereinit {
17270:     my ($loncaparev,$interval) = @_;
17271:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
17272:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
17273:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
17274:     my $now = time;
17275:     if ($interval eq '') {
17276:         $interval = 600;
17277:     }
17278:     if (($now-$env{'request.course.timechecked'})>$interval) {
17279:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
17280:         my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
17281:         if ($blocked) {
17282:             return ();
17283:         }
17284:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
17285:         if ($lastchange > $env{'request.course.tied'}) {
17286:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
17287:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
17288:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
17289:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
17290:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
17291:                                              $curr_reqd_hash{'internal.releaserequired'}});
17292:                     my ($switchserver,$switchwarning) =
17293:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
17294:                                                 $curr_reqd_hash{'internal.releaserequired'});
17295:                     if ($switchwarning ne '' || $switchserver ne '') {
17296:                         return ('switch',$switchwarning,$switchserver);
17297:                     }
17298:                 }
17299:             }
17300:             return ('update');
17301:         }
17302:     }
17303:     return ();
17304: }
17305: 
17306: sub update_content_constraints {
17307:     my ($cdom,$cnum,$chome,$cid) = @_;
17308:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
17309:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
17310:     my %checkresponsetypes;
17311:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
17312:         my ($item,$name,$value) = split(/:/,$key);
17313:         if ($item eq 'resourcetag') {
17314:             if ($name eq 'responsetype') {
17315:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
17316:             }
17317:         }
17318:     }
17319:     my $navmap = Apache::lonnavmaps::navmap->new();
17320:     if (defined($navmap)) {
17321:         my %allresponses;
17322:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
17323:             my %responses = $res->responseTypes();
17324:             foreach my $key (keys(%responses)) {
17325:                 next unless(exists($checkresponsetypes{$key}));
17326:                 $allresponses{$key} += $responses{$key};
17327:             }
17328:         }
17329:         foreach my $key (keys(%allresponses)) {
17330:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
17331:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
17332:                 ($reqdmajor,$reqdminor) = ($major,$minor);
17333:             }
17334:         }
17335:         undef($navmap);
17336:     }
17337:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
17338:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
17339:     }
17340:     return;
17341: }
17342: 
17343: sub allmaps_incourse {
17344:     my ($cdom,$cnum,$chome,$cid) = @_;
17345:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
17346:         $cid = $env{'request.course.id'};
17347:         $cdom = $env{'course.'.$cid.'.domain'};
17348:         $cnum = $env{'course.'.$cid.'.num'};
17349:         $chome = $env{'course.'.$cid.'.home'};
17350:     }
17351:     my %allmaps = ();
17352:     my $lastchange =
17353:         &Apache::lonnet::get_coursechange($cdom,$cnum);
17354:     if ($lastchange > $env{'request.course.tied'}) {
17355:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
17356:         unless ($ferr) {
17357:             &update_content_constraints($cdom,$cnum,$chome,$cid);
17358:         }
17359:     }
17360:     my $navmap = Apache::lonnavmaps::navmap->new();
17361:     if (defined($navmap)) {
17362:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
17363:             $allmaps{$res->src()} = 1;
17364:         }
17365:     }
17366:     return \%allmaps;
17367: }
17368: 
17369: sub parse_supplemental_title {
17370:     my ($title) = @_;
17371: 
17372:     my ($foldertitle,$renametitle);
17373:     if ($title =~ /&amp;&amp;&amp;/) {
17374:         $title = &HTML::Entites::decode($title);
17375:     }
17376:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
17377:         $renametitle=$4;
17378:         my ($time,$uname,$udom) = ($1,$2,$3);
17379:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
17380:         my $name =  &plainname($uname,$udom);
17381:         $name = &HTML::Entities::encode($name,'"<>&\'');
17382:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
17383:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
17384:             $name.': <br />'.$foldertitle;
17385:     }
17386:     if (wantarray) {
17387:         return ($title,$foldertitle,$renametitle);
17388:     }
17389:     return $title;
17390: }
17391: 
17392: sub recurse_supplemental {
17393:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
17394:     if ($suppmap) {
17395:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
17396:         if ($fatal) {
17397:             $errors ++;
17398:         } else {
17399:             if ($#LONCAPA::map::resources > 0) {
17400:                 foreach my $res (@LONCAPA::map::resources) {
17401:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
17402:                     if (($src ne '') && ($status eq 'res')) {
17403:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
17404:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
17405:                         } else {
17406:                             $numfiles ++;
17407:                         }
17408:                     }
17409:                 }
17410:             }
17411:         }
17412:     }
17413:     return ($numfiles,$errors);
17414: }
17415: 
17416: sub symb_to_docspath {
17417:     my ($symb,$navmapref) = @_;
17418:     return unless ($symb && ref($navmapref));
17419:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
17420:     if ($resurl=~/\.(sequence|page)$/) {
17421:         $mapurl=$resurl;
17422:     } elsif ($resurl eq 'adm/navmaps') {
17423:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
17424:     }
17425:     my $mapresobj;
17426:     unless (ref($$navmapref)) {
17427:         $$navmapref = Apache::lonnavmaps::navmap->new();
17428:     }
17429:     if (ref($$navmapref)) {
17430:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
17431:     }
17432:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
17433:     my $type=$2;
17434:     my $path;
17435:     if (ref($mapresobj)) {
17436:         my $pcslist = $mapresobj->map_hierarchy();
17437:         if ($pcslist ne '') {
17438:             foreach my $pc (split(/,/,$pcslist)) {
17439:                 next if ($pc <= 1);
17440:                 my $res = $$navmapref->getByMapPc($pc);
17441:                 if (ref($res)) {
17442:                     my $thisurl = $res->src();
17443:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
17444:                     my $thistitle = $res->title();
17445:                     $path .= '&'.
17446:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
17447:                              &escape($thistitle).
17448:                              ':'.$res->randompick().
17449:                              ':'.$res->randomout().
17450:                              ':'.$res->encrypted().
17451:                              ':'.$res->randomorder().
17452:                              ':'.$res->is_page();
17453:                 }
17454:             }
17455:         }
17456:         $path =~ s/^\&//;
17457:         my $maptitle = $mapresobj->title();
17458:         if ($mapurl eq 'default') {
17459:             $maptitle = 'Main Content';
17460:         }
17461:         $path .= (($path ne '')? '&' : '').
17462:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
17463:                  &escape($maptitle).
17464:                  ':'.$mapresobj->randompick().
17465:                  ':'.$mapresobj->randomout().
17466:                  ':'.$mapresobj->encrypted().
17467:                  ':'.$mapresobj->randomorder().
17468:                  ':'.$mapresobj->is_page();
17469:     } else {
17470:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
17471:         my $ispage = (($type eq 'page')? 1 : '');
17472:         if ($mapurl eq 'default') {
17473:             $maptitle = 'Main Content';
17474:         }
17475:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
17476:                 &escape($maptitle).':::::'.$ispage;
17477:     }
17478:     unless ($mapurl eq 'default') {
17479:         $path = 'default&'.
17480:                 &escape('Main Content').
17481:                 ':::::&'.$path;
17482:     }
17483:     return $path;
17484: }
17485: 
17486: sub captcha_display {
17487:     my ($context,$lonhost,$defdom) = @_;
17488:     my ($output,$error);
17489:     my ($captcha,$pubkey,$privkey,$version) =
17490:         &get_captcha_config($context,$lonhost,$defdom);
17491:     if ($captcha eq 'original') {
17492:         $output = &create_captcha();
17493:         unless ($output) {
17494:             $error = 'captcha';
17495:         }
17496:     } elsif ($captcha eq 'recaptcha') {
17497:         $output = &create_recaptcha($pubkey,$version);
17498:         unless ($output) {
17499:             $error = 'recaptcha';
17500:         }
17501:     }
17502:     return ($output,$error,$captcha,$version);
17503: }
17504: 
17505: sub captcha_response {
17506:     my ($context,$lonhost,$defdom) = @_;
17507:     my ($captcha_chk,$captcha_error);
17508:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
17509:     if ($captcha eq 'original') {
17510:         ($captcha_chk,$captcha_error) = &check_captcha();
17511:     } elsif ($captcha eq 'recaptcha') {
17512:         $captcha_chk = &check_recaptcha($privkey,$version);
17513:     } else {
17514:         $captcha_chk = 1;
17515:     }
17516:     return ($captcha_chk,$captcha_error);
17517: }
17518: 
17519: sub get_captcha_config {
17520:     my ($context,$lonhost,$dom_in_effect) = @_;
17521:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
17522:     my $hostname = &Apache::lonnet::hostname($lonhost);
17523:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
17524:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
17525:     if ($context eq 'usercreation') {
17526:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
17527:         if (ref($domconfig{$context}) eq 'HASH') {
17528:             $hashtocheck = $domconfig{$context}{'cancreate'};
17529:             if (ref($hashtocheck) eq 'HASH') {
17530:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
17531:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
17532:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
17533:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
17534:                     }
17535:                     if ($privkey && $pubkey) {
17536:                         $captcha = 'recaptcha';
17537:                         $version = $hashtocheck->{'recaptchaversion'};
17538:                         if ($version ne '2') {
17539:                             $version = 1;
17540:                         }
17541:                     } else {
17542:                         $captcha = 'original';
17543:                     }
17544:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
17545:                     $captcha = 'original';
17546:                 }
17547:             }
17548:         } else {
17549:             $captcha = 'captcha';
17550:         }
17551:     } elsif ($context eq 'login') {
17552:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
17553:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
17554:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
17555:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
17556:             if ($privkey && $pubkey) {
17557:                 $captcha = 'recaptcha';
17558:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
17559:                 if ($version ne '2') {
17560:                     $version = 1;
17561:                 }
17562:             } else {
17563:                 $captcha = 'original';
17564:             }
17565:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
17566:             $captcha = 'original';
17567:         }
17568:     } elsif ($context eq 'passwords') {
17569:         if ($dom_in_effect) {
17570:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
17571:             if ($passwdconf{'captcha'} eq 'recaptcha') {
17572:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
17573:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
17574:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
17575:                 }
17576:                 if ($privkey && $pubkey) {
17577:                     $captcha = 'recaptcha';
17578:                     $version = $passwdconf{'recaptchaversion'};
17579:                     if ($version ne '2') {
17580:                         $version = 1;
17581:                     }
17582:                 } else {
17583:                     $captcha = 'original';
17584:                 }
17585:             } elsif ($passwdconf{'captcha'} ne 'notused') {
17586:                 $captcha = 'original';
17587:             }
17588:         }
17589:     }
17590:     return ($captcha,$pubkey,$privkey,$version);
17591: }
17592: 
17593: sub create_captcha {
17594:     my %captcha_params = &captcha_settings();
17595:     my ($output,$maxtries,$tries) = ('',10,0);
17596:     while ($tries < $maxtries) {
17597:         $tries ++;
17598:         my $captcha = Authen::Captcha->new (
17599:                                            output_folder => $captcha_params{'output_dir'},
17600:                                            data_folder   => $captcha_params{'db_dir'},
17601:                                           );
17602:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
17603: 
17604:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
17605:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
17606:                       '<span class="LC_nobreak">'.
17607:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
17608:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
17609:                       '</span><br />'.
17610:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
17611:             last;
17612:         }
17613:     }
17614:     if ($output eq '') {
17615:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
17616:     }
17617:     return $output;
17618: }
17619: 
17620: sub captcha_settings {
17621:     my %captcha_params = (
17622:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
17623:                            www_output_dir => "/captchaspool",
17624:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
17625:                            numchars       => '5',
17626:                          );
17627:     return %captcha_params;
17628: }
17629: 
17630: sub check_captcha {
17631:     my ($captcha_chk,$captcha_error);
17632:     my $code = $env{'form.code'};
17633:     my $md5sum = $env{'form.crypt'};
17634:     my %captcha_params = &captcha_settings();
17635:     my $captcha = Authen::Captcha->new(
17636:                       output_folder => $captcha_params{'output_dir'},
17637:                       data_folder   => $captcha_params{'db_dir'},
17638:                   );
17639:     $captcha_chk = $captcha->check_code($code,$md5sum);
17640:     my %captcha_hash = (
17641:                         0       => 'Code not checked (file error)',
17642:                        -1      => 'Failed: code expired',
17643:                        -2      => 'Failed: invalid code (not in database)',
17644:                        -3      => 'Failed: invalid code (code does not match crypt)',
17645:     );
17646:     if ($captcha_chk != 1) {
17647:         $captcha_error = $captcha_hash{$captcha_chk}
17648:     }
17649:     return ($captcha_chk,$captcha_error);
17650: }
17651: 
17652: sub create_recaptcha {
17653:     my ($pubkey,$version) = @_;
17654:     if ($version >= 2) {
17655:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
17656:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
17657:     } else {
17658:         my $use_ssl;
17659:         if ($ENV{'SERVER_PORT'} == 443) {
17660:             $use_ssl = 1;
17661:         }
17662:         my $captcha = Captcha::reCAPTCHA->new;
17663:         return $captcha->get_options_setter({theme => 'white'})."\n".
17664:                $captcha->get_html($pubkey,undef,$use_ssl).
17665:                &mt('If the text is hard to read, [_1] will replace them.',
17666:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
17667:                '<br /><br />';
17668:      }
17669: }
17670: 
17671: sub check_recaptcha {
17672:     my ($privkey,$version) = @_;
17673:     my $captcha_chk;
17674:     my $ip = &Apache::lonnet::get_requestor_ip(); 
17675:     if ($version >= 2) {
17676:         my $ua = LWP::UserAgent->new;
17677:         $ua->timeout(10);
17678:         my %info = (
17679:                      secret   => $privkey,
17680:                      response => $env{'form.g-recaptcha-response'},
17681:                      remoteip => $ip,
17682:                    );
17683:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
17684:         if ($response->is_success)  {
17685:             my $data = JSON::DWIW->from_json($response->decoded_content);
17686:             if (ref($data) eq 'HASH') {
17687:                 if ($data->{'success'}) {
17688:                     $captcha_chk = 1;
17689:                 }
17690:             }
17691:         }
17692:     } else {
17693:         my $captcha = Captcha::reCAPTCHA->new;
17694:         my $captcha_result =
17695:             $captcha->check_answer(
17696:                                     $privkey,
17697:                                     $ip,
17698:                                     $env{'form.recaptcha_challenge_field'},
17699:                                     $env{'form.recaptcha_response_field'},
17700:                                   );
17701:         if ($captcha_result->{is_valid}) {
17702:             $captcha_chk = 1;
17703:         }
17704:     }
17705:     return $captcha_chk;
17706: }
17707: 
17708: sub emailusername_info {
17709:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
17710:     my %titles = &Apache::lonlocal::texthash (
17711:                      lastname      => 'Last Name',
17712:                      firstname     => 'First Name',
17713:                      institution   => 'School/college/university',
17714:                      location      => "School's city, state/province, country",
17715:                      web           => "School's web address",
17716:                      officialemail => 'E-mail address at institution (if different)',
17717:                      id            => 'Student/Employee ID',
17718:                  );
17719:     return (\@fields,\%titles);
17720: }
17721: 
17722: sub cleanup_html {
17723:     my ($incoming) = @_;
17724:     my $outgoing;
17725:     if ($incoming ne '') {
17726:         $outgoing = $incoming;
17727:         $outgoing =~ s/;/&#059;/g;
17728:         $outgoing =~ s/\#/&#035;/g;
17729:         $outgoing =~ s/\&/&#038;/g;
17730:         $outgoing =~ s/</&#060;/g;
17731:         $outgoing =~ s/>/&#062;/g;
17732:         $outgoing =~ s/\(/&#040/g;
17733:         $outgoing =~ s/\)/&#041;/g;
17734:         $outgoing =~ s/"/&#034;/g;
17735:         $outgoing =~ s/'/&#039;/g;
17736:         $outgoing =~ s/\$/&#036;/g;
17737:         $outgoing =~ s{/}{&#047;}g;
17738:         $outgoing =~ s/=/&#061;/g;
17739:         $outgoing =~ s/\\/&#092;/g
17740:     }
17741:     return $outgoing;
17742: }
17743: 
17744: # Checks for critical messages and returns a redirect url if one exists.
17745: # $interval indicates how often to check for messages.
17746: # $context is the calling context -- roles, grades, contents, menu or flip.
17747: sub critical_redirect {
17748:     my ($interval,$context) = @_;
17749:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
17750:         return ();
17751:     }
17752:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
17753:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
17754:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
17755:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
17756:             my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
17757:             if ($blocked) {
17758:                 my $checkrole = "cm./$cdom/$cnum";
17759:                 if ($env{'request.course.sec'} ne '') {
17760:                     $checkrole .= "/$env{'request.course.sec'}";
17761:                 }
17762:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
17763:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
17764:                     return;
17765:                 }
17766:             }
17767:         }
17768:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
17769:                                         $env{'user.name'});
17770:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
17771:         my $redirecturl;
17772:         if ($what[0]) {
17773:             if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
17774:                 $redirecturl='/adm/email?critical=display';
17775:                 my $url=&Apache::lonnet::absolute_url().$redirecturl;
17776:                 return (1, $url);
17777:             }
17778:         }
17779:     }
17780:     return ();
17781: }
17782: 
17783: # Use:
17784: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
17785: #
17786: ##################################################
17787: #          password associated functions         #
17788: ##################################################
17789: sub des_keys {
17790:     # Make a new key for DES encryption.
17791:     # Each key has two parts which are returned separately.
17792:     # Please note:  Each key must be passed through the &hex function
17793:     # before it is output to the web browser.  The hex versions cannot
17794:     # be used to decrypt.
17795:     my @hexstr=('0','1','2','3','4','5','6','7',
17796:                 '8','9','a','b','c','d','e','f');
17797:     my $lkey='';
17798:     for (0..7) {
17799:         $lkey.=$hexstr[rand(15)];
17800:     }
17801:     my $ukey='';
17802:     for (0..7) {
17803:         $ukey.=$hexstr[rand(15)];
17804:     }
17805:     return ($lkey,$ukey);
17806: }
17807: 
17808: sub des_decrypt {
17809:     my ($key,$cyphertext) = @_;
17810:     my $keybin=pack("H16",$key);
17811:     my $cypher;
17812:     if ($Crypt::DES::VERSION>=2.03) {
17813:         $cypher=new Crypt::DES $keybin;
17814:     } else {
17815:         $cypher=new DES $keybin;
17816:     }
17817:     my $plaintext='';
17818:     my $cypherlength = length($cyphertext);
17819:     my $numchunks = int($cypherlength/32);
17820:     for (my $j=0; $j<$numchunks; $j++) {
17821:         my $start = $j*32;
17822:         my $cypherblock = substr($cyphertext,$start,32);
17823:         my $chunk =
17824:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
17825:         $chunk .=
17826:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
17827:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
17828:         $plaintext .= $chunk;
17829:     }
17830:     return $plaintext;
17831: }
17832: 
17833: sub get_requested_shorturls {
17834:     my ($cdom,$cnum,$navmap) = @_;
17835:     return unless (ref($navmap));
17836:     my ($numnew,$errors);
17837:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
17838:     if (@toshorten) {
17839:         my (%maps,%resources,%titles);
17840:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
17841:                                                                'shorturls',$cdom,$cnum);
17842:         if (keys(%resources)) {
17843:             my %tocreate;
17844:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
17845:                 my $symb = $resources{$item};
17846:                 if ($symb) {
17847:                     $tocreate{$cnum.'&'.$symb} = 1;
17848:                 }
17849:             }
17850:             if (keys(%tocreate)) {
17851:                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
17852:                                                       \%tocreate);
17853:             }
17854:         }
17855:     }
17856:     return ($numnew,$errors);
17857: }
17858: 
17859: sub make_short_symbs {
17860:     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
17861:     my ($numnew,@errors);
17862:     if (ref($tocreateref) eq 'HASH') {
17863:         my %tocreate = %{$tocreateref};
17864:         if (keys(%tocreate)) {
17865:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
17866:             my $su = Short::URL->new(no_vowels => 1);
17867:             my $init = '';
17868:             my (%newunique,%addcourse,%courseonly,%failed);
17869:             # get lock on tiny db
17870:             my $now = time;
17871:             if ($lockuser eq '') {
17872:                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
17873:             }
17874:             my $lockhash = {
17875:                                 "lock\0$now" => $lockuser,
17876:                             };
17877:             my $tries = 0;
17878:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
17879:             my ($code,$error);
17880:             while (($gotlock ne 'ok') && ($tries<3)) {
17881:                 $tries ++;
17882:                 sleep 1;
17883:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
17884:             }
17885:             if ($gotlock eq 'ok') {
17886:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
17887:                                        \%addcourse,\%courseonly,\%failed);
17888:                 if (keys(%failed)) {
17889:                     my $numfailed = scalar(keys(%failed));
17890:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
17891:                 }
17892:                 if (keys(%newunique)) {
17893:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
17894:                     if ($putres eq 'ok') {
17895:                         $numnew = scalar(keys(%newunique));
17896:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
17897:                         unless ($newputres eq 'ok') {
17898:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
17899:                         }
17900:                     } else {
17901:                         push(@errors,&mt('error: could not store unique six character URLs'));
17902:                     }
17903:                 }
17904:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
17905:                 unless ($dellockres eq 'ok') {
17906:                     push(@errors,&mt('error: could not release lockfile'));
17907:                 }
17908:             } else {
17909:                 push(@errors,&mt('error: could not obtain lockfile'));
17910:             }
17911:             if (keys(%courseonly)) {
17912:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
17913:                 if ($result ne 'ok') {
17914:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
17915:                 }
17916:             }
17917:         }
17918:     }
17919:     return ($numnew,\@errors);
17920: }
17921: 
17922: sub shorten_symbs {
17923:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
17924:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
17925:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
17926:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
17927:     my (%possibles,%collisions);
17928:     foreach my $key (keys(%{$tocreate})) {
17929:         my $num = String::CRC32::crc32($key);
17930:         my $tiny = $su->encode($num,$init);
17931:         if ($tiny) {
17932:             $possibles{$tiny} = $key;
17933:         }
17934:     }
17935:     if (!$init) {
17936:         $init = 1;
17937:     } else {
17938:         $init ++;
17939:     }
17940:     if (keys(%possibles)) {
17941:         my @posstiny = keys(%possibles);
17942:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
17943:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
17944:         if (keys(%currtiny)) {
17945:             foreach my $key (keys(%currtiny)) {
17946:                 next if ($currtiny{$key} eq '');
17947:                 if ($currtiny{$key} eq $possibles{$key}) {
17948:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
17949:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
17950:                         $courseonly->{$tsymb} = $key;
17951:                     }
17952:                 } else {
17953:                     $collisions{$possibles{$key}} = 1;
17954:                 }
17955:                 delete($possibles{$key});
17956:             }
17957:         }
17958:         foreach my $key (keys(%possibles)) {
17959:             $newunique->{$key} = $possibles{$key};
17960:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
17961:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
17962:                 $addcourse->{$tsymb} = $key;
17963:             }
17964:         }
17965:     }
17966:     if (keys(%collisions)) {
17967:         if ($init <5) {
17968:             if (!$init) {
17969:                 $init = 1;
17970:             } else {
17971:                 $init ++;
17972:             }
17973:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
17974:                                    $newunique,$addcourse,$courseonly,$failed);
17975:         } else {
17976:             foreach my $key (keys(%collisions)) {
17977:                 $failed->{$key} = 1;
17978:                 $failed->{$key} = 1;
17979:             }
17980:         }
17981:     }
17982:     return $init;
17983: }
17984: 
17985: sub is_nonframeable {
17986:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
17987:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
17988:     return if (($remprotocol eq '') || ($remhost eq ''));
17989: 
17990:     $remprotocol = lc($remprotocol);
17991:     $remhost = lc($remhost);
17992:     my $remport = 80;
17993:     if ($remprotocol eq 'https') {
17994:         $remport = 443;
17995:     }
17996:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
17997:     if ($cached) {
17998:         unless ($nocache) {
17999:             if ($result) {
18000:                 return 1;
18001:             } else {
18002:                 return 0;
18003:             }
18004:         }
18005:     }
18006:     my $uselink;
18007:     my $request = new HTTP::Request('HEAD',$url);
18008:     my $ua = LWP::UserAgent->new;
18009:     $ua->timeout(5);
18010:     my $response=$ua->request($request);
18011:     if ($response->is_success()) {
18012:         my $secpolicy = lc($response->header('content-security-policy'));
18013:         my $xframeop = lc($response->header('x-frame-options'));
18014:         $secpolicy =~ s/^\s+|\s+$//g;
18015:         $xframeop =~ s/^\s+|\s+$//g;
18016:         if (($secpolicy ne '') || ($xframeop ne '')) {
18017:             my $remotehost = $remprotocol.'://'.$remhost;
18018:             my ($origin,$protocol,$port);
18019:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
18020:                 $port = $ENV{'SERVER_PORT'};
18021:             } else {
18022:                 $port = 80;
18023:             }
18024:             if ($absolute eq '') {
18025:                 $protocol = 'http:';
18026:                 if ($port == 443) {
18027:                     $protocol = 'https:';
18028:                 }
18029:                 $origin = $protocol.'//'.lc($hostname);
18030:             } else {
18031:                 $origin = lc($absolute);
18032:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
18033:             }
18034:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
18035:                 my $framepolicy = $1;
18036:                 $framepolicy =~ s/^\s+|\s+$//g;
18037:                 my @policies = split(/\s+/,$framepolicy);
18038:                 if (@policies) {
18039:                     if (grep(/^\Q'none'\E$/,@policies)) {
18040:                         $uselink = 1;
18041:                     } else {
18042:                         $uselink = 1;
18043:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
18044:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
18045:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
18046:                             undef($uselink);
18047:                         }
18048:                         if ($uselink) {
18049:                             if (grep(/^\Q'self'\E$/,@policies)) {
18050:                                 if (($origin ne '') && ($remotehost eq $origin)) {
18051:                                     undef($uselink);
18052:                                 }
18053:                             }
18054:                         }
18055:                         if ($uselink) {
18056:                             my @possok;
18057:                             if ($ip ne '') {
18058:                                 push(@possok,$ip);
18059:                             }
18060:                             my $hoststr = '';
18061:                             foreach my $part (reverse(split(/\./,$hostname))) {
18062:                                 if ($hoststr eq '') {
18063:                                     $hoststr = $part;
18064:                                 } else {
18065:                                     $hoststr = "$part.$hoststr";
18066:                                 }
18067:                                 if ($hoststr eq $hostname) {
18068:                                     push(@possok,$hostname);
18069:                                 } else {
18070:                                     push(@possok,"*.$hoststr");
18071:                                 }
18072:                             }
18073:                             if (@possok) {
18074:                                 foreach my $poss (@possok) {
18075:                                     last if (!$uselink);
18076:                                     foreach my $policy (@policies) {
18077:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
18078:                                             undef($uselink);
18079:                                             last;
18080:                                         }
18081:                                     }
18082:                                 }
18083:                             }
18084:                         }
18085:                     }
18086:                 }
18087:             } elsif ($xframeop ne '') {
18088:                 $uselink = 1;
18089:                 my @policies = split(/\s*,\s*/,$xframeop);
18090:                 if (@policies) {
18091:                     unless (grep(/^deny$/,@policies)) {
18092:                         if ($origin ne '') {
18093:                             if (grep(/^sameorigin$/,@policies)) {
18094:                                 if ($remotehost eq $origin) {
18095:                                     undef($uselink);
18096:                                 }
18097:                             }
18098:                             if ($uselink) {
18099:                                 foreach my $policy (@policies) {
18100:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
18101:                                         my $allowfrom = $1;
18102:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
18103:                                             undef($uselink);
18104:                                             last;
18105:                                         }
18106:                                     }
18107:                                 }
18108:                             }
18109:                         }
18110:                     }
18111:                 }
18112:             }
18113:         }
18114:     }
18115:     if ($nocache) {
18116:         if ($cached) {
18117:             my $devalidate;
18118:             if ($uselink && !$result) {
18119:                 $devalidate = 1;
18120:             } elsif (!$uselink && $result) {
18121:                 $devalidate = 1;
18122:             }
18123:             if ($devalidate) {
18124:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
18125:             }
18126:         }
18127:     } else {
18128:         if ($uselink) {
18129:             $result = 1;
18130:         } else {
18131:             $result = 0;
18132:         }
18133:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
18134:     }
18135:     return $uselink;
18136: }
18137: 
18138: sub page_menu {
18139:     my ($menucolls,$menunum) = @_;
18140:     my %menu;
18141:     foreach my $item (split(/;/,$menucolls)) {
18142:         my ($num,$value) = split(/\%/,$item);
18143:         if ($num eq $menunum) {
18144:             my @entries = split(/\&/,$value);
18145:             foreach my $entry (@entries) {
18146:                 my ($name,$fields) = split(/=/,$entry);
18147:                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
18148:                     $menu{$name} = $fields;
18149:                 } else {
18150:                     my @shown;
18151:                     if ($fields =~ /,/) {
18152:                         @shown = split(/,/,$fields);
18153:                     } else {
18154:                         @shown = ($fields);
18155:                     }
18156:                     if (@shown) {
18157:                         foreach my $field (@shown) {
18158:                             next if ($field eq '');
18159:                             $menu{$field} = 1;
18160:                         }
18161:                     }
18162:                 }
18163:             }
18164:         }
18165:     }
18166:     return %menu;
18167: }
18168: 
18169: 1;
18170: __END__;
18171: 

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