File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1370: download - view: text, annotated - select for diffs
Wed Nov 17 19:55:15 2021 UTC (2 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6907
  If session was initiated via launch from a deep-link use menu in effect for
  the launch URL if current resource is a map and navmap object unavailable,
  or if resource should have a symb, but symb is unknown.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1370 2021/11/17 19:55:15 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 LONCAPA::LWPReq;
   75: use HTTP::Request;
   76: use DateTime::TimeZone;
   77: use DateTime::Locale;
   78: use Encode();
   79: use Text::Aspell;
   80: use Authen::Captcha;
   81: use Captcha::reCAPTCHA;
   82: use JSON::DWIW;
   83: use Crypt::DES;
   84: use DynaLoader; # for Crypt::DES version
   85: use MIME::Lite;
   86: use MIME::Types;
   87: use File::Copy();
   88: use File::Path();
   89: use String::CRC32();
   90: use Short::URL();
   91: 
   92: # ---------------------------------------------- Designs
   93: use vars qw(%defaultdesign);
   94: 
   95: my $readit;
   96: 
   97: 
   98: ##
   99: ## Global Variables
  100: ##
  101: 
  102: 
  103: # ----------------------------------------------- SSI with retries:
  104: #
  105: 
  106: =pod
  107: 
  108: =head1 Server Side include with retries:
  109: 
  110: =over 4
  111: 
  112: =item * &ssi_with_retries(resource,retries form)
  113: 
  114: Performs an ssi with some number of retries.  Retries continue either
  115: until the result is ok or until the retry count supplied by the
  116: caller is exhausted.  
  117: 
  118: Inputs:
  119: 
  120: =over 4
  121: 
  122: resource   - Identifies the resource to insert.
  123: 
  124: retries    - Count of the number of retries allowed.
  125: 
  126: form       - Hash that identifies the rendering options.
  127: 
  128: =back
  129: 
  130: Returns:
  131: 
  132: =over 4
  133: 
  134: content    - The content of the response.  If retries were exhausted this is empty.
  135: 
  136: response   - The response from the last attempt (which may or may not have been successful.
  137: 
  138: =back
  139: 
  140: =back
  141: 
  142: =cut
  143: 
  144: sub ssi_with_retries {
  145:     my ($resource, $retries, %form) = @_;
  146: 
  147: 
  148:     my $ok = 0;			# True if we got a good response.
  149:     my $content;
  150:     my $response;
  151: 
  152:     # Try to get the ssi done. within the retries count:
  153: 
  154:     do {
  155: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  156: 	$ok      = $response->is_success;
  157:         if (!$ok) {
  158:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  159:         }
  160: 	$retries--;
  161:     } while (!$ok && ($retries > 0));
  162: 
  163:     if (!$ok) {
  164: 	$content = '';		# On error return an empty content.
  165:     }
  166:     return ($content, $response);
  167: 
  168: }
  169: 
  170: 
  171: 
  172: # ----------------------------------------------- Filetypes/Languages/Copyright
  173: my %language;
  174: my %supported_language;
  175: my %supported_codes;
  176: my %latex_language;		# For choosing hyphenation in <transl..>
  177: my %latex_language_bykey;	# for choosing hyphenation from metadata
  178: my %cprtag;
  179: my %scprtag;
  180: my %fe; my %fd; my %fm;
  181: my %category_extensions;
  182: 
  183: # ---------------------------------------------- Thesaurus variables
  184: #
  185: # %Keywords:
  186: #      A hash used by &keyword to determine if a word is considered a keyword.
  187: # $thesaurus_db_file 
  188: #      Scalar containing the full path to the thesaurus database.
  189: 
  190: my %Keywords;
  191: my $thesaurus_db_file;
  192: 
  193: #
  194: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  195: # thesaurus.tab, and filecategories.tab.
  196: #
  197: BEGIN {
  198:     # Variable initialization
  199:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  200:     #
  201:     unless ($readit) {
  202: # ------------------------------------------------------------------- languages
  203:     {
  204:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  205:                                    '/language.tab';
  206:         if ( open(my $fh,'<',$langtabfile) ) {
  207:             while (my $line = <$fh>) {
  208:                 next if ($line=~/^\#/);
  209:                 chomp($line);
  210:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  211:                 $language{$key}=$val.' - '.$enc;
  212:                 if ($sup) {
  213:                     $supported_language{$key}=$sup;
  214: 		    $supported_codes{$key}   = $code;
  215:                 }
  216: 		if ($latex) {
  217: 		    $latex_language_bykey{$key} = $latex;
  218: 		    $latex_language{$code} = $latex;
  219: 		}
  220:             }
  221:             close($fh);
  222:         }
  223:     }
  224: # ------------------------------------------------------------------ copyrights
  225:     {
  226:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  227:                                   '/copyright.tab';
  228:         if ( open (my $fh,'<',$copyrightfile) ) {
  229:             while (my $line = <$fh>) {
  230:                 next if ($line=~/^\#/);
  231:                 chomp($line);
  232:                 my ($key,$val)=(split(/\s+/,$line,2));
  233:                 $cprtag{$key}=$val;
  234:             }
  235:             close($fh);
  236:         }
  237:     }
  238: # ----------------------------------------------------------- source copyrights
  239:     {
  240:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  241:                                   '/source_copyright.tab';
  242:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
  243:             while (my $line = <$fh>) {
  244:                 next if ($line =~ /^\#/);
  245:                 chomp($line);
  246:                 my ($key,$val)=(split(/\s+/,$line,2));
  247:                 $scprtag{$key}=$val;
  248:             }
  249:             close($fh);
  250:         }
  251:     }
  252: 
  253: # -------------------------------------------------------------- default domain designs
  254:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  255:     my $designfile = $designdir.'/default.tab';
  256:     if ( open (my $fh,'<',$designfile) ) {
  257:         while (my $line = <$fh>) {
  258:             next if ($line =~ /^\#/);
  259:             chomp($line);
  260:             my ($key,$val)=(split(/\=/,$line));
  261:             if ($val) { $defaultdesign{$key}=$val; }
  262:         }
  263:         close($fh);
  264:     }
  265: 
  266: # ------------------------------------------------------------- file categories
  267:     {
  268:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  269:                                   '/filecategories.tab';
  270:         if ( open (my $fh,'<',$categoryfile) ) {
  271: 	    while (my $line = <$fh>) {
  272: 		next if ($line =~ /^\#/);
  273: 		chomp($line);
  274:                 my ($extension,$category)=(split(/\s+/,$line,2));
  275:                 push(@{$category_extensions{lc($category)}},$extension);
  276:             }
  277:             close($fh);
  278:         }
  279: 
  280:     }
  281: # ------------------------------------------------------------------ file types
  282:     {
  283:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  284:                '/filetypes.tab';
  285:         if ( open (my $fh,'<',$typesfile) ) {
  286:             while (my $line = <$fh>) {
  287: 		next if ($line =~ /^\#/);
  288: 		chomp($line);
  289:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  290:                 if ($descr ne '') {
  291:                     $fe{$ending}=lc($emb);
  292:                     $fd{$ending}=$descr;
  293:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  294:                 }
  295:             }
  296:             close($fh);
  297:         }
  298:     }
  299:     &Apache::lonnet::logthis(
  300:              "<span style='color:yellow;'>INFO: Read file types</span>");
  301:     $readit=1;
  302:     }  # end of unless($readit) 
  303:     
  304: }
  305: 
  306: ###############################################################
  307: ##           HTML and Javascript Helper Functions            ##
  308: ###############################################################
  309: 
  310: =pod 
  311: 
  312: =head1 HTML and Javascript Functions
  313: 
  314: =over 4
  315: 
  316: =item * &browser_and_searcher_javascript()
  317: 
  318: X<browsing, javascript>X<searching, javascript>Returns a string
  319: containing javascript with two functions, C<openbrowser> and
  320: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  321: tags.
  322: 
  323: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  324: 
  325: inputs: formname, elementname, only, omit
  326: 
  327: formname and elementname indicate the name of the html form and name of
  328: the element that the results of the browsing selection are to be placed in. 
  329: 
  330: Specifying 'only' will restrict the browser to displaying only files
  331: with the given extension.  Can be a comma separated list.
  332: 
  333: Specifying 'omit' will restrict the browser to NOT displaying files
  334: with the given extension.  Can be a comma separated list.
  335: 
  336: =item * &opensearcher(formname,elementname) [javascript]
  337: 
  338: Inputs: formname, elementname
  339: 
  340: formname and elementname specify the name of the html form and the name
  341: of the element the selection from the search results will be placed in.
  342: 
  343: =cut
  344: 
  345: sub browser_and_searcher_javascript {
  346:     my ($mode)=@_;
  347:     if (!defined($mode)) { $mode='edit'; }
  348:     my $resurl=&escape_single(&lastresurl());
  349:     return <<END;
  350: // <!-- BEGIN LON-CAPA Internal
  351:     var editbrowser = null;
  352:     function openbrowser(formname,elementname,only,omit,titleelement) {
  353:         var url = '$resurl/?';
  354:         if (editbrowser == null) {
  355:             url += 'launch=1&';
  356:         }
  357:         url += 'catalogmode=interactive&';
  358:         url += 'mode=$mode&';
  359:         url += 'inhibitmenu=yes&';
  360:         url += 'form=' + formname + '&';
  361:         if (only != null) {
  362:             url += 'only=' + only + '&';
  363:         } else {
  364:             url += 'only=&';
  365: 	}
  366:         if (omit != null) {
  367:             url += 'omit=' + omit + '&';
  368:         } else {
  369:             url += 'omit=&';
  370: 	}
  371:         if (titleelement != null) {
  372:             url += 'titleelement=' + titleelement + '&';
  373:         } else {
  374: 	    url += 'titleelement=&';
  375: 	}
  376:         url += 'element=' + elementname + '';
  377:         var title = 'Browser';
  378:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  379:         options += ',width=700,height=600';
  380:         editbrowser = open(url,title,options,'1');
  381:         editbrowser.focus();
  382:     }
  383:     var editsearcher;
  384:     function opensearcher(formname,elementname,titleelement) {
  385:         var url = '/adm/searchcat?';
  386:         if (editsearcher == null) {
  387:             url += 'launch=1&';
  388:         }
  389:         url += 'catalogmode=interactive&';
  390:         url += 'mode=$mode&';
  391:         url += 'form=' + formname + '&';
  392:         if (titleelement != null) {
  393:             url += 'titleelement=' + titleelement + '&';
  394:         } else {
  395: 	    url += 'titleelement=&';
  396: 	}
  397:         url += 'element=' + elementname + '';
  398:         var title = 'Search';
  399:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  400:         options += ',width=700,height=600';
  401:         editsearcher = open(url,title,options,'1');
  402:         editsearcher.focus();
  403:     }
  404: // END LON-CAPA Internal -->
  405: END
  406: }
  407: 
  408: sub lastresurl {
  409:     if ($env{'environment.lastresurl'}) {
  410: 	return $env{'environment.lastresurl'}
  411:     } else {
  412: 	return '/res';
  413:     }
  414: }
  415: 
  416: sub storeresurl {
  417:     my $resurl=&Apache::lonnet::clutter(shift);
  418:     unless ($resurl=~/^\/res/) { return 0; }
  419:     $resurl=~s/\/$//;
  420:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  421:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  422:     return 1;
  423: }
  424: 
  425: sub studentbrowser_javascript {
  426:    unless (
  427:             (($env{'request.course.id'}) && 
  428:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  429: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  430: 					  '/'.$env{'request.course.sec'})
  431: 	      ))
  432:          || ($env{'request.role'}=~/^(au|dc|su)/)
  433:           ) { return ''; }  
  434:    return (<<'ENDSTDBRW');
  435: <script type="text/javascript" language="Javascript">
  436: // <![CDATA[
  437:     var stdeditbrowser;
  438:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv) {
  439:         var url = '/adm/pickstudent?';
  440:         var filter;
  441: 	if (!ignorefilter) {
  442: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  443: 	}
  444:         if (filter != null) {
  445:            if (filter != '') {
  446:                url += 'filter='+filter+'&';
  447: 	   }
  448:         }
  449:         url += 'form=' + formname + '&unameelement='+uname+
  450:                                     '&udomelement='+udom+
  451:                                     '&clicker='+clicker;
  452: 	if (roleflag) { url+="&roles=1"; }
  453:         if (courseadv == 'condition') {
  454:             if (document.getElementById('courseadv')) {
  455:                 courseadv = document.getElementById('courseadv').value;
  456:             }
  457:         }
  458:         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
  459:         var title = 'Student_Browser';
  460:         var options = 'scrollbars=1,resizable=1,menubar=0';
  461:         options += ',width=700,height=600';
  462:         stdeditbrowser = open(url,title,options,'1');
  463:         stdeditbrowser.focus();
  464:     }
  465: // ]]>
  466: </script>
  467: ENDSTDBRW
  468: }
  469: 
  470: sub resourcebrowser_javascript {
  471:    unless ($env{'request.course.id'}) { return ''; }
  472:    return (<<'ENDRESBRW');
  473: <script type="text/javascript" language="Javascript">
  474: // <![CDATA[
  475:     var reseditbrowser;
  476:     function openresbrowser(formname,reslink) {
  477:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  478:         var title = 'Resource_Browser';
  479:         var options = 'scrollbars=1,resizable=1,menubar=0';
  480:         options += ',width=700,height=500';
  481:         reseditbrowser = open(url,title,options,'1');
  482:         reseditbrowser.focus();
  483:     }
  484: // ]]>
  485: </script>
  486: ENDRESBRW
  487: }
  488: 
  489: sub selectstudent_link {
  490:    my ($form,$unameele,$udomele,$courseadv,$clickerid)=@_;
  491:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  492:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  493:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  494:    if ($env{'request.course.id'}) {  
  495:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  496: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  497: 					'/'.$env{'request.course.sec'})) {
  498: 	   return '';
  499:        }
  500:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  501:        if ($courseadv eq 'only') {
  502:            $callargs .= ",'',1,'$courseadv'";
  503:        } elsif ($courseadv eq 'none') {
  504:            $callargs .= ",'','','$courseadv'";
  505:        } elsif ($courseadv eq 'condition') {
  506:            $callargs .= ",'','','$courseadv'";
  507:        }
  508:        return '<span class="LC_nobreak">'.
  509:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  510:               &mt('Select User').'</a></span>';
  511:    }
  512:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  513:        $callargs .= ",'',1"; 
  514:        return '<span class="LC_nobreak">'.
  515:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  516:               &mt('Select User').'</a></span>';
  517:    }
  518:    return '';
  519: }
  520: 
  521: sub selectresource_link {
  522:    my ($form,$reslink,$arg)=@_;
  523:    
  524:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  525:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  526:    unless ($env{'request.course.id'}) { return $arg; }
  527:    return '<span class="LC_nobreak">'.
  528:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  529:               $arg.'</a></span>';
  530: }
  531: 
  532: 
  533: 
  534: sub authorbrowser_javascript {
  535:     return <<"ENDAUTHORBRW";
  536: <script type="text/javascript" language="JavaScript">
  537: // <![CDATA[
  538: var stdeditbrowser;
  539: 
  540: function openauthorbrowser(formname,udom) {
  541:     var url = '/adm/pickauthor?';
  542:     url += 'form='+formname+'&roledom='+udom;
  543:     var title = 'Author_Browser';
  544:     var options = 'scrollbars=1,resizable=1,menubar=0';
  545:     options += ',width=700,height=600';
  546:     stdeditbrowser = open(url,title,options,'1');
  547:     stdeditbrowser.focus();
  548: }
  549: 
  550: // ]]>
  551: </script>
  552: ENDAUTHORBRW
  553: }
  554: 
  555: sub coursebrowser_javascript {
  556:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
  557:         $credits_element,$instcode) = @_;
  558:     my $wintitle = 'Course_Browser';
  559:     if ($crstype eq 'Community') {
  560:         $wintitle = 'Community_Browser';
  561:     }
  562:     my $id_functions = &javascript_index_functions();
  563:     my $output = '
  564: <script type="text/javascript" language="JavaScript">
  565: // <![CDATA[
  566:     var stdeditbrowser;'."\n";
  567: 
  568:     $output .= <<"ENDSTDBRW";
  569:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  570:         var url = '/adm/pickcourse?';
  571:         var formid = getFormIdByName(formname);
  572:         var domainfilter = getDomainFromSelectbox(formname,udom);
  573:         if (domainfilter != null) {
  574:            if (domainfilter != '') {
  575:                url += 'domainfilter='+domainfilter+'&';
  576: 	   }
  577:         }
  578:         url += 'form=' + formname + '&cnumelement='+uname+
  579: 	                            '&cdomelement='+udom+
  580:                                     '&cnameelement='+desc;
  581:         if (extra_element !=null && extra_element != '') {
  582:             if (formname == 'rolechoice' || formname == 'studentform') {
  583:                 url += '&roleelement='+extra_element;
  584:                 if (domainfilter == null || domainfilter == '') {
  585:                     url += '&domainfilter='+extra_element;
  586:                 }
  587:             }
  588:             else {
  589:                 if (formname == 'portform') {
  590:                     url += '&setroles='+extra_element;
  591:                 } else {
  592:                     if (formname == 'rules') {
  593:                         url += '&fixeddom='+extra_element; 
  594:                     }
  595:                 }
  596:             }     
  597:         }
  598:         if (type != null && type != '') {
  599:             url += '&type='+type;
  600:         }
  601:         if (type_elem != null && type_elem != '') {
  602:             url += '&typeelement='+type_elem;
  603:         }
  604:         if (formname == 'ccrs') {
  605:             var ownername = document.forms[formid].ccuname.value;
  606:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  607:             url += '&cloner='+ownername+':'+ownerdom;
  608:             if (type == 'Course') {
  609:                 url += '&crscode='+document.forms[formid].crscode.value;
  610:             }
  611:         }
  612:         if (formname == 'requestcrs') {
  613:             url += '&crsdom=$domainfilter&crscode=$instcode';
  614:         }
  615:         if (multflag !=null && multflag != '') {
  616:             url += '&multiple='+multflag;
  617:         }
  618:         var title = '$wintitle';
  619:         var options = 'scrollbars=1,resizable=1,menubar=0';
  620:         options += ',width=700,height=600';
  621:         stdeditbrowser = open(url,title,options,'1');
  622:         stdeditbrowser.focus();
  623:     }
  624: $id_functions
  625: ENDSTDBRW
  626:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
  627:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
  628:                                       $credits_element);
  629:     }
  630:     $output .= '
  631: // ]]>
  632: </script>';
  633:     return $output;
  634: }
  635: 
  636: sub javascript_index_functions {
  637:     return <<"ENDJS";
  638: 
  639: function getFormIdByName(formname) {
  640:     for (var i=0;i<document.forms.length;i++) {
  641:         if (document.forms[i].name == formname) {
  642:             return i;
  643:         }
  644:     }
  645:     return -1;
  646: }
  647: 
  648: function getIndexByName(formid,item) {
  649:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  650:         if (document.forms[formid].elements[i].name == item) {
  651:             return i;
  652:         }
  653:     }
  654:     return -1;
  655: }
  656: 
  657: function getDomainFromSelectbox(formname,udom) {
  658:     var userdom;
  659:     var formid = getFormIdByName(formname);
  660:     if (formid > -1) {
  661:         var domid = getIndexByName(formid,udom);
  662:         if (domid > -1) {
  663:             if (document.forms[formid].elements[domid].type == 'select-one') {
  664:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  665:             }
  666:             if (document.forms[formid].elements[domid].type == 'hidden') {
  667:                 userdom=document.forms[formid].elements[domid].value;
  668:             }
  669:         }
  670:     }
  671:     return userdom;
  672: }
  673: 
  674: ENDJS
  675: 
  676: }
  677: 
  678: sub javascript_array_indexof {
  679:     return <<ENDJS;
  680: <script type="text/javascript" language="JavaScript">
  681: // <![CDATA[
  682: 
  683: if (!Array.prototype.indexOf) {
  684:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  685:         "use strict";
  686:         if (this === void 0 || this === null) {
  687:             throw new TypeError();
  688:         }
  689:         var t = Object(this);
  690:         var len = t.length >>> 0;
  691:         if (len === 0) {
  692:             return -1;
  693:         }
  694:         var n = 0;
  695:         if (arguments.length > 0) {
  696:             n = Number(arguments[1]);
  697:             if (n !== n) { // shortcut for verifying if it is NaN
  698:                 n = 0;
  699:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  700:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  701:             }
  702:         }
  703:         if (n >= len) {
  704:             return -1;
  705:         }
  706:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  707:         for (; k < len; k++) {
  708:             if (k in t && t[k] === searchElement) {
  709:                 return k;
  710:             }
  711:         }
  712:         return -1;
  713:     }
  714: }
  715: 
  716: // ]]>
  717: </script>
  718: 
  719: ENDJS
  720: 
  721: }
  722: 
  723: sub userbrowser_javascript {
  724:     my $id_functions = &javascript_index_functions();
  725:     return <<"ENDUSERBRW";
  726: 
  727: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  728:     var url = '/adm/pickuser?';
  729:     var userdom = getDomainFromSelectbox(formname,udom);
  730:     if (userdom != null) {
  731:        if (userdom != '') {
  732:            url += 'srchdom='+userdom+'&';
  733:        }
  734:     }
  735:     url += 'form=' + formname + '&unameelement='+uname+
  736:                                 '&udomelement='+udom+
  737:                                 '&ulastelement='+ulast+
  738:                                 '&ufirstelement='+ufirst+
  739:                                 '&uemailelement='+uemail+
  740:                                 '&hideudomelement='+hideudom+
  741:                                 '&coursedom='+crsdom;
  742:     if ((caller != null) && (caller != undefined)) {
  743:         url += '&caller='+caller;
  744:     }
  745:     var title = 'User_Browser';
  746:     var options = 'scrollbars=1,resizable=1,menubar=0';
  747:     options += ',width=700,height=600';
  748:     var stdeditbrowser = open(url,title,options,'1');
  749:     stdeditbrowser.focus();
  750: }
  751: 
  752: function fix_domain (formname,udom,origdom,uname) {
  753:     var formid = getFormIdByName(formname);
  754:     if (formid > -1) {
  755:         var unameid = getIndexByName(formid,uname);
  756:         var domid = getIndexByName(formid,udom);
  757:         var hidedomid = getIndexByName(formid,origdom);
  758:         if (hidedomid > -1) {
  759:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  760:             var unameval = document.forms[formid].elements[unameid].value;
  761:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  762:                 if (domid > -1) {
  763:                     var slct = document.forms[formid].elements[domid];
  764:                     if (slct.type == 'select-one') {
  765:                         var i;
  766:                         for (i=0;i<slct.length;i++) {
  767:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  768:                         }
  769:                     }
  770:                     if (slct.type == 'hidden') {
  771:                         slct.value = fixeddom;
  772:                     }
  773:                 }
  774:             }
  775:         }
  776:     }
  777:     return;
  778: }
  779: 
  780: $id_functions
  781: ENDUSERBRW
  782: }
  783: 
  784: sub setsec_javascript {
  785:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
  786:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  787:         $communityrolestr);
  788:     if ($role_element ne '') {
  789:         my @allroles = ('st','ta','ep','in','ad');
  790:         foreach my $crstype ('Course','Community') {
  791:             if ($crstype eq 'Community') {
  792:                 foreach my $role (@allroles) {
  793:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  794:                 }
  795:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  796:             } else {
  797:                 foreach my $role (@allroles) {
  798:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  799:                 }
  800:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  801:             }
  802:         }
  803:         $rolestr = '"'.join('","',@allroles).'"';
  804:         $courserolestr = '"'.join('","',@courserolenames).'"';
  805:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  806:     }
  807:     my $setsections = qq|
  808: function setSect(sectionlist) {
  809:     var sectionsArray = new Array();
  810:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  811:         sectionsArray = sectionlist.split(",");
  812:     }
  813:     var numSections = sectionsArray.length;
  814:     document.$formname.$sec_element.length = 0;
  815:     if (numSections == 0) {
  816:         document.$formname.$sec_element.multiple=false;
  817:         document.$formname.$sec_element.size=1;
  818:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  819:     } else {
  820:         if (numSections == 1) {
  821:             document.$formname.$sec_element.multiple=false;
  822:             document.$formname.$sec_element.size=1;
  823:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  824:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  825:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  826:         } else {
  827:             for (var i=0; i<numSections; i++) {
  828:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  829:             }
  830:             document.$formname.$sec_element.multiple=true
  831:             if (numSections < 3) {
  832:                 document.$formname.$sec_element.size=numSections;
  833:             } else {
  834:                 document.$formname.$sec_element.size=3;
  835:             }
  836:             document.$formname.$sec_element.options[0].selected = false
  837:         }
  838:     }
  839: }
  840: 
  841: function setRole(crstype) {
  842: |;
  843:     if ($role_element eq '') {
  844:         $setsections .= '    return;
  845: }
  846: ';
  847:     } else {
  848:         $setsections .= qq|
  849:     var elementLength = document.$formname.$role_element.length;
  850:     var allroles = Array($rolestr);
  851:     var courserolenames = Array($courserolestr);
  852:     var communityrolenames = Array($communityrolestr);
  853:     if (elementLength != undefined) {
  854:         if (document.$formname.$role_element.options[5].value == 'cc') {
  855:             if (crstype == 'Course') {
  856:                 return;
  857:             } else {
  858:                 allroles[5] = 'co';
  859:                 for (var i=0; i<6; i++) {
  860:                     document.$formname.$role_element.options[i].value = allroles[i];
  861:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  862:                 }
  863:             }
  864:         } else {
  865:             if (crstype == 'Community') {
  866:                 return;
  867:             } else {
  868:                 allroles[5] = 'cc';
  869:                 for (var i=0; i<6; i++) {
  870:                     document.$formname.$role_element.options[i].value = allroles[i];
  871:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  872:                 }
  873:             }
  874:         }
  875:     }
  876:     return;
  877: }
  878: |;
  879:     }
  880:     if ($credits_element) {
  881:         $setsections .= qq|
  882: function setCredits(defaultcredits) {
  883:     document.$formname.$credits_element.value = defaultcredits;
  884:     return;
  885: }
  886: |;
  887:     }
  888:     return $setsections;
  889: }
  890: 
  891: sub selectcourse_link {
  892:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  893:        $typeelement) = @_;
  894:    my $type = $selecttype;
  895:    my $linktext = &mt('Select Course');
  896:    if ($selecttype eq 'Community') {
  897:        $linktext = &mt('Select Community');
  898:    } elsif ($selecttype eq 'Placement') {
  899:        $linktext = &mt('Select Placement Test'); 
  900:    } elsif ($selecttype eq 'Course/Community') {
  901:        $linktext = &mt('Select Course/Community');
  902:        $type = '';
  903:    } elsif ($selecttype eq 'Select') {
  904:        $linktext = &mt('Select');
  905:        $type = '';
  906:    }
  907:    return '<span class="LC_nobreak">'
  908:          ."<a href='"
  909:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  910:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  911:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  912:          ."'>".$linktext.'</a>'
  913:          .'</span>';
  914: }
  915: 
  916: sub selectauthor_link {
  917:    my ($form,$udom)=@_;
  918:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  919:           &mt('Select Author').'</a>';
  920: }
  921: 
  922: sub selectuser_link {
  923:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  924:         $coursedom,$linktext,$caller) = @_;
  925:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  926:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  927:            ');">'.$linktext.'</a>';
  928: }
  929: 
  930: sub check_uncheck_jscript {
  931:     my $jscript = <<"ENDSCRT";
  932: function checkAll(field) {
  933:     if (field.length > 0) {
  934:         for (i = 0; i < field.length; i++) {
  935:             if (!field[i].disabled) { 
  936:                 field[i].checked = true;
  937:             }
  938:         }
  939:     } else {
  940:         if (!field.disabled) { 
  941:             field.checked = true;
  942:         }
  943:     }
  944: }
  945:  
  946: function uncheckAll(field) {
  947:     if (field.length > 0) {
  948:         for (i = 0; i < field.length; i++) {
  949:             field[i].checked = false ;
  950:         }
  951:     } else {
  952:         field.checked = false ;
  953:     }
  954: }
  955: ENDSCRT
  956:     return $jscript;
  957: }
  958: 
  959: sub select_timezone {
  960:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  961:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  962:    if ($includeempty) {
  963:        $output .= '<option value=""';
  964:        if (($selected eq '') || ($selected eq 'local')) {
  965:            $output .= ' selected="selected" ';
  966:        }
  967:        $output .= '> </option>';
  968:    }
  969:    my @timezones = DateTime::TimeZone->all_names;
  970:    foreach my $tzone (@timezones) {
  971:        $output.= '<option value="'.$tzone.'"';
  972:        if ($tzone eq $selected) {
  973:            $output.=' selected="selected"';
  974:        }
  975:        $output.=">$tzone</option>\n";
  976:    }
  977:    $output.="</select>";
  978:    return $output;
  979: }
  980: 
  981: sub select_datelocale {
  982:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  983:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  984:     if ($includeempty) {
  985:         $output .= '<option value=""';
  986:         if ($selected eq '') {
  987:             $output .= ' selected="selected" ';
  988:         }
  989:         $output .= '> </option>';
  990:     }
  991:     my @languages = &Apache::lonlocal::preferred_languages();
  992:     my (@possibles,%locale_names);
  993:     my @locales = DateTime::Locale->ids();
  994:     foreach my $id (@locales) {
  995:         if ($id ne '') {
  996:             my ($en_terr,$native_terr);
  997:             my $loc = DateTime::Locale->load($id);
  998:             if (ref($loc)) {
  999:                 $en_terr = $loc->name();
 1000:                 $native_terr = $loc->native_name();
 1001:                 if (grep(/^en$/,@languages) || !@languages) {
 1002:                     if ($en_terr ne '') {
 1003:                         $locale_names{$id} = '('.$en_terr.')';
 1004:                     } elsif ($native_terr ne '') {
 1005:                         $locale_names{$id} = $native_terr;
 1006:                     }
 1007:                 } else {
 1008:                     if ($native_terr ne '') {
 1009:                         $locale_names{$id} = $native_terr.' ';
 1010:                     } elsif ($en_terr ne '') {
 1011:                         $locale_names{$id} = '('.$en_terr.')';
 1012:                     }
 1013:                 }
 1014:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
 1015:                 push(@possibles,$id);
 1016:             } 
 1017:         }
 1018:     }
 1019:     foreach my $item (sort(@possibles)) {
 1020:         $output.= '<option value="'.$item.'"';
 1021:         if ($item eq $selected) {
 1022:             $output.=' selected="selected"';
 1023:         }
 1024:         $output.=">$item";
 1025:         if ($locale_names{$item} ne '') {
 1026:             $output.='  '.$locale_names{$item};
 1027:         }
 1028:         $output.="</option>\n";
 1029:     }
 1030:     $output.="</select>";
 1031:     return $output;
 1032: }
 1033: 
 1034: sub select_language {
 1035:     my ($name,$selected,$includeempty,$noedit) = @_;
 1036:     my %langchoices;
 1037:     if ($includeempty) {
 1038:         %langchoices = ('' => 'No language preference');
 1039:     }
 1040:     foreach my $id (&languageids()) {
 1041:         my $code = &supportedlanguagecode($id);
 1042:         if ($code) {
 1043:             $langchoices{$code} = &plainlanguagedescription($id);
 1044:         }
 1045:     }
 1046:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
 1047:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
 1048: }
 1049: 
 1050: =pod
 1051: 
 1052: 
 1053: =item * &list_languages()
 1054: 
 1055: Returns an array reference that is suitable for use in language prompters.
 1056: Each array element is itself a two element array.  The first element
 1057: is the language code.  The second element a descsriptiuon of the 
 1058: language itself.  This is suitable for use in e.g.
 1059: &Apache::edit::select_arg (once dereferenced that is).
 1060: 
 1061: =cut 
 1062: 
 1063: sub list_languages {
 1064:     my @lang_choices;
 1065: 
 1066:     foreach my $id (&languageids()) {
 1067: 	my $code = &supportedlanguagecode($id);
 1068: 	if ($code) {
 1069: 	    my $selector    = $supported_codes{$id};
 1070: 	    my $description = &plainlanguagedescription($id);
 1071: 	    push(@lang_choices, [$selector, $description]);
 1072: 	}
 1073:     }
 1074:     return \@lang_choices;
 1075: }
 1076: 
 1077: =pod
 1078: 
 1079: =item * &linked_select_forms(...)
 1080: 
 1081: linked_select_forms returns a string containing a <script></script> block
 1082: and html for two <select> menus.  The select menus will be linked in that
 1083: changing the value of the first menu will result in new values being placed
 1084: in the second menu.  The values in the select menu will appear in alphabetical
 1085: order unless a defined order is provided.
 1086: 
 1087: linked_select_forms takes the following ordered inputs:
 1088: 
 1089: =over 4
 1090: 
 1091: =item * $formname, the name of the <form> tag
 1092: 
 1093: =item * $middletext, the text which appears between the <select> tags
 1094: 
 1095: =item * $firstdefault, the default value for the first menu
 1096: 
 1097: =item * $firstselectname, the name of the first <select> tag
 1098: 
 1099: =item * $secondselectname, the name of the second <select> tag
 1100: 
 1101: =item * $hashref, a reference to a hash containing the data for the menus.
 1102: 
 1103: =item * $menuorder, the order of values in the first menu
 1104: 
 1105: =item * $onchangefirst, additional javascript call to execute for an onchange
 1106:         event for the first <select> tag
 1107: 
 1108: =item * $onchangesecond, additional javascript call to execute for an onchange
 1109:         event for the second <select> tag
 1110: 
 1111: =item * $suffix, to differentiate separate uses of select2data javascript
 1112:         objects in a page.
 1113: 
 1114: =back 
 1115: 
 1116: Below is an example of such a hash.  Only the 'text', 'default', and 
 1117: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1118: values for the first select menu.  The text that coincides with the 
 1119: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1120: and text for the second menu are given in the hash pointed to by 
 1121: $menu{$choice1}->{'select2'}.  
 1122: 
 1123:  my %menu = ( A1 => { text =>"Choice A1" ,
 1124:                        default => "B3",
 1125:                        select2 => { 
 1126:                            B1 => "Choice B1",
 1127:                            B2 => "Choice B2",
 1128:                            B3 => "Choice B3",
 1129:                            B4 => "Choice B4"
 1130:                            },
 1131:                        order => ['B4','B3','B1','B2'],
 1132:                    },
 1133:                A2 => { text =>"Choice A2" ,
 1134:                        default => "C2",
 1135:                        select2 => { 
 1136:                            C1 => "Choice C1",
 1137:                            C2 => "Choice C2",
 1138:                            C3 => "Choice C3"
 1139:                            },
 1140:                        order => ['C2','C1','C3'],
 1141:                    },
 1142:                A3 => { text =>"Choice A3" ,
 1143:                        default => "D6",
 1144:                        select2 => { 
 1145:                            D1 => "Choice D1",
 1146:                            D2 => "Choice D2",
 1147:                            D3 => "Choice D3",
 1148:                            D4 => "Choice D4",
 1149:                            D5 => "Choice D5",
 1150:                            D6 => "Choice D6",
 1151:                            D7 => "Choice D7"
 1152:                            },
 1153:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1154:                    }
 1155:                );
 1156: 
 1157: =cut
 1158: 
 1159: sub linked_select_forms {
 1160:     my ($formname,
 1161:         $middletext,
 1162:         $firstdefault,
 1163:         $firstselectname,
 1164:         $secondselectname, 
 1165:         $hashref,
 1166:         $menuorder,
 1167:         $onchangefirst,
 1168:         $onchangesecond,
 1169:         $suffix
 1170:         ) = @_;
 1171:     my $second = "document.$formname.$secondselectname";
 1172:     my $first = "document.$formname.$firstselectname";
 1173:     # output the javascript to do the changing
 1174:     my $result = '';
 1175:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1176:     $result.="// <![CDATA[\n";
 1177:     $result.="var select2data${suffix} = new Object();\n";
 1178:     $" = '","';
 1179:     my $debug = '';
 1180:     foreach my $s1 (sort(keys(%$hashref))) {
 1181:         $result.="select2data${suffix}['d_$s1'] = new Object();\n";        
 1182:         $result.="select2data${suffix}['d_$s1'].def = new String('".
 1183:             $hashref->{$s1}->{'default'}."');\n";
 1184:         $result.="select2data${suffix}['d_$s1'].values = new Array(";
 1185:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1186:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1187:             @s2values = @{$hashref->{$s1}->{'order'}};
 1188:         }
 1189:         $result.="\"@s2values\");\n";
 1190:         $result.="select2data${suffix}['d_$s1'].texts = new Array(";        
 1191:         my @s2texts;
 1192:         foreach my $value (@s2values) {
 1193:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
 1194:         }
 1195:         $result.="\"@s2texts\");\n";
 1196:     }
 1197:     $"=' ';
 1198:     $result.= <<"END";
 1199: 
 1200: function select1${suffix}_changed() {
 1201:     // Determine new choice
 1202:     var newvalue = "d_" + $first.options[$first.selectedIndex].value;
 1203:     // update select2
 1204:     var values     = select2data${suffix}[newvalue].values;
 1205:     var texts      = select2data${suffix}[newvalue].texts;
 1206:     var select2def = select2data${suffix}[newvalue].def;
 1207:     var i;
 1208:     // out with the old
 1209:     $second.options.length = 0;
 1210:     // in with the new
 1211:     for (i=0;i<values.length; i++) {
 1212:         $second.options[i] = new Option(values[i]);
 1213:         $second.options[i].value = values[i];
 1214:         $second.options[i].text = texts[i];
 1215:         if (values[i] == select2def) {
 1216:             $second.options[i].selected = true;
 1217:         }
 1218:     }
 1219: }
 1220: // ]]>
 1221: </script>
 1222: END
 1223:     # output the initial values for the selection lists
 1224:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
 1225:     my @order = sort(keys(%{$hashref}));
 1226:     if (ref($menuorder) eq 'ARRAY') {
 1227:         @order = @{$menuorder};
 1228:     }
 1229:     foreach my $value (@order) {
 1230:         $result.="    <option value=\"$value\" ";
 1231:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1232:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1233:     }
 1234:     $result .= "</select>\n";
 1235:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1236:     $result .= $middletext;
 1237:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
 1238:     if ($onchangesecond) {
 1239:         $result .= ' onchange="'.$onchangesecond.'"';
 1240:     }
 1241:     $result .= ">\n";
 1242:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1243:     
 1244:     my @secondorder = sort(keys(%select2));
 1245:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1246:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1247:     }
 1248:     foreach my $value (@secondorder) {
 1249:         $result.="    <option value=\"$value\" ";        
 1250:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1251:         $result.=">".&mt($select2{$value})."</option>\n";
 1252:     }
 1253:     $result .= "</select>\n";
 1254:     #    return $debug;
 1255:     return $result;
 1256: }   #  end of sub linked_select_forms {
 1257: 
 1258: =pod
 1259: 
 1260: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1261: 
 1262: Returns a string corresponding to an HTML link to the given help
 1263: $topic, where $topic corresponds to the name of a .tex file in
 1264: /home/httpd/html/adm/help/tex, with underscores replaced by
 1265: spaces. 
 1266: 
 1267: $text will optionally be linked to the same topic, allowing you to
 1268: link text in addition to the graphic. If you do not want to link
 1269: text, but wish to specify one of the later parameters, pass an
 1270: empty string. 
 1271: 
 1272: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1273: the link will not open a new window. If false, the link will open
 1274: a new window using Javascript. (Default is false.) 
 1275: 
 1276: $width and $height are optional numerical parameters that will
 1277: override the width and height of the popped up window, which may
 1278: be useful for certain help topics with big pictures included.
 1279: 
 1280: $imgid is the id of the img tag used for the help icon. This may be
 1281: used in a javascript call to switch the image src.  See 
 1282: lonhtmlcommon::htmlareaselectactive() for an example.
 1283: 
 1284: =cut
 1285: 
 1286: sub help_open_topic {
 1287:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1288:     $text = "" if (not defined $text);
 1289:     $stayOnPage = 0 if (not defined $stayOnPage);
 1290:     $width = 500 if (not defined $width);
 1291:     $height = 400 if (not defined $height);
 1292:     my $filename = $topic;
 1293:     $filename =~ s/ /_/g;
 1294: 
 1295:     my $template = "";
 1296:     my $link;
 1297:     
 1298:     $topic=~s/\W/\_/g;
 1299: 
 1300:     if (!$stayOnPage) {
 1301: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1302:     } elsif ($stayOnPage eq 'popup') {
 1303:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1304:     } else {
 1305: 	$link = "/adm/help/${filename}.hlp";
 1306:     }
 1307: 
 1308:     # Add the text
 1309:     my $target = ' target="_top"';
 1310:     if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
 1311:         $target = '';
 1312:     }
 1313:     if ($text ne "") {	
 1314: 	$template.='<span class="LC_help_open_topic">'
 1315:                   .'<a'.$target.' href="'.$link.'">'
 1316:                   .$text.'</a>';
 1317:     }
 1318: 
 1319:     # (Always) Add the graphic
 1320:     my $title = &mt('Online Help');
 1321:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1322:     if ($imgid ne '') {
 1323:         $imgid = ' id="'.$imgid.'"';
 1324:     }
 1325:     $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
 1326:               .'<img src="'.$helpicon.'" border="0"'
 1327:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1328:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1329:               .' /></a>';
 1330:     if ($text ne "") {	
 1331:         $template.='</span>';
 1332:     }
 1333:     return $template;
 1334: 
 1335: }
 1336: 
 1337: # This is a quicky function for Latex cheatsheet editing, since it 
 1338: # appears in at least four places
 1339: sub helpLatexCheatsheet {
 1340:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1341:     my $out;
 1342:     my $addOther = '';
 1343:     if ($topic) {
 1344: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1345:     }
 1346:     $out = '<span>' # Start cheatsheet
 1347: 	  .$addOther
 1348:           .'<span>'
 1349: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1350: 	  .'</span> <span>'
 1351: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1352: 	  .'</span>';
 1353:     unless ($not_author) {
 1354:         $out .= '<span>'
 1355:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1356:                .'</span> <span>'
 1357:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
 1358: 	       .'</span>';
 1359:     }
 1360:     $out .= '</span>'; # End cheatsheet
 1361:     return $out;
 1362: }
 1363: 
 1364: sub general_help {
 1365:     my $helptopic='Student_Intro';
 1366:     if ($env{'request.role'}=~/^(ca|au)/) {
 1367: 	$helptopic='Authoring_Intro';
 1368:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1369: 	$helptopic='Course_Coordination_Intro';
 1370:     } elsif ($env{'request.role'}=~/^dc/) {
 1371:         $helptopic='Domain_Coordination_Intro';
 1372:     }
 1373:     return $helptopic;
 1374: }
 1375: 
 1376: sub update_help_link {
 1377:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1378:     my $origurl = $ENV{'REQUEST_URI'};
 1379:     $origurl=~s|^/~|/priv/|;
 1380:     my $timestamp = time;
 1381:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1382:         $$datum = &escape($$datum);
 1383:     }
 1384: 
 1385:     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";
 1386:     my $output .= <<"ENDOUTPUT";
 1387: <script type="text/javascript">
 1388: // <![CDATA[
 1389: banner_link = '$banner_link';
 1390: // ]]>
 1391: </script>
 1392: ENDOUTPUT
 1393:     return $output;
 1394: }
 1395: 
 1396: # now just updates the help link and generates a blue icon
 1397: sub help_open_menu {
 1398:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1399: 	= @_;    
 1400:     $stayOnPage = 1;
 1401:     my $output;
 1402:     if ($component_help) {
 1403: 	if (!$text) {
 1404: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1405: 				       $width,$height);
 1406: 	} else {
 1407: 	    my $help_text;
 1408: 	    $help_text=&unescape($topic);
 1409: 	    $output='<table><tr><td>'.
 1410: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1411: 				 $width,$height).'</td></tr></table>';
 1412: 	}
 1413:     }
 1414:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1415:     return $output.$banner_link;
 1416: }
 1417: 
 1418: sub top_nav_help {
 1419:     my ($text,$linkattr) = @_;
 1420:     $text = &mt($text);
 1421:     my $stay_on_page = 1;
 1422: 
 1423:     my ($link,$banner_link);
 1424:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
 1425:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1426: 	                         : "javascript:helpMenu('open')";
 1427:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1428:     }
 1429:     my $title = &mt('Get help');
 1430:     if ($link) {
 1431:         return <<"END";
 1432: $banner_link
 1433: <a href="$link" title="$title" $linkattr>$text</a>
 1434: END
 1435:     } else {
 1436:         return '&nbsp;'.$text.'&nbsp;';
 1437:     }
 1438: }
 1439: 
 1440: sub help_menu_js {
 1441:     my ($httphost) = @_;
 1442:     my $stayOnPage = 1;
 1443:     my $width = 620;
 1444:     my $height = 600;
 1445:     my $helptopic=&general_help();
 1446:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
 1447:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1448:     my $start_page =
 1449:         &Apache::loncommon::start_page('Help Menu', undef,
 1450: 				       {'frameset'    => 1,
 1451: 					'js_ready'    => 1,
 1452:                                         'use_absolute' => $httphost,
 1453: 					'add_entries' => {
 1454: 					    'border' => '0', 
 1455: 					    'rows'   => "110,*",},});
 1456:     my $end_page =
 1457:         &Apache::loncommon::end_page({'frameset' => 1,
 1458: 				      'js_ready' => 1,});
 1459: 
 1460:     my $template .= <<"ENDTEMPLATE";
 1461: <script type="text/javascript">
 1462: // <![CDATA[
 1463: // <!-- BEGIN LON-CAPA Internal
 1464: var banner_link = '';
 1465: function helpMenu(target) {
 1466:     var caller = this;
 1467:     if (target == 'open') {
 1468:         var newWindow = null;
 1469:         try {
 1470:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1471:         }
 1472:         catch(error) {
 1473:             writeHelp(caller);
 1474:             return;
 1475:         }
 1476:         if (newWindow) {
 1477:             caller = newWindow;
 1478:         }
 1479:     }
 1480:     writeHelp(caller);
 1481:     return;
 1482: }
 1483: function writeHelp(caller) {
 1484:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
 1485:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
 1486:     caller.document.close();
 1487:     caller.focus();
 1488: }
 1489: // END LON-CAPA Internal -->
 1490: // ]]>
 1491: </script>
 1492: ENDTEMPLATE
 1493:     return $template;
 1494: }
 1495: 
 1496: sub help_open_bug {
 1497:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1498:     unless ($env{'user.adv'}) { return ''; }
 1499:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1500:     $text = "" if (not defined $text);
 1501: 	$stayOnPage=1;
 1502:     $width = 600 if (not defined $width);
 1503:     $height = 600 if (not defined $height);
 1504: 
 1505:     $topic=~s/\W+/\+/g;
 1506:     my $link='';
 1507:     my $template='';
 1508:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1509: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1510:     if (!$stayOnPage)
 1511:     {
 1512: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1513:     }
 1514:     else
 1515:     {
 1516: 	$link = $url;
 1517:     }
 1518: 
 1519:     my $target = ' target="_top"';
 1520:     if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
 1521:         $target = '';
 1522:     }
 1523:     # Add the text
 1524:     if ($text ne "")
 1525:     {
 1526: 	$template .= 
 1527:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1528:   "<td bgcolor='#FF5555'><a".$target." href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1529:     }
 1530: 
 1531:     # Add the graphic
 1532:     my $title = &mt('Report a Bug');
 1533:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1534:     $template .= <<"ENDTEMPLATE";
 1535:  <a$target href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1536: ENDTEMPLATE
 1537:     if ($text ne '') { $template.='</td></tr></table>' };
 1538:     return $template;
 1539: 
 1540: }
 1541: 
 1542: sub help_open_faq {
 1543:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1544:     unless ($env{'user.adv'}) { return ''; }
 1545:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1546:     $text = "" if (not defined $text);
 1547: 	$stayOnPage=1;
 1548:     $width = 350 if (not defined $width);
 1549:     $height = 400 if (not defined $height);
 1550: 
 1551:     $topic=~s/\W+/\+/g;
 1552:     my $link='';
 1553:     my $template='';
 1554:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1555:     if (!$stayOnPage)
 1556:     {
 1557: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1558:     }
 1559:     else
 1560:     {
 1561: 	$link = $url;
 1562:     }
 1563: 
 1564:     # Add the text
 1565:     if ($text ne "")
 1566:     {
 1567: 	$template .= 
 1568:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1569:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1570:     }
 1571: 
 1572:     # Add the graphic
 1573:     my $title = &mt('View the FAQ');
 1574:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1575:     $template .= <<"ENDTEMPLATE";
 1576:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1577: ENDTEMPLATE
 1578:     if ($text ne '') { $template.='</td></tr></table>' };
 1579:     return $template;
 1580: 
 1581: }
 1582: 
 1583: ###############################################################
 1584: ###############################################################
 1585: 
 1586: =pod
 1587: 
 1588: =item * &change_content_javascript():
 1589: 
 1590: This and the next function allow you to create small sections of an
 1591: otherwise static HTML page that you can update on the fly with
 1592: Javascript, even in Netscape 4.
 1593: 
 1594: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1595: must be written to the HTML page once. It will prove the Javascript
 1596: function "change(name, content)". Calling the change function with the
 1597: name of the section 
 1598: you want to update, matching the name passed to C<changable_area>, and
 1599: the new content you want to put in there, will put the content into
 1600: that area.
 1601: 
 1602: B<Note>: Netscape 4 only reserves enough space for the changable area
 1603: to contain room for the original contents. You need to "make space"
 1604: for whatever changes you wish to make, and be B<sure> to check your
 1605: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1606: it's adequate for updating a one-line status display, but little more.
 1607: This script will set the space to 100% width, so you only need to
 1608: worry about height in Netscape 4.
 1609: 
 1610: Modern browsers are much less limiting, and if you can commit to the
 1611: user not using Netscape 4, this feature may be used freely with
 1612: pretty much any HTML.
 1613: 
 1614: =cut
 1615: 
 1616: sub change_content_javascript {
 1617:     # If we're on Netscape 4, we need to use Layer-based code
 1618:     if ($env{'browser.type'} eq 'netscape' &&
 1619: 	$env{'browser.version'} =~ /^4\./) {
 1620: 	return (<<NETSCAPE4);
 1621: 	function change(name, content) {
 1622: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1623: 	    doc.open();
 1624: 	    doc.write(content);
 1625: 	    doc.close();
 1626: 	}
 1627: NETSCAPE4
 1628:     } else {
 1629: 	# Otherwise, we need to use semi-standards-compliant code
 1630: 	# (technically, "innerHTML" isn't standard but the equivalent
 1631: 	# is really scary, and every useful browser supports it
 1632: 	return (<<DOMBASED);
 1633: 	function change(name, content) {
 1634: 	    element = document.getElementById(name);
 1635: 	    element.innerHTML = content;
 1636: 	}
 1637: DOMBASED
 1638:     }
 1639: }
 1640: 
 1641: =pod
 1642: 
 1643: =item * &changable_area($name,$origContent):
 1644: 
 1645: This provides a "changable area" that can be modified on the fly via
 1646: the Javascript code provided in C<change_content_javascript>. $name is
 1647: the name you will use to reference the area later; do not repeat the
 1648: same name on a given HTML page more then once. $origContent is what
 1649: the area will originally contain, which can be left blank.
 1650: 
 1651: =cut
 1652: 
 1653: sub changable_area {
 1654:     my ($name, $origContent) = @_;
 1655: 
 1656:     if ($env{'browser.type'} eq 'netscape' &&
 1657: 	$env{'browser.version'} =~ /^4\./) {
 1658: 	# If this is netscape 4, we need to use the Layer tag
 1659: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1660:     } else {
 1661: 	return "<span id='$name'>$origContent</span>";
 1662:     }
 1663: }
 1664: 
 1665: =pod
 1666: 
 1667: =item * &viewport_geometry_js 
 1668: 
 1669: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1670: 
 1671: =cut
 1672: 
 1673: 
 1674: sub viewport_geometry_js { 
 1675:     return <<"GEOMETRY";
 1676: var Geometry = {};
 1677: function init_geometry() {
 1678:     if (Geometry.init) { return };
 1679:     Geometry.init=1;
 1680:     if (window.innerHeight) {
 1681:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1682:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1683:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1684:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1685:     }
 1686:     else if (document.documentElement && document.documentElement.clientHeight) {
 1687:         Geometry.getViewportHeight =
 1688:             function() { return document.documentElement.clientHeight; };
 1689:         Geometry.getViewportWidth =
 1690:             function() { return document.documentElement.clientWidth; };
 1691: 
 1692:         Geometry.getHorizontalScroll =
 1693:             function() { return document.documentElement.scrollLeft; };
 1694:         Geometry.getVerticalScroll =
 1695:             function() { return document.documentElement.scrollTop; };
 1696:     }
 1697:     else if (document.body.clientHeight) {
 1698:         Geometry.getViewportHeight =
 1699:             function() { return document.body.clientHeight; };
 1700:         Geometry.getViewportWidth =
 1701:             function() { return document.body.clientWidth; };
 1702:         Geometry.getHorizontalScroll =
 1703:             function() { return document.body.scrollLeft; };
 1704:         Geometry.getVerticalScroll =
 1705:             function() { return document.body.scrollTop; };
 1706:     }
 1707: }
 1708: 
 1709: GEOMETRY
 1710: }
 1711: 
 1712: =pod
 1713: 
 1714: =item * &viewport_size_js()
 1715: 
 1716: 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. 
 1717: 
 1718: =cut
 1719: 
 1720: sub viewport_size_js {
 1721:     my $geometry = &viewport_geometry_js();
 1722:     return <<"DIMS";
 1723: 
 1724: $geometry
 1725: 
 1726: function getViewportDims(width,height) {
 1727:     init_geometry();
 1728:     width.value = Geometry.getViewportWidth();
 1729:     height.value = Geometry.getViewportHeight();
 1730:     return;
 1731: }
 1732: 
 1733: DIMS
 1734: }
 1735: 
 1736: =pod
 1737: 
 1738: =item * &resize_textarea_js()
 1739: 
 1740: emits the needed javascript to resize a textarea to be as big as possible
 1741: 
 1742: creates a function resize_textrea that takes two IDs first should be
 1743: the id of the element to resize, second should be the id of a div that
 1744: surrounds everything that comes after the textarea, this routine needs
 1745: to be attached to the <body> for the onload and onresize events.
 1746: 
 1747: =back
 1748: 
 1749: =cut
 1750: 
 1751: sub resize_textarea_js {
 1752:     my $geometry = &viewport_geometry_js();
 1753:     return <<"RESIZE";
 1754:     <script type="text/javascript">
 1755: // <![CDATA[
 1756: $geometry
 1757: 
 1758: function getX(element) {
 1759:     var x = 0;
 1760:     while (element) {
 1761: 	x += element.offsetLeft;
 1762: 	element = element.offsetParent;
 1763:     }
 1764:     return x;
 1765: }
 1766: function getY(element) {
 1767:     var y = 0;
 1768:     while (element) {
 1769: 	y += element.offsetTop;
 1770: 	element = element.offsetParent;
 1771:     }
 1772:     return y;
 1773: }
 1774: 
 1775: 
 1776: function resize_textarea(textarea_id,bottom_id) {
 1777:     init_geometry();
 1778:     var textarea        = document.getElementById(textarea_id);
 1779:     //alert(textarea);
 1780: 
 1781:     var textarea_top    = getY(textarea);
 1782:     var textarea_height = textarea.offsetHeight;
 1783:     var bottom          = document.getElementById(bottom_id);
 1784:     var bottom_top      = getY(bottom);
 1785:     var bottom_height   = bottom.offsetHeight;
 1786:     var window_height   = Geometry.getViewportHeight();
 1787:     var fudge           = 23;
 1788:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1789:     if (new_height < 300) {
 1790: 	new_height = 300;
 1791:     }
 1792:     textarea.style.height=new_height+'px';
 1793: }
 1794: // ]]>
 1795: </script>
 1796: RESIZE
 1797: 
 1798: }
 1799: 
 1800: sub colorfuleditor_js {
 1801:     my $browse_or_search;
 1802:     my $respath;
 1803:     my ($cnum,$cdom) = &crsauthor_url();
 1804:     if ($cnum) {
 1805:         $respath = "/res/$cdom/$cnum/";
 1806:         my %js_lt = &Apache::lonlocal::texthash(
 1807:             sunm => 'Sub-directory name',
 1808:             save => 'Save page to make this permanent',
 1809:         );
 1810:         &js_escape(\%js_lt);
 1811:         $browse_or_search = <<"END";
 1812: 
 1813:     function toggleChooser(form,element,titleid,only,search) {
 1814:         var disp = 'none';
 1815:         if (document.getElementById('chooser_'+element)) {
 1816:             var curr = document.getElementById('chooser_'+element).style.display;
 1817:             if (curr == 'none') {
 1818:                 disp='inline';
 1819:                 if (form.elements['chooser_'+element].length) {
 1820:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
 1821:                         form.elements['chooser_'+element][i].checked = false;
 1822:                     }
 1823:                 }
 1824:                 toggleResImport(form,element);
 1825:             }
 1826:             document.getElementById('chooser_'+element).style.display = disp;
 1827:         }
 1828:     }
 1829: 
 1830:     function toggleCrsFile(form,element,numdirs) {
 1831:         if (document.getElementById('chooser_'+element+'_crsres')) {
 1832:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
 1833:             if (curr == 'none') {
 1834:                 if (numdirs) {
 1835:                     form.elements['coursepath_'+element].selectedIndex = 0;
 1836:                     if (numdirs > 1) {
 1837:                         window['select1'+element+'_changed']();
 1838:                     }
 1839:                 }
 1840:             } 
 1841:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
 1842:             
 1843:         }
 1844:         if (document.getElementById('chooser_'+element+'_upload')) {
 1845:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
 1846:             if (document.getElementById('uploadcrsres_'+element)) {
 1847:                 document.getElementById('uploadcrsres_'+element).value = '';
 1848:             }
 1849:         }
 1850:         return;
 1851:     }
 1852: 
 1853:     function toggleCrsUpload(form,element,numcrsdirs) {
 1854:         if (document.getElementById('chooser_'+element+'_crsres')) {
 1855:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
 1856:         }
 1857:         if (document.getElementById('chooser_'+element+'_upload')) {
 1858:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
 1859:             if (curr == 'none') {
 1860:                 if (numcrsdirs) {
 1861:                    form.elements['crsauthorpath_'+element].selectedIndex = 0;
 1862:                    form.elements['newsubdir_'+element][0].checked = true;
 1863:                    toggleNewsubdir(form,element);
 1864:                 }
 1865:             }
 1866:             document.getElementById('chooser_'+element+'_upload').style.display = 'block';
 1867:         }
 1868:         return;
 1869:     }
 1870: 
 1871:     function toggleResImport(form,element) {
 1872:         var choices = new Array('crsres','upload');
 1873:         for (var i=0; i<choices.length; i++) {
 1874:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
 1875:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
 1876:             }
 1877:         }
 1878:     }
 1879: 
 1880:     function toggleNewsubdir(form,element) {
 1881:         var newsub = form.elements['newsubdir_'+element];
 1882:         if (newsub) {
 1883:             if (newsub.length) {
 1884:                 for (var j=0; j<newsub.length; j++) {
 1885:                     if (newsub[j].checked) {
 1886:                         if (document.getElementById('newsubdirname_'+element)) {
 1887:                             if (newsub[j].value == '1') {
 1888:                                 document.getElementById('newsubdirname_'+element).type = "text";
 1889:                                 if (document.getElementById('newsubdir_'+element)) {
 1890:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
 1891:                                 }
 1892:                             } else {
 1893:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
 1894:                                 document.getElementById('newsubdirname_'+element).value = "";
 1895:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
 1896:                             }
 1897:                         }
 1898:                         break; 
 1899:                     }
 1900:                 }
 1901:             }
 1902:         }
 1903:     }
 1904: 
 1905:     function updateCrsFile(form,element) {
 1906:         var directory = form.elements['coursepath_'+element];
 1907:         var filename = form.elements['coursefile_'+element];
 1908:         var path = directory.options[directory.selectedIndex].value;
 1909:         var file = filename.options[filename.selectedIndex].value;
 1910:         form.elements[element].value = '$respath';
 1911:         if (path == '/') {
 1912:             form.elements[element].value += file;
 1913:         } else {
 1914:             form.elements[element].value += path+'/'+file;
 1915:         }
 1916:         unClean();
 1917:         if (document.getElementById('previewimg_'+element)) {
 1918:             document.getElementById('previewimg_'+element).src = form.elements[element].value;
 1919:             var newsrc = document.getElementById('previewimg_'+element).src; 
 1920:         }
 1921:         if (document.getElementById('showimg_'+element)) {
 1922:             document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
 1923:         }
 1924:         toggleChooser(form,element);
 1925:         return;
 1926:     }
 1927: 
 1928:     function uploadDone(suffix,name) {
 1929:         if (name) {
 1930: 	    document.forms["lonhomework"].elements[suffix].value = name;
 1931:             unClean();
 1932:             toggleChooser(document.forms["lonhomework"],suffix);
 1933:         }
 1934:     }
 1935: 
 1936: \$(document).ready(function(){
 1937: 
 1938:     \$(document).delegate('form :submit', 'click', function( event ) {
 1939:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
 1940:             var buttonId = this.id;
 1941:             var suffix = buttonId.toString();
 1942:             suffix = suffix.replace(/^crsupload_/,'');
 1943:             event.preventDefault();
 1944:             document.lonhomework.target = 'crsupload_target_'+suffix;
 1945:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
 1946:             \$(this.form).submit();
 1947:             document.lonhomework.target = '';
 1948:             if (document.getElementById('crsuploadto_'+suffix)) {
 1949:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
 1950:             }
 1951:             return false;
 1952:         }
 1953:     });
 1954: });
 1955: END
 1956:     }
 1957:     return <<"COLORFULEDIT"
 1958: <script type="text/javascript">
 1959: // <![CDATA[>
 1960:     function fold_box(curDepth, lastresource){
 1961: 
 1962:     // we need a list because there can be several blocks you need to fold in one tag
 1963:         var block = document.getElementsByName('foldblock_'+curDepth);
 1964:     // but there is only one folding button per tag
 1965:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
 1966: 
 1967:         if(block.item(0).style.display == 'none'){
 1968: 
 1969:             foldbutton.value = '@{[&mt("Hide")]}';
 1970:             for (i = 0; i < block.length; i++){
 1971:                 block.item(i).style.display = '';
 1972:             }
 1973:         }else{
 1974: 
 1975:             foldbutton.value = '@{[&mt("Show")]}';
 1976:             for (i = 0; i < block.length; i++){
 1977:                 // block.item(i).style.visibility = 'collapse';
 1978:                 block.item(i).style.display = 'none';
 1979:             }
 1980:         };
 1981:         saveState(lastresource);
 1982:     }
 1983: 
 1984:     function saveState (lastresource) {
 1985: 
 1986:         var tag_list = getTagList();
 1987:         if(tag_list != null){
 1988:             var timestamp = new Date().getTime();
 1989:             var key = lastresource;
 1990: 
 1991:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
 1992:             // starting with timestamp
 1993:             var value = timestamp+';';
 1994: 
 1995:             // building the list of key-value pairs
 1996:             for(var i = 0; i < tag_list.length; i++){
 1997:                 value += tag_list[i]+',';
 1998:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
 1999:             }
 2000: 
 2001:             // only iterate whole storage if nothing to override
 2002:             if(localStorage.getItem(key) == null){        
 2003: 
 2004:                 // prevent storage from growing large
 2005:                 if(localStorage.length > 50){
 2006:                     var regex_getTimestamp = /^(?:\d)+;/;
 2007:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
 2008:                     var oldest_key;
 2009:                     
 2010:                     for(var i = 1; i < localStorage.length; i++){
 2011:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
 2012:                             oldest_key = localStorage.key(i);
 2013:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
 2014:                         }
 2015:                     }
 2016:                     localStorage.removeItem(oldest_key);
 2017:                 }
 2018:             }
 2019:             localStorage.setItem(key,value);
 2020:         }
 2021:     }
 2022: 
 2023:     // restore folding status of blocks (on page load)
 2024:     function restoreState (lastresource) {
 2025:         if(localStorage.getItem(lastresource) != null){
 2026:             var key = lastresource;
 2027:             var value = localStorage.getItem(key);
 2028:             var regex_delTimestamp = /^\d+;/;
 2029: 
 2030:             value.replace(regex_delTimestamp, '');
 2031: 
 2032:             var valueArr = value.split(';');
 2033:             var pairs;
 2034:             var elements;
 2035:             for (var i = 0; i < valueArr.length; i++){
 2036:                 pairs = valueArr[i].split(',');
 2037:                 elements = document.getElementsByName(pairs[0]);
 2038: 
 2039:                 for (var j = 0; j < elements.length; j++){  
 2040:                     elements[j].style.display = pairs[1];
 2041:                     if (pairs[1] == "none"){
 2042:                         var regex_id = /([_\\d]+)\$/;
 2043:                         regex_id.exec(pairs[0]);
 2044:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
 2045:                     }
 2046:                 }
 2047:             }
 2048:         }
 2049:     }
 2050: 
 2051:     function getTagList () {
 2052:         
 2053:         var stringToSearch = document.lonhomework.innerHTML;
 2054: 
 2055:         var ret = new Array();
 2056:         var regex_findBlock = /(foldblock_.*?)"/g;
 2057:         var tag_list = stringToSearch.match(regex_findBlock);
 2058: 
 2059:         if(tag_list != null){
 2060:             for(var i = 0; i < tag_list.length; i++){            
 2061:                 ret.push(tag_list[i].replace(/"/, ''));
 2062:             }
 2063:         }
 2064:         return ret;
 2065:     }
 2066: 
 2067:     function saveScrollPosition (resource) {
 2068:         var tag_list = getTagList();
 2069: 
 2070:         // we dont always want to jump to the first block
 2071:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
 2072:         if(\$(window).scrollTop() > 170){
 2073:             if(tag_list != null){
 2074:                 var result;
 2075:                 for(var i = 0; i < tag_list.length; i++){
 2076:                     if(isElementInViewport(tag_list[i])){
 2077:                         result += tag_list[i]+';';
 2078:                     }
 2079:                 }
 2080:                 sessionStorage.setItem('anchor_'+resource, result);
 2081:             }
 2082:         } else {
 2083:             // we dont need to save zero, just delete the item to leave everything tidy
 2084:             sessionStorage.removeItem('anchor_'+resource);
 2085:         }
 2086:     }
 2087: 
 2088:     function restoreScrollPosition(resource){
 2089: 
 2090:         var elem = sessionStorage.getItem('anchor_'+resource);
 2091:         if(elem != null){
 2092:             var tag_list = elem.split(';');
 2093:             var elem_list;
 2094: 
 2095:             for(var i = 0; i < tag_list.length; i++){
 2096:                 elem_list = document.getElementsByName(tag_list[i]);
 2097:                 
 2098:                 if(elem_list.length > 0){
 2099:                     elem = elem_list[0];
 2100:                     break;
 2101:                 }
 2102:             }
 2103:             elem.scrollIntoView();
 2104:         }
 2105:     }
 2106: 
 2107:     function isElementInViewport(el) {
 2108: 
 2109:         // change to last element instead of first
 2110:         var elem = document.getElementsByName(el);
 2111:         var rect = elem[0].getBoundingClientRect();
 2112: 
 2113:         return (
 2114:             rect.top >= 0 &&
 2115:             rect.left >= 0 &&
 2116:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
 2117:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
 2118:         );
 2119:     }
 2120:     
 2121:     function autosize(depth){
 2122:         var cmInst = window['cm'+depth];
 2123:         var fitsizeButton = document.getElementById('fitsize'+depth);
 2124: 
 2125:         // is fixed size, switching to dynamic
 2126:         if (sessionStorage.getItem("autosized_"+depth) == null) {
 2127:             cmInst.setSize("","auto");
 2128:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
 2129:             sessionStorage.setItem("autosized_"+depth, "yes");
 2130: 
 2131:         // is dynamic size, switching to fixed
 2132:         } else {
 2133:             cmInst.setSize("","300px");
 2134:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
 2135:             sessionStorage.removeItem("autosized_"+depth);
 2136:         }
 2137:     }
 2138: 
 2139: $browse_or_search
 2140: 
 2141: // ]]>
 2142: </script>
 2143: COLORFULEDIT
 2144: }
 2145: 
 2146: sub xmleditor_js {
 2147:     return <<XMLEDIT
 2148: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
 2149: <script type="text/javascript">
 2150: // <![CDATA[>
 2151: 
 2152:     function saveScrollPosition (resource) {
 2153: 
 2154:         var scrollPos = \$(window).scrollTop();
 2155:         sessionStorage.setItem(resource,scrollPos);
 2156:     }
 2157: 
 2158:     function restoreScrollPosition(resource){
 2159: 
 2160:         var scrollPos = sessionStorage.getItem(resource);
 2161:         \$(window).scrollTop(scrollPos);
 2162:     }
 2163: 
 2164:     // unless internet explorer
 2165:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
 2166: 
 2167:         \$(document).ready(function() {
 2168:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
 2169:         });
 2170:     }
 2171: 
 2172:     // inserts text at cursor position into codemirror (xml editor only)
 2173:     function insertText(text){
 2174:         cm.focus();
 2175:         var curPos = cm.getCursor();
 2176:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
 2177:     }
 2178: // ]]>
 2179: </script>
 2180: XMLEDIT
 2181: }
 2182: 
 2183: sub insert_folding_button {
 2184:     my $curDepth = $Apache::lonxml::curdepth;
 2185:     my $lastresource = $env{'request.ambiguous'};
 2186: 
 2187:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
 2188:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
 2189: }
 2190: 
 2191: sub crsauthor_url {
 2192:     my ($url) = @_;
 2193:     if ($url eq '') {
 2194:         $url = $ENV{'REQUEST_URI'};
 2195:     }
 2196:     my ($cnum,$cdom);
 2197:     if ($env{'request.course.id'}) {
 2198:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
 2199:         if ($audom ne '' && $auname ne '') {
 2200:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
 2201:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
 2202:                 $cnum = $auname;
 2203:                 $cdom = $audom;
 2204:             }
 2205:         }
 2206:     }
 2207:     return ($cnum,$cdom);
 2208: }
 2209: 
 2210: sub import_crsauthor_form {
 2211:     my ($form,$firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
 2212:     return (0) unless ($env{'request.course.id'});
 2213:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2214:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2215:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
 2216:     return (0) unless (($cnum ne '') && ($cdom ne ''));
 2217:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 2218:     my @ids=&Apache::lonnet::current_machine_ids();
 2219:     my ($output,$is_home,$relpath,%subdirs,%files,%selimport_menus);
 2220:     
 2221:     if (grep(/^\Q$crshome\E$/,@ids)) {
 2222:         $is_home = 1;
 2223:     }
 2224:     $relpath = "/priv/$cdom/$cnum";
 2225:     &Apache::lonnet::recursedirs($is_home,'priv',$londocroot,$relpath,'',\%subdirs,\%files);
 2226:     my %lt = &Apache::lonlocal::texthash (
 2227:         fnam => 'Filename',
 2228:         dire => 'Directory',
 2229:     );
 2230:     my $numdirs = scalar(keys(%files));
 2231:     my (%possexts,$singledir,@singledirfiles);
 2232:     if ($only) {
 2233:         map { $possexts{$_} = 1; } split(/\s*,\s*/,$only);
 2234:     }
 2235:     my (%nonemptydirs,$possdirs);
 2236:     if ($numdirs > 1) {
 2237:         my @order;
 2238:         foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
 2239:             if (ref($files{$key}) eq 'HASH') {
 2240:                 my $shown = $key;
 2241:                 if ($key eq '') {
 2242:                     $shown = '/';
 2243:                 }
 2244:                 my @ordered = ();
 2245:                 foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$key}}))) {
 2246:                     next if ($file =~ /\.rights$/);
 2247:                     if ($only) {
 2248:                         my ($ext) = ($file =~ /\.([^.]+)$/);
 2249:                         unless ($possexts{lc($ext)}) {
 2250:                             next;
 2251:                         }
 2252:                     }
 2253:                     $selimport_menus{$key}->{'select2'}->{$file} = $file;
 2254:                     push(@ordered,$file);
 2255:                 }
 2256:                 if (@ordered) {
 2257:                     push(@order,$key);
 2258:                     $nonemptydirs{$key} = 1;
 2259:                     $selimport_menus{$key}->{'text'} = $shown;
 2260:                     $selimport_menus{$key}->{'default'} = '';
 2261:                     $selimport_menus{$key}->{'select2'}->{''} = '';
 2262:                     $selimport_menus{$key}->{'order'} = \@ordered;
 2263:                 }
 2264:             }
 2265:         }
 2266:         $possdirs = scalar(keys(%nonemptydirs));
 2267:         if ($possdirs > 1) {
 2268:             my @order = sort { lc($a) cmp lc($b) } (keys(%nonemptydirs));
 2269:             $output = $lt{'dire'}.
 2270:                       &linked_select_forms($form,'<br />'.
 2271:                                            $lt{'fnam'},'',
 2272:                                            $firstselectname,$secondselectname,
 2273:                                            \%selimport_menus,\@order,
 2274:                                            $onchangefirst,'',$suffix).'<br />';
 2275:         } elsif ($possdirs == 1) {
 2276:             $singledir = (keys(%nonemptydirs))[0];
 2277:             if (ref($selimport_menus{$singledir}->{'order'}) eq 'ARRAY') {
 2278:                 @singledirfiles = @{$selimport_menus{$singledir}->{'order'}};
 2279:             }
 2280:             delete($selimport_menus{$singledir});
 2281:         }
 2282:     } elsif ($numdirs == 1) {
 2283:         $singledir = (keys(%files))[0];
 2284:         foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$singledir}}))) {
 2285:             if ($only) {
 2286:                 my ($ext) = ($file =~ /\.([^.]+)$/);
 2287:                 unless ($possexts{lc($ext)}) {
 2288:                     next;
 2289:                 }
 2290:             } else {
 2291:                 next if ($file =~ /\.rights$/);
 2292:             }
 2293:             push(@singledirfiles,$file);
 2294:         }
 2295:         if (@singledirfiles) {
 2296:             $possdirs = 1;
 2297:         }
 2298:     }
 2299:     if (($possdirs == 1) && (@singledirfiles)) {
 2300:         my $showdir = $singledir;
 2301:         if ($singledir eq '') {
 2302:             $showdir = '/';
 2303:         }
 2304:         $output = $lt{'dire'}.
 2305:                   '<select name="'.$firstselectname.'">'.
 2306:                   '<option value="'.$singledir.'">'.$showdir.'</option>'."\n".
 2307:                   '</select><br />'.
 2308:                   $lt{'fnam'}.'<select name="'.$secondselectname.'">'."\n".
 2309:                   '<option value="" selected="selected">'.$lt{'se'}.'</option>'."\n";
 2310:         foreach my $file (@singledirfiles) {
 2311:             $output .= '<option value="'.$file.'">'.$file.'</option>'."\n";
 2312:         }
 2313:         $output .= '</select><br />'."\n";
 2314:     }
 2315:     return ($possdirs,$output);
 2316: }
 2317: 
 2318: =pod
 2319: 
 2320: =head1 Excel and CSV file utility routines
 2321: 
 2322: =cut
 2323: 
 2324: ###############################################################
 2325: ###############################################################
 2326: 
 2327: =pod
 2328: 
 2329: =over 4
 2330: 
 2331: =item * &csv_translate($text) 
 2332: 
 2333: Translate $text to allow it to be output as a 'comma separated values' 
 2334: format.
 2335: 
 2336: =cut
 2337: 
 2338: ###############################################################
 2339: ###############################################################
 2340: sub csv_translate {
 2341:     my $text = shift;
 2342:     $text =~ s/\"/\"\"/g;
 2343:     $text =~ s/\n/ /g;
 2344:     return $text;
 2345: }
 2346: 
 2347: ###############################################################
 2348: ###############################################################
 2349: 
 2350: =pod
 2351: 
 2352: =item * &define_excel_formats()
 2353: 
 2354: Define some commonly used Excel cell formats.
 2355: 
 2356: Currently supported formats:
 2357: 
 2358: =over 4
 2359: 
 2360: =item header
 2361: 
 2362: =item bold
 2363: 
 2364: =item h1
 2365: 
 2366: =item h2
 2367: 
 2368: =item h3
 2369: 
 2370: =item h4
 2371: 
 2372: =item i
 2373: 
 2374: =item date
 2375: 
 2376: =back
 2377: 
 2378: Inputs: $workbook
 2379: 
 2380: Returns: $format, a hash reference.
 2381: 
 2382: 
 2383: =cut
 2384: 
 2385: ###############################################################
 2386: ###############################################################
 2387: sub define_excel_formats {
 2388:     my ($workbook) = @_;
 2389:     my $format;
 2390:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 2391:                                                 bottom    => 1,
 2392:                                                 align     => 'center');
 2393:     $format->{'bold'} = $workbook->add_format(bold=>1);
 2394:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 2395:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 2396:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 2397:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 2398:     $format->{'i'}    = $workbook->add_format(italic=>1);
 2399:     $format->{'date'} = $workbook->add_format(num_format=>
 2400:                                             'mm/dd/yyyy hh:mm:ss');
 2401:     return $format;
 2402: }
 2403: 
 2404: ###############################################################
 2405: ###############################################################
 2406: 
 2407: =pod
 2408: 
 2409: =item * &create_workbook()
 2410: 
 2411: Create an Excel worksheet.  If it fails, output message on the
 2412: request object and return undefs.
 2413: 
 2414: Inputs: Apache request object
 2415: 
 2416: Returns (undef) on failure, 
 2417:     Excel worksheet object, scalar with filename, and formats 
 2418:     from &Apache::loncommon::define_excel_formats on success
 2419: 
 2420: =cut
 2421: 
 2422: ###############################################################
 2423: ###############################################################
 2424: sub create_workbook {
 2425:     my ($r) = @_;
 2426:         #
 2427:     # Create the excel spreadsheet
 2428:     my $filename = '/prtspool/'.
 2429:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2430:         time.'_'.rand(1000000000).'.xls';
 2431:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 2432:     if (! defined($workbook)) {
 2433:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 2434:         $r->print(
 2435:             '<p class="LC_error">'
 2436:            .&mt('Problems occurred in creating the new Excel file.')
 2437:            .' '.&mt('This error has been logged.')
 2438:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2439:            .'</p>'
 2440:         );
 2441:         return (undef);
 2442:     }
 2443:     #
 2444:     $workbook->set_tempdir(LONCAPA::tempdir());
 2445:     #
 2446:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 2447:     return ($workbook,$filename,$format);
 2448: }
 2449: 
 2450: ###############################################################
 2451: ###############################################################
 2452: 
 2453: =pod
 2454: 
 2455: =item * &create_text_file()
 2456: 
 2457: Create a file to write to and eventually make available to the user.
 2458: If file creation fails, outputs an error message on the request object and 
 2459: return undefs.
 2460: 
 2461: Inputs: Apache request object, and file suffix
 2462: 
 2463: Returns (undef) on failure, 
 2464:     Filehandle and filename on success.
 2465: 
 2466: =cut
 2467: 
 2468: ###############################################################
 2469: ###############################################################
 2470: sub create_text_file {
 2471:     my ($r,$suffix) = @_;
 2472:     if (! defined($suffix)) { $suffix = 'txt'; };
 2473:     my $fh;
 2474:     my $filename = '/prtspool/'.
 2475:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2476:         time.'_'.rand(1000000000).'.'.$suffix;
 2477:     $fh = Apache::File->new('>/home/httpd'.$filename);
 2478:     if (! defined($fh)) {
 2479:         $r->log_error("Couldn't open $filename for output $!");
 2480:         $r->print(
 2481:             '<p class="LC_error">'
 2482:            .&mt('Problems occurred in creating the output file.')
 2483:            .' '.&mt('This error has been logged.')
 2484:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2485:            .'</p>'
 2486:         );
 2487:     }
 2488:     return ($fh,$filename)
 2489: }
 2490: 
 2491: 
 2492: =pod 
 2493: 
 2494: =back
 2495: 
 2496: =cut
 2497: 
 2498: ###############################################################
 2499: ##        Home server <option> list generating code          ##
 2500: ###############################################################
 2501: 
 2502: # ------------------------------------------
 2503: 
 2504: sub domain_select {
 2505:     my ($name,$value,$multiple,$incdoms,$excdoms)=@_;
 2506:     my @possdoms;
 2507:     if (ref($incdoms) eq 'ARRAY') {
 2508:         @possdoms = @{$incdoms};
 2509:     } else {
 2510:         @possdoms = &Apache::lonnet::all_domains();
 2511:     }
 2512: 
 2513:     my %domains=map { 
 2514: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 2515:     } @possdoms;
 2516: 
 2517:     if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
 2518:         foreach my $dom (@{$excdoms}) {
 2519:             delete($domains{$dom});
 2520:         }
 2521:     }
 2522: 
 2523:     if ($multiple) {
 2524: 	$domains{''}=&mt('Any domain');
 2525: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2526: 	return &multiple_select_form($name,$value,4,\%domains);
 2527:     } else {
 2528: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2529: 	return &select_form($name,$value,\%domains);
 2530:     }
 2531: }
 2532: 
 2533: #-------------------------------------------
 2534: 
 2535: =pod
 2536: 
 2537: =head1 Routines for form select boxes
 2538: 
 2539: =over 4
 2540: 
 2541: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 2542: 
 2543: Returns a string containing a <select> element int multiple mode
 2544: 
 2545: 
 2546: Args:
 2547:   $name - name of the <select> element
 2548:   $value - scalar or array ref of values that should already be selected
 2549:   $size - number of rows long the select element is
 2550:   $hash - the elements should be 'option' => 'shown text'
 2551:           (shown text should already have been &mt())
 2552:   $order - (optional) array ref of the order to show the elements in
 2553: 
 2554: =cut
 2555: 
 2556: #-------------------------------------------
 2557: sub multiple_select_form {
 2558:     my ($name,$value,$size,$hash,$order)=@_;
 2559:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 2560:     my $output='';
 2561:     if (! defined($size)) {
 2562:         $size = 4;
 2563:         if (scalar(keys(%$hash))<4) {
 2564:             $size = scalar(keys(%$hash));
 2565:         }
 2566:     }
 2567:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 2568:     my @order;
 2569:     if (ref($order) eq 'ARRAY')  {
 2570:         @order = @{$order};
 2571:     } else {
 2572:         @order = sort(keys(%$hash));
 2573:     }
 2574:     if (exists($$hash{'select_form_order'})) {
 2575:         @order = @{$$hash{'select_form_order'}};
 2576:     }
 2577:         
 2578:     foreach my $key (@order) {
 2579:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 2580:         $output.='selected="selected" ' if ($selected{$key});
 2581:         $output.='>'.$hash->{$key}."</option>\n";
 2582:     }
 2583:     $output.="</select>\n";
 2584:     return $output;
 2585: }
 2586: 
 2587: #-------------------------------------------
 2588: 
 2589: =pod
 2590: 
 2591: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
 2592: 
 2593: Returns a string containing a <select name='$name' size='1'> form to 
 2594: allow a user to select options from a ref to a hash containing:
 2595: option_name => displayed text. An optional $onchange can include
 2596: a javascript onchange item, e.g., onchange="this.form.submit();".
 2597: An optional arg -- $readonly -- if true will cause the select form
 2598: to be disabled, e.g., for the case where an instructor has a section-
 2599: specific role, and is viewing/modifying parameters. 
 2600: 
 2601: See lonrights.pm for an example invocation and use.
 2602: 
 2603: =cut
 2604: 
 2605: #-------------------------------------------
 2606: sub select_form {
 2607:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
 2608:     return unless (ref($hashref) eq 'HASH');
 2609:     if ($onchange) {
 2610:         $onchange = ' onchange="'.$onchange.'"';
 2611:     }
 2612:     my $disabled;
 2613:     if ($readonly) {
 2614:         $disabled = ' disabled="disabled"';
 2615:     }
 2616:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2617:     my @keys;
 2618:     if (exists($hashref->{'select_form_order'})) {
 2619: 	@keys=@{$hashref->{'select_form_order'}};
 2620:     } else {
 2621: 	@keys=sort(keys(%{$hashref}));
 2622:     }
 2623:     foreach my $key (@keys) {
 2624:         $selectform.=
 2625: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2626:             ($key eq $def ? 'selected="selected" ' : '').
 2627:                 ">".$hashref->{$key}."</option>\n";
 2628:     }
 2629:     $selectform.="</select>";
 2630:     return $selectform;
 2631: }
 2632: 
 2633: # For display filters
 2634: 
 2635: sub display_filter {
 2636:     my ($context) = @_;
 2637:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2638:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2639:     my $phraseinput = 'hidden';
 2640:     my $includeinput = 'hidden';
 2641:     my ($checked,$includetypestext);
 2642:     if ($env{'form.displayfilter'} eq 'containing') {
 2643:         $phraseinput = 'text'; 
 2644:         if ($context eq 'parmslog') {
 2645:             $includeinput = 'checkbox';
 2646:             if ($env{'form.includetypes'}) {
 2647:                 $checked = ' checked="checked"';
 2648:             }
 2649:             $includetypestext = &mt('Include parameter types');
 2650:         }
 2651:     } else {
 2652:         $includetypestext = '&nbsp;';
 2653:     }
 2654:     my ($additional,$secondid,$thirdid);
 2655:     if ($context eq 'parmslog') {
 2656:         $additional = 
 2657:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2658:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2659:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2660:             '</label>';
 2661:         $secondid = 'includetypes';
 2662:         $thirdid = 'includetypestext';
 2663:     }
 2664:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2665:                                                     '$secondid','$thirdid')";
 2666:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2667: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 2668: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2669: 	   '</label></span> <span class="LC_nobreak">'.
 2670:            &mt('Filter: [_1]',
 2671: 	   &select_form($env{'form.displayfilter'},
 2672: 			'displayfilter',
 2673: 			{'currentfolder' => 'Current folder/page',
 2674: 			 'containing' => 'Containing phrase',
 2675: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2676: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2677:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2678:                          '" />'.$additional;
 2679: }
 2680: 
 2681: sub display_filter_js {
 2682:     my $includetext = &mt('Include parameter types');
 2683:     return <<"ENDJS";
 2684:   
 2685: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2686:     var firstType = 'hidden';
 2687:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2688:         firstType = 'text';
 2689:     }
 2690:     firstObject = document.getElementById(firstid);
 2691:     if (typeof(firstObject) == 'object') {
 2692:         if (firstObject.type != firstType) {
 2693:             changeInputType(firstObject,firstType);
 2694:         }
 2695:     }
 2696:     if (context == 'parmslog') {
 2697:         var secondType = 'hidden';
 2698:         if (firstType == 'text') {
 2699:             secondType = 'checkbox';
 2700:         }
 2701:         secondObject = document.getElementById(secondid);  
 2702:         if (typeof(secondObject) == 'object') {
 2703:             if (secondObject.type != secondType) {
 2704:                 changeInputType(secondObject,secondType);
 2705:             }
 2706:         }
 2707:         var textItem = document.getElementById(thirdid);
 2708:         var currtext = textItem.innerHTML;
 2709:         var newtext;
 2710:         if (firstType == 'text') {
 2711:             newtext = '$includetext';
 2712:         } else {
 2713:             newtext = '&nbsp;';
 2714:         }
 2715:         if (currtext != newtext) {
 2716:             textItem.innerHTML = newtext;
 2717:         }
 2718:     }
 2719:     return;
 2720: }
 2721: 
 2722: function changeInputType(oldObject,newType) {
 2723:     var newObject = document.createElement('input');
 2724:     newObject.type = newType;
 2725:     if (oldObject.size) {
 2726:         newObject.size = oldObject.size;
 2727:     }
 2728:     if (oldObject.value) {
 2729:         newObject.value = oldObject.value;
 2730:     }
 2731:     if (oldObject.name) {
 2732:         newObject.name = oldObject.name;
 2733:     }
 2734:     if (oldObject.id) {
 2735:         newObject.id = oldObject.id;
 2736:     }
 2737:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2738:     return;
 2739: }
 2740: 
 2741: ENDJS
 2742: }
 2743: 
 2744: sub gradeleveldescription {
 2745:     my $gradelevel=shift;
 2746:     my %gradelevels=(0 => 'Not specified',
 2747: 		     1 => 'Grade 1',
 2748: 		     2 => 'Grade 2',
 2749: 		     3 => 'Grade 3',
 2750: 		     4 => 'Grade 4',
 2751: 		     5 => 'Grade 5',
 2752: 		     6 => 'Grade 6',
 2753: 		     7 => 'Grade 7',
 2754: 		     8 => 'Grade 8',
 2755: 		     9 => 'Grade 9',
 2756: 		     10 => 'Grade 10',
 2757: 		     11 => 'Grade 11',
 2758: 		     12 => 'Grade 12',
 2759: 		     13 => 'Grade 13',
 2760: 		     14 => '100 Level',
 2761: 		     15 => '200 Level',
 2762: 		     16 => '300 Level',
 2763: 		     17 => '400 Level',
 2764: 		     18 => 'Graduate Level');
 2765:     return &mt($gradelevels{$gradelevel});
 2766: }
 2767: 
 2768: sub select_level_form {
 2769:     my ($deflevel,$name)=@_;
 2770:     unless ($deflevel) { $deflevel=0; }
 2771:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2772:     for (my $i=0; $i<=18; $i++) {
 2773:         $selectform.="<option value=\"$i\" ".
 2774:             ($i==$deflevel ? 'selected="selected" ' : '').
 2775:                 ">".&gradeleveldescription($i)."</option>\n";
 2776:     }
 2777:     $selectform.="</select>";
 2778:     return $selectform;
 2779: }
 2780: 
 2781: #-------------------------------------------
 2782: 
 2783: =pod
 2784: 
 2785: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
 2786: 
 2787: Returns a string containing a <select name='$name' size='1'> form to 
 2788: allow a user to select the domain to preform an operation in.  
 2789: See loncreateuser.pm for an example invocation and use.
 2790: 
 2791: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2792: selected");
 2793: 
 2794: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2795: 
 2796: 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.
 2797: 
 2798: The optional $incdoms is a reference to an array of domains which will be the only available options.
 2799: 
 2800: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
 2801: 
 2802: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
 2803: 
 2804: =cut
 2805: 
 2806: #-------------------------------------------
 2807: sub select_dom_form {
 2808:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
 2809:     if ($onchange) {
 2810:         $onchange = ' onchange="'.$onchange.'"';
 2811:     }
 2812:     if ($disabled) {
 2813:         $disabled = ' disabled="disabled"';
 2814:     }
 2815:     my (@domains,%exclude);
 2816:     if (ref($incdoms) eq 'ARRAY') {
 2817:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2818:     } else {
 2819:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2820:     }
 2821:     if ($includeempty) { @domains=('',@domains); }
 2822:     if (ref($excdoms) eq 'ARRAY') {
 2823:         map { $exclude{$_} = 1; } @{$excdoms}; 
 2824:     }
 2825:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2826:     foreach my $dom (@domains) {
 2827:         next if ($exclude{$dom});
 2828:         $selectdomain.="<option value=\"$dom\" ".
 2829:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2830:         if ($showdomdesc) {
 2831:             if ($dom ne '') {
 2832:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2833:                 if ($domdesc ne '') {
 2834:                     $selectdomain .= ' ('.$domdesc.')';
 2835:                 }
 2836:             } 
 2837:         }
 2838:         $selectdomain .= "</option>\n";
 2839:     }
 2840:     $selectdomain.="</select>";
 2841:     return $selectdomain;
 2842: }
 2843: 
 2844: #-------------------------------------------
 2845: 
 2846: =pod
 2847: 
 2848: =item * &home_server_form_item($domain,$name,$defaultflag)
 2849: 
 2850: input: 4 arguments (two required, two optional) - 
 2851:     $domain - domain of new user
 2852:     $name - name of form element
 2853:     $default - Value of 'default' causes a default item to be first 
 2854:                             option, and selected by default. 
 2855:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2856:                             if 1 server found, or default, if 0 found.
 2857: output: returns 2 items: 
 2858: (a) form element which contains either:
 2859:    (i) <select name="$name">
 2860:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2861:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2862:        </select>
 2863:        form item if there are multiple library servers in $domain, or
 2864:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2865:        if there is only one library server in $domain.
 2866: 
 2867: (b) number of library servers found.
 2868: 
 2869: See loncreateuser.pm for example of use.
 2870: 
 2871: =cut
 2872: 
 2873: #-------------------------------------------
 2874: sub home_server_form_item {
 2875:     my ($domain,$name,$default,$hide) = @_;
 2876:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2877:     my $result;
 2878:     my $numlib = keys(%servers);
 2879:     if ($numlib > 1) {
 2880:         $result .= '<select name="'.$name.'" />'."\n";
 2881:         if ($default) {
 2882:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2883:                        '</option>'."\n";
 2884:         }
 2885:         foreach my $hostid (sort(keys(%servers))) {
 2886:             $result.= '<option value="'.$hostid.'">'.
 2887: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2888:         }
 2889:         $result .= '</select>'."\n";
 2890:     } elsif ($numlib == 1) {
 2891:         my $hostid;
 2892:         foreach my $item (keys(%servers)) {
 2893:             $hostid = $item;
 2894:         }
 2895:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2896:                    $hostid.'" />';
 2897:                    if (!$hide) {
 2898:                        $result .= $hostid.' '.$servers{$hostid};
 2899:                    }
 2900:                    $result .= "\n";
 2901:     } elsif ($default) {
 2902:         $result .= '<input type="hidden" name="'.$name.
 2903:                    '" value="default" />';
 2904:                    if (!$hide) {
 2905:                        $result .= &mt('default');
 2906:                    }
 2907:                    $result .= "\n";
 2908:     }
 2909:     return ($result,$numlib);
 2910: }
 2911: 
 2912: =pod
 2913: 
 2914: =back 
 2915: 
 2916: =cut
 2917: 
 2918: ###############################################################
 2919: ##                  Decoding User Agent                      ##
 2920: ###############################################################
 2921: 
 2922: =pod
 2923: 
 2924: =head1 Decoding the User Agent
 2925: 
 2926: =over 4
 2927: 
 2928: =item * &decode_user_agent()
 2929: 
 2930: Inputs: $r
 2931: 
 2932: Outputs:
 2933: 
 2934: =over 4
 2935: 
 2936: =item * $httpbrowser
 2937: 
 2938: =item * $clientbrowser
 2939: 
 2940: =item * $clientversion
 2941: 
 2942: =item * $clientmathml
 2943: 
 2944: =item * $clientunicode
 2945: 
 2946: =item * $clientos
 2947: 
 2948: =item * $clientmobile
 2949: 
 2950: =item * $clientinfo
 2951: 
 2952: =item * $clientosversion
 2953: 
 2954: =back
 2955: 
 2956: =back 
 2957: 
 2958: =cut
 2959: 
 2960: ###############################################################
 2961: ###############################################################
 2962: sub decode_user_agent {
 2963:     my ($r)=@_;
 2964:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2965:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2966:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2967:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2968:     my $clientbrowser='unknown';
 2969:     my $clientversion='0';
 2970:     my $clientmathml='';
 2971:     my $clientunicode='0';
 2972:     my $clientmobile=0;
 2973:     my $clientosversion='';
 2974:     for (my $i=0;$i<=$#browsertype;$i++) {
 2975:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
 2976: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2977: 	    $clientbrowser=$bname;
 2978:             $httpbrowser=~/$vreg/i;
 2979: 	    $clientversion=$1;
 2980:             $clientmathml=($clientversion>=$minv);
 2981:             $clientunicode=($clientversion>=$univ);
 2982: 	}
 2983:     }
 2984:     my $clientos='unknown';
 2985:     my $clientinfo;
 2986:     if (($httpbrowser=~/linux/i) ||
 2987:         ($httpbrowser=~/unix/i) ||
 2988:         ($httpbrowser=~/ux/i) ||
 2989:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2990:     if (($httpbrowser=~/vax/i) ||
 2991:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2992:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2993:     if (($httpbrowser=~/mac/i) ||
 2994:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2995:     if ($httpbrowser=~/win/i) {
 2996:         $clientos='win';
 2997:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
 2998:             $clientosversion = $1;
 2999:         }
 3000:     }
 3001:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 3002:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 3003:         $clientmobile=lc($1);
 3004:     }
 3005:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 3006:         $clientinfo = 'firefox-'.$1;
 3007:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 3008:         $clientinfo = 'chromeframe-'.$1;
 3009:     }
 3010:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 3011:             $clientunicode,$clientos,$clientmobile,$clientinfo,
 3012:             $clientosversion);
 3013: }
 3014: 
 3015: ###############################################################
 3016: ##    Authentication changing form generation subroutines    ##
 3017: ###############################################################
 3018: ##
 3019: ## All of the authform_xxxxxxx subroutines take their inputs in a
 3020: ## hash, and have reasonable default values.
 3021: ##
 3022: ##    formname = the name given in the <form> tag.
 3023: #-------------------------------------------
 3024: 
 3025: =pod
 3026: 
 3027: =head1 Authentication Routines
 3028: 
 3029: =over 4
 3030: 
 3031: =item * &authform_xxxxxx()
 3032: 
 3033: The authform_xxxxxx subroutines provide javascript and html forms which 
 3034: handle some of the conveniences required for authentication forms.  
 3035: This is not an optimal method, but it works.  
 3036: 
 3037: =over 4
 3038: 
 3039: =item * authform_header
 3040: 
 3041: =item * authform_authorwarning
 3042: 
 3043: =item * authform_nochange
 3044: 
 3045: =item * authform_kerberos
 3046: 
 3047: =item * authform_internal
 3048: 
 3049: =item * authform_filesystem
 3050: 
 3051: =item * authform_lti
 3052: 
 3053: =back
 3054: 
 3055: See loncreateuser.pm for invocation and use examples.
 3056: 
 3057: =cut
 3058: 
 3059: #-------------------------------------------
 3060: sub authform_header{  
 3061:     my %in = (
 3062:         formname => 'cu',
 3063:         kerb_def_dom => '',
 3064:         @_,
 3065:     );
 3066:     $in{'formname'} = 'document.' . $in{'formname'};
 3067:     my $result='';
 3068: 
 3069: #---------------------------------------------- Code for upper case translation
 3070:     my $Javascript_toUpperCase;
 3071:     unless ($in{kerb_def_dom}) {
 3072:         $Javascript_toUpperCase =<<"END";
 3073:         switch (choice) {
 3074:            case 'krb': currentform.elements[choicearg].value =
 3075:                currentform.elements[choicearg].value.toUpperCase();
 3076:                break;
 3077:            default:
 3078:         }
 3079: END
 3080:     } else {
 3081:         $Javascript_toUpperCase = "";
 3082:     }
 3083: 
 3084:     my $radioval = "'nochange'";
 3085:     if (defined($in{'curr_authtype'})) {
 3086:         if ($in{'curr_authtype'} ne '') {
 3087:             $radioval = "'".$in{'curr_authtype'}."arg'";
 3088:         }
 3089:     }
 3090:     my $argfield = 'null';
 3091:     if (defined($in{'mode'})) {
 3092:         if ($in{'mode'} eq 'modifycourse')  {
 3093:             if (defined($in{'curr_autharg'})) {
 3094:                 if ($in{'curr_autharg'} ne '') {
 3095:                     $argfield = "'$in{'curr_autharg'}'";
 3096:                 }
 3097:             }
 3098:         }
 3099:     }
 3100: 
 3101:     $result.=<<"END";
 3102: var current = new Object();
 3103: current.radiovalue = $radioval;
 3104: current.argfield = $argfield;
 3105: 
 3106: function changed_radio(choice,currentform) {
 3107:     var choicearg = choice + 'arg';
 3108:     // If a radio button in changed, we need to change the argfield
 3109:     if (current.radiovalue != choice) {
 3110:         current.radiovalue = choice;
 3111:         if (current.argfield != null) {
 3112:             currentform.elements[current.argfield].value = '';
 3113:         }
 3114:         if (choice == 'nochange') {
 3115:             current.argfield = null;
 3116:         } else {
 3117:             current.argfield = choicearg;
 3118:             switch(choice) {
 3119:                 case 'krb': 
 3120:                     currentform.elements[current.argfield].value = 
 3121:                         "$in{'kerb_def_dom'}";
 3122:                 break;
 3123:               default:
 3124:                 break;
 3125:             }
 3126:         }
 3127:     }
 3128:     return;
 3129: }
 3130: 
 3131: function changed_text(choice,currentform) {
 3132:     var choicearg = choice + 'arg';
 3133:     if (currentform.elements[choicearg].value !='') {
 3134:         $Javascript_toUpperCase
 3135:         // clear old field
 3136:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 3137:             currentform.elements[current.argfield].value = '';
 3138:         }
 3139:         current.argfield = choicearg;
 3140:     }
 3141:     set_auth_radio_buttons(choice,currentform);
 3142:     return;
 3143: }
 3144: 
 3145: function set_auth_radio_buttons(newvalue,currentform) {
 3146:     var numauthchoices = currentform.login.length;
 3147:     if (typeof numauthchoices  == "undefined") {
 3148:         return;
 3149:     } 
 3150:     var i=0;
 3151:     while (i < numauthchoices) {
 3152:         if (currentform.login[i].value == newvalue) { break; }
 3153:         i++;
 3154:     }
 3155:     if (i == numauthchoices) {
 3156:         return;
 3157:     }
 3158:     current.radiovalue = newvalue;
 3159:     currentform.login[i].checked = true;
 3160:     return;
 3161: }
 3162: END
 3163:     return $result;
 3164: }
 3165: 
 3166: sub authform_authorwarning {
 3167:     my $result='';
 3168:     $result='<i>'.
 3169:         &mt('As a general rule, only authors or co-authors should be '.
 3170:             'filesystem authenticated '.
 3171:             '(which allows access to the server filesystem).')."</i>\n";
 3172:     return $result;
 3173: }
 3174: 
 3175: sub authform_nochange {
 3176:     my %in = (
 3177:               formname => 'document.cu',
 3178:               kerb_def_dom => 'MSU.EDU',
 3179:               @_,
 3180:           );
 3181:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3182:     my $result;
 3183:     if (!$authnum) {
 3184:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 3185:     } else {
 3186:         $result = '<label>'.&mt('[_1] Do not change login data',
 3187:                   '<input type="radio" name="login" value="nochange" '.
 3188:                   'checked="checked" onclick="'.
 3189:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 3190: 	    '</label>';
 3191:     }
 3192:     return $result;
 3193: }
 3194: 
 3195: sub authform_kerberos {
 3196:     my %in = (
 3197:               formname => 'document.cu',
 3198:               kerb_def_dom => 'MSU.EDU',
 3199:               kerb_def_auth => 'krb4',
 3200:               @_,
 3201:               );
 3202:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 3203:         $autharg,$jscall,$disabled);
 3204:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3205:     if ($in{'kerb_def_auth'} eq 'krb5') {
 3206:        $check5 = ' checked="checked"';
 3207:     } else {
 3208:        $check4 = ' checked="checked"';
 3209:     }
 3210:     if ($in{'readonly'}) {
 3211:         $disabled = ' disabled="disabled"';
 3212:     }
 3213:     $krbarg = $in{'kerb_def_dom'};
 3214:     if (defined($in{'curr_authtype'})) {
 3215:         if ($in{'curr_authtype'} eq 'krb') {
 3216:             $krbcheck = ' checked="checked"';
 3217:             if (defined($in{'mode'})) {
 3218:                 if ($in{'mode'} eq 'modifyuser') {
 3219:                     $krbcheck = '';
 3220:                 }
 3221:             }
 3222:             if (defined($in{'curr_kerb_ver'})) {
 3223:                 if ($in{'curr_krb_ver'} eq '5') {
 3224:                     $check5 = ' checked="checked"';
 3225:                     $check4 = '';
 3226:                 } else {
 3227:                     $check4 = ' checked="checked"';
 3228:                     $check5 = '';
 3229:                 }
 3230:             }
 3231:             if (defined($in{'curr_autharg'})) {
 3232:                 $krbarg = $in{'curr_autharg'};
 3233:             }
 3234:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 3235:                 if (defined($in{'curr_autharg'})) {
 3236:                     $result = 
 3237:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 3238:         $in{'curr_autharg'},$krbver);
 3239:                 } else {
 3240:                     $result =
 3241:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 3242:                 }
 3243:                 return $result; 
 3244:             }
 3245:         }
 3246:     } else {
 3247:         if ($authnum == 1) {
 3248:             $authtype = '<input type="hidden" name="login" value="krb" />';
 3249:         }
 3250:     }
 3251:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 3252:         return;
 3253:     } elsif ($authtype eq '') {
 3254:         if (defined($in{'mode'})) {
 3255:             if ($in{'mode'} eq 'modifycourse') {
 3256:                 if ($authnum == 1) {
 3257:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
 3258:                 }
 3259:             }
 3260:         }
 3261:     }
 3262:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 3263:     if ($authtype eq '') {
 3264:         $authtype = '<input type="radio" name="login" value="krb" '.
 3265:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 3266:                     $krbcheck.$disabled.' />';
 3267:     }
 3268:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 3269:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 3270:          $in{'curr_authtype'} eq 'krb5') ||
 3271:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 3272:          $in{'curr_authtype'} eq 'krb4')) {
 3273:         $result .= &mt
 3274:         ('[_1] Kerberos authenticated with domain [_2] '.
 3275:          '[_3] Version 4 [_4] Version 5 [_5]',
 3276:          '<label>'.$authtype,
 3277:          '</label><input type="text" size="10" name="krbarg" '.
 3278:              'value="'.$krbarg.'" '.
 3279:              'onchange="'.$jscall.'"'.$disabled.' />',
 3280:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
 3281:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
 3282: 	 '</label>');
 3283:     } elsif ($can_assign{'krb4'}) {
 3284:         $result .= &mt
 3285:         ('[_1] Kerberos authenticated with domain [_2] '.
 3286:          '[_3] Version 4 [_4]',
 3287:          '<label>'.$authtype,
 3288:          '</label><input type="text" size="10" name="krbarg" '.
 3289:              'value="'.$krbarg.'" '.
 3290:              'onchange="'.$jscall.'"'.$disabled.' />',
 3291:          '<label><input type="hidden" name="krbver" value="4" />',
 3292:          '</label>');
 3293:     } elsif ($can_assign{'krb5'}) {
 3294:         $result .= &mt
 3295:         ('[_1] Kerberos authenticated with domain [_2] '.
 3296:          '[_3] Version 5 [_4]',
 3297:          '<label>'.$authtype,
 3298:          '</label><input type="text" size="10" name="krbarg" '.
 3299:              'value="'.$krbarg.'" '.
 3300:              'onchange="'.$jscall.'"'.$disabled.' />',
 3301:          '<label><input type="hidden" name="krbver" value="5" />',
 3302:          '</label>');
 3303:     }
 3304:     return $result;
 3305: }
 3306: 
 3307: sub authform_internal {
 3308:     my %in = (
 3309:                 formname => 'document.cu',
 3310:                 kerb_def_dom => 'MSU.EDU',
 3311:                 @_,
 3312:                 );
 3313:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
 3314:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3315:     if ($in{'readonly'}) {
 3316:         $disabled = ' disabled="disabled"';
 3317:     }
 3318:     if (defined($in{'curr_authtype'})) {
 3319:         if ($in{'curr_authtype'} eq 'int') {
 3320:             if ($can_assign{'int'}) {
 3321:                 $intcheck = 'checked="checked" ';
 3322:                 if (defined($in{'mode'})) {
 3323:                     if ($in{'mode'} eq 'modifyuser') {
 3324:                         $intcheck = '';
 3325:                     }
 3326:                 }
 3327:                 if (defined($in{'curr_autharg'})) {
 3328:                     $intarg = $in{'curr_autharg'};
 3329:                 }
 3330:             } else {
 3331:                 $result = &mt('Currently internally authenticated.');
 3332:                 return $result;
 3333:             }
 3334:         }
 3335:     } else {
 3336:         if ($authnum == 1) {
 3337:             $authtype = '<input type="hidden" name="login" value="int" />';
 3338:         }
 3339:     }
 3340:     if (!$can_assign{'int'}) {
 3341:         return;
 3342:     } elsif ($authtype eq '') {
 3343:         if (defined($in{'mode'})) {
 3344:             if ($in{'mode'} eq 'modifycourse') {
 3345:                 if ($authnum == 1) {
 3346:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
 3347:                 }
 3348:             }
 3349:         }
 3350:     }
 3351:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 3352:     if ($authtype eq '') {
 3353:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 3354:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
 3355:     }
 3356:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 3357:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3358:     $result = &mt
 3359:         ('[_1] Internally authenticated (with initial password [_2])',
 3360:          '<label>'.$authtype,'</label>'.$autharg);
 3361:     $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>';
 3362:     return $result;
 3363: }
 3364: 
 3365: sub authform_local {
 3366:     my %in = (
 3367:               formname => 'document.cu',
 3368:               kerb_def_dom => 'MSU.EDU',
 3369:               @_,
 3370:               );
 3371:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
 3372:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3373:     if ($in{'readonly'}) {
 3374:         $disabled = ' disabled="disabled"';
 3375:     } 
 3376:     if (defined($in{'curr_authtype'})) {
 3377:         if ($in{'curr_authtype'} eq 'loc') {
 3378:             if ($can_assign{'loc'}) {
 3379:                 $loccheck = 'checked="checked" ';
 3380:                 if (defined($in{'mode'})) {
 3381:                     if ($in{'mode'} eq 'modifyuser') {
 3382:                         $loccheck = '';
 3383:                     }
 3384:                 }
 3385:                 if (defined($in{'curr_autharg'})) {
 3386:                     $locarg = $in{'curr_autharg'};
 3387:                 }
 3388:             } else {
 3389:                 $result = &mt('Currently using local (institutional) authentication.');
 3390:                 return $result;
 3391:             }
 3392:         }
 3393:     } else {
 3394:         if ($authnum == 1) {
 3395:             $authtype = '<input type="hidden" name="login" value="loc" />';
 3396:         }
 3397:     }
 3398:     if (!$can_assign{'loc'}) {
 3399:         return;
 3400:     } elsif ($authtype eq '') {
 3401:         if (defined($in{'mode'})) {
 3402:             if ($in{'mode'} eq 'modifycourse') {
 3403:                 if ($authnum == 1) {
 3404:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
 3405:                 }
 3406:             }
 3407:         }
 3408:     }
 3409:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 3410:     if ($authtype eq '') {
 3411:         $authtype = '<input type="radio" name="login" value="loc" '.
 3412:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 3413:                     $jscall.'"'.$disabled.' />';
 3414:     }
 3415:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 3416:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3417:     $result = &mt('[_1] Local Authentication with argument [_2]',
 3418:                   '<label>'.$authtype,'</label>'.$autharg);
 3419:     return $result;
 3420: }
 3421: 
 3422: sub authform_filesystem {
 3423:     my %in = (
 3424:               formname => 'document.cu',
 3425:               kerb_def_dom => 'MSU.EDU',
 3426:               @_,
 3427:               );
 3428:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
 3429:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3430:     if ($in{'readonly'}) {
 3431:         $disabled = ' disabled="disabled"';
 3432:     }
 3433:     if (defined($in{'curr_authtype'})) {
 3434:         if ($in{'curr_authtype'} eq 'fsys') {
 3435:             if ($can_assign{'fsys'}) {
 3436:                 $fsyscheck = 'checked="checked" ';
 3437:                 if (defined($in{'mode'})) {
 3438:                     if ($in{'mode'} eq 'modifyuser') {
 3439:                         $fsyscheck = '';
 3440:                     }
 3441:                 }
 3442:             } else {
 3443:                 $result = &mt('Currently Filesystem Authenticated.');
 3444:                 return $result;
 3445:             }
 3446:         }
 3447:     } else {
 3448:         if ($authnum == 1) {
 3449:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 3450:         }
 3451:     }
 3452:     if (!$can_assign{'fsys'}) {
 3453:         return;
 3454:     } elsif ($authtype eq '') {
 3455:         if (defined($in{'mode'})) {
 3456:             if ($in{'mode'} eq 'modifycourse') {
 3457:                 if ($authnum == 1) {
 3458:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
 3459:                 }
 3460:             }
 3461:         }
 3462:     }
 3463:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 3464:     if ($authtype eq '') {
 3465:         $authtype = '<input type="radio" name="login" value="fsys" '.
 3466:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 3467:                     $jscall.'"'.$disabled.' />';
 3468:     }
 3469:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
 3470:                ' onchange="'.$jscall.'"'.$disabled.' />';
 3471:     $result = &mt
 3472:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 3473:          '<label>'.$authtype,'</label>'.$autharg);
 3474:     return $result;
 3475: }
 3476: 
 3477: sub authform_lti {
 3478:     my %in = (
 3479:               formname => 'document.cu',
 3480:               kerb_def_dom => 'MSU.EDU',
 3481:               @_,
 3482:               );
 3483:     my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
 3484:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3485:     if ($in{'readonly'}) {
 3486:         $disabled = ' disabled="disabled"';
 3487:     }
 3488:     if (defined($in{'curr_authtype'})) {
 3489:         if ($in{'curr_authtype'} eq 'lti') {
 3490:             if ($can_assign{'lti'}) {
 3491:                 $lticheck = 'checked="checked" ';
 3492:                 if (defined($in{'mode'})) {
 3493:                     if ($in{'mode'} eq 'modifyuser') {
 3494:                         $lticheck = '';
 3495:                     }
 3496:                 }
 3497:             } else {
 3498:                 $result = &mt('Currently LTI Authenticated.');
 3499:                 return $result;
 3500:             }
 3501:         }
 3502:     } else {
 3503:         if ($authnum == 1) {
 3504:             $authtype = '<input type="hidden" name="login" value="lti" />';
 3505:         }
 3506:     }
 3507:     if (!$can_assign{'lti'}) {
 3508:         return;
 3509:     } elsif ($authtype eq '') {
 3510:         if (defined($in{'mode'})) {
 3511:             if ($in{'mode'} eq 'modifycourse') {
 3512:                 if ($authnum == 1) {
 3513:                     $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
 3514:                 }
 3515:             }
 3516:         }
 3517:     }
 3518:     $jscall = "javascript:changed_radio('lti',$in{'formname'});";
 3519:     if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
 3520:         $authtype = '<input type="radio" name="login" value="lti" '.
 3521:                     $lticheck.' onchange="'.$jscall.'" onclick="'.
 3522:                     $jscall.'"'.$disabled.' />';
 3523:     }
 3524:     $autharg = '<input type="hidden" name="ltiarg" value="" />';
 3525:     if ($authtype) {
 3526:         $result = &mt('[_1] LTI Authenticated',
 3527:                       '<label>'.$authtype.'</label>'.$autharg);
 3528:     } else {
 3529:         $result = '<b>'.&mt('LTI Authenticated').'</b>'.
 3530:                   $autharg;
 3531:     }
 3532:     return $result;
 3533: }
 3534: 
 3535: sub get_assignable_auth {
 3536:     my ($dom) = @_;
 3537:     if ($dom eq '') {
 3538:         $dom = $env{'request.role.domain'};
 3539:     }
 3540:     my %can_assign = (
 3541:                           krb4 => 1,
 3542:                           krb5 => 1,
 3543:                           int  => 1,
 3544:                           loc  => 1,
 3545:                           lti  => 1,
 3546:                      );
 3547:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 3548:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 3549:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 3550:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 3551:             my $context;
 3552:             if ($env{'request.role'} =~ /^au/) {
 3553:                 $context = 'author';
 3554:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
 3555:                 $context = 'domain';
 3556:             } elsif ($env{'request.course.id'}) {
 3557:                 $context = 'course';
 3558:             }
 3559:             if ($context) {
 3560:                 if (ref($authhash->{$context}) eq 'HASH') {
 3561:                    %can_assign = %{$authhash->{$context}}; 
 3562:                 }
 3563:             }
 3564:         }
 3565:     }
 3566:     my $authnum = 0;
 3567:     foreach my $key (keys(%can_assign)) {
 3568:         if ($can_assign{$key}) {
 3569:             $authnum ++;
 3570:         }
 3571:     }
 3572:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 3573:         $authnum --;
 3574:     }
 3575:     return ($authnum,%can_assign);
 3576: }
 3577: 
 3578: sub check_passwd_rules {
 3579:     my ($domain,$plainpass) = @_;
 3580:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
 3581:     my ($min,$max,@chars,@brokerule,$warning);
 3582:     $min = $Apache::lonnet::passwdmin;
 3583:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
 3584:         if ($passwdconf{'min'} =~ /^\d+$/) {
 3585:             if ($passwdconf{'min'} > $min) {
 3586:                 $min = $passwdconf{'min'};
 3587:             }
 3588:         }
 3589:         if ($passwdconf{'max'} =~ /^\d+$/) {
 3590:             $max = $passwdconf{'max'};
 3591:         }
 3592:         @chars = @{$passwdconf{'chars'}};
 3593:     }
 3594:     if (($min) && (length($plainpass) < $min)) {
 3595:         push(@brokerule,'min');
 3596:     }
 3597:     if (($max) && (length($plainpass) > $max)) {
 3598:         push(@brokerule,'max');
 3599:     }
 3600:     if (@chars) {
 3601:         my %rules;
 3602:         map { $rules{$_} = 1; } @chars;
 3603:         if ($rules{'uc'}) {
 3604:             unless ($plainpass =~ /[A-Z]/) {
 3605:                 push(@brokerule,'uc');
 3606:             }
 3607:         }
 3608:         if ($rules{'lc'}) {
 3609:             unless ($plainpass =~ /[a-z]/) {
 3610:                 push(@brokerule,'lc');
 3611:             }
 3612:         }
 3613:         if ($rules{'num'}) {
 3614:             unless ($plainpass =~ /\d/) {
 3615:                 push(@brokerule,'num');
 3616:             }
 3617:         }
 3618:         if ($rules{'spec'}) {
 3619:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
 3620:                 push(@brokerule,'spec');
 3621:             }
 3622:         }
 3623:     }
 3624:     if (@brokerule) {
 3625:         my %rulenames = &Apache::lonlocal::texthash(
 3626:             uc   => 'At least one upper case letter',
 3627:             lc   => 'At least one lower case letter',
 3628:             num  => 'At least one number',
 3629:             spec => 'At least one non-alphanumeric',
 3630:         );
 3631:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
 3632:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
 3633:         $rulenames{'num'} .= ': 0123456789';
 3634:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
 3635:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
 3636:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
 3637:         $warning = &mt('Password did not satisfy the following:').'<ul>';
 3638:         foreach my $rule ('min','max','uc','lc','num','spec') {
 3639:             if (grep(/^$rule$/,@brokerule)) {
 3640:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
 3641:             }
 3642:         }
 3643:         $warning .= '</ul>';
 3644:     }
 3645:     if (wantarray) {
 3646:         return @brokerule;
 3647:     }
 3648:     return $warning;
 3649: }
 3650: 
 3651: ###############################################################
 3652: ##    Get Kerberos Defaults for Domain                 ##
 3653: ###############################################################
 3654: ##
 3655: ## Returns default kerberos version and an associated argument
 3656: ## as listed in file domain.tab. If not listed, provides
 3657: ## appropriate default domain and kerberos version.
 3658: ##
 3659: #-------------------------------------------
 3660: 
 3661: =pod
 3662: 
 3663: =item * &get_kerberos_defaults()
 3664: 
 3665: get_kerberos_defaults($target_domain) returns the default kerberos
 3666: version and domain. If not found, it defaults to version 4 and the 
 3667: domain of the server.
 3668: 
 3669: =over 4
 3670: 
 3671: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 3672: 
 3673: =back
 3674: 
 3675: =back
 3676: 
 3677: =cut
 3678: 
 3679: #-------------------------------------------
 3680: sub get_kerberos_defaults {
 3681:     my $domain=shift;
 3682:     my ($krbdef,$krbdefdom);
 3683:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 3684:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 3685:         $krbdef = $domdefaults{'auth_def'};
 3686:         $krbdefdom = $domdefaults{'auth_arg_def'};
 3687:     } else {
 3688:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 3689:         my $krbdefdom=$1;
 3690:         $krbdefdom=~tr/a-z/A-Z/;
 3691:         $krbdef = "krb4";
 3692:     }
 3693:     return ($krbdef,$krbdefdom);
 3694: }
 3695: 
 3696: 
 3697: ###############################################################
 3698: ##                Thesaurus Functions                        ##
 3699: ###############################################################
 3700: 
 3701: =pod
 3702: 
 3703: =head1 Thesaurus Functions
 3704: 
 3705: =over 4
 3706: 
 3707: =item * &initialize_keywords()
 3708: 
 3709: Initializes the package variable %Keywords if it is empty.  Uses the
 3710: package variable $thesaurus_db_file.
 3711: 
 3712: =cut
 3713: 
 3714: ###################################################
 3715: 
 3716: sub initialize_keywords {
 3717:     return 1 if (scalar keys(%Keywords));
 3718:     # If we are here, %Keywords is empty, so fill it up
 3719:     #   Make sure the file we need exists...
 3720:     if (! -e $thesaurus_db_file) {
 3721:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 3722:                                  " failed because it does not exist");
 3723:         return 0;
 3724:     }
 3725:     #   Set up the hash as a database
 3726:     my %thesaurus_db;
 3727:     if (! tie(%thesaurus_db,'GDBM_File',
 3728:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3729:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 3730:                                  $thesaurus_db_file);
 3731:         return 0;
 3732:     } 
 3733:     #  Get the average number of appearances of a word.
 3734:     my $avecount = $thesaurus_db{'average.count'};
 3735:     #  Put keywords (those that appear > average) into %Keywords
 3736:     while (my ($word,$data)=each (%thesaurus_db)) {
 3737:         my ($count,undef) = split /:/,$data;
 3738:         $Keywords{$word}++ if ($count > $avecount);
 3739:     }
 3740:     untie %thesaurus_db;
 3741:     # Remove special values from %Keywords.
 3742:     foreach my $value ('total.count','average.count') {
 3743:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 3744:   }
 3745:     return 1;
 3746: }
 3747: 
 3748: ###################################################
 3749: 
 3750: =pod
 3751: 
 3752: =item * &keyword($word)
 3753: 
 3754: Returns true if $word is a keyword.  A keyword is a word that appears more 
 3755: than the average number of times in the thesaurus database.  Calls 
 3756: &initialize_keywords
 3757: 
 3758: =cut
 3759: 
 3760: ###################################################
 3761: 
 3762: sub keyword {
 3763:     return if (!&initialize_keywords());
 3764:     my $word=lc(shift());
 3765:     $word=~s/\W//g;
 3766:     return exists($Keywords{$word});
 3767: }
 3768: 
 3769: ###############################################################
 3770: 
 3771: =pod 
 3772: 
 3773: =item * &get_related_words()
 3774: 
 3775: Look up a word in the thesaurus.  Takes a scalar argument and returns
 3776: an array of words.  If the keyword is not in the thesaurus, an empty array
 3777: will be returned.  The order of the words returned is determined by the
 3778: database which holds them.
 3779: 
 3780: Uses global $thesaurus_db_file.
 3781: 
 3782: 
 3783: =cut
 3784: 
 3785: ###############################################################
 3786: sub get_related_words {
 3787:     my $keyword = shift;
 3788:     my %thesaurus_db;
 3789:     if (! -e $thesaurus_db_file) {
 3790:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 3791:                                  "failed because the file does not exist");
 3792:         return ();
 3793:     }
 3794:     if (! tie(%thesaurus_db,'GDBM_File',
 3795:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3796:         return ();
 3797:     } 
 3798:     my @Words=();
 3799:     my $count=0;
 3800:     if (exists($thesaurus_db{$keyword})) {
 3801: 	# The first element is the number of times
 3802: 	# the word appears.  We do not need it now.
 3803: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 3804: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 3805: 	my $threshold=$mostfrequentcount/10;
 3806:         foreach my $possibleword (@RelatedWords) {
 3807:             my ($word,$wordcount)=split(/\,/,$possibleword);
 3808:             if ($wordcount>$threshold) {
 3809: 		push(@Words,$word);
 3810:                 $count++;
 3811:                 if ($count>10) { last; }
 3812: 	    }
 3813:         }
 3814:     }
 3815:     untie %thesaurus_db;
 3816:     return @Words;
 3817: }
 3818: ###############################################################
 3819: #
 3820: #  Spell checking
 3821: #
 3822: 
 3823: =pod
 3824: 
 3825: =back
 3826: 
 3827: =head1 Spell checking
 3828: 
 3829: =over 4
 3830: 
 3831: =item * &check_spelling($wordlist $language)
 3832: 
 3833: Takes a string containing words and feeds it to an external
 3834: spellcheck program via a pipeline. Returns a string containing
 3835: them mis-spelled words.
 3836: 
 3837: Parameters:
 3838: 
 3839: =over 4
 3840: 
 3841: =item - $wordlist
 3842: 
 3843: String that will be fed into the spellcheck program.
 3844: 
 3845: =item - $language
 3846: 
 3847: Language string that specifies the language for which the spell
 3848: check will be performed.
 3849: 
 3850: =back
 3851: 
 3852: =back
 3853: 
 3854: Note: This sub assumes that aspell is installed.
 3855: 
 3856: 
 3857: =cut
 3858: 
 3859: 
 3860: sub check_spelling {
 3861:     my ($wordlist, $language) = @_;
 3862:     my @misspellings;
 3863:     
 3864:     # Generate the speller and set the langauge.
 3865:     # if explicitly selected:
 3866: 
 3867:     my $speller = Text::Aspell->new;
 3868:     if ($language) {
 3869: 	$speller->set_option('lang', $language);
 3870:     }
 3871: 
 3872:     # Turn the word list into an array of words by splittingon whitespace
 3873: 
 3874:     my @words = split(/\s+/, $wordlist);
 3875: 
 3876:     foreach my $word (@words) {
 3877: 	if(! $speller->check($word)) {
 3878: 	    push(@misspellings, $word);
 3879: 	}
 3880:     }
 3881:     return join(' ', @misspellings);
 3882:     
 3883: }
 3884: 
 3885: # -------------------------------------------------------------- Plaintext name
 3886: =pod
 3887: 
 3888: =head1 User Name Functions
 3889: 
 3890: =over 4
 3891: 
 3892: =item * &plainname($uname,$udom,$first)
 3893: 
 3894: Takes a users logon name and returns it as a string in
 3895: "first middle last generation" form 
 3896: if $first is set to 'lastname' then it returns it as
 3897: 'lastname generation, firstname middlename' if their is a lastname
 3898: 
 3899: =cut
 3900: 
 3901: 
 3902: ###############################################################
 3903: sub plainname {
 3904:     my ($uname,$udom,$first)=@_;
 3905:     return if (!defined($uname) || !defined($udom));
 3906:     my %names=&getnames($uname,$udom);
 3907:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 3908: 					  $names{'middlename'},
 3909: 					  $names{'lastname'},
 3910: 					  $names{'generation'},$first);
 3911:     $name=~s/^\s+//;
 3912:     $name=~s/\s+$//;
 3913:     $name=~s/\s+/ /g;
 3914:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 3915:     return $name;
 3916: }
 3917: 
 3918: # -------------------------------------------------------------------- Nickname
 3919: =pod
 3920: 
 3921: =item * &nickname($uname,$udom)
 3922: 
 3923: Gets a users name and returns it as a string as
 3924: 
 3925: "&quot;nickname&quot;"
 3926: 
 3927: if the user has a nickname or
 3928: 
 3929: "first middle last generation"
 3930: 
 3931: if the user does not
 3932: 
 3933: =cut
 3934: 
 3935: sub nickname {
 3936:     my ($uname,$udom)=@_;
 3937:     return if (!defined($uname) || !defined($udom));
 3938:     my %names=&getnames($uname,$udom);
 3939:     my $name=$names{'nickname'};
 3940:     if ($name) {
 3941:        $name='&quot;'.$name.'&quot;'; 
 3942:     } else {
 3943:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 3944: 	     $names{'lastname'}.' '.$names{'generation'};
 3945:        $name=~s/\s+$//;
 3946:        $name=~s/\s+/ /g;
 3947:     }
 3948:     return $name;
 3949: }
 3950: 
 3951: sub getnames {
 3952:     my ($uname,$udom)=@_;
 3953:     return if (!defined($uname) || !defined($udom));
 3954:     if ($udom eq 'public' && $uname eq 'public') {
 3955: 	return ('lastname' => &mt('Public'));
 3956:     }
 3957:     my $id=$uname.':'.$udom;
 3958:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 3959:     if ($cached) {
 3960: 	return %{$names};
 3961:     } else {
 3962: 	my %loadnames=&Apache::lonnet::get('environment',
 3963:                     ['firstname','middlename','lastname','generation','nickname'],
 3964: 					 $udom,$uname);
 3965: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 3966: 	return %loadnames;
 3967:     }
 3968: }
 3969: 
 3970: # -------------------------------------------------------------------- getemails
 3971: 
 3972: =pod
 3973: 
 3974: =item * &getemails($uname,$udom)
 3975: 
 3976: Gets a user's email information and returns it as a hash with keys:
 3977: notification, critnotification, permanentemail
 3978: 
 3979: For notification and critnotification, values are comma-separated lists 
 3980: of e-mail addresses; for permanentemail, value is a single e-mail address.
 3981:  
 3982: 
 3983: =cut
 3984: 
 3985: 
 3986: sub getemails {
 3987:     my ($uname,$udom)=@_;
 3988:     if ($udom eq 'public' && $uname eq 'public') {
 3989: 	return;
 3990:     }
 3991:     if (!$udom) { $udom=$env{'user.domain'}; }
 3992:     if (!$uname) { $uname=$env{'user.name'}; }
 3993:     my $id=$uname.':'.$udom;
 3994:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 3995:     if ($cached) {
 3996: 	return %{$names};
 3997:     } else {
 3998: 	my %loadnames=&Apache::lonnet::get('environment',
 3999:                     			   ['notification','critnotification',
 4000: 					    'permanentemail'],
 4001: 					   $udom,$uname);
 4002: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 4003: 	return %loadnames;
 4004:     }
 4005: }
 4006: 
 4007: sub flush_email_cache {
 4008:     my ($uname,$udom)=@_;
 4009:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4010:     if (!$uname) { $uname=$env{'user.name'};   }
 4011:     return if ($udom eq 'public' && $uname eq 'public');
 4012:     my $id=$uname.':'.$udom;
 4013:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 4014: }
 4015: 
 4016: # -------------------------------------------------------------------- getlangs
 4017: 
 4018: =pod
 4019: 
 4020: =item * &getlangs($uname,$udom)
 4021: 
 4022: Gets a user's language preference and returns it as a hash with key:
 4023: language.
 4024: 
 4025: =cut
 4026: 
 4027: 
 4028: sub getlangs {
 4029:     my ($uname,$udom) = @_;
 4030:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4031:     if (!$uname) { $uname=$env{'user.name'};   }
 4032:     my $id=$uname.':'.$udom;
 4033:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 4034:     if ($cached) {
 4035:         return %{$langs};
 4036:     } else {
 4037:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 4038:                                            $udom,$uname);
 4039:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 4040:         return %loadlangs;
 4041:     }
 4042: }
 4043: 
 4044: sub flush_langs_cache {
 4045:     my ($uname,$udom)=@_;
 4046:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4047:     if (!$uname) { $uname=$env{'user.name'};   }
 4048:     return if ($udom eq 'public' && $uname eq 'public');
 4049:     my $id=$uname.':'.$udom;
 4050:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 4051: }
 4052: 
 4053: # ------------------------------------------------------------------ Screenname
 4054: 
 4055: =pod
 4056: 
 4057: =item * &screenname($uname,$udom)
 4058: 
 4059: Gets a users screenname and returns it as a string
 4060: 
 4061: =cut
 4062: 
 4063: sub screenname {
 4064:     my ($uname,$udom)=@_;
 4065:     if ($uname eq $env{'user.name'} &&
 4066: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 4067:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 4068:     return $names{'screenname'};
 4069: }
 4070: 
 4071: 
 4072: # ------------------------------------------------------------- Confirm Wrapper
 4073: =pod
 4074: 
 4075: =item * &confirmwrapper($message)
 4076: 
 4077: Wrap messages about completion of operation in box
 4078: 
 4079: =cut
 4080: 
 4081: sub confirmwrapper {
 4082:     my ($message)=@_;
 4083:     if ($message) {
 4084:         return "\n".'<div class="LC_confirm_box">'."\n"
 4085:                .$message."\n"
 4086:                .'</div>'."\n";
 4087:     } else {
 4088:         return $message;
 4089:     }
 4090: }
 4091: 
 4092: # ------------------------------------------------------------- Message Wrapper
 4093: 
 4094: sub messagewrapper {
 4095:     my ($link,$username,$domain,$subject,$text)=@_;
 4096:     return 
 4097:         '<a href="/adm/email?compose=individual&amp;'.
 4098:         'recname='.$username.'&amp;recdom='.$domain.
 4099: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 4100:         'title="'.&mt('Send message').'">'.$link.'</a>';
 4101: }
 4102: 
 4103: # --------------------------------------------------------------- Notes Wrapper
 4104: 
 4105: sub noteswrapper {
 4106:     my ($link,$un,$do)=@_;
 4107:     return 
 4108: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 4109: }
 4110: 
 4111: # ------------------------------------------------------------- Aboutme Wrapper
 4112: 
 4113: sub aboutmewrapper {
 4114:     my ($link,$username,$domain,$target,$class)=@_;
 4115:     if (!defined($username)  && !defined($domain)) {
 4116:         return;
 4117:     }
 4118:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 4119: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 4120: }
 4121: 
 4122: # ------------------------------------------------------------ Syllabus Wrapper
 4123: 
 4124: sub syllabuswrapper {
 4125:     my ($linktext,$coursedir,$domain)=@_;
 4126:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 4127: }
 4128: 
 4129: # -----------------------------------------------------------------------------
 4130: 
 4131: sub track_student_link {
 4132:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 4133:     my $link ="/adm/trackstudent?";
 4134:     my $title = 'View recent activity';
 4135:     if (defined($sname) && $sname !~ /^\s*$/ &&
 4136:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 4137:         $link .= "selected_student=$sname:$sdom";
 4138:         $title .= ' of this student';
 4139:     } 
 4140:     if (defined($target) && $target !~ /^\s*$/) {
 4141:         $target = qq{target="$target"};
 4142:     } else {
 4143:         $target = '';
 4144:     }
 4145:     if ($start) { $link.='&amp;start='.$start; }
 4146:     if ($only_body) { $link .= '&amp;only_body=1'; }
 4147:     $title = &mt($title);
 4148:     $linktext = &mt($linktext);
 4149:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 4150: 	&help_open_topic('View_recent_activity');
 4151: }
 4152: 
 4153: sub slot_reservations_link {
 4154:     my ($linktext,$sname,$sdom,$target) = @_;
 4155:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 4156:     my $title = 'View slot reservation history';
 4157:     if (defined($sname) && $sname !~ /^\s*$/ &&
 4158:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 4159:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 4160:         $title .= ' of this student';
 4161:     }
 4162:     if (defined($target) && $target !~ /^\s*$/) {
 4163:         $target = qq{target="$target"};
 4164:     } else {
 4165:         $target = '';
 4166:     }
 4167:     $title = &mt($title);
 4168:     $linktext = &mt($linktext);
 4169:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 4170: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 4171: 
 4172: }
 4173: 
 4174: # ===================================================== Display a student photo
 4175: 
 4176: 
 4177: sub student_image_tag {
 4178:     my ($domain,$user)=@_;
 4179:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 4180:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 4181: 	return '<img src="'.$imgsrc.'" align="right" />';
 4182:     } else {
 4183: 	return '';
 4184:     }
 4185: }
 4186: 
 4187: =pod
 4188: 
 4189: =back
 4190: 
 4191: =head1 Access .tab File Data
 4192: 
 4193: =over 4
 4194: 
 4195: =item * &languageids() 
 4196: 
 4197: returns list of all language ids
 4198: 
 4199: =cut
 4200: 
 4201: sub languageids {
 4202:     return sort(keys(%language));
 4203: }
 4204: 
 4205: =pod
 4206: 
 4207: =item * &languagedescription() 
 4208: 
 4209: returns description of a specified language id
 4210: 
 4211: =cut
 4212: 
 4213: sub languagedescription {
 4214:     my $code=shift;
 4215:     return  ($supported_language{$code}?'* ':'').
 4216:             $language{$code}.
 4217: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 4218: }
 4219: 
 4220: =pod
 4221: 
 4222: =item * &plainlanguagedescription
 4223: 
 4224: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 4225: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 4226: 
 4227: =cut
 4228: 
 4229: sub plainlanguagedescription {
 4230:     my $code=shift;
 4231:     return $language{$code};
 4232: }
 4233: 
 4234: =pod
 4235: 
 4236: =item * &supportedlanguagecode
 4237: 
 4238: Returns the supported language code (e.g. sptutf maps to pt) given a language
 4239: code.
 4240: 
 4241: =cut
 4242: 
 4243: sub supportedlanguagecode {
 4244:     my $code=shift;
 4245:     return $supported_language{$code};
 4246: }
 4247: 
 4248: =pod
 4249: 
 4250: =item * &latexlanguage()
 4251: 
 4252: Given a language key code returns the correspondnig language to use
 4253: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 4254: is no supported hyphenation for the language code.
 4255: 
 4256: =cut
 4257: 
 4258: sub latexlanguage {
 4259:     my $code = shift;
 4260:     return $latex_language{$code};
 4261: }
 4262: 
 4263: =pod
 4264: 
 4265: =item * &latexhyphenation()
 4266: 
 4267: Same as above but what's supplied is the language as it might be stored
 4268: in the metadata.
 4269: 
 4270: =cut
 4271: 
 4272: sub latexhyphenation {
 4273:     my $key = shift;
 4274:     return $latex_language_bykey{$key};
 4275: }
 4276: 
 4277: =pod
 4278: 
 4279: =item * &copyrightids() 
 4280: 
 4281: returns list of all copyrights
 4282: 
 4283: =cut
 4284: 
 4285: sub copyrightids {
 4286:     return sort(keys(%cprtag));
 4287: }
 4288: 
 4289: =pod
 4290: 
 4291: =item * &copyrightdescription() 
 4292: 
 4293: returns description of a specified copyright id
 4294: 
 4295: =cut
 4296: 
 4297: sub copyrightdescription {
 4298:     return &mt($cprtag{shift(@_)});
 4299: }
 4300: 
 4301: =pod
 4302: 
 4303: =item * &source_copyrightids() 
 4304: 
 4305: returns list of all source copyrights
 4306: 
 4307: =cut
 4308: 
 4309: sub source_copyrightids {
 4310:     return sort(keys(%scprtag));
 4311: }
 4312: 
 4313: =pod
 4314: 
 4315: =item * &source_copyrightdescription() 
 4316: 
 4317: returns description of a specified source copyright id
 4318: 
 4319: =cut
 4320: 
 4321: sub source_copyrightdescription {
 4322:     return &mt($scprtag{shift(@_)});
 4323: }
 4324: 
 4325: =pod
 4326: 
 4327: =item * &filecategories() 
 4328: 
 4329: returns list of all file categories
 4330: 
 4331: =cut
 4332: 
 4333: sub filecategories {
 4334:     return sort(keys(%category_extensions));
 4335: }
 4336: 
 4337: =pod
 4338: 
 4339: =item * &filecategorytypes() 
 4340: 
 4341: returns list of file types belonging to a given file
 4342: category
 4343: 
 4344: =cut
 4345: 
 4346: sub filecategorytypes {
 4347:     my ($cat) = @_;
 4348:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
 4349:         return @{$category_extensions{lc($cat)}};
 4350:     } else {
 4351:         return ();
 4352:     }
 4353: }
 4354: 
 4355: =pod
 4356: 
 4357: =item * &fileembstyle() 
 4358: 
 4359: returns embedding style for a specified file type
 4360: 
 4361: =cut
 4362: 
 4363: sub fileembstyle {
 4364:     return $fe{lc(shift(@_))};
 4365: }
 4366: 
 4367: sub filemimetype {
 4368:     return $fm{lc(shift(@_))};
 4369: }
 4370: 
 4371: 
 4372: sub filecategoryselect {
 4373:     my ($name,$value)=@_;
 4374:     return &select_form($value,$name,
 4375:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 4376: }
 4377: 
 4378: =pod
 4379: 
 4380: =item * &filedescription() 
 4381: 
 4382: returns description for a specified file type
 4383: 
 4384: =cut
 4385: 
 4386: sub filedescription {
 4387:     my $file_description = $fd{lc(shift())};
 4388:     $file_description =~ s:([\[\]]):~$1:g;
 4389:     return &mt($file_description);
 4390: }
 4391: 
 4392: =pod
 4393: 
 4394: =item * &filedescriptionex() 
 4395: 
 4396: returns description for a specified file type with
 4397: extra formatting
 4398: 
 4399: =cut
 4400: 
 4401: sub filedescriptionex {
 4402:     my $ex=shift;
 4403:     my $file_description = $fd{lc($ex)};
 4404:     $file_description =~ s:([\[\]]):~$1:g;
 4405:     return '.'.$ex.' '.&mt($file_description);
 4406: }
 4407: 
 4408: # End of .tab access
 4409: =pod
 4410: 
 4411: =back
 4412: 
 4413: =cut
 4414: 
 4415: # ------------------------------------------------------------------ File Types
 4416: sub fileextensions {
 4417:     return sort(keys(%fe));
 4418: }
 4419: 
 4420: # ----------------------------------------------------------- Display Languages
 4421: # returns a hash with all desired display languages
 4422: #
 4423: 
 4424: sub display_languages {
 4425:     my %languages=();
 4426:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 4427: 	$languages{$lang}=1;
 4428:     }
 4429:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 4430:     if ($env{'form.displaylanguage'}) {
 4431: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 4432: 	    $languages{$lang}=1;
 4433:         }
 4434:     }
 4435:     return %languages;
 4436: }
 4437: 
 4438: sub languages {
 4439:     my ($possible_langs) = @_;
 4440:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 4441:     if (!ref($possible_langs)) {
 4442: 	if( wantarray ) {
 4443: 	    return @preferred_langs;
 4444: 	} else {
 4445: 	    return $preferred_langs[0];
 4446: 	}
 4447:     }
 4448:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 4449:     my @preferred_possibilities;
 4450:     foreach my $preferred_lang (@preferred_langs) {
 4451: 	if (exists($possibilities{$preferred_lang})) {
 4452: 	    push(@preferred_possibilities, $preferred_lang);
 4453: 	}
 4454:     }
 4455:     if( wantarray ) {
 4456: 	return @preferred_possibilities;
 4457:     }
 4458:     return $preferred_possibilities[0];
 4459: }
 4460: 
 4461: sub user_lang {
 4462:     my ($touname,$toudom,$fromcid) = @_;
 4463:     my @userlangs;
 4464:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 4465:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 4466:                     $env{'course.'.$fromcid.'.languages'}));
 4467:     } else {
 4468:         my %langhash = &getlangs($touname,$toudom);
 4469:         if ($langhash{'languages'} ne '') {
 4470:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 4471:         } else {
 4472:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 4473:             if ($domdefs{'lang_def'} ne '') {
 4474:                 @userlangs = ($domdefs{'lang_def'});
 4475:             }
 4476:         }
 4477:     }
 4478:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 4479:     my $user_lh = Apache::localize->get_handle(@languages);
 4480:     return $user_lh;
 4481: }
 4482: 
 4483: 
 4484: ###############################################################
 4485: ##               Student Answer Attempts                     ##
 4486: ###############################################################
 4487: 
 4488: =pod
 4489: 
 4490: =head1 Alternate Problem Views
 4491: 
 4492: =over 4
 4493: 
 4494: =item * &get_previous_attempt($symb, $username, $domain, $course,
 4495:     $getattempt, $regexp, $gradesub, $usec, $identifier)
 4496: 
 4497: Return string with previous attempt on problem. Arguments:
 4498: 
 4499: =over 4
 4500: 
 4501: =item * $symb: Problem, including path
 4502: 
 4503: =item * $username: username of the desired student
 4504: 
 4505: =item * $domain: domain of the desired student
 4506: 
 4507: =item * $course: Course ID
 4508: 
 4509: =item * $getattempt: Leave blank for all attempts, otherwise put
 4510:     something
 4511: 
 4512: =item * $regexp: if string matches this regexp, the string will be
 4513:     sent to $gradesub
 4514: 
 4515: =item * $gradesub: routine that processes the string if it matches $regexp
 4516: 
 4517: =item * $usec: section of the desired student
 4518: 
 4519: =item * $identifier: counter for student (multiple students one problem) or 
 4520:     problem (one student; whole sequence).
 4521: 
 4522: =back
 4523: 
 4524: The output string is a table containing all desired attempts, if any.
 4525: 
 4526: =cut
 4527: 
 4528: sub get_previous_attempt {
 4529:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
 4530:   my $prevattempts='';
 4531:   no strict 'refs';
 4532:   if ($symb) {
 4533:     my (%returnhash)=
 4534:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 4535:     if ($returnhash{'version'}) {
 4536:       my %lasthash=();
 4537:       my $version;
 4538:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 4539:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
 4540:             if ($key =~ /\.rawrndseed$/) {
 4541:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
 4542:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
 4543:             } else {
 4544:                 $lasthash{$key}=$returnhash{$version.':'.$key};
 4545:             }
 4546:         }
 4547:       }
 4548:       $prevattempts=&start_data_table().&start_data_table_header_row();
 4549:       $prevattempts.='<th>'.&mt('History').'</th>';
 4550:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
 4551:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 4552:       foreach my $key (sort(keys(%lasthash))) {
 4553: 	my ($ign,@parts) = split(/\./,$key);
 4554: 	if ($#parts > 0) {
 4555: 	  my $data=$parts[-1];
 4556:           next if ($data eq 'foilorder');
 4557: 	  pop(@parts);
 4558:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 4559:           if ($data eq 'type') {
 4560:               unless ($showsurv) {
 4561:                   my $id = join(',',@parts);
 4562:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 4563:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 4564:                       $lasthidden{$ign.'.'.$id} = 1;
 4565:                   }
 4566:               }
 4567:               if ($identifier ne '') {
 4568:                   my $id = join(',',@parts);
 4569:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
 4570:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
 4571:                       $hidestatus{$ign.'.'.$id} = 1;
 4572:                   }
 4573:               }
 4574:           } elsif ($data eq 'regrader') {
 4575:               if (($identifier ne '') && (@parts)) {
 4576:                   my $id = join(',',@parts);
 4577:                   $regraded{$ign.'.'.$id} = 1;
 4578:               }
 4579:           } 
 4580: 	} else {
 4581: 	  if ($#parts == 0) {
 4582: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 4583: 	  } else {
 4584: 	    $prevattempts.='<th>'.$ign.'</th>';
 4585: 	  }
 4586: 	}
 4587:       }
 4588:       $prevattempts.=&end_data_table_header_row();
 4589:       if ($getattempt eq '') {
 4590:         my (%solved,%resets,%probstatus);
 4591:         if (($identifier ne '') && (keys(%regraded) > 0)) {
 4592:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 4593:                 foreach my $id (keys(%regraded)) {
 4594:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
 4595:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
 4596:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
 4597:                         push(@{$resets{$id}},$version);
 4598:                     }
 4599:                 }
 4600:             }
 4601:         }
 4602: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 4603:             my (@hidden,@unsolved);
 4604:             if (%typeparts) {
 4605:                 foreach my $id (keys(%typeparts)) {
 4606:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
 4607:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 4608:                         push(@hidden,$id);
 4609:                     } elsif ($identifier ne '') {
 4610:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
 4611:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
 4612:                                 ($hidestatus{$id})) {
 4613:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
 4614:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
 4615:                                 push(@{$solved{$id}},$version);
 4616:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
 4617:                                      (ref($solved{$id}) eq 'ARRAY')) {
 4618:                                 my $skip;
 4619:                                 if (ref($resets{$id}) eq 'ARRAY') {
 4620:                                     foreach my $reset (@{$resets{$id}}) {
 4621:                                         if ($reset > $solved{$id}[-1]) {
 4622:                                             $skip=1;
 4623:                                             last;
 4624:                                         }
 4625:                                     }
 4626:                                 }
 4627:                                 unless ($skip) {
 4628:                                     my ($ign,$partslist) = split(/\./,$id,2);
 4629:                                     push(@unsolved,$partslist);
 4630:                                 }
 4631:                             }
 4632:                         }
 4633:                     }
 4634:                 }
 4635:             }
 4636:             $prevattempts.=&start_data_table_row().
 4637:                            '<td>'.&mt('Transaction [_1]',$version);
 4638:             if (@unsolved) {
 4639:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
 4640:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
 4641:                                  &mt('Hide').'</label></span>';
 4642:             }
 4643:             $prevattempts .= '</td>';
 4644:             if (@hidden) {
 4645:                 foreach my $key (sort(keys(%lasthash))) {
 4646:                     next if ($key =~ /\.foilorder$/);
 4647:                     my $hide;
 4648:                     foreach my $id (@hidden) {
 4649:                         if ($key =~ /^\Q$id\E/) {
 4650:                             $hide = 1;
 4651:                             last;
 4652:                         }
 4653:                     }
 4654:                     if ($hide) {
 4655:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4656:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 4657:                             my $value = &format_previous_attempt_value($key,
 4658:                                              $returnhash{$version.':'.$key});
 4659:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4660:                         } else {
 4661:                             $prevattempts.='<td>&nbsp;</td>';
 4662:                         }
 4663:                     } else {
 4664:                         if ($key =~ /\./) {
 4665:                             my $value = $returnhash{$version.':'.$key};
 4666:                             if ($key =~ /\.rndseed$/) {
 4667:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 4668:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4669:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4670:                                 }
 4671:                             }
 4672:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4673:                                            '&nbsp;</td>';
 4674:                         } else {
 4675:                             $prevattempts.='<td>&nbsp;</td>';
 4676:                         }
 4677:                     }
 4678:                 }
 4679:             } else {
 4680: 	        foreach my $key (sort(keys(%lasthash))) {
 4681:                     next if ($key =~ /\.foilorder$/);
 4682:                     my $value = $returnhash{$version.':'.$key};
 4683:                     if ($key =~ /\.rndseed$/) {
 4684:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 4685:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4686:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4687:                         }
 4688:                     }
 4689:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4690:                                    '&nbsp;</td>';
 4691: 	        }
 4692:             }
 4693: 	    $prevattempts.=&end_data_table_row();
 4694: 	 }
 4695:       }
 4696:       my @currhidden = keys(%lasthidden);
 4697:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 4698:       foreach my $key (sort(keys(%lasthash))) {
 4699:           next if ($key =~ /\.foilorder$/);
 4700:           if (%typeparts) {
 4701:               my $hidden;
 4702:               foreach my $id (@currhidden) {
 4703:                   if ($key =~ /^\Q$id\E/) {
 4704:                       $hidden = 1;
 4705:                       last;
 4706:                   }
 4707:               }
 4708:               if ($hidden) {
 4709:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4710:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 4711:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4712:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4713:                           $value = &$gradesub($value);
 4714:                       }
 4715:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
 4716:                   } else {
 4717:                       $prevattempts.='<td>&nbsp;</td>';
 4718:                   }
 4719:               } else {
 4720:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4721:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4722:                       $value = &$gradesub($value);
 4723:                   }
 4724:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4725:               }
 4726:           } else {
 4727: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4728: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4729:                   $value = &$gradesub($value);
 4730:               }
 4731: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4732:           }
 4733:       }
 4734:       $prevattempts.= &end_data_table_row().&end_data_table();
 4735:     } else {
 4736:       my $msg;
 4737:       if ($symb =~ /ext\.tool$/) {
 4738:           $msg = &mt('No grade passed back.');
 4739:       } else {
 4740:           $msg = &mt('Nothing submitted - no attempts.');
 4741:       }
 4742:       $prevattempts=
 4743: 	  &start_data_table().&start_data_table_row().
 4744: 	  '<td>'.$msg.'</td>'.
 4745: 	  &end_data_table_row().&end_data_table();
 4746:     }
 4747:   } else {
 4748:     $prevattempts=
 4749: 	  &start_data_table().&start_data_table_row().
 4750: 	  '<td>'.&mt('No data.').'</td>'.
 4751: 	  &end_data_table_row().&end_data_table();
 4752:   }
 4753: }
 4754: 
 4755: sub format_previous_attempt_value {
 4756:     my ($key,$value) = @_;
 4757:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 4758:         $value = &Apache::lonlocal::locallocaltime($value);
 4759:     } elsif (ref($value) eq 'ARRAY') {
 4760:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
 4761:     } elsif ($key =~ /answerstring$/) {
 4762:         my %answers = &Apache::lonnet::str2hash($value);
 4763:         my @answer = %answers;
 4764:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
 4765:         my @anskeys = sort(keys(%answers));
 4766:         if (@anskeys == 1) {
 4767:             my $answer = $answers{$anskeys[0]};
 4768:             if ($answer =~ m{\0}) {
 4769:                 $answer =~ s{\0}{,}g;
 4770:             }
 4771:             my $tag_internal_answer_name = 'INTERNAL';
 4772:             if ($anskeys[0] eq $tag_internal_answer_name) {
 4773:                 $value = $answer; 
 4774:             } else {
 4775:                 $value = $anskeys[0].'='.$answer;
 4776:             }
 4777:         } else {
 4778:             foreach my $ans (@anskeys) {
 4779:                 my $answer = $answers{$ans};
 4780:                 if ($answer =~ m{\0}) {
 4781:                     $answer =~ s{\0}{,}g;
 4782:                 }
 4783:                 $value .=  $ans.'='.$answer.'<br />';;
 4784:             } 
 4785:         }
 4786:     } else {
 4787:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
 4788:     }
 4789:     return $value;
 4790: }
 4791: 
 4792: 
 4793: sub relative_to_absolute {
 4794:     my ($url,$output)=@_;
 4795:     my $parser=HTML::TokeParser->new(\$output);
 4796:     my $token;
 4797:     my $thisdir=$url;
 4798:     my @rlinks=();
 4799:     while ($token=$parser->get_token) {
 4800: 	if ($token->[0] eq 'S') {
 4801: 	    if ($token->[1] eq 'a') {
 4802: 		if ($token->[2]->{'href'}) {
 4803: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 4804: 		}
 4805: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 4806: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 4807: 	    } elsif ($token->[1] eq 'base') {
 4808: 		$thisdir=$token->[2]->{'href'};
 4809: 	    }
 4810: 	}
 4811:     }
 4812:     $thisdir=~s-/[^/]*$--;
 4813:     foreach my $link (@rlinks) {
 4814: 	unless (($link=~/^https?\:\/\//i) ||
 4815: 		($link=~/^\//) ||
 4816: 		($link=~/^javascript:/i) ||
 4817: 		($link=~/^mailto:/i) ||
 4818: 		($link=~/^\#/)) {
 4819: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 4820: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 4821: 	}
 4822:     }
 4823: # -------------------------------------------------- Deal with Applet codebases
 4824:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 4825:     return $output;
 4826: }
 4827: 
 4828: =pod
 4829: 
 4830: =item * &get_student_view()
 4831: 
 4832: show a snapshot of what student was looking at
 4833: 
 4834: =cut
 4835: 
 4836: sub get_student_view {
 4837:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 4838:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4839:   my (%form);
 4840:   my @elements=('symb','courseid','domain','username');
 4841:   foreach my $element (@elements) {
 4842:       $form{'grade_'.$element}=eval '$'.$element #'
 4843:   }
 4844:   if (defined($moreenv)) {
 4845:       %form=(%form,%{$moreenv});
 4846:   }
 4847:   if (defined($target)) { $form{'grade_target'} = $target; }
 4848:   $feedurl=&Apache::lonnet::clutter($feedurl);
 4849:   if (($feedurl =~ /ext\.tool$/) && ($target eq 'tex')) {
 4850:       $feedurl =~ s{^/adm/wrapper}{};
 4851:   }
 4852:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 4853:   $userview=~s/\<body[^\>]*\>//gi;
 4854:   $userview=~s/\<\/body\>//gi;
 4855:   $userview=~s/\<html\>//gi;
 4856:   $userview=~s/\<\/html\>//gi;
 4857:   $userview=~s/\<head\>//gi;
 4858:   $userview=~s/\<\/head\>//gi;
 4859:   $userview=~s/action\s*\=/would_be_action\=/gi;
 4860:   $userview=&relative_to_absolute($feedurl,$userview);
 4861:   if (wantarray) {
 4862:      return ($userview,$response);
 4863:   } else {
 4864:      return $userview;
 4865:   }
 4866: }
 4867: 
 4868: sub get_student_view_with_retries {
 4869:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 4870: 
 4871:     my $ok = 0;                 # True if we got a good response.
 4872:     my $content;
 4873:     my $response;
 4874: 
 4875:     # Try to get the student_view done. within the retries count:
 4876:     
 4877:     do {
 4878:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 4879:          $ok      = $response->is_success;
 4880:          if (!$ok) {
 4881:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 4882:          }
 4883:          $retries--;
 4884:     } while (!$ok && ($retries > 0));
 4885:     
 4886:     if (!$ok) {
 4887:        $content = '';          # On error return an empty content.
 4888:     }
 4889:     if (wantarray) {
 4890:        return ($content, $response);
 4891:     } else {
 4892:        return $content;
 4893:     }
 4894: }
 4895: 
 4896: sub css_links {
 4897:     my ($currsymb,$level) = @_;
 4898:     my ($links,@symbs,%cssrefs,%httpref);
 4899:     if ($level eq 'map') {
 4900:         my $navmap = Apache::lonnavmaps::navmap->new();
 4901:         if (ref($navmap)) {
 4902:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
 4903:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
 4904:             foreach my $res (@resources) {
 4905:                 if (ref($res) && $res->symb()) {
 4906:                     push(@symbs,$res->symb());
 4907:                 }
 4908:             }
 4909:         }
 4910:     } else {
 4911:         @symbs = ($currsymb);
 4912:     }
 4913:     foreach my $symb (@symbs) {
 4914:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
 4915:         if ($css_href =~ /\S/) {
 4916:             unless ($css_href =~ m{https?://}) {
 4917:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
 4918:                 my $proburl =  &Apache::lonnet::clutter($url);
 4919:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
 4920:                 unless ($css_href =~ m{^/}) {
 4921:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
 4922:                 }
 4923:                 if ($css_href =~ m{^/(res|uploaded)/}) {
 4924:                     unless (($httpref{'httpref.'.$css_href}) ||
 4925:                             (&Apache::lonnet::is_on_map($css_href))) {
 4926:                         my $thisurl = $proburl;
 4927:                         if ($env{'httpref.'.$proburl}) {
 4928:                             $thisurl = $env{'httpref.'.$proburl};
 4929:                         }
 4930:                         $httpref{'httpref.'.$css_href} = $thisurl;
 4931:                     }
 4932:                 }
 4933:             }
 4934:             $cssrefs{$css_href} = 1;
 4935:         }
 4936:     }
 4937:     if (keys(%httpref)) {
 4938:         &Apache::lonnet::appenv(\%httpref);
 4939:     }
 4940:     if (keys(%cssrefs)) {
 4941:         foreach my $css_href (keys(%cssrefs)) {
 4942:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
 4943:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
 4944:         }
 4945:     }
 4946:     return $links;
 4947: }
 4948: 
 4949: =pod
 4950: 
 4951: =item * &get_student_answers() 
 4952: 
 4953: show a snapshot of how student was answering problem
 4954: 
 4955: =cut
 4956: 
 4957: sub get_student_answers {
 4958:   my ($symb,$username,$domain,$courseid,%form) = @_;
 4959:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4960:   my (%moreenv);
 4961:   my @elements=('symb','courseid','domain','username');
 4962:   foreach my $element (@elements) {
 4963:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 4964:   }
 4965:   $moreenv{'grade_target'}='answer';
 4966:   %moreenv=(%form,%moreenv);
 4967:   $feedurl = &Apache::lonnet::clutter($feedurl);
 4968:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 4969:   return $userview;
 4970: }
 4971: 
 4972: =pod
 4973: 
 4974: =item * &submlink()
 4975: 
 4976: Inputs: $text $uname $udom $symb $target
 4977: 
 4978: Returns: A link to grades.pm such as to see the SUBM view of a student
 4979: 
 4980: =cut
 4981: 
 4982: ###############################################
 4983: sub submlink {
 4984:     my ($text,$uname,$udom,$symb,$target)=@_;
 4985:     if (!($uname && $udom)) {
 4986: 	(my $cursymb, my $courseid,$udom,$uname)=
 4987: 	    &Apache::lonnet::whichuser($symb);
 4988: 	if (!$symb) { $symb=$cursymb; }
 4989:     }
 4990:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4991:     $symb=&escape($symb);
 4992:     if ($target) { $target=" target=\"$target\""; }
 4993:     return
 4994:         '<a href="/adm/grades?command=submission'.
 4995:         '&amp;symb='.$symb.
 4996:         '&amp;student='.$uname.
 4997:         '&amp;userdom='.$udom.'"'.
 4998:         $target.'>'.$text.'</a>';
 4999: }
 5000: ##############################################
 5001: 
 5002: =pod
 5003: 
 5004: =item * &pgrdlink()
 5005: 
 5006: Inputs: $text $uname $udom $symb $target
 5007: 
 5008: Returns: A link to grades.pm such as to see the PGRD view of a student
 5009: 
 5010: =cut
 5011: 
 5012: ###############################################
 5013: sub pgrdlink {
 5014:     my $link=&submlink(@_);
 5015:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 5016:     return $link;
 5017: }
 5018: ##############################################
 5019: 
 5020: =pod
 5021: 
 5022: =item * &pprmlink()
 5023: 
 5024: Inputs: $text $uname $udom $symb $target
 5025: 
 5026: Returns: A link to parmset.pm such as to see the PPRM view of a
 5027: student and a specific resource
 5028: 
 5029: =cut
 5030: 
 5031: ###############################################
 5032: sub pprmlink {
 5033:     my ($text,$uname,$udom,$symb,$target)=@_;
 5034:     if (!($uname && $udom)) {
 5035: 	(my $cursymb, my $courseid,$udom,$uname)=
 5036: 	    &Apache::lonnet::whichuser($symb);
 5037: 	if (!$symb) { $symb=$cursymb; }
 5038:     }
 5039:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 5040:     $symb=&escape($symb);
 5041:     if ($target) { $target="target=\"$target\""; }
 5042:     return '<a href="/adm/parmset?command=set&amp;'.
 5043: 	'symb='.$symb.'&amp;uname='.$uname.
 5044: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 5045: }
 5046: ##############################################
 5047: 
 5048: =pod
 5049: 
 5050: =back
 5051: 
 5052: =cut
 5053: 
 5054: ###############################################
 5055: 
 5056: 
 5057: sub timehash {
 5058:     my ($thistime) = @_;
 5059:     my $timezone = &Apache::lonlocal::gettimezone();
 5060:     my $dt = DateTime->from_epoch(epoch => $thistime)
 5061:                      ->set_time_zone($timezone);
 5062:     my $wday = $dt->day_of_week();
 5063:     if ($wday == 7) { $wday = 0; }
 5064:     return ( 'second' => $dt->second(),
 5065:              'minute' => $dt->minute(),
 5066:              'hour'   => $dt->hour(),
 5067:              'day'     => $dt->day_of_month(),
 5068:              'month'   => $dt->month(),
 5069:              'year'    => $dt->year(),
 5070:              'weekday' => $wday,
 5071:              'dayyear' => $dt->day_of_year(),
 5072:              'dlsav'   => $dt->is_dst() );
 5073: }
 5074: 
 5075: sub utc_string {
 5076:     my ($date)=@_;
 5077:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 5078: }
 5079: 
 5080: sub maketime {
 5081:     my %th=@_;
 5082:     my ($epoch_time,$timezone,$dt);
 5083:     $timezone = &Apache::lonlocal::gettimezone();
 5084:     eval {
 5085:         $dt = DateTime->new( year   => $th{'year'},
 5086:                              month  => $th{'month'},
 5087:                              day    => $th{'day'},
 5088:                              hour   => $th{'hour'},
 5089:                              minute => $th{'minute'},
 5090:                              second => $th{'second'},
 5091:                              time_zone => $timezone,
 5092:                          );
 5093:     };
 5094:     if (!$@) {
 5095:         $epoch_time = $dt->epoch;
 5096:         if ($epoch_time) {
 5097:             return $epoch_time;
 5098:         }
 5099:     }
 5100:     return POSIX::mktime(
 5101:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 5102:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 5103: }
 5104: 
 5105: #########################################
 5106: 
 5107: sub findallcourses {
 5108:     my ($roles,$uname,$udom) = @_;
 5109:     my %roles;
 5110:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 5111:     my %courses;
 5112:     my $now=time;
 5113:     if (!defined($uname)) {
 5114:         $uname = $env{'user.name'};
 5115:     }
 5116:     if (!defined($udom)) {
 5117:         $udom = $env{'user.domain'};
 5118:     }
 5119:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 5120:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 5121:         if (!%roles) {
 5122:             %roles = (
 5123:                        cc => 1,
 5124:                        co => 1,
 5125:                        in => 1,
 5126:                        ep => 1,
 5127:                        ta => 1,
 5128:                        cr => 1,
 5129:                        st => 1,
 5130:              );
 5131:         }
 5132:         foreach my $entry (keys(%roleshash)) {
 5133:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 5134:             if ($trole =~ /^cr/) { 
 5135:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 5136:             } else {
 5137:                 next if (!exists($roles{$trole}));
 5138:             }
 5139:             if ($tend) {
 5140:                 next if ($tend < $now);
 5141:             }
 5142:             if ($tstart) {
 5143:                 next if ($tstart > $now);
 5144:             }
 5145:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 5146:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 5147:             my $value = $trole.'/'.$cdom.'/';
 5148:             if ($secpart eq '') {
 5149:                 ($cnum,$role) = split(/_/,$cnumpart); 
 5150:                 $sec = 'none';
 5151:                 $value .= $cnum.'/';
 5152:             } else {
 5153:                 $cnum = $cnumpart;
 5154:                 ($sec,$role) = split(/_/,$secpart);
 5155:                 $value .= $cnum.'/'.$sec;
 5156:             }
 5157:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 5158:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 5159:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 5160:                 }
 5161:             } else {
 5162:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 5163:             }
 5164:         }
 5165:     } else {
 5166:         foreach my $key (keys(%env)) {
 5167: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 5168:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 5169: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 5170: 	        next if ($role eq 'ca' || $role eq 'aa');
 5171: 	        next if (%roles && !exists($roles{$role}));
 5172: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 5173:                 my $active=1;
 5174:                 if ($starttime) {
 5175: 		    if ($now<$starttime) { $active=0; }
 5176:                 }
 5177:                 if ($endtime) {
 5178:                     if ($now>$endtime) { $active=0; }
 5179:                 }
 5180:                 if ($active) {
 5181:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 5182:                     if ($sec eq '') {
 5183:                         $sec = 'none';
 5184:                     } else {
 5185:                         $value .= $sec;
 5186:                     }
 5187:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 5188:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 5189:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 5190:                         }
 5191:                     } else {
 5192:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 5193:                     }
 5194:                 }
 5195:             }
 5196:         }
 5197:     }
 5198:     return %courses;
 5199: }
 5200: 
 5201: ###############################################
 5202: 
 5203: sub blockcheck {
 5204:     my ($setters,$activity,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
 5205: 
 5206:     if (defined($udom) && defined($uname)) {
 5207:         # If uname and udom are for a course, check for blocks in the course.
 5208:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
 5209:             my ($startblock,$endblock,$triggerblock) =
 5210:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
 5211:             return ($startblock,$endblock,$triggerblock);
 5212:         }
 5213:     } else {
 5214:         $udom = $env{'user.domain'};
 5215:         $uname = $env{'user.name'};
 5216:     }
 5217: 
 5218:     my $startblock = 0;
 5219:     my $endblock = 0;
 5220:     my $triggerblock = '';
 5221:     my %live_courses = &findallcourses(undef,$uname,$udom);
 5222: 
 5223:     # If uname is for a user, and activity is course-specific, i.e.,
 5224:     # boards, chat or groups, check for blocking in current course only.
 5225: 
 5226:     if (($activity eq 'boards' || $activity eq 'chat' ||
 5227:          $activity eq 'groups' || $activity eq 'printout' ||
 5228:          $activity eq 'search' || $activity eq 'reinit' ||
 5229:          $activity eq 'alert') &&
 5230:         ($env{'request.course.id'})) {
 5231:         foreach my $key (keys(%live_courses)) {
 5232:             if ($key ne $env{'request.course.id'}) {
 5233:                 delete($live_courses{$key});
 5234:             }
 5235:         }
 5236:     }
 5237: 
 5238:     my $otheruser = 0;
 5239:     my %own_courses;
 5240:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 5241:         # Resource belongs to user other than current user.
 5242:         $otheruser = 1;
 5243:         # Gather courses for current user
 5244:         %own_courses = 
 5245:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 5246:     }
 5247: 
 5248:     # Gather active course roles - course coordinator, instructor, 
 5249:     # exam proctor, ta, student, or custom role.
 5250: 
 5251:     foreach my $course (keys(%live_courses)) {
 5252:         my ($cdom,$cnum);
 5253:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 5254:             $cdom = $env{'course.'.$course.'.domain'};
 5255:             $cnum = $env{'course.'.$course.'.num'};
 5256:         } else {
 5257:             ($cdom,$cnum) = split(/_/,$course); 
 5258:         }
 5259:         my $no_ownblock = 0;
 5260:         my $no_userblock = 0;
 5261:         if ($otheruser && $activity ne 'com') {
 5262:             # Check if current user has 'evb' priv for this
 5263:             if (defined($own_courses{$course})) {
 5264:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 5265:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5266:                     if ($sec ne 'none') {
 5267:                         $checkrole .= '/'.$sec;
 5268:                     }
 5269:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5270:                         $no_ownblock = 1;
 5271:                         last;
 5272:                     }
 5273:                 }
 5274:             }
 5275:             # if they have 'evb' priv and are currently not playing student
 5276:             next if (($no_ownblock) &&
 5277:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 5278:         }
 5279:         foreach my $sec (keys(%{$live_courses{$course}})) {
 5280:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5281:             if ($sec ne 'none') {
 5282:                 $checkrole .= '/'.$sec;
 5283:             }
 5284:             if ($otheruser) {
 5285:                 # Resource belongs to user other than current user.
 5286:                 # Assemble privs for that user, and check for 'evb' priv.
 5287:                 my (%allroles,%userroles);
 5288:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 5289:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 5290:                         my ($trole,$tdom,$tnum,$tsec);
 5291:                         if ($entry =~ /^cr/) {
 5292:                             ($trole,$tdom,$tnum,$tsec) = 
 5293:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 5294:                         } else {
 5295:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 5296:                         }
 5297:                         my ($spec,$area,$trest);
 5298:                         $area = '/'.$tdom.'/'.$tnum;
 5299:                         $trest = $tnum;
 5300:                         if ($tsec ne '') {
 5301:                             $area .= '/'.$tsec;
 5302:                             $trest .= '/'.$tsec;
 5303:                         }
 5304:                         $spec = $trole.'.'.$area;
 5305:                         if ($trole =~ /^cr/) {
 5306:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 5307:                                                               $tdom,$spec,$trest,$area);
 5308:                         } else {
 5309:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 5310:                                                                 $tdom,$spec,$trest,$area);
 5311:                         }
 5312:                     }
 5313:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 5314:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 5315:                         if ($1) {
 5316:                             $no_userblock = 1;
 5317:                             last;
 5318:                         }
 5319:                     }
 5320:                 }
 5321:             } else {
 5322:                 # Resource belongs to current user
 5323:                 # Check for 'evb' priv via lonnet::allowed().
 5324:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5325:                     $no_ownblock = 1;
 5326:                     last;
 5327:                 }
 5328:             }
 5329:         }
 5330:         # if they have the evb priv and are currently not playing student
 5331:         next if (($no_ownblock) &&
 5332:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 5333:         next if ($no_userblock);
 5334: 
 5335:         # Retrieve blocking times and identity of blocker for course
 5336:         # of specified user, unless user has 'evb' privilege.
 5337: 
 5338:         my ($start,$end,$trigger) = 
 5339:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
 5340:         if (($start != 0) && 
 5341:             (($startblock == 0) || ($startblock > $start))) {
 5342:             $startblock = $start;
 5343:             if ($trigger ne '') {
 5344:                 $triggerblock = $trigger;
 5345:             }
 5346:         }
 5347:         if (($end != 0)  &&
 5348:             (($endblock == 0) || ($endblock < $end))) {
 5349:             $endblock = $end;
 5350:             if ($trigger ne '') {
 5351:                 $triggerblock = $trigger;
 5352:             }
 5353:         }
 5354:     }
 5355:     return ($startblock,$endblock,$triggerblock);
 5356: }
 5357: 
 5358: sub get_blocks {
 5359:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
 5360:     my $startblock = 0;
 5361:     my $endblock = 0;
 5362:     my $triggerblock = '';
 5363:     my $course = $cdom.'_'.$cnum;
 5364:     $setters->{$course} = {};
 5365:     $setters->{$course}{'staff'} = [];
 5366:     $setters->{$course}{'times'} = [];
 5367:     $setters->{$course}{'triggers'} = [];
 5368:     my (@blockers,%triggered);
 5369:     my $now = time;
 5370:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 5371:     if ($activity eq 'docs') {
 5372:         my ($blocked,$nosymbcache,$noenccheck);
 5373:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
 5374:             $blocked = 1;
 5375:             $nosymbcache = 1;
 5376:             $noenccheck = 1;
 5377:         }
 5378:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
 5379:         foreach my $block (@blockers) {
 5380:             if ($block =~ /^firstaccess____(.+)$/) {
 5381:                 my $item = $1;
 5382:                 my $type = 'map';
 5383:                 my $timersymb = $item;
 5384:                 if ($item eq 'course') {
 5385:                     $type = 'course';
 5386:                 } elsif ($item =~ /___\d+___/) {
 5387:                     $type = 'resource';
 5388:                 } else {
 5389:                     $timersymb = &Apache::lonnet::symbread($item);
 5390:                 }
 5391:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5392:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 5393:                 $triggered{$block} = {
 5394:                                        start => $start,
 5395:                                        end   => $end,
 5396:                                        type  => $type,
 5397:                                      };
 5398:             }
 5399:         }
 5400:     } else {
 5401:         foreach my $block (keys(%commblocks)) {
 5402:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 5403:                 my ($start,$end) = ($1,$2);
 5404:                 if ($start <= time && $end >= time) {
 5405:                     if (ref($commblocks{$block}) eq 'HASH') {
 5406:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5407:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5408:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 5409:                                     push(@blockers,$block);
 5410:                                 }
 5411:                             }
 5412:                         }
 5413:                     }
 5414:                 }
 5415:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 5416:                 my $item = $1;
 5417:                 my $timersymb = $item; 
 5418:                 my $type = 'map';
 5419:                 if ($item eq 'course') {
 5420:                     $type = 'course';
 5421:                 } elsif ($item =~ /___\d+___/) {
 5422:                     $type = 'resource';
 5423:                 } else {
 5424:                     $timersymb = &Apache::lonnet::symbread($item);
 5425:                 }
 5426:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5427:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 5428:                 if ($start && $end) {
 5429:                     if (($start <= time) && ($end >= time)) {
 5430:                         if (ref($commblocks{$block}) eq 'HASH') {
 5431:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5432:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5433:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
 5434:                                         push(@blockers,$block);
 5435:                                         $triggered{$block} = {
 5436:                                                                start => $start,
 5437:                                                                end   => $end,
 5438:                                                                type  => $type,
 5439:                                                              };
 5440:                                     }
 5441:                                 }
 5442:                             }
 5443:                         }
 5444:                     }
 5445:                 }
 5446:             }
 5447:         }
 5448:     }
 5449:     foreach my $blocker (@blockers) {
 5450:         my ($staff_name,$staff_dom,$title,$blocks) =
 5451:             &parse_block_record($commblocks{$blocker});
 5452:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 5453:         my ($start,$end,$triggertype);
 5454:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 5455:             ($start,$end) = ($1,$2);
 5456:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 5457:             $start = $triggered{$blocker}{'start'};
 5458:             $end = $triggered{$blocker}{'end'};
 5459:             $triggertype = $triggered{$blocker}{'type'};
 5460:         }
 5461:         if ($start) {
 5462:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 5463:             if ($triggertype) {
 5464:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 5465:             } else {
 5466:                 push(@{$$setters{$course}{'triggers'}},0);
 5467:             }
 5468:             if ( ($startblock == 0) || ($startblock > $start) ) {
 5469:                 $startblock = $start;
 5470:                 if ($triggertype) {
 5471:                     $triggerblock = $blocker;
 5472:                 }
 5473:             }
 5474:             if ( ($endblock == 0) || ($endblock < $end) ) {
 5475:                $endblock = $end;
 5476:                if ($triggertype) {
 5477:                    $triggerblock = $blocker;
 5478:                }
 5479:             }
 5480:         }
 5481:     }
 5482:     return ($startblock,$endblock,$triggerblock);
 5483: }
 5484: 
 5485: sub parse_block_record {
 5486:     my ($record) = @_;
 5487:     my ($setuname,$setudom,$title,$blocks);
 5488:     if (ref($record) eq 'HASH') {
 5489:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 5490:         $title = &unescape($record->{'event'});
 5491:         $blocks = $record->{'blocks'};
 5492:     } else {
 5493:         my @data = split(/:/,$record,3);
 5494:         if (scalar(@data) eq 2) {
 5495:             $title = $data[1];
 5496:             ($setuname,$setudom) = split(/@/,$data[0]);
 5497:         } else {
 5498:             ($setuname,$setudom,$title) = @data;
 5499:         }
 5500:         $blocks = { 'com' => 'on' };
 5501:     }
 5502:     return ($setuname,$setudom,$title,$blocks);
 5503: }
 5504: 
 5505: sub blocking_status {
 5506:     my ($activity,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
 5507:     my %setters;
 5508: 
 5509: # check for active blocking
 5510:     my ($startblock,$endblock,$triggerblock) = 
 5511:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course,$symb,$caller);
 5512:     my $blocked = 0;
 5513:     if ($startblock && $endblock) {
 5514:         $blocked = 1;
 5515:     }
 5516: 
 5517: # caller just wants to know whether a block is active
 5518:     if (!wantarray) { return $blocked; }
 5519: 
 5520: # build a link to a popup window containing the details
 5521:     my $querystring  = "?activity=$activity";
 5522: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
 5523:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
 5524:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
 5525:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
 5526:     } elsif ($activity eq 'docs') {
 5527:         my $showurl = &Apache::lonenc::check_encrypt($url);
 5528:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
 5529:         if ($symb) {
 5530:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
 5531:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
 5532:         }
 5533:     }
 5534: 
 5535:     my $output .= <<'END_MYBLOCK';
 5536: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 5537:     var options = "width=" + w + ",height=" + h + ",";
 5538:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 5539:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 5540:     var newWin = window.open(url, wdwName, options);
 5541:     newWin.focus();
 5542: }
 5543: END_MYBLOCK
 5544: 
 5545:     $output = Apache::lonhtmlcommon::scripttag($output);
 5546:   
 5547:     my $popupUrl = "/adm/blockingstatus/$querystring";
 5548:     my $text = &mt('Communication Blocked');
 5549:     my $class = 'LC_comblock';
 5550:     if ($activity eq 'docs') {
 5551:         $text = &mt('Content Access Blocked');
 5552:         $class = '';
 5553:     } elsif ($activity eq 'printout') {
 5554:         $text = &mt('Printing Blocked');
 5555:     } elsif ($activity eq 'passwd') {
 5556:         $text = &mt('Password Changing Blocked');
 5557:     } elsif ($activity eq 'grades') {
 5558:         $text = &mt('Gradebook Blocked');
 5559:     } elsif ($activity eq 'search') {
 5560:         $text = &mt('Search Blocked');
 5561:     } elsif ($activity eq 'alert') {
 5562:         $text = &mt('Checking Critical Messages Blocked');
 5563:     } elsif ($activity eq 'reinit') {
 5564:         $text = &mt('Checking Course Update Blocked');
 5565:     } elsif ($activity eq 'about') {
 5566:         $text = &mt('Access to User Information Pages Blocked');
 5567:     }
 5568:     $output .= <<"END_BLOCK";
 5569: <div class='$class'>
 5570:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 5571:   title='$text'>
 5572:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 5573:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 5574:   title='$text'>$text</a>
 5575: </div>
 5576: 
 5577: END_BLOCK
 5578: 
 5579:     return ($blocked, $output);
 5580: }
 5581: 
 5582: ###############################################
 5583: 
 5584: sub check_ip_acc {
 5585:     my ($acc,$clientip)=@_;
 5586:     &Apache::lonxml::debug("acc is $acc");
 5587:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 5588:         return 1;
 5589:     }
 5590:     my ($ip,$allowed);
 5591:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
 5592:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
 5593:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
 5594:     } else {
 5595:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
 5596:         $ip = $remote_ip || $env{'request.host'} || $clientip;
 5597:     }
 5598: 
 5599:     my $name;
 5600:     my %access = (
 5601:                      allowfrom => 1,
 5602:                      denyfrom  => 0,
 5603:                  );
 5604:     my @allows;
 5605:     my @denies;
 5606:     foreach my $item (split(',',$acc)) {
 5607:         $item =~ s/^\s*//;
 5608:         $item =~ s/\s*$//;
 5609:         my $pattern;
 5610:         if ($item =~ /^\!(.+)$/) {
 5611:             push(@denies,$1);
 5612:         } else {
 5613:             push(@allows,$item);
 5614:         }
 5615:    }
 5616:    my $numdenies = scalar(@denies);
 5617:    my $numallows = scalar(@allows);
 5618:    my $count = 0;
 5619:    foreach my $pattern (@denies,@allows) {
 5620:         $count ++; 
 5621:         my $acctype = 'allowfrom';
 5622:         if ($count <= $numdenies) {
 5623:             $acctype = 'denyfrom';
 5624:         }
 5625:         if ($pattern =~ /\*$/) {
 5626:             #35.8.*
 5627:             $pattern=~s/\*//;
 5628:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 5629:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 5630:             #35.8.3.[34-56]
 5631:             my $low=$2;
 5632:             my $high=$3;
 5633:             $pattern=$1;
 5634:             if ($ip =~ /^\Q$pattern\E/) {
 5635:                 my $last=(split(/\./,$ip))[3];
 5636:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
 5637:             }
 5638:         } elsif ($pattern =~ /^\*/) {
 5639:             #*.msu.edu
 5640:             $pattern=~s/\*//;
 5641:             if (!defined($name)) {
 5642:                 use Socket;
 5643:                 my $netaddr=inet_aton($ip);
 5644:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5645:             }
 5646:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5647:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 5648:             #127.0.0.1
 5649:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 5650:         } else {
 5651:             #some.name.com
 5652:             if (!defined($name)) {
 5653:                 use Socket;
 5654:                 my $netaddr=inet_aton($ip);
 5655:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5656:             }
 5657:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5658:         }
 5659:         if ($allowed =~ /^(0|1)$/) { last; }
 5660:     }
 5661:     if ($allowed eq '') {
 5662:         if ($numdenies && !$numallows) {
 5663:             $allowed = 1;
 5664:         } else {
 5665:             $allowed = 0;
 5666:         }
 5667:     }
 5668:     return $allowed;
 5669: }
 5670: 
 5671: ###############################################
 5672: 
 5673: =pod
 5674: 
 5675: =head1 Domain Template Functions
 5676: 
 5677: =over 4
 5678: 
 5679: =item * &determinedomain()
 5680: 
 5681: Inputs: $domain (usually will be undef)
 5682: 
 5683: Returns: Determines which domain should be used for designs
 5684: 
 5685: =cut
 5686: 
 5687: ###############################################
 5688: sub determinedomain {
 5689:     my $domain=shift;
 5690:     if (! $domain) {
 5691:         # Determine domain if we have not been given one
 5692:         $domain = &Apache::lonnet::default_login_domain();
 5693:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 5694:         if ($env{'request.role.domain'}) { 
 5695:             $domain=$env{'request.role.domain'}; 
 5696:         }
 5697:     }
 5698:     return $domain;
 5699: }
 5700: ###############################################
 5701: 
 5702: sub devalidate_domconfig_cache {
 5703:     my ($udom)=@_;
 5704:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 5705: }
 5706: 
 5707: # ---------------------- Get domain configuration for a domain
 5708: sub get_domainconf {
 5709:     my ($udom) = @_;
 5710:     my $cachetime=1800;
 5711:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 5712:     if (defined($cached)) { return %{$result}; }
 5713: 
 5714:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 5715: 					     ['login','rolecolors','autoenroll'],$udom);
 5716:     my (%designhash,%legacy);
 5717:     if (keys(%domconfig) > 0) {
 5718:         if (ref($domconfig{'login'}) eq 'HASH') {
 5719:             if (keys(%{$domconfig{'login'}})) {
 5720:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 5721:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5722:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
 5723:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5724:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
 5725:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
 5726:                                         if ($key eq 'loginvia') {
 5727:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 5728:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 5729:                                                 $designhash{$udom.'.login.loginvia'} = $server;
 5730:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 5731: 
 5732:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 5733:                                                 } else {
 5734:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 5735:                                                 }
 5736:                                             }
 5737:                                         } elsif ($key eq 'headtag') {
 5738:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
 5739:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
 5740:                                             }
 5741:                                         }
 5742:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
 5743:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
 5744:                                         }
 5745:                                     }
 5746:                                 }
 5747:                             }
 5748:                         } elsif ($key eq 'saml') {
 5749:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5750:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
 5751:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
 5752:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
 5753:                                         foreach my $item ('text','img','alt','url','title','notsso') {
 5754:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
 5755:                                         }
 5756:                                     }
 5757:                                 }
 5758:                             }
 5759:                         } else {
 5760:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 5761:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 5762:                                     $domconfig{'login'}{$key}{$img};
 5763:                             }
 5764:                         }
 5765:                     } else {
 5766:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 5767:                     }
 5768:                 }
 5769:             } else {
 5770:                 $legacy{'login'} = 1;
 5771:             }
 5772:         } else {
 5773:             $legacy{'login'} = 1;
 5774:         }
 5775:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 5776:             if (keys(%{$domconfig{'rolecolors'}})) {
 5777:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 5778:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 5779:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 5780:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 5781:                         }
 5782:                     }
 5783:                 }
 5784:             } else {
 5785:                 $legacy{'rolecolors'} = 1;
 5786:             }
 5787:         } else {
 5788:             $legacy{'rolecolors'} = 1;
 5789:         }
 5790:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5791:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 5792:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 5793:             }
 5794:         }
 5795:         if (keys(%legacy) > 0) {
 5796:             my %legacyhash = &get_legacy_domconf($udom);
 5797:             foreach my $item (keys(%legacyhash)) {
 5798:                 if ($item =~ /^\Q$udom\E\.login/) {
 5799:                     if ($legacy{'login'}) { 
 5800:                         $designhash{$item} = $legacyhash{$item};
 5801:                     }
 5802:                 } else {
 5803:                     if ($legacy{'rolecolors'}) {
 5804:                         $designhash{$item} = $legacyhash{$item};
 5805:                     }
 5806:                 }
 5807:             }
 5808:         }
 5809:     } else {
 5810:         %designhash = &get_legacy_domconf($udom); 
 5811:     }
 5812:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 5813: 				  $cachetime);
 5814:     return %designhash;
 5815: }
 5816: 
 5817: sub get_legacy_domconf {
 5818:     my ($udom) = @_;
 5819:     my %legacyhash;
 5820:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 5821:     my $designfile =  $designdir.'/'.$udom.'.tab';
 5822:     if (-e $designfile) {
 5823:         if ( open (my $fh,'<',$designfile) ) {
 5824:             while (my $line = <$fh>) {
 5825:                 next if ($line =~ /^\#/);
 5826:                 chomp($line);
 5827:                 my ($key,$val)=(split(/\=/,$line));
 5828:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 5829:             }
 5830:             close($fh);
 5831:         }
 5832:     }
 5833:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 5834:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 5835:     }
 5836:     return %legacyhash;
 5837: }
 5838: 
 5839: =pod
 5840: 
 5841: =item * &domainlogo()
 5842: 
 5843: Inputs: $domain (usually will be undef)
 5844: 
 5845: Returns: A link to a domain logo, if the domain logo exists.
 5846: If the domain logo does not exist, a description of the domain.
 5847: 
 5848: =cut
 5849: 
 5850: ###############################################
 5851: sub domainlogo {
 5852:     my $domain = &determinedomain(shift);
 5853:     my %designhash = &get_domainconf($domain);    
 5854:     # See if there is a logo
 5855:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 5856:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 5857:         if ($imgsrc =~ m{^/(adm|res)/}) {
 5858: 	    if ($imgsrc =~ m{^/res/}) {
 5859: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 5860: 		&Apache::lonnet::repcopy($local_name);
 5861: 	    }
 5862: 	   $imgsrc = &lonhttpdurl($imgsrc);
 5863:         } 
 5864:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 5865:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 5866:         return &Apache::lonnet::domain($domain,'description');
 5867:     } else {
 5868:         return '';
 5869:     }
 5870: }
 5871: ##############################################
 5872: 
 5873: =pod
 5874: 
 5875: =item * &designparm()
 5876: 
 5877: Inputs: $which parameter; $domain (usually will be undef)
 5878: 
 5879: Returns: value of designparamter $which
 5880: 
 5881: =cut
 5882: 
 5883: 
 5884: ##############################################
 5885: sub designparm {
 5886:     my ($which,$domain)=@_;
 5887:     if (exists($env{'environment.color.'.$which})) {
 5888:         return $env{'environment.color.'.$which};
 5889:     }
 5890:     $domain=&determinedomain($domain);
 5891:     my %domdesign;
 5892:     unless ($domain eq 'public') {
 5893:         %domdesign = &get_domainconf($domain);
 5894:     }
 5895:     my $output;
 5896:     if ($domdesign{$domain.'.'.$which} ne '') {
 5897:         $output = $domdesign{$domain.'.'.$which};
 5898:     } else {
 5899:         $output = $defaultdesign{$which};
 5900:     }
 5901:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 5902:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 5903:         if ($output =~ m{^/(adm|res)/}) {
 5904:             if ($output =~ m{^/res/}) {
 5905:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 5906:                 &Apache::lonnet::repcopy($local_name);
 5907:             }
 5908:             $output = &lonhttpdurl($output);
 5909:         }
 5910:     }
 5911:     return $output;
 5912: }
 5913: 
 5914: ##############################################
 5915: =pod
 5916: 
 5917: =item * &authorspace()
 5918: 
 5919: Inputs: $url (usually will be undef).
 5920: 
 5921: Returns: Path to Authoring Space containing the resource or 
 5922:          directory being viewed (or for which action is being taken). 
 5923:          If $url is provided, and begins /priv/<domain>/<uname>
 5924:          the path will be that portion of the $context argument.
 5925:          Otherwise the path will be for the author space of the current
 5926:          user when the current role is author, or for that of the 
 5927:          co-author/assistant co-author space when the current role 
 5928:          is co-author or assistant co-author.
 5929: 
 5930: =cut
 5931: 
 5932: sub authorspace {
 5933:     my ($url) = @_;
 5934:     if ($url ne '') {
 5935:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 5936:            return $1;
 5937:         }
 5938:     }
 5939:     my $caname = '';
 5940:     my $cadom = '';
 5941:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 5942:         ($cadom,$caname) =
 5943:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 5944:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 5945:         $caname = $env{'user.name'};
 5946:         $cadom = $env{'user.domain'};
 5947:     }
 5948:     if (($caname ne '') && ($cadom ne '')) {
 5949:         return "/priv/$cadom/$caname/";
 5950:     }
 5951:     return;
 5952: }
 5953: 
 5954: ##############################################
 5955: =pod
 5956: 
 5957: =item * &head_subbox()
 5958: 
 5959: Inputs: $content (contains HTML code with page functions, etc.)
 5960: 
 5961: Returns: HTML div with $content
 5962:          To be included in page header
 5963: 
 5964: =cut
 5965: 
 5966: sub head_subbox {
 5967:     my ($content)=@_;
 5968:     my $output =
 5969:         '<div class="LC_head_subbox">'
 5970:        .$content
 5971:        .'</div>'
 5972: }
 5973: 
 5974: ##############################################
 5975: =pod
 5976: 
 5977: =item * &CSTR_pageheader()
 5978: 
 5979: Input: (optional) filename from which breadcrumb trail is built.
 5980:        In most cases no input as needed, as $env{'request.filename'}
 5981:        is appropriate for use in building the breadcrumb trail.
 5982: 
 5983: Returns: HTML div with CSTR path and recent box
 5984:          To be included on Authoring Space pages
 5985: 
 5986: =cut
 5987: 
 5988: sub CSTR_pageheader {
 5989:     my ($trailfile) = @_;
 5990:     if ($trailfile eq '') {
 5991:         $trailfile = $env{'request.filename'};
 5992:     }
 5993: 
 5994: # this is for resources; directories have customtitle, and crumbs
 5995: # and select recent are created in lonpubdir.pm
 5996: 
 5997:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 5998:     my ($udom,$uname,$thisdisfn)=
 5999:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 6000:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 6001:     $formaction =~ s{/+}{/}g;
 6002: 
 6003:     my $parentpath = '';
 6004:     my $lastitem = '';
 6005:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 6006:         $parentpath = $1;
 6007:         $lastitem = $2;
 6008:     } else {
 6009:         $lastitem = $thisdisfn;
 6010:     }
 6011: 
 6012:     my ($crsauthor,$title);
 6013:     if (($env{'request.course.id'}) &&
 6014:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
 6015:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
 6016:         $crsauthor = 1;
 6017:         $title = &mt('Course Authoring Space');
 6018:     } else {
 6019:         $title = &mt('Authoring Space');
 6020:     }
 6021: 
 6022:     my ($target,$crumbtarget) = (' target="_top"','_top'); #FIXME lonpubdir: target="_parent"
 6023:     if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
 6024:         $target = '';
 6025:         $crumbtarget = '';
 6026:     }
 6027: 
 6028:     my $output =
 6029:          '<div>'
 6030:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 6031:         .'<b>'.$title.'</b> '
 6032:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
 6033:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
 6034: 
 6035:     if ($lastitem) {
 6036:         $output .=
 6037:              '<span class="LC_filename">'
 6038:             .$lastitem
 6039:             .'</span>';
 6040:     }
 6041: 
 6042:     if ($crsauthor) {
 6043:         $output .= '</form>'.&Apache::lonmenu::constspaceform();
 6044:     } else {
 6045:         $output .=
 6046:              '<br />'
 6047:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
 6048:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 6049:             .'</form>'
 6050:             .&Apache::lonmenu::constspaceform();
 6051:     }
 6052:     $output .= '</div>';
 6053: 
 6054:     return $output;
 6055: }
 6056: 
 6057: ###############################################
 6058: ###############################################
 6059: 
 6060: =pod
 6061: 
 6062: =back
 6063: 
 6064: =head1 HTML Helpers
 6065: 
 6066: =over 4
 6067: 
 6068: =item * &bodytag()
 6069: 
 6070: Returns a uniform header for LON-CAPA web pages.
 6071: 
 6072: Inputs: 
 6073: 
 6074: =over 4
 6075: 
 6076: =item * $title, A title to be displayed on the page.
 6077: 
 6078: =item * $function, the current role (can be undef).
 6079: 
 6080: =item * $addentries, extra parameters for the <body> tag.
 6081: 
 6082: =item * $bodyonly, if defined, only return the <body> tag.
 6083: 
 6084: =item * $domain, if defined, force a given domain.
 6085: 
 6086: =item * $forcereg, if page should register as content page (relevant for 
 6087:             text interface only)
 6088: 
 6089: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 6090:                      navigational links
 6091: 
 6092: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 6093: 
 6094: =item * $args, optional argument valid values are
 6095:             no_auto_mt_title -> prevents &mt()ing the title arg
 6096:             use_absolute     -> for external resource or syllabus, this will
 6097:                                 contain https://<hostname> if server uses
 6098:                                 https (as per hosts.tab), but request is for http
 6099:             hostname         -> hostname, from $r->hostname().
 6100: 
 6101: =item * $advtoolsref, optional argument, ref to an array containing
 6102:             inlineremote items to be added in "Functions" menu below
 6103:             breadcrumbs.
 6104: 
 6105: =item * $ltiscope, optional argument, will be one of: resource, map or
 6106:             course, if LON-CAPA is in LTI Provider context. Value is
 6107:             the scope of use, i.e., launch was for access to a single, a map
 6108:             or the entire course.
 6109: 
 6110: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
 6111:             context, this will contain the URL for the landing item in
 6112:             the course, after launch from an LTI Consumer
 6113: 
 6114: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
 6115:             context, this will contain a reference to hash of items
 6116:             to be included in the page header and/or inline menu.
 6117: 
 6118: =back
 6119: 
 6120: Returns: A uniform header for LON-CAPA web pages.  
 6121: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 6122: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 6123: other decorations will be returned.
 6124: 
 6125: =cut
 6126: 
 6127: sub bodytag {
 6128:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 6129:         $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri,
 6130:         $ltimenu,$menucoll,$menuref)=@_;
 6131: 
 6132:     my $public;
 6133:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 6134:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 6135:         $public = 1;
 6136:     }
 6137:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 6138:     my $httphost = $args->{'use_absolute'};
 6139:     my $hostname = $args->{'hostname'};
 6140: 
 6141:     $function = &get_users_function() if (!$function);
 6142:     my $img =    &designparm($function.'.img',$domain);
 6143:     my $font =   &designparm($function.'.font',$domain);
 6144:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 6145: 
 6146:     my %design = ( 'style'   => 'margin-top: 0',
 6147: 		   'bgcolor' => $pgbg,
 6148: 		   'text'    => $font,
 6149:                    'alink'   => &designparm($function.'.alink',$domain),
 6150: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 6151: 		   'link'    => &designparm($function.'.link',$domain),);
 6152:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 6153: 
 6154:  # role and realm
 6155:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
 6156:     if ($realm) {
 6157:         $realm = '/'.$realm;
 6158:     }
 6159:     if ($role eq 'ca') {
 6160:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 6161:         $realm = &plainname($rname,$rdom);
 6162:     } 
 6163: # realm
 6164:     my ($cid,$sec);
 6165:     if ($env{'request.course.id'}) {
 6166:         $cid = $env{'request.course.id'};
 6167:         if ($env{'request.course.sec'}) {
 6168:             $sec = $env{'request.course.sec'};
 6169:         }
 6170:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
 6171:         if (&Apache::lonnet::is_course($1,$2)) {
 6172:             $cid = $1.'_'.$2;
 6173:             $sec = $3;
 6174:         }
 6175:     }
 6176:     if ($cid) {
 6177:         if ($env{'request.role'} !~ /^cr/) {
 6178:             $role = &Apache::lonnet::plaintext($role,&course_type());
 6179:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
 6180:             if ($env{'request.role.desc'}) {
 6181:                 $role = $env{'request.role.desc'};
 6182:             } else {
 6183:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
 6184:             }
 6185:         } else {
 6186:             $role = (split(/\//,$role,4))[-1]; 
 6187:         }
 6188:         if ($sec) {
 6189:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
 6190:         }   
 6191: 	$realm = $env{'course.'.$cid.'.description'};
 6192:     } else {
 6193:         $role = &Apache::lonnet::plaintext($role);
 6194:     }
 6195: 
 6196:     if (!$realm) { $realm='&nbsp;'; }
 6197: 
 6198:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 6199: 
 6200: # construct main body tag
 6201:     my $bodytag = "<body $extra_body_attr>".
 6202: 	&Apache::lontexconvert::init_math_support();
 6203: 
 6204:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 6205: 
 6206:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 6207:         return $bodytag;
 6208:     }
 6209: 
 6210:     if ($public) {
 6211: 	undef($role);
 6212:     }
 6213: 
 6214:     my $showcrstitle = 1;
 6215:     if (($cid) && ($env{'request.lti.login'})) {
 6216:         if (ref($ltimenu) eq 'HASH') {
 6217:             unless ($ltimenu->{'role'}) {
 6218:                 undef($role);
 6219:             }
 6220:             unless ($ltimenu->{'coursetitle'}) {
 6221:                 $realm='&nbsp;';
 6222:                 $showcrstitle = 0;
 6223:             }
 6224:         }
 6225:     } elsif (($cid) && ($menucoll)) {
 6226:         if (ref($menuref) eq 'HASH') {
 6227:             unless ($menuref->{'role'}) {
 6228:                 undef($role);
 6229:             }
 6230:             unless ($menuref->{'crs'}) {
 6231:                 $realm='&nbsp;';
 6232:                 $showcrstitle = 0;
 6233:             }
 6234:         }
 6235:     }
 6236: 
 6237:     my $titleinfo = '<h1>'.$title.'</h1>';
 6238:     #
 6239:     # Extra info if you are the DC
 6240:     my $dc_info = '';
 6241:     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
 6242:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
 6243:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 6244:         $dc_info =~ s/\s+$//;
 6245:     }
 6246: 
 6247:     my $crstype;
 6248:     if ($cid) {
 6249:         $crstype = $env{'course.'.$cid.'.type'};
 6250:     } elsif ($args->{'crstype'}) {
 6251:         $crstype = $args->{'crstype'};
 6252:     }
 6253:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
 6254:         undef($role);
 6255:     } else {
 6256:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
 6257:     }
 6258: 
 6259:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 6260: 
 6261:         #    if ($env{'request.state'} eq 'construct') {
 6262:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 6263:         #    }
 6264: 
 6265:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 6266:             Apache::lonmenu::utilityfunctions($httphost), 'start');
 6267: 
 6268:         unless ($args->{'no_primary_menu'}) {
 6269:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
 6270:                                                               $args->{'links_disabled'});
 6271: 
 6272:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 6273:                 if ($dc_info) {
 6274:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 6275:                 }
 6276:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 6277:                                <em>$realm</em> $dc_info</div>|;
 6278:                 return $bodytag;
 6279:             }
 6280: 
 6281:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 6282:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 6283:             }
 6284: 
 6285:             $bodytag .= $right;
 6286: 
 6287:             if ($dc_info) {
 6288:                 $dc_info = &dc_courseid_toggle($dc_info);
 6289:             }
 6290:             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 6291:         }
 6292: 
 6293:         #if directed to not display the secondary menu, don't.  
 6294:         if ($args->{'no_secondary_menu'}) {
 6295:             return $bodytag;
 6296:         }
 6297:         #don't show menus for public users
 6298:         if (!$public){
 6299:             unless ($args->{'no_inline_menu'}) {
 6300:                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
 6301:                                                             $args->{'no_primary_menu'},
 6302:                                                             $menucoll,$menuref,
 6303:                                                             $args->{'links_disabled'});
 6304:             }
 6305:             $bodytag .= Apache::lonmenu::serverform();
 6306:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 6307:             if ($env{'request.state'} eq 'construct') {
 6308:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 6309:                                 $args->{'bread_crumbs'},'','',$hostname,$ltiscope,$ltiuri);
 6310:             } elsif ($forcereg) {
 6311:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 6312:                                                             $args->{'group'},
 6313:                                                             $args->{'hide_buttons'},
 6314:                                                             $hostname,$ltiscope,$ltiuri);
 6315:             } else {
 6316:                 $bodytag .= 
 6317:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 6318:                                                         $forcereg,$args->{'group'},
 6319:                                                         $args->{'bread_crumbs'},
 6320:                                                         $advtoolsref,'',$hostname);
 6321:             }
 6322:         }else{
 6323:             # this is to seperate menu from content when there's no secondary
 6324:             # menu. Especially needed for public accessible ressources.
 6325:             $bodytag .= '<hr style="clear:both" />';
 6326:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 6327:         }
 6328: 
 6329:         return $bodytag;
 6330: }
 6331: 
 6332: sub dc_courseid_toggle {
 6333:     my ($dc_info) = @_;
 6334:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 6335:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 6336:            &mt('(More ...)').'</a></span>'.
 6337:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 6338: }
 6339: 
 6340: sub make_attr_string {
 6341:     my ($register,$attr_ref) = @_;
 6342: 
 6343:     if ($attr_ref && !ref($attr_ref)) {
 6344: 	die("addentries Must be a hash ref ".
 6345: 	    join(':',caller(1))." ".
 6346: 	    join(':',caller(0))." ");
 6347:     }
 6348: 
 6349:     if ($register) {
 6350: 	my ($on_load,$on_unload);
 6351: 	foreach my $key (keys(%{$attr_ref})) {
 6352: 	    if      (lc($key) eq 'onload') {
 6353: 		$on_load.=$attr_ref->{$key}.';';
 6354: 		delete($attr_ref->{$key});
 6355: 
 6356: 	    } elsif (lc($key) eq 'onunload') {
 6357: 		$on_unload.=$attr_ref->{$key}.';';
 6358: 		delete($attr_ref->{$key});
 6359: 	    }
 6360: 	}
 6361: 	$attr_ref->{'onload'}  = $on_load;
 6362: 	$attr_ref->{'onunload'}= $on_unload;
 6363:     }
 6364: 
 6365:     my $attr_string;
 6366:     foreach my $attr (sort(keys(%$attr_ref))) {
 6367: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 6368:     }
 6369:     return $attr_string;
 6370: }
 6371: 
 6372: 
 6373: ###############################################
 6374: ###############################################
 6375: 
 6376: =pod
 6377: 
 6378: =item * &endbodytag()
 6379: 
 6380: Returns a uniform footer for LON-CAPA web pages.
 6381: 
 6382: Inputs: 1 - optional reference to an args hash
 6383: If in the hash, key for noredirectlink has a value which evaluates to true,
 6384: a 'Continue' link is not displayed if the page contains an
 6385: internal redirect in the <head></head> section,
 6386: i.e., $env{'internal.head.redirect'} exists   
 6387: 
 6388: =cut
 6389: 
 6390: sub endbodytag {
 6391:     my ($args) = @_;
 6392:     my $endbodytag;
 6393:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 6394:         $endbodytag='</body>';
 6395:     }
 6396:     if ( exists( $env{'internal.head.redirect'} ) ) {
 6397:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 6398: 	    $endbodytag=
 6399: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 6400: 	        &mt('Continue').'</a>'.
 6401: 	        $endbodytag;
 6402:         }
 6403:     }
 6404:     return $endbodytag;
 6405: }
 6406: 
 6407: =pod
 6408: 
 6409: =item * &standard_css()
 6410: 
 6411: Returns a style sheet
 6412: 
 6413: Inputs: (all optional)
 6414:             domain         -> force to color decorate a page for a specific
 6415:                                domain
 6416:             function       -> force usage of a specific rolish color scheme
 6417:             bgcolor        -> override the default page bgcolor
 6418: 
 6419: =cut
 6420: 
 6421: sub standard_css {
 6422:     my ($function,$domain,$bgcolor) = @_;
 6423:     $function  = &get_users_function() if (!$function);
 6424:     my $img    = &designparm($function.'.img',   $domain);
 6425:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 6426:     my $font   = &designparm($function.'.font',  $domain);
 6427:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 6428: #second colour for later usage
 6429:     my $sidebg = &designparm($function.'.sidebg',$domain);
 6430:     my $pgbg_or_bgcolor =
 6431: 	         $bgcolor ||
 6432: 	         &designparm($function.'.pgbg',  $domain);
 6433:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 6434:     my $alink  = &designparm($function.'.alink', $domain);
 6435:     my $vlink  = &designparm($function.'.vlink', $domain);
 6436:     my $link   = &designparm($function.'.link',  $domain);
 6437: 
 6438:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 6439:     my $mono                 = 'monospace';
 6440:     my $data_table_head      = $sidebg;
 6441:     my $data_table_light     = '#FAFAFA';
 6442:     my $data_table_dark      = '#E0E0E0';
 6443:     my $data_table_darker    = '#CCCCCC';
 6444:     my $data_table_highlight = '#FFFF00';
 6445:     my $mail_new             = '#FFBB77';
 6446:     my $mail_new_hover       = '#DD9955';
 6447:     my $mail_read            = '#BBBB77';
 6448:     my $mail_read_hover      = '#999944';
 6449:     my $mail_replied         = '#AAAA88';
 6450:     my $mail_replied_hover   = '#888855';
 6451:     my $mail_other           = '#99BBBB';
 6452:     my $mail_other_hover     = '#669999';
 6453:     my $table_header         = '#DDDDDD';
 6454:     my $feedback_link_bg     = '#BBBBBB';
 6455:     my $lg_border_color      = '#C8C8C8';
 6456:     my $button_hover         = '#BF2317';
 6457: 
 6458:     my $border = ($env{'browser.type'} eq 'explorer' ||
 6459:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 6460:                                              : '0 3px 0 4px';
 6461: 
 6462: 
 6463:     return <<END;
 6464: 
 6465: /* needed for iframe to allow 100% height in FF */
 6466: body, html { 
 6467:     margin: 0;
 6468:     padding: 0 0.5%;
 6469:     height: 99%; /* to avoid scrollbars */
 6470: }
 6471: 
 6472: body {
 6473:   font-family: $sans;
 6474:   line-height:130%;
 6475:   font-size:0.83em;
 6476:   color:$font;
 6477: }
 6478: 
 6479: a:focus,
 6480: a:focus img {
 6481:   color: red;
 6482: }
 6483: 
 6484: form, .inline {
 6485:   display: inline;
 6486: }
 6487: 
 6488: .LC_right {
 6489:   text-align:right;
 6490: }
 6491: 
 6492: .LC_middle {
 6493:   vertical-align:middle;
 6494: }
 6495: 
 6496: .LC_floatleft {
 6497:   float: left;
 6498: }
 6499: 
 6500: .LC_floatright {
 6501:   float: right;
 6502: }
 6503: 
 6504: .LC_400Box {
 6505:   width:400px;
 6506: }
 6507: 
 6508: .LC_iframecontainer {
 6509:     width: 98%;
 6510:     margin: 0;
 6511:     position: fixed;
 6512:     top: 8.5em;
 6513:     bottom: 0;
 6514: }
 6515: 
 6516: .LC_iframecontainer iframe{
 6517:     border: none;
 6518:     width: 100%;
 6519:     height: 100%;
 6520: }
 6521: 
 6522: .LC_filename {
 6523:   font-family: $mono;
 6524:   white-space:pre;
 6525:   font-size: 120%;
 6526: }
 6527: 
 6528: .LC_fileicon {
 6529:   border: none;
 6530:   height: 1.3em;
 6531:   vertical-align: text-bottom;
 6532:   margin-right: 0.3em;
 6533:   text-decoration:none;
 6534: }
 6535: 
 6536: .LC_setting {
 6537:   text-decoration:underline;
 6538: }
 6539: 
 6540: .LC_error {
 6541:   color: red;
 6542: }
 6543: 
 6544: .LC_warning {
 6545:   color: darkorange;
 6546: }
 6547: 
 6548: .LC_diff_removed {
 6549:   color: red;
 6550: }
 6551: 
 6552: .LC_info,
 6553: .LC_success,
 6554: .LC_diff_added {
 6555:   color: green;
 6556: }
 6557: 
 6558: div.LC_confirm_box {
 6559:   background-color: #FAFAFA;
 6560:   border: 1px solid $lg_border_color;
 6561:   margin-right: 0;
 6562:   padding: 5px;
 6563: }
 6564: 
 6565: div.LC_confirm_box .LC_error img,
 6566: div.LC_confirm_box .LC_success img {
 6567:   vertical-align: middle;
 6568: }
 6569: 
 6570: .LC_maxwidth {
 6571:   max-width: 100%;
 6572:   height: auto;
 6573: }
 6574: 
 6575: .LC_textsize_mobile {
 6576:   \@media only screen and (max-device-width: 480px) {
 6577:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
 6578:   }
 6579: }
 6580: 
 6581: .LC_icon {
 6582:   border: none;
 6583:   vertical-align: middle;
 6584: }
 6585: 
 6586: .LC_docs_spacer {
 6587:   width: 25px;
 6588:   height: 1px;
 6589:   border: none;
 6590: }
 6591: 
 6592: .LC_internal_info {
 6593:   color: #999999;
 6594: }
 6595: 
 6596: .LC_discussion {
 6597:   background: $data_table_dark;
 6598:   border: 1px solid black;
 6599:   margin: 2px;
 6600: }
 6601: 
 6602: .LC_disc_action_left {
 6603:   background: $sidebg;
 6604:   text-align: left;
 6605:   padding: 4px;
 6606:   margin: 2px;
 6607: }
 6608: 
 6609: .LC_disc_action_right {
 6610:   background: $sidebg;
 6611:   text-align: right;
 6612:   padding: 4px;
 6613:   margin: 2px;
 6614: }
 6615: 
 6616: .LC_disc_new_item {
 6617:   background: white;
 6618:   border: 2px solid red;
 6619:   margin: 4px;
 6620:   padding: 4px;
 6621: }
 6622: 
 6623: .LC_disc_old_item {
 6624:   background: white;
 6625:   margin: 4px;
 6626:   padding: 4px;
 6627: }
 6628: 
 6629: table.LC_pastsubmission {
 6630:   border: 1px solid black;
 6631:   margin: 2px;
 6632: }
 6633: 
 6634: table#LC_menubuttons {
 6635:   width: 100%;
 6636:   background: $pgbg;
 6637:   border: 2px;
 6638:   border-collapse: separate;
 6639:   padding: 0;
 6640: }
 6641: 
 6642: table#LC_title_bar a {
 6643:   color: $fontmenu;
 6644: }
 6645: 
 6646: table#LC_title_bar {
 6647:   clear: both;
 6648:   display: none;
 6649: }
 6650: 
 6651: table#LC_title_bar,
 6652: table.LC_breadcrumbs, /* obsolete? */
 6653: table#LC_title_bar.LC_with_remote {
 6654:   width: 100%;
 6655:   border-color: $pgbg;
 6656:   border-style: solid;
 6657:   border-width: $border;
 6658:   background: $pgbg;
 6659:   color: $fontmenu;
 6660:   border-collapse: collapse;
 6661:   padding: 0;
 6662:   margin: 0;
 6663: }
 6664: 
 6665: ul.LC_breadcrumb_tools_outerlist {
 6666:     margin: 0;
 6667:     padding: 0;
 6668:     position: relative;
 6669:     list-style: none;
 6670: }
 6671: ul.LC_breadcrumb_tools_outerlist li {
 6672:     display: inline;
 6673: }
 6674: 
 6675: .LC_breadcrumb_tools_navigation {
 6676:     padding: 0;
 6677:     margin: 0;
 6678:     float: left;
 6679: }
 6680: .LC_breadcrumb_tools_tools {
 6681:     padding: 0;
 6682:     margin: 0;
 6683:     float: right;
 6684: }
 6685: 
 6686: .LC_placement_prog {
 6687:     padding-right: 20px;
 6688:     font-weight: bold;
 6689:     font-size: 90%;
 6690: }
 6691: 
 6692: table#LC_title_bar td {
 6693:   background: $tabbg;
 6694: }
 6695: 
 6696: table#LC_menubuttons img {
 6697:   border: none;
 6698: }
 6699: 
 6700: .LC_breadcrumbs_component {
 6701:   float: right;
 6702:   margin: 0 1em;
 6703: }
 6704: .LC_breadcrumbs_component img {
 6705:   vertical-align: middle;
 6706: }
 6707: 
 6708: .LC_breadcrumbs_hoverable {
 6709:   background: $sidebg;
 6710: }
 6711: 
 6712: td.LC_table_cell_checkbox {
 6713:   text-align: center;
 6714: }
 6715: 
 6716: .LC_fontsize_small {
 6717:   font-size: 70%;
 6718: }
 6719: 
 6720: #LC_breadcrumbs {
 6721:   clear:both;
 6722:   background: $sidebg;
 6723:   border-bottom: 1px solid $lg_border_color;
 6724:   line-height: 2.5em;
 6725:   overflow: hidden;
 6726:   margin: 0;
 6727:   padding: 0;
 6728:   text-align: left;
 6729: }
 6730: 
 6731: .LC_head_subbox, .LC_actionbox {
 6732:   clear:both;
 6733:   background: #F8F8F8; /* $sidebg; */
 6734:   border: 1px solid $sidebg;
 6735:   margin: 0 0 10px 0;
 6736:   padding: 3px;
 6737:   text-align: left;
 6738: }
 6739: 
 6740: .LC_fontsize_medium {
 6741:   font-size: 85%;
 6742: }
 6743: 
 6744: .LC_fontsize_large {
 6745:   font-size: 120%;
 6746: }
 6747: 
 6748: .LC_menubuttons_inline_text {
 6749:   color: $font;
 6750:   font-size: 90%;
 6751:   padding-left:3px;
 6752: }
 6753: 
 6754: .LC_menubuttons_inline_text img{
 6755:   vertical-align: middle;
 6756: }
 6757: 
 6758: li.LC_menubuttons_inline_text img {
 6759:   cursor:pointer;
 6760:   text-decoration: none;
 6761: }
 6762: 
 6763: .LC_menubuttons_link {
 6764:   text-decoration: none;
 6765: }
 6766: 
 6767: .LC_menubuttons_category {
 6768:   color: $font;
 6769:   background: $pgbg;
 6770:   font-size: larger;
 6771:   font-weight: bold;
 6772: }
 6773: 
 6774: td.LC_menubuttons_text {
 6775:   color: $font;
 6776: }
 6777: 
 6778: .LC_current_location {
 6779:   background: $tabbg;
 6780: }
 6781: 
 6782: td.LC_zero_height {
 6783:   line-height: 0; 
 6784:   cellpadding: 0;
 6785: }
 6786: 
 6787: table.LC_data_table {
 6788:   border: 1px solid #000000;
 6789:   border-collapse: separate;
 6790:   border-spacing: 1px;
 6791:   background: $pgbg;
 6792: }
 6793: 
 6794: .LC_data_table_dense {
 6795:   font-size: small;
 6796: }
 6797: 
 6798: table.LC_nested_outer {
 6799:   border: 1px solid #000000;
 6800:   border-collapse: collapse;
 6801:   border-spacing: 0;
 6802:   width: 100%;
 6803: }
 6804: 
 6805: table.LC_innerpickbox,
 6806: table.LC_nested {
 6807:   border: none;
 6808:   border-collapse: collapse;
 6809:   border-spacing: 0;
 6810:   width: 100%;
 6811: }
 6812: 
 6813: table.LC_data_table tr th,
 6814: table.LC_calendar tr th,
 6815: table.LC_prior_tries tr th,
 6816: table.LC_innerpickbox tr th {
 6817:   font-weight: bold;
 6818:   background-color: $data_table_head;
 6819:   color:$fontmenu;
 6820:   font-size:90%;
 6821: }
 6822: 
 6823: table.LC_innerpickbox tr th,
 6824: table.LC_innerpickbox tr td {
 6825:   vertical-align: top;
 6826: }
 6827: 
 6828: table.LC_data_table tr.LC_info_row > td {
 6829:   background-color: #CCCCCC;
 6830:   font-weight: bold;
 6831:   text-align: left;
 6832: }
 6833: 
 6834: table.LC_data_table tr.LC_odd_row > td {
 6835:   background-color: $data_table_light;
 6836:   padding: 2px;
 6837:   vertical-align: top;
 6838: }
 6839: 
 6840: table.LC_pick_box tr > td.LC_odd_row {
 6841:   background-color: $data_table_light;
 6842:   vertical-align: top;
 6843: }
 6844: 
 6845: table.LC_data_table tr.LC_even_row > td {
 6846:   background-color: $data_table_dark;
 6847:   padding: 2px;
 6848:   vertical-align: top;
 6849: }
 6850: 
 6851: table.LC_pick_box tr > td.LC_even_row {
 6852:   background-color: $data_table_dark;
 6853:   vertical-align: top;
 6854: }
 6855: 
 6856: table.LC_data_table tr.LC_data_table_highlight td {
 6857:   background-color: $data_table_darker;
 6858: }
 6859: 
 6860: table.LC_data_table tr td.LC_leftcol_header {
 6861:   background-color: $data_table_head;
 6862:   font-weight: bold;
 6863: }
 6864: 
 6865: table.LC_data_table tr.LC_empty_row td,
 6866: table.LC_nested tr.LC_empty_row td {
 6867:   font-weight: bold;
 6868:   font-style: italic;
 6869:   text-align: center;
 6870:   padding: 8px;
 6871: }
 6872: 
 6873: table.LC_data_table tr.LC_empty_row td,
 6874: table.LC_data_table tr.LC_footer_row td {
 6875:   background-color: $sidebg;
 6876: }
 6877: 
 6878: table.LC_nested tr.LC_empty_row td {
 6879:   background-color: #FFFFFF;
 6880: }
 6881: 
 6882: table.LC_caption {
 6883: }
 6884: 
 6885: table.LC_nested tr.LC_empty_row td {
 6886:   padding: 4ex
 6887: }
 6888: 
 6889: table.LC_nested_outer tr th {
 6890:   font-weight: bold;
 6891:   color:$fontmenu;
 6892:   background-color: $data_table_head;
 6893:   font-size: small;
 6894:   border-bottom: 1px solid #000000;
 6895: }
 6896: 
 6897: table.LC_nested_outer tr td.LC_subheader {
 6898:   background-color: $data_table_head;
 6899:   font-weight: bold;
 6900:   font-size: small;
 6901:   border-bottom: 1px solid #000000;
 6902:   text-align: right;
 6903: }
 6904: 
 6905: table.LC_nested tr.LC_info_row td {
 6906:   background-color: #CCCCCC;
 6907:   font-weight: bold;
 6908:   font-size: small;
 6909:   text-align: center;
 6910: }
 6911: 
 6912: table.LC_nested tr.LC_info_row td.LC_left_item,
 6913: table.LC_nested_outer tr th.LC_left_item {
 6914:   text-align: left;
 6915: }
 6916: 
 6917: table.LC_nested td {
 6918:   background-color: #FFFFFF;
 6919:   font-size: small;
 6920: }
 6921: 
 6922: table.LC_nested_outer tr th.LC_right_item,
 6923: table.LC_nested tr.LC_info_row td.LC_right_item,
 6924: table.LC_nested tr.LC_odd_row td.LC_right_item,
 6925: table.LC_nested tr td.LC_right_item {
 6926:   text-align: right;
 6927: }
 6928: 
 6929: table.LC_nested tr.LC_odd_row td {
 6930:   background-color: #EEEEEE;
 6931: }
 6932: 
 6933: table.LC_createuser {
 6934: }
 6935: 
 6936: table.LC_createuser tr.LC_section_row td {
 6937:   font-size: small;
 6938: }
 6939: 
 6940: table.LC_createuser tr.LC_info_row td  {
 6941:   background-color: #CCCCCC;
 6942:   font-weight: bold;
 6943:   text-align: center;
 6944: }
 6945: 
 6946: table.LC_calendar {
 6947:   border: 1px solid #000000;
 6948:   border-collapse: collapse;
 6949:   width: 98%;
 6950: }
 6951: 
 6952: table.LC_calendar_pickdate {
 6953:   font-size: xx-small;
 6954: }
 6955: 
 6956: table.LC_calendar tr td {
 6957:   border: 1px solid #000000;
 6958:   vertical-align: top;
 6959:   width: 14%;
 6960: }
 6961: 
 6962: table.LC_calendar tr td.LC_calendar_day_empty {
 6963:   background-color: $data_table_dark;
 6964: }
 6965: 
 6966: table.LC_calendar tr td.LC_calendar_day_current {
 6967:   background-color: $data_table_highlight;
 6968: }
 6969: 
 6970: table.LC_data_table tr td.LC_mail_new {
 6971:   background-color: $mail_new;
 6972: }
 6973: 
 6974: table.LC_data_table tr.LC_mail_new:hover {
 6975:   background-color: $mail_new_hover;
 6976: }
 6977: 
 6978: table.LC_data_table tr td.LC_mail_read {
 6979:   background-color: $mail_read;
 6980: }
 6981: 
 6982: /*
 6983: table.LC_data_table tr.LC_mail_read:hover {
 6984:   background-color: $mail_read_hover;
 6985: }
 6986: */
 6987: 
 6988: table.LC_data_table tr td.LC_mail_replied {
 6989:   background-color: $mail_replied;
 6990: }
 6991: 
 6992: /*
 6993: table.LC_data_table tr.LC_mail_replied:hover {
 6994:   background-color: $mail_replied_hover;
 6995: }
 6996: */
 6997: 
 6998: table.LC_data_table tr td.LC_mail_other {
 6999:   background-color: $mail_other;
 7000: }
 7001: 
 7002: /*
 7003: table.LC_data_table tr.LC_mail_other:hover {
 7004:   background-color: $mail_other_hover;
 7005: }
 7006: */
 7007: 
 7008: table.LC_data_table tr > td.LC_browser_file,
 7009: table.LC_data_table tr > td.LC_browser_file_published {
 7010:   background: #AAEE77;
 7011: }
 7012: 
 7013: table.LC_data_table tr > td.LC_browser_file_locked,
 7014: table.LC_data_table tr > td.LC_browser_file_unpublished {
 7015:   background: #FFAA99;
 7016: }
 7017: 
 7018: table.LC_data_table tr > td.LC_browser_file_obsolete {
 7019:   background: #888888;
 7020: }
 7021: 
 7022: table.LC_data_table tr > td.LC_browser_file_modified,
 7023: table.LC_data_table tr > td.LC_browser_file_metamodified {
 7024:   background: #F8F866;
 7025: }
 7026: 
 7027: table.LC_data_table tr.LC_browser_folder > td {
 7028:   background: #E0E8FF;
 7029: }
 7030: 
 7031: table.LC_data_table tr > td.LC_roles_is {
 7032:   /* background: #77FF77; */
 7033: }
 7034: 
 7035: table.LC_data_table tr > td.LC_roles_future {
 7036:   border-right: 8px solid #FFFF77;
 7037: }
 7038: 
 7039: table.LC_data_table tr > td.LC_roles_will {
 7040:   border-right: 8px solid #FFAA77;
 7041: }
 7042: 
 7043: table.LC_data_table tr > td.LC_roles_expired {
 7044:   border-right: 8px solid #FF7777;
 7045: }
 7046: 
 7047: table.LC_data_table tr > td.LC_roles_will_not {
 7048:   border-right: 8px solid #AAFF77;
 7049: }
 7050: 
 7051: table.LC_data_table tr > td.LC_roles_selected {
 7052:   border-right: 8px solid #11CC55;
 7053: }
 7054: 
 7055: span.LC_current_location {
 7056:   font-size:larger;
 7057:   background: $pgbg;
 7058: }
 7059: 
 7060: span.LC_current_nav_location {
 7061:   font-weight:bold;
 7062:   background: $sidebg;
 7063: }
 7064: 
 7065: span.LC_parm_menu_item {
 7066:   font-size: larger;
 7067: }
 7068: 
 7069: span.LC_parm_scope_all {
 7070:   color: red;
 7071: }
 7072: 
 7073: span.LC_parm_scope_folder {
 7074:   color: green;
 7075: }
 7076: 
 7077: span.LC_parm_scope_resource {
 7078:   color: orange;
 7079: }
 7080: 
 7081: span.LC_parm_part {
 7082:   color: blue;
 7083: }
 7084: 
 7085: span.LC_parm_folder,
 7086: span.LC_parm_symb {
 7087:   font-size: x-small;
 7088:   font-family: $mono;
 7089:   color: #AAAAAA;
 7090: }
 7091: 
 7092: ul.LC_parm_parmlist li {
 7093:   display: inline-block;
 7094:   padding: 0.3em 0.8em;
 7095:   vertical-align: top;
 7096:   width: 150px;
 7097:   border-top:1px solid $lg_border_color;
 7098: }
 7099: 
 7100: td.LC_parm_overview_level_menu,
 7101: td.LC_parm_overview_map_menu,
 7102: td.LC_parm_overview_parm_selectors,
 7103: td.LC_parm_overview_restrictions  {
 7104:   border: 1px solid black;
 7105:   border-collapse: collapse;
 7106: }
 7107: 
 7108: span.LC_parm_recursive,
 7109: td.LC_parm_recursive {
 7110:   font-weight: bold;
 7111:   font-size: smaller;
 7112: }
 7113: 
 7114: table.LC_parm_overview_restrictions td {
 7115:   border-width: 1px 4px 1px 4px;
 7116:   border-style: solid;
 7117:   border-color: $pgbg;
 7118:   text-align: center;
 7119: }
 7120: 
 7121: table.LC_parm_overview_restrictions th {
 7122:   background: $tabbg;
 7123:   border-width: 1px 4px 1px 4px;
 7124:   border-style: solid;
 7125:   border-color: $pgbg;
 7126: }
 7127: 
 7128: table#LC_helpmenu {
 7129:   border: none;
 7130:   height: 55px;
 7131:   border-spacing: 0;
 7132: }
 7133: 
 7134: table#LC_helpmenu fieldset legend {
 7135:   font-size: larger;
 7136: }
 7137: 
 7138: table#LC_helpmenu_links {
 7139:   width: 100%;
 7140:   border: 1px solid black;
 7141:   background: $pgbg;
 7142:   padding: 0;
 7143:   border-spacing: 1px;
 7144: }
 7145: 
 7146: table#LC_helpmenu_links tr td {
 7147:   padding: 1px;
 7148:   background: $tabbg;
 7149:   text-align: center;
 7150:   font-weight: bold;
 7151: }
 7152: 
 7153: table#LC_helpmenu_links a:link,
 7154: table#LC_helpmenu_links a:visited,
 7155: table#LC_helpmenu_links a:active {
 7156:   text-decoration: none;
 7157:   color: $font;
 7158: }
 7159: 
 7160: table#LC_helpmenu_links a:hover {
 7161:   text-decoration: underline;
 7162:   color: $vlink;
 7163: }
 7164: 
 7165: .LC_chrt_popup_exists {
 7166:   border: 1px solid #339933;
 7167:   margin: -1px;
 7168: }
 7169: 
 7170: .LC_chrt_popup_up {
 7171:   border: 1px solid yellow;
 7172:   margin: -1px;
 7173: }
 7174: 
 7175: .LC_chrt_popup {
 7176:   border: 1px solid #8888FF;
 7177:   background: #CCCCFF;
 7178: }
 7179: 
 7180: table.LC_pick_box {
 7181:   border-collapse: separate;
 7182:   background: white;
 7183:   border: 1px solid black;
 7184:   border-spacing: 1px;
 7185: }
 7186: 
 7187: table.LC_pick_box td.LC_pick_box_title {
 7188:   background: $sidebg;
 7189:   font-weight: bold;
 7190:   text-align: left;
 7191:   vertical-align: top;
 7192:   width: 184px;
 7193:   padding: 8px;
 7194: }
 7195: 
 7196: table.LC_pick_box td.LC_pick_box_value {
 7197:   text-align: left;
 7198:   padding: 8px;
 7199: }
 7200: 
 7201: table.LC_pick_box td.LC_pick_box_select {
 7202:   text-align: left;
 7203:   padding: 8px;
 7204: }
 7205: 
 7206: table.LC_pick_box td.LC_pick_box_separator {
 7207:   padding: 0;
 7208:   height: 1px;
 7209:   background: black;
 7210: }
 7211: 
 7212: table.LC_pick_box td.LC_pick_box_submit {
 7213:   text-align: right;
 7214: }
 7215: 
 7216: table.LC_pick_box td.LC_evenrow_value {
 7217:   text-align: left;
 7218:   padding: 8px;
 7219:   background-color: $data_table_light;
 7220: }
 7221: 
 7222: table.LC_pick_box td.LC_oddrow_value {
 7223:   text-align: left;
 7224:   padding: 8px;
 7225:   background-color: $data_table_light;
 7226: }
 7227: 
 7228: span.LC_helpform_receipt_cat {
 7229:   font-weight: bold;
 7230: }
 7231: 
 7232: table.LC_group_priv_box {
 7233:   background: white;
 7234:   border: 1px solid black;
 7235:   border-spacing: 1px;
 7236: }
 7237: 
 7238: table.LC_group_priv_box td.LC_pick_box_title {
 7239:   background: $tabbg;
 7240:   font-weight: bold;
 7241:   text-align: right;
 7242:   width: 184px;
 7243: }
 7244: 
 7245: table.LC_group_priv_box td.LC_groups_fixed {
 7246:   background: $data_table_light;
 7247:   text-align: center;
 7248: }
 7249: 
 7250: table.LC_group_priv_box td.LC_groups_optional {
 7251:   background: $data_table_dark;
 7252:   text-align: center;
 7253: }
 7254: 
 7255: table.LC_group_priv_box td.LC_groups_functionality {
 7256:   background: $data_table_darker;
 7257:   text-align: center;
 7258:   font-weight: bold;
 7259: }
 7260: 
 7261: table.LC_group_priv td {
 7262:   text-align: left;
 7263:   padding: 0;
 7264: }
 7265: 
 7266: .LC_navbuttons {
 7267:   margin: 2ex 0ex 2ex 0ex;
 7268: }
 7269: 
 7270: .LC_topic_bar {
 7271:   font-weight: bold;
 7272:   background: $tabbg;
 7273:   margin: 1em 0em 1em 2em;
 7274:   padding: 3px;
 7275:   font-size: 1.2em;
 7276: }
 7277: 
 7278: .LC_topic_bar span {
 7279:   left: 0.5em;
 7280:   position: absolute;
 7281:   vertical-align: middle;
 7282:   font-size: 1.2em;
 7283: }
 7284: 
 7285: table.LC_course_group_status {
 7286:   margin: 20px;
 7287: }
 7288: 
 7289: table.LC_status_selector td {
 7290:   vertical-align: top;
 7291:   text-align: center;
 7292:   padding: 4px;
 7293: }
 7294: 
 7295: div.LC_feedback_link {
 7296:   clear: both;
 7297:   background: $sidebg;
 7298:   width: 100%;
 7299:   padding-bottom: 10px;
 7300:   border: 1px $tabbg solid;
 7301:   height: 22px;
 7302:   line-height: 22px;
 7303:   padding-top: 5px;
 7304: }
 7305: 
 7306: div.LC_feedback_link img {
 7307:   height: 22px;
 7308:   vertical-align:middle;
 7309: }
 7310: 
 7311: div.LC_feedback_link a {
 7312:   text-decoration: none;
 7313: }
 7314: 
 7315: div.LC_comblock {
 7316:   display:inline;
 7317:   color:$font;
 7318:   font-size:90%;
 7319: }
 7320: 
 7321: div.LC_feedback_link div.LC_comblock {
 7322:   padding-left:5px;
 7323: }
 7324: 
 7325: div.LC_feedback_link div.LC_comblock a {
 7326:   color:$font;
 7327: }
 7328: 
 7329: span.LC_feedback_link {
 7330:   /* background: $feedback_link_bg; */
 7331:   font-size: larger;
 7332: }
 7333: 
 7334: span.LC_message_link {
 7335:   /* background: $feedback_link_bg; */
 7336:   font-size: larger;
 7337:   position: absolute;
 7338:   right: 1em;
 7339: }
 7340: 
 7341: table.LC_prior_tries {
 7342:   border: 1px solid #000000;
 7343:   border-collapse: separate;
 7344:   border-spacing: 1px;
 7345: }
 7346: 
 7347: table.LC_prior_tries td {
 7348:   padding: 2px;
 7349: }
 7350: 
 7351: .LC_answer_correct {
 7352:   background: lightgreen;
 7353:   color: darkgreen;
 7354:   padding: 6px;
 7355: }
 7356: 
 7357: .LC_answer_charged_try {
 7358:   background: #FFAAAA;
 7359:   color: darkred;
 7360:   padding: 6px;
 7361: }
 7362: 
 7363: .LC_answer_not_charged_try,
 7364: .LC_answer_no_grade,
 7365: .LC_answer_late {
 7366:   background: lightyellow;
 7367:   color: black;
 7368:   padding: 6px;
 7369: }
 7370: 
 7371: .LC_answer_previous {
 7372:   background: lightblue;
 7373:   color: darkblue;
 7374:   padding: 6px;
 7375: }
 7376: 
 7377: .LC_answer_no_message {
 7378:   background: #FFFFFF;
 7379:   color: black;
 7380:   padding: 6px;
 7381: }
 7382: 
 7383: .LC_answer_unknown,
 7384: .LC_answer_warning {
 7385:   background: orange;
 7386:   color: black;
 7387:   padding: 6px;
 7388: }
 7389: 
 7390: span.LC_prior_numerical,
 7391: span.LC_prior_string,
 7392: span.LC_prior_custom,
 7393: span.LC_prior_reaction,
 7394: span.LC_prior_math {
 7395:   font-family: $mono;
 7396:   white-space: pre;
 7397: }
 7398: 
 7399: span.LC_prior_string {
 7400:   font-family: $mono;
 7401:   white-space: pre;
 7402: }
 7403: 
 7404: table.LC_prior_option {
 7405:   width: 100%;
 7406:   border-collapse: collapse;
 7407: }
 7408: 
 7409: table.LC_prior_rank,
 7410: table.LC_prior_match {
 7411:   border-collapse: collapse;
 7412: }
 7413: 
 7414: table.LC_prior_option tr td,
 7415: table.LC_prior_rank tr td,
 7416: table.LC_prior_match tr td {
 7417:   border: 1px solid #000000;
 7418: }
 7419: 
 7420: .LC_nobreak {
 7421:   white-space: nowrap;
 7422: }
 7423: 
 7424: span.LC_cusr_emph {
 7425:   font-style: italic;
 7426: }
 7427: 
 7428: span.LC_cusr_subheading {
 7429:   font-weight: normal;
 7430:   font-size: 85%;
 7431: }
 7432: 
 7433: div.LC_docs_entry_move {
 7434:   border: 1px solid #BBBBBB;
 7435:   background: #DDDDDD;
 7436:   width: 22px;
 7437:   padding: 1px;
 7438:   margin: 0;
 7439: }
 7440: 
 7441: table.LC_data_table tr > td.LC_docs_entry_commands,
 7442: table.LC_data_table tr > td.LC_docs_entry_parameter {
 7443:   font-size: x-small;
 7444: }
 7445: 
 7446: .LC_docs_entry_parameter {
 7447:   white-space: nowrap;
 7448: }
 7449: 
 7450: .LC_docs_copy {
 7451:   color: #000099;
 7452: }
 7453: 
 7454: .LC_docs_cut {
 7455:   color: #550044;
 7456: }
 7457: 
 7458: .LC_docs_rename {
 7459:   color: #009900;
 7460: }
 7461: 
 7462: .LC_docs_remove {
 7463:   color: #990000;
 7464: }
 7465: 
 7466: .LC_docs_alias {
 7467:   color: #440055;  
 7468: }
 7469: 
 7470: .LC_domprefs_email,
 7471: .LC_docs_alias_name,
 7472: .LC_docs_reinit_warn,
 7473: .LC_docs_ext_edit {
 7474:   font-size: x-small;
 7475: }
 7476: 
 7477: table.LC_docs_adddocs td,
 7478: table.LC_docs_adddocs th {
 7479:   border: 1px solid #BBBBBB;
 7480:   padding: 4px;
 7481:   background: #DDDDDD;
 7482: }
 7483: 
 7484: table.LC_sty_begin {
 7485:   background: #BBFFBB;
 7486: }
 7487: 
 7488: table.LC_sty_end {
 7489:   background: #FFBBBB;
 7490: }
 7491: 
 7492: table.LC_double_column {
 7493:   border-width: 0;
 7494:   border-collapse: collapse;
 7495:   width: 100%;
 7496:   padding: 2px;
 7497: }
 7498: 
 7499: table.LC_double_column tr td.LC_left_col {
 7500:   top: 2px;
 7501:   left: 2px;
 7502:   width: 47%;
 7503:   vertical-align: top;
 7504: }
 7505: 
 7506: table.LC_double_column tr td.LC_right_col {
 7507:   top: 2px;
 7508:   right: 2px;
 7509:   width: 47%;
 7510:   vertical-align: top;
 7511: }
 7512: 
 7513: div.LC_left_float {
 7514:   float: left;
 7515:   padding-right: 5%;
 7516:   padding-bottom: 4px;
 7517: }
 7518: 
 7519: div.LC_clear_float_header {
 7520:   padding-bottom: 2px;
 7521: }
 7522: 
 7523: div.LC_clear_float_footer {
 7524:   padding-top: 10px;
 7525:   clear: both;
 7526: }
 7527: 
 7528: div.LC_grade_show_user {
 7529: /*  border-left: 5px solid $sidebg; */
 7530:   border-top: 5px solid #000000;
 7531:   margin: 50px 0 0 0;
 7532:   padding: 15px 0 5px 10px;
 7533: }
 7534: 
 7535: div.LC_grade_show_user_odd_row {
 7536: /*  border-left: 5px solid #000000; */
 7537: }
 7538: 
 7539: div.LC_grade_show_user div.LC_Box {
 7540:   margin-right: 50px;
 7541: }
 7542: 
 7543: div.LC_grade_submissions,
 7544: div.LC_grade_message_center,
 7545: div.LC_grade_info_links {
 7546:   margin: 5px;
 7547:   width: 99%;
 7548:   background: #FFFFFF;
 7549: }
 7550: 
 7551: div.LC_grade_submissions_header,
 7552: div.LC_grade_message_center_header {
 7553:   font-weight: bold;
 7554:   font-size: large;
 7555: }
 7556: 
 7557: div.LC_grade_submissions_body,
 7558: div.LC_grade_message_center_body {
 7559:   border: 1px solid black;
 7560:   width: 99%;
 7561:   background: #FFFFFF;
 7562: }
 7563: 
 7564: table.LC_scantron_action {
 7565:   width: 100%;
 7566: }
 7567: 
 7568: table.LC_scantron_action tr th {
 7569:   font-weight:bold;
 7570:   font-style:normal;
 7571: }
 7572: 
 7573: .LC_edit_problem_header,
 7574: div.LC_edit_problem_footer {
 7575:   font-weight: normal;
 7576:   font-size:  medium;
 7577:   margin: 2px;
 7578:   background-color: $sidebg;
 7579: }
 7580: 
 7581: div.LC_edit_problem_header,
 7582: div.LC_edit_problem_header div,
 7583: div.LC_edit_problem_footer,
 7584: div.LC_edit_problem_footer div,
 7585: div.LC_edit_problem_editxml_header,
 7586: div.LC_edit_problem_editxml_header div {
 7587:   z-index: 100;
 7588: }
 7589: 
 7590: div.LC_edit_problem_header_title {
 7591:   font-weight: bold;
 7592:   font-size: larger;
 7593:   background: $tabbg;
 7594:   padding: 3px;
 7595:   margin: 0 0 5px 0;
 7596: }
 7597: 
 7598: table.LC_edit_problem_header_title {
 7599:   width: 100%;
 7600:   background: $tabbg;
 7601: }
 7602: 
 7603: div.LC_edit_actionbar {
 7604:     background-color: $sidebg;
 7605:     margin: 0;
 7606:     padding: 0;
 7607:     line-height: 200%;
 7608: }
 7609: 
 7610: div.LC_edit_actionbar div{
 7611:     padding: 0;
 7612:     margin: 0;
 7613:     display: inline-block;
 7614: }
 7615: 
 7616: .LC_edit_opt {
 7617:   padding-left: 1em;
 7618:   white-space: nowrap;
 7619: }
 7620: 
 7621: .LC_edit_problem_latexhelper{
 7622:     text-align: right;
 7623: }
 7624: 
 7625: #LC_edit_problem_colorful div{
 7626:     margin-left: 40px;
 7627: }
 7628: 
 7629: #LC_edit_problem_codemirror div{
 7630:     margin-left: 0px;
 7631: }
 7632: 
 7633: img.stift {
 7634:   border-width: 0;
 7635:   vertical-align: middle;
 7636: }
 7637: 
 7638: table td.LC_mainmenu_col_fieldset {
 7639:   vertical-align: top;
 7640: }
 7641: 
 7642: div.LC_createcourse {
 7643:   margin: 10px 10px 10px 10px;
 7644: }
 7645: 
 7646: .LC_dccid {
 7647:   float: right;
 7648:   margin: 0.2em 0 0 0;
 7649:   padding: 0;
 7650:   font-size: 90%;
 7651:   display:none;
 7652: }
 7653: 
 7654: ol.LC_primary_menu a:hover,
 7655: ol#LC_MenuBreadcrumbs a:hover,
 7656: ol#LC_PathBreadcrumbs a:hover,
 7657: ul#LC_secondary_menu a:hover,
 7658: .LC_FormSectionClearButton input:hover
 7659: ul.LC_TabContent   li:hover a {
 7660:   color:$button_hover;
 7661:   text-decoration:none;
 7662: }
 7663: 
 7664: h1 {
 7665:   padding: 0;
 7666:   line-height:130%;
 7667: }
 7668: 
 7669: h2,
 7670: h3,
 7671: h4,
 7672: h5,
 7673: h6 {
 7674:   margin: 5px 0 5px 0;
 7675:   padding: 0;
 7676:   line-height:130%;
 7677: }
 7678: 
 7679: .LC_hcell {
 7680:   padding:3px 15px 3px 15px;
 7681:   margin: 0;
 7682:   background-color:$tabbg;
 7683:   color:$fontmenu;
 7684:   border-bottom:solid 1px $lg_border_color;
 7685: }
 7686: 
 7687: .LC_Box > .LC_hcell {
 7688:   margin: 0 -10px 10px -10px;
 7689: }
 7690: 
 7691: .LC_noBorder {
 7692:   border: 0;
 7693: }
 7694: 
 7695: .LC_FormSectionClearButton input {
 7696:   background-color:transparent;
 7697:   border: none;
 7698:   cursor:pointer;
 7699:   text-decoration:underline;
 7700: }
 7701: 
 7702: .LC_help_open_topic {
 7703:   color: #FFFFFF;
 7704:   background-color: #EEEEFF;
 7705:   margin: 1px;
 7706:   padding: 4px;
 7707:   border: 1px solid #000033;
 7708:   white-space: nowrap;
 7709:   /* vertical-align: middle; */
 7710: }
 7711: 
 7712: dl,
 7713: ul,
 7714: div,
 7715: fieldset {
 7716:   margin: 10px 10px 10px 0;
 7717:   /* overflow: hidden; */
 7718: }
 7719: 
 7720: article.geogebraweb div {
 7721:     margin: 0;
 7722: }
 7723: 
 7724: fieldset > legend {
 7725:   font-weight: bold;
 7726:   padding: 0 5px 0 5px;
 7727: }
 7728: 
 7729: #LC_nav_bar {
 7730:   float: left;
 7731:   background-color: $pgbg_or_bgcolor;
 7732:   margin: 0 0 2px 0;
 7733: }
 7734: 
 7735: #LC_realm {
 7736:   margin: 0.2em 0 0 0;
 7737:   padding: 0;
 7738:   font-weight: bold;
 7739:   text-align: center;
 7740:   background-color: $pgbg_or_bgcolor;
 7741: }
 7742: 
 7743: #LC_nav_bar em {
 7744:   font-weight: bold;
 7745:   font-style: normal;
 7746: }
 7747: 
 7748: ol.LC_primary_menu {
 7749:   margin: 0;
 7750:   padding: 0;
 7751: }
 7752: 
 7753: ol#LC_PathBreadcrumbs {
 7754:   margin: 0;
 7755: }
 7756: 
 7757: ol.LC_primary_menu li {
 7758:   color: RGB(80, 80, 80);
 7759:   vertical-align: middle;
 7760:   text-align: left;
 7761:   list-style: none;
 7762:   position: relative;
 7763:   float: left;
 7764:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
 7765:   line-height: 1.5em;
 7766: }
 7767: 
 7768: ol.LC_primary_menu li a,
 7769: ol.LC_primary_menu li p {
 7770:   display: block;
 7771:   margin: 0;
 7772:   padding: 0 5px 0 10px;
 7773:   text-decoration: none;
 7774: }
 7775: 
 7776: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
 7777:   display: inline-block;
 7778:   width: 95%;
 7779:   text-align: left;
 7780: }
 7781: 
 7782: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
 7783:   display: inline-block;	
 7784:   width: 5%;
 7785:   float: right;
 7786:   text-align: right;
 7787:   font-size: 70%;
 7788: }
 7789: 
 7790: ol.LC_primary_menu ul {
 7791:   display: none;
 7792:   width: 15em;
 7793:   background-color: $data_table_light;
 7794:   position: absolute;
 7795:   top: 100%;
 7796: }
 7797: 
 7798: ol.LC_primary_menu ul ul {
 7799:   left: 100%;
 7800:   top: 0;
 7801: }
 7802: 
 7803: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
 7804:   display: block;
 7805:   position: absolute;
 7806:   margin: 0;
 7807:   padding: 0;
 7808:   z-index: 2;
 7809: }
 7810: 
 7811: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 7812: /* First Submenu -> size should be smaller than the menu title of the whole menu */
 7813:   font-size: 90%;
 7814:   vertical-align: top;
 7815:   float: none;
 7816:   border-left: 1px solid black;
 7817:   border-right: 1px solid black;
 7818: /* A dark bottom border to visualize different menu options; 
 7819: overwritten in the create_submenu routine for the last border-bottom of the menu */
 7820:   border-bottom: 1px solid $data_table_dark; 
 7821: }
 7822: 
 7823: ol.LC_primary_menu li li p:hover {
 7824:   color:$button_hover;
 7825:   text-decoration:none;
 7826:   background-color:$data_table_dark;
 7827: }
 7828: 
 7829: ol.LC_primary_menu li li a:hover {
 7830:    color:$button_hover;
 7831:    background-color:$data_table_dark;
 7832: }
 7833: 
 7834: /* Font-size equal to the size of the predecessors*/
 7835: ol.LC_primary_menu li:hover li li {
 7836:   font-size: 100%;
 7837: }
 7838: 
 7839: ol.LC_primary_menu li img {
 7840:   vertical-align: bottom;
 7841:   height: 1.1em;
 7842:   margin: 0.2em 0 0 0;
 7843: }
 7844: 
 7845: ol.LC_primary_menu a {
 7846:   color: RGB(80, 80, 80);
 7847:   text-decoration: none;
 7848: }
 7849: 
 7850: ol.LC_primary_menu a.LC_new_message {
 7851:   font-weight:bold;
 7852:   color: darkred;
 7853: }
 7854: 
 7855: ol.LC_docs_parameters {
 7856:   margin-left: 0;
 7857:   padding: 0;
 7858:   list-style: none;
 7859: }
 7860: 
 7861: ol.LC_docs_parameters li {
 7862:   margin: 0;
 7863:   padding-right: 20px;
 7864:   display: inline;
 7865: }
 7866: 
 7867: ol.LC_docs_parameters li:before {
 7868:   content: "\\002022 \\0020";
 7869: }
 7870: 
 7871: li.LC_docs_parameters_title {
 7872:   font-weight: bold;
 7873: }
 7874: 
 7875: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 7876:   content: "";
 7877: }
 7878: 
 7879: ul#LC_secondary_menu {
 7880:   clear: right;
 7881:   color: $fontmenu;
 7882:   background: $tabbg;
 7883:   list-style: none;
 7884:   padding: 0;
 7885:   margin: 0;
 7886:   width: 100%;
 7887:   text-align: left;
 7888:   float: left;
 7889: }
 7890: 
 7891: ul#LC_secondary_menu li {
 7892:   font-weight: bold;
 7893:   line-height: 1.8em;
 7894:   border-right: 1px solid black;
 7895:   float: left;
 7896: }
 7897: 
 7898: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 7899:   background-color: $data_table_light;
 7900: }
 7901: 
 7902: ul#LC_secondary_menu li a {
 7903:   padding: 0 0.8em;
 7904: }
 7905: 
 7906: ul#LC_secondary_menu li ul {
 7907:   display: none;
 7908: }
 7909: 
 7910: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 7911:   display: block;
 7912:   position: absolute;
 7913:   margin: 0;
 7914:   padding: 0;
 7915:   list-style:none;
 7916:   float: none;
 7917:   background-color: $data_table_light;
 7918:   z-index: 2;
 7919:   margin-left: -1px;
 7920: }
 7921: 
 7922: ul#LC_secondary_menu li ul li {
 7923:   font-size: 90%;
 7924:   vertical-align: top;
 7925:   border-left: 1px solid black;
 7926:   border-right: 1px solid black;
 7927:   background-color: $data_table_light;
 7928:   list-style:none;
 7929:   float: none;
 7930: }
 7931: 
 7932: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 7933:   background-color: $data_table_dark;
 7934: }
 7935: 
 7936: ul.LC_TabContent {
 7937:   display:block;
 7938:   background: $sidebg;
 7939:   border-bottom: solid 1px $lg_border_color;
 7940:   list-style:none;
 7941:   margin: -1px -10px 0 -10px;
 7942:   padding: 0;
 7943: }
 7944: 
 7945: ul.LC_TabContent li,
 7946: ul.LC_TabContentBigger li {
 7947:   float:left;
 7948: }
 7949: 
 7950: ul#LC_secondary_menu li a {
 7951:   color: $fontmenu;
 7952:   text-decoration: none;
 7953: }
 7954: 
 7955: ul.LC_TabContent {
 7956:   min-height:20px;
 7957: }
 7958: 
 7959: ul.LC_TabContent li {
 7960:   vertical-align:middle;
 7961:   padding: 0 16px 0 10px;
 7962:   background-color:$tabbg;
 7963:   border-bottom:solid 1px $lg_border_color;
 7964:   border-left: solid 1px $font;
 7965: }
 7966: 
 7967: ul.LC_TabContent .right {
 7968:   float:right;
 7969: }
 7970: 
 7971: ul.LC_TabContent li a,
 7972: ul.LC_TabContent li {
 7973:   color:rgb(47,47,47);
 7974:   text-decoration:none;
 7975:   font-size:95%;
 7976:   font-weight:bold;
 7977:   min-height:20px;
 7978: }
 7979: 
 7980: ul.LC_TabContent li a:hover,
 7981: ul.LC_TabContent li a:focus {
 7982:   color: $button_hover;
 7983:   background:none;
 7984:   outline:none;
 7985: }
 7986: 
 7987: ul.LC_TabContent li:hover {
 7988:   color: $button_hover;
 7989:   cursor:pointer;
 7990: }
 7991: 
 7992: ul.LC_TabContent li.active {
 7993:   color: $font;
 7994:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 7995:   border-bottom:solid 1px #FFFFFF;
 7996:   cursor: default;
 7997: }
 7998: 
 7999: ul.LC_TabContent li.active a {
 8000:   color:$font;
 8001:   background:#FFFFFF;
 8002:   outline: none;
 8003: }
 8004: 
 8005: ul.LC_TabContent li.goback {
 8006:   float: left;
 8007:   border-left: none;
 8008: }
 8009: 
 8010: #maincoursedoc {
 8011:   clear:both;
 8012: }
 8013: 
 8014: ul.LC_TabContentBigger {
 8015:   display:block;
 8016:   list-style:none;
 8017:   padding: 0;
 8018: }
 8019: 
 8020: ul.LC_TabContentBigger li {
 8021:   vertical-align:bottom;
 8022:   height: 30px;
 8023:   font-size:110%;
 8024:   font-weight:bold;
 8025:   color: #737373;
 8026: }
 8027: 
 8028: ul.LC_TabContentBigger li.active {
 8029:   position: relative;
 8030:   top: 1px;
 8031: }
 8032: 
 8033: ul.LC_TabContentBigger li a {
 8034:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 8035:   height: 30px;
 8036:   line-height: 30px;
 8037:   text-align: center;
 8038:   display: block;
 8039:   text-decoration: none;
 8040:   outline: none;  
 8041: }
 8042: 
 8043: ul.LC_TabContentBigger li.active a {
 8044:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 8045:   color:$font;
 8046: }
 8047: 
 8048: ul.LC_TabContentBigger li b {
 8049:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 8050:   display: block;
 8051:   float: left;
 8052:   padding: 0 30px;
 8053:   border-bottom: 1px solid $lg_border_color;
 8054: }
 8055: 
 8056: ul.LC_TabContentBigger li:hover b {
 8057:   color:$button_hover;
 8058: }
 8059: 
 8060: ul.LC_TabContentBigger li.active b {
 8061:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 8062:   color:$font;
 8063:   border: 0;
 8064: }
 8065: 
 8066: 
 8067: ul.LC_CourseBreadcrumbs {
 8068:   background: $sidebg;
 8069:   height: 2em;
 8070:   padding-left: 10px;
 8071:   margin: 0;
 8072:   list-style-position: inside;
 8073: }
 8074: 
 8075: ol#LC_MenuBreadcrumbs,
 8076: ol#LC_PathBreadcrumbs {
 8077:   padding-left: 10px;
 8078:   margin: 0;
 8079:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 8080: }
 8081: 
 8082: ol#LC_MenuBreadcrumbs li,
 8083: ol#LC_PathBreadcrumbs li,
 8084: ul.LC_CourseBreadcrumbs li {
 8085:   display: inline;
 8086:   white-space: normal;  
 8087: }
 8088: 
 8089: ol#LC_MenuBreadcrumbs li a,
 8090: ul.LC_CourseBreadcrumbs li a {
 8091:   text-decoration: none;
 8092:   font-size:90%;
 8093: }
 8094: 
 8095: ol#LC_MenuBreadcrumbs h1 {
 8096:   display: inline;
 8097:   font-size: 90%;
 8098:   line-height: 2.5em;
 8099:   margin: 0;
 8100:   padding: 0;
 8101: }
 8102: 
 8103: ol#LC_PathBreadcrumbs li a {
 8104:   text-decoration:none;
 8105:   font-size:100%;
 8106:   font-weight:bold;
 8107: }
 8108: 
 8109: .LC_Box {
 8110:   border: solid 1px $lg_border_color;
 8111:   padding: 0 10px 10px 10px;
 8112: }
 8113: 
 8114: .LC_DocsBox {
 8115:   border: solid 1px $lg_border_color;
 8116:   padding: 0 0 10px 10px;
 8117: }
 8118: 
 8119: .LC_AboutMe_Image {
 8120:   float:left;
 8121:   margin-right:10px;
 8122: }
 8123: 
 8124: .LC_Clear_AboutMe_Image {
 8125:   clear:left;
 8126: }
 8127: 
 8128: dl.LC_ListStyleClean dt {
 8129:   padding-right: 5px;
 8130:   display: table-header-group;
 8131: }
 8132: 
 8133: dl.LC_ListStyleClean dd {
 8134:   display: table-row;
 8135: }
 8136: 
 8137: .LC_ListStyleClean,
 8138: .LC_ListStyleSimple,
 8139: .LC_ListStyleNormal,
 8140: .LC_ListStyleSpecial {
 8141:   /* display:block; */
 8142:   list-style-position: inside;
 8143:   list-style-type: none;
 8144:   overflow: hidden;
 8145:   padding: 0;
 8146: }
 8147: 
 8148: .LC_ListStyleSimple li,
 8149: .LC_ListStyleSimple dd,
 8150: .LC_ListStyleNormal li,
 8151: .LC_ListStyleNormal dd,
 8152: .LC_ListStyleSpecial li,
 8153: .LC_ListStyleSpecial dd {
 8154:   margin: 0;
 8155:   padding: 5px 5px 5px 10px;
 8156:   clear: both;
 8157: }
 8158: 
 8159: .LC_ListStyleClean li,
 8160: .LC_ListStyleClean dd {
 8161:   padding-top: 0;
 8162:   padding-bottom: 0;
 8163: }
 8164: 
 8165: .LC_ListStyleSimple dd,
 8166: .LC_ListStyleSimple li {
 8167:   border-bottom: solid 1px $lg_border_color;
 8168: }
 8169: 
 8170: .LC_ListStyleSpecial li,
 8171: .LC_ListStyleSpecial dd {
 8172:   list-style-type: none;
 8173:   background-color: RGB(220, 220, 220);
 8174:   margin-bottom: 4px;
 8175: }
 8176: 
 8177: table.LC_SimpleTable {
 8178:   margin:5px;
 8179:   border:solid 1px $lg_border_color;
 8180: }
 8181: 
 8182: table.LC_SimpleTable tr {
 8183:   padding: 0;
 8184:   border:solid 1px $lg_border_color;
 8185: }
 8186: 
 8187: table.LC_SimpleTable thead {
 8188:   background:rgb(220,220,220);
 8189: }
 8190: 
 8191: div.LC_columnSection {
 8192:   display: block;
 8193:   clear: both;
 8194:   overflow: hidden;
 8195:   margin: 0;
 8196: }
 8197: 
 8198: div.LC_columnSection>* {
 8199:   float: left;
 8200:   margin: 10px 20px 10px 0;
 8201:   overflow:hidden;
 8202: }
 8203: 
 8204: table em {
 8205:   font-weight: bold;
 8206:   font-style: normal;
 8207: }
 8208: 
 8209: table.LC_tableBrowseRes,
 8210: table.LC_tableOfContent {
 8211:   border:none;
 8212:   border-spacing: 1px;
 8213:   padding: 3px;
 8214:   background-color: #FFFFFF;
 8215:   font-size: 90%;
 8216: }
 8217: 
 8218: table.LC_tableOfContent {
 8219:   border-collapse: collapse;
 8220: }
 8221: 
 8222: table.LC_tableBrowseRes a,
 8223: table.LC_tableOfContent a {
 8224:   background-color: transparent;
 8225:   text-decoration: none;
 8226: }
 8227: 
 8228: table.LC_tableOfContent img {
 8229:   border: none;
 8230:   height: 1.3em;
 8231:   vertical-align: text-bottom;
 8232:   margin-right: 0.3em;
 8233: }
 8234: 
 8235: a#LC_content_toolbar_firsthomework {
 8236:   background-image:url(/res/adm/pages/open-first-problem.gif);
 8237: }
 8238: 
 8239: a#LC_content_toolbar_everything {
 8240:   background-image:url(/res/adm/pages/show-all.gif);
 8241: }
 8242: 
 8243: a#LC_content_toolbar_uncompleted {
 8244:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 8245: }
 8246: 
 8247: #LC_content_toolbar_clearbubbles {
 8248:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 8249: }
 8250: 
 8251: a#LC_content_toolbar_changefolder {
 8252:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 8253: }
 8254: 
 8255: a#LC_content_toolbar_changefolder_toggled {
 8256:   background-image:url(/res/adm/pages/open-all-folders.gif);
 8257: }
 8258: 
 8259: a#LC_content_toolbar_edittoplevel {
 8260:   background-image:url(/res/adm/pages/edittoplevel.gif);
 8261: }
 8262: 
 8263: ul#LC_toolbar li a:hover {
 8264:   background-position: bottom center;
 8265: }
 8266: 
 8267: ul#LC_toolbar {
 8268:   padding: 0;
 8269:   margin: 2px;
 8270:   list-style:none;
 8271:   position:relative;
 8272:   background-color:white;
 8273:   overflow: auto;
 8274: }
 8275: 
 8276: ul#LC_toolbar li {
 8277:   border:1px solid white;
 8278:   padding: 0;
 8279:   margin: 0;
 8280:   float: left;
 8281:   display:inline;
 8282:   vertical-align:middle;
 8283:   white-space: nowrap;
 8284: }
 8285: 
 8286: 
 8287: a.LC_toolbarItem {
 8288:   display:block;
 8289:   padding: 0;
 8290:   margin: 0;
 8291:   height: 32px;
 8292:   width: 32px;
 8293:   color:white;
 8294:   border: none;
 8295:   background-repeat:no-repeat;
 8296:   background-color:transparent;
 8297: }
 8298: 
 8299: ul.LC_funclist {
 8300:     margin: 0;
 8301:     padding: 0.5em 1em 0.5em 0;
 8302: }
 8303: 
 8304: ul.LC_funclist > li:first-child {
 8305:     font-weight:bold; 
 8306:     margin-left:0.8em;
 8307: }
 8308: 
 8309: ul.LC_funclist + ul.LC_funclist {
 8310:     /* 
 8311:        left border as a seperator if we have more than
 8312:        one list 
 8313:     */
 8314:     border-left: 1px solid $sidebg;
 8315:     /* 
 8316:        this hides the left border behind the border of the 
 8317:        outer box if element is wrapped to the next 'line' 
 8318:     */
 8319:     margin-left: -1px;
 8320: }
 8321: 
 8322: ul.LC_funclist li {
 8323:   display: inline;
 8324:   white-space: nowrap;
 8325:   margin: 0 0 0 25px;
 8326:   line-height: 150%;
 8327: }
 8328: 
 8329: .LC_hidden {
 8330:   display: none;
 8331: }
 8332: 
 8333: .LCmodal-overlay {
 8334: 		position:fixed;
 8335: 		top:0;
 8336: 		right:0;
 8337: 		bottom:0;
 8338: 		left:0;
 8339: 		height:100%;
 8340: 		width:100%;
 8341: 		margin:0;
 8342: 		padding:0;
 8343: 		background:#999;
 8344: 		opacity:.75;
 8345: 		filter: alpha(opacity=75);
 8346: 		-moz-opacity: 0.75;
 8347: 		z-index:101;
 8348: }
 8349: 
 8350: * html .LCmodal-overlay {   
 8351: 		position: absolute;
 8352: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 8353: }
 8354: 
 8355: .LCmodal-window {
 8356: 		position:fixed;
 8357: 		top:50%;
 8358: 		left:50%;
 8359: 		margin:0;
 8360: 		padding:0;
 8361: 		z-index:102;
 8362: 	}
 8363: 
 8364: * html .LCmodal-window {
 8365: 		position:absolute;
 8366: }
 8367: 
 8368: .LCclose-window {
 8369: 		position:absolute;
 8370: 		width:32px;
 8371: 		height:32px;
 8372: 		right:8px;
 8373: 		top:8px;
 8374: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 8375: 		text-indent:-99999px;
 8376: 		overflow:hidden;
 8377: 		cursor:pointer;
 8378: }
 8379: 
 8380: .LCisDisabled {
 8381:   cursor: not-allowed;
 8382:   opacity: 0.5;
 8383: }
 8384: 
 8385: a[aria-disabled="true"] {
 8386:   color: currentColor;
 8387:   display: inline-block;  /* For IE11/ MS Edge bug */
 8388:   pointer-events: none;
 8389:   text-decoration: none;
 8390: }
 8391: 
 8392: pre.LC_wordwrap {
 8393:   white-space: pre-wrap;
 8394:   white-space: -moz-pre-wrap;
 8395:   white-space: -pre-wrap;
 8396:   white-space: -o-pre-wrap;
 8397:   word-wrap: break-word;
 8398: }
 8399: 
 8400: /*
 8401:   styles used for response display
 8402: */
 8403: div.LC_radiofoil, div.LC_rankfoil {
 8404:   margin: .5em 0em .5em 0em;
 8405: }
 8406: table.LC_itemgroup {
 8407:   margin-top: 1em;
 8408: }
 8409: 
 8410: /*
 8411:   styles used by TTH when "Default set of options to pass to tth/m
 8412:   when converting TeX" in course settings has been set
 8413: 
 8414:   option passed: -t
 8415: 
 8416: */
 8417: 
 8418: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 8419: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 8420: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 8421: td div.norm {line-height:normal;}
 8422: 
 8423: /*
 8424:   option passed -y3
 8425: */
 8426: 
 8427: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 8428: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 8429: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 8430: 
 8431: /*
 8432:   sections with roles, for content only
 8433: */
 8434: section[class^="role-"] {
 8435:   padding-left: 10px;
 8436:   padding-right: 5px;
 8437:   margin-top: 8px;
 8438:   margin-bottom: 8px;
 8439:   border: 1px solid #2A4;
 8440:   border-radius: 5px;
 8441:   box-shadow: 0px 1px 1px #BBB;
 8442: }
 8443: section[class^="role-"]>h1 {
 8444:   position: relative;
 8445:   margin: 0px;
 8446:   padding-top: 10px;
 8447:   padding-left: 40px;
 8448: }
 8449: section[class^="role-"]>h1:before {
 8450:   position: absolute;
 8451:   left: -5px;
 8452:   top: 5px;
 8453: }
 8454: section.role-activity>h1:before {
 8455:   content:url('/adm/daxe/images/section_icons/activity.png');
 8456: }
 8457: section.role-advice>h1:before {
 8458:   content:url('/adm/daxe/images/section_icons/advice.png');
 8459: }
 8460: section.role-bibliography>h1:before {
 8461:   content:url('/adm/daxe/images/section_icons/bibliography.png');
 8462: }
 8463: section.role-citation>h1:before {
 8464:   content:url('/adm/daxe/images/section_icons/citation.png');
 8465: }
 8466: section.role-conclusion>h1:before {
 8467:   content:url('/adm/daxe/images/section_icons/conclusion.png');
 8468: }
 8469: section.role-definition>h1:before {
 8470:   content:url('/adm/daxe/images/section_icons/definition.png');
 8471: }
 8472: section.role-demonstration>h1:before {
 8473:   content:url('/adm/daxe/images/section_icons/demonstration.png');
 8474: }
 8475: section.role-example>h1:before {
 8476:   content:url('/adm/daxe/images/section_icons/example.png');
 8477: }
 8478: section.role-explanation>h1:before {
 8479:   content:url('/adm/daxe/images/section_icons/explanation.png');
 8480: }
 8481: section.role-introduction>h1:before {
 8482:   content:url('/adm/daxe/images/section_icons/introduction.png');
 8483: }
 8484: section.role-method>h1:before {
 8485:   content:url('/adm/daxe/images/section_icons/method.png');
 8486: }
 8487: section.role-more_information>h1:before {
 8488:   content:url('/adm/daxe/images/section_icons/more_information.png');
 8489: }
 8490: section.role-objectives>h1:before {
 8491:   content:url('/adm/daxe/images/section_icons/objectives.png');
 8492: }
 8493: section.role-prerequisites>h1:before {
 8494:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
 8495: }
 8496: section.role-remark>h1:before {
 8497:   content:url('/adm/daxe/images/section_icons/remark.png');
 8498: }
 8499: section.role-reminder>h1:before {
 8500:   content:url('/adm/daxe/images/section_icons/reminder.png');
 8501: }
 8502: section.role-summary>h1:before {
 8503:   content:url('/adm/daxe/images/section_icons/summary.png');
 8504: }
 8505: section.role-syntax>h1:before {
 8506:   content:url('/adm/daxe/images/section_icons/syntax.png');
 8507: }
 8508: section.role-warning>h1:before {
 8509:   content:url('/adm/daxe/images/section_icons/warning.png');
 8510: }
 8511: 
 8512: #LC_minitab_header {
 8513:   float:left;
 8514:   width:100%;
 8515:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
 8516:   font-size:93%;
 8517:   line-height:normal;
 8518:   margin: 0.5em 0 0.5em 0;
 8519: }
 8520: #LC_minitab_header ul {
 8521:   margin:0;
 8522:   padding:10px 10px 0;
 8523:   list-style:none;
 8524: }
 8525: #LC_minitab_header li {
 8526:   float:left;
 8527:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
 8528:   margin:0;
 8529:   padding:0 0 0 9px;
 8530: }
 8531: #LC_minitab_header a {
 8532:   display:block;
 8533:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
 8534:   padding:5px 15px 4px 6px;
 8535: }
 8536: #LC_minitab_header #LC_current_minitab {
 8537:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
 8538: }
 8539: #LC_minitab_header #LC_current_minitab a {
 8540:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
 8541:   padding-bottom:5px;
 8542: }
 8543: 
 8544: 
 8545: END
 8546: }
 8547: 
 8548: =pod
 8549: 
 8550: =item * &headtag()
 8551: 
 8552: Returns a uniform footer for LON-CAPA web pages.
 8553: 
 8554: Inputs: $title - optional title for the head
 8555:         $head_extra - optional extra HTML to put inside the <head>
 8556:         $args - optional arguments
 8557:             force_register - if is true call registerurl so the remote is 
 8558:                              informed
 8559:             redirect       -> array ref of
 8560:                                    1- seconds before redirect occurs
 8561:                                    2- url to redirect to
 8562:                                    3- whether the side effect should occur
 8563:                            (side effect of setting 
 8564:                                $env{'internal.head.redirect'} to the url 
 8565:                                redirected too)
 8566:             domain         -> force to color decorate a page for a specific
 8567:                                domain
 8568:             function       -> force usage of a specific rolish color scheme
 8569:             bgcolor        -> override the default page bgcolor
 8570:             no_auto_mt_title
 8571:                            -> prevent &mt()ing the title arg
 8572: 
 8573: =cut
 8574: 
 8575: sub headtag {
 8576:     my ($title,$head_extra,$args) = @_;
 8577:     
 8578:     my $function = $args->{'function'} || &get_users_function();
 8579:     my $domain   = $args->{'domain'}   || &determinedomain();
 8580:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 8581:     my $httphost = $args->{'use_absolute'};
 8582:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 8583: 		   $Apache::lonnet::perlvar{'lonVersion'},
 8584: 		   #time(),
 8585: 		   $env{'environment.color.timestamp'},
 8586: 		   $function,$domain,$bgcolor);
 8587: 
 8588:     $url = '/adm/css/'.&escape($url).'.css';
 8589: 
 8590:     my $result =
 8591: 	'<head>'.
 8592: 	&font_settings($args);
 8593: 
 8594:     my $inhibitprint;
 8595:     if ($args->{'print_suppress'}) {
 8596:         $inhibitprint = &print_suppression();
 8597:     }
 8598: 
 8599:     if (!$args->{'frameset'}) {
 8600: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 8601:     }
 8602:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
 8603:         $result .= Apache::lonxml::display_title();
 8604:     }
 8605:     if (!$args->{'no_nav_bar'} 
 8606: 	&& !$args->{'only_body'}
 8607: 	&& !$args->{'frameset'}) {
 8608: 	$result .= &help_menu_js($httphost);
 8609:         $result.=&modal_window();
 8610:         $result.=&togglebox_script();
 8611:         $result.=&wishlist_window();
 8612:         $result.=&LCprogressbarUpdate_script();
 8613:     } else {
 8614:         if ($args->{'add_modal'}) {
 8615:            $result.=&modal_window();
 8616:         }
 8617:         if ($args->{'add_wishlist'}) {
 8618:            $result.=&wishlist_window();
 8619:         }
 8620:         if ($args->{'add_togglebox'}) {
 8621:            $result.=&togglebox_script();
 8622:         }
 8623:         if ($args->{'add_progressbar'}) {
 8624:            $result.=&LCprogressbarUpdate_script();
 8625:         }
 8626:     }
 8627:     if (ref($args->{'redirect'})) {
 8628: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 8629: 	$url = &Apache::lonenc::check_encrypt($url);
 8630: 	if (!$inhibit_continue) {
 8631: 	    $env{'internal.head.redirect'} = $url;
 8632: 	}
 8633: 	$result.=<<ADDMETA
 8634: <meta http-equiv="pragma" content="no-cache" />
 8635: <meta http-equiv="Refresh" content="$time; url=$url" />
 8636: ADDMETA
 8637:     } else {
 8638:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
 8639:             my $requrl = $env{'request.uri'};
 8640:             if ($requrl eq '') {
 8641:                 $requrl = $ENV{'REQUEST_URI'};
 8642:                 $requrl =~ s/\?.+$//;
 8643:             }
 8644:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
 8645:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
 8646:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
 8647:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
 8648:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
 8649:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
 8650:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 8651:                     my ($offload,$offloadoth);
 8652:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
 8653:                         if ($domdefs{'offloadnow'}{$lonhost}) {
 8654:                             $offload = 1;
 8655:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
 8656:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
 8657:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
 8658:                                     $offloadoth = 1;
 8659:                                     $dom_in_use = $env{'user.domain'};
 8660:                                 }
 8661:                             }
 8662:                         }
 8663:                     }
 8664:                     unless ($offload) {
 8665:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
 8666:                             if ($domdefs{'offloadoth'}{$lonhost}) {
 8667:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
 8668:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
 8669:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
 8670:                                         $offload = 1;
 8671:                                         $offloadoth = 1;
 8672:                                         $dom_in_use = $env{'user.domain'};
 8673:                                     }
 8674:                                 }
 8675:                             }
 8676:                         }
 8677:                     }
 8678:                     if ($offload) {
 8679:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
 8680:                         if (($newserver eq '') && ($offloadoth)) {
 8681:                             my @domains = &Apache::lonnet::current_machine_domains();
 8682:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) { 
 8683:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
 8684:                             }
 8685:                         }
 8686:                         if (($newserver) && ($newserver ne $lonhost)) {
 8687:                             my $numsec = 5;
 8688:                             my $timeout = $numsec * 1000;
 8689:                             my ($newurl,$locknum,%locks,$msg);
 8690:                             if ($env{'request.role.adv'}) {
 8691:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
 8692:                             }
 8693:                             my $disable_submit = 0;
 8694:                             if ($requrl =~ /$LONCAPA::assess_re/) {
 8695:                                 $disable_submit = 1;
 8696:                             }
 8697:                             if ($locknum) {
 8698:                                 my @lockinfo = sort(values(%locks));
 8699:                                 $msg = &mt('Once the following tasks are complete:')." \n".
 8700:                                        join(", ",sort(values(%locks)))."\n";
 8701:                                 if (&show_course()) {
 8702:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
 8703:                                 } else {
 8704:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
 8705:                                 }
 8706:                             } else {
 8707:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
 8708:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
 8709:                                 }
 8710:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
 8711:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
 8712:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
 8713:                                     $newurl .= '&role='.$env{'request.role'};
 8714:                                 }
 8715:                                 if ($env{'request.symb'}) {
 8716:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
 8717:                                     if ($shownsymb =~ m{^/enc/}) {
 8718:                                         my $reqdmajor = 2;
 8719:                                         my $reqdminor = 11;
 8720:                                         my $reqdsubminor = 3;
 8721:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
 8722:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
 8723:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
 8724:                                         if (($major eq '' && $minor eq '') ||
 8725:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
 8726:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
 8727:                                              ($reqdsubminor > $subminor))))) {
 8728:                                             undef($shownsymb);
 8729:                                         }
 8730:                                     }
 8731:                                     if ($shownsymb) {
 8732:                                         &js_escape(\$shownsymb);
 8733:                                         $newurl .= '&symb='.$shownsymb;
 8734:                                     }
 8735:                                 } else {
 8736:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
 8737:                                     &js_escape(\$shownurl);
 8738:                                     $newurl .= '&origurl='.$shownurl;
 8739:                                 }
 8740:                             }
 8741:                             &js_escape(\$msg);
 8742:                             $result.=<<OFFLOAD
 8743: <meta http-equiv="pragma" content="no-cache" />
 8744: <script type="text/javascript">
 8745: // <![CDATA[
 8746: function LC_Offload_Now() {
 8747:     var dest = "$newurl";
 8748:     if (dest != '') {
 8749:         window.location.href="$newurl";
 8750:     }
 8751: }
 8752: \$(document).ready(function () {
 8753:     window.alert('$msg');
 8754:     if ($disable_submit) {
 8755:         \$(".LC_hwk_submit").prop("disabled", true);
 8756:         \$( ".LC_textline" ).prop( "readonly", "readonly");
 8757:     }
 8758:     setTimeout('LC_Offload_Now()', $timeout);
 8759: });
 8760: // ]]>
 8761: </script>
 8762: OFFLOAD
 8763:                         }
 8764:                     }
 8765:                 }
 8766:             }
 8767:         }
 8768:     }
 8769:     if (!defined($title)) {
 8770: 	$title = 'The LearningOnline Network with CAPA';
 8771:     }
 8772:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 8773:     $result .= '<title> LON-CAPA '.$title.'</title>'
 8774: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
 8775:     if (!$args->{'frameset'}) {
 8776:         $result .= ' /';
 8777:     }
 8778:     $result .= '>' 
 8779:         .$inhibitprint
 8780: 	.$head_extra;
 8781:     my $clientmobile;
 8782:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 8783:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
 8784:     } else {
 8785:         $clientmobile = $env{'browser.mobile'};
 8786:     }
 8787:     if ($clientmobile) {
 8788:         $result .= '
 8789: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 8790: <meta name="apple-mobile-web-app-capable" content="yes" />';
 8791:     }
 8792:     $result .= '<meta name="google" content="notranslate" />'."\n";
 8793:     return $result.'</head>';
 8794: }
 8795: 
 8796: =pod
 8797: 
 8798: =item * &font_settings()
 8799: 
 8800: Returns neccessary <meta> to set the proper encoding
 8801: 
 8802: Inputs: optional reference to HASH -- $args passed to &headtag()
 8803: 
 8804: =cut
 8805: 
 8806: sub font_settings {
 8807:     my ($args) = @_;
 8808:     my $headerstring='';
 8809:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
 8810:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
 8811:         $headerstring.=
 8812:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
 8813:         if (!$args->{'frameset'}) {
 8814: 	    $headerstring.= ' /';
 8815:         }
 8816: 	$headerstring .= '>'."\n";
 8817:     }
 8818:     return $headerstring;
 8819: }
 8820: 
 8821: =pod
 8822: 
 8823: =item * &print_suppression()
 8824: 
 8825: In course context returns css which causes the body to be blank when media="print",
 8826: if printout generation is unavailable for the current resource.
 8827: 
 8828: This could be because:
 8829: 
 8830: (a) printstartdate is in the future
 8831: 
 8832: (b) printenddate is in the past
 8833: 
 8834: (c) there is an active exam block with "printout"
 8835: functionality blocked
 8836: 
 8837: Users with pav, pfo or evb privileges are exempt.
 8838: 
 8839: Inputs: none
 8840: 
 8841: =cut
 8842: 
 8843: 
 8844: sub print_suppression {
 8845:     my $noprint;
 8846:     if ($env{'request.course.id'}) {
 8847:         my $scope = $env{'request.course.id'};
 8848:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8849:             (&Apache::lonnet::allowed('pfo',$scope))) {
 8850:             return;
 8851:         }
 8852:         if ($env{'request.course.sec'} ne '') {
 8853:             $scope .= "/$env{'request.course.sec'}";
 8854:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8855:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 8856:                 return;
 8857:             }
 8858:         }
 8859:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8860:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8861:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
 8862:         if ($blocked) {
 8863:             my $checkrole = "cm./$cdom/$cnum";
 8864:             if ($env{'request.course.sec'} ne '') {
 8865:                 $checkrole .= "/$env{'request.course.sec'}";
 8866:             }
 8867:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 8868:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 8869:                 $noprint = 1;
 8870:             }
 8871:         }
 8872:         unless ($noprint) {
 8873:             my $symb = &Apache::lonnet::symbread();
 8874:             if ($symb ne '') {
 8875:                 my $navmap = Apache::lonnavmaps::navmap->new();
 8876:                 if (ref($navmap)) {
 8877:                     my $res = $navmap->getBySymb($symb);
 8878:                     if (ref($res)) {
 8879:                         if (!$res->resprintable()) {
 8880:                             $noprint = 1;
 8881:                         }
 8882:                     }
 8883:                 }
 8884:             }
 8885:         }
 8886:         if ($noprint) {
 8887:             return <<"ENDSTYLE";
 8888: <style type="text/css" media="print">
 8889:     body { display:none }
 8890: </style>
 8891: ENDSTYLE
 8892:         }
 8893:     }
 8894:     return;
 8895: }
 8896: 
 8897: =pod
 8898: 
 8899: =item * &xml_begin()
 8900: 
 8901: Returns the needed doctype and <html>
 8902: 
 8903: Inputs: none
 8904: 
 8905: =cut
 8906: 
 8907: sub xml_begin {
 8908:     my ($is_frameset) = @_;
 8909:     my $output='';
 8910: 
 8911:     if ($env{'browser.mathml'}) {
 8912: 	$output='<?xml version="1.0"?>'
 8913:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 8914: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 8915:             
 8916: #	    .'<!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">] >'
 8917: 	    .'<!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">'
 8918:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 8919: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 8920:     } elsif ($is_frameset) {
 8921:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
 8922:                 '<html>'."\n";
 8923:     } else {
 8924: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
 8925:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
 8926:     }
 8927:     return $output;
 8928: }
 8929: 
 8930: =pod
 8931: 
 8932: =item * &start_page()
 8933: 
 8934: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 8935: 
 8936: Inputs:
 8937: 
 8938: =over 4
 8939: 
 8940: $title - optional title for the page
 8941: 
 8942: $head_extra - optional extra HTML to incude inside the <head>
 8943: 
 8944: $args - additional optional args supported are:
 8945: 
 8946: =over 8
 8947: 
 8948:              only_body      -> is true will set &bodytag() onlybodytag
 8949:                                     arg on
 8950:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 8951:              add_entries    -> additional attributes to add to the  <body>
 8952:              domain         -> force to color decorate a page for a 
 8953:                                     specific domain
 8954:              function       -> force usage of a specific rolish color
 8955:                                     scheme
 8956:              redirect       -> see &headtag()
 8957:              bgcolor        -> override the default page bg color
 8958:              js_ready       -> return a string ready for being used in 
 8959:                                     a javascript writeln
 8960:              html_encode    -> return a string ready for being used in 
 8961:                                     a html attribute
 8962:              force_register -> if is true will turn on the &bodytag()
 8963:                                     $forcereg arg
 8964:              frameset       -> if true will start with a <frameset>
 8965:                                     rather than <body>
 8966:              skip_phases    -> hash ref of 
 8967:                                     head -> skip the <html><head> generation
 8968:                                     body -> skip all <body> generation
 8969:              no_auto_mt_title -> prevent &mt()ing the title arg
 8970:              bread_crumbs ->             Array containing breadcrumbs
 8971:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 8972:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
 8973:                                     to lonhtmlcommon::breadcrumbs
 8974:              group          -> includes the current group, if page is for a 
 8975:                                specific group
 8976:              use_absolute   -> for request for external resource or syllabus, this
 8977:                                will contain https://<hostname> if server uses
 8978:                                https (as per hosts.tab), but request is for http
 8979:              hostname       -> hostname, originally from $r->hostname(), (optional).
 8980:              links_disabled -> Links in primary and secondary menus are disabled
 8981:                                (Can enable them once page has loaded - see lonroles.pm
 8982:                                for an example).
 8983: 
 8984: =back
 8985: 
 8986: =back
 8987: 
 8988: =cut
 8989: 
 8990: sub start_page {
 8991:     my ($title,$head_extra,$args) = @_;
 8992:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 8993: 
 8994:     $env{'internal.start_page'}++;
 8995:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
 8996: 
 8997:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 8998:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
 8999:     }
 9000: 
 9001:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
 9002:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
 9003:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
 9004:                 $args->{'no_primary_menu'} = 1;
 9005:             }
 9006:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
 9007:                 $args->{'no_inline_menu'} = 1;
 9008:             }
 9009:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
 9010:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
 9011:             }
 9012:         } else {
 9013:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9014:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
 9015:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
 9016:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
 9017:                     $args->{'no_primary_menu'} = 1;
 9018:                 }
 9019:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
 9020:                     $args->{'no_inline_menu'} = 1;
 9021:                 }
 9022:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
 9023:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
 9024:                 }
 9025:             }
 9026:         }
 9027:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
 9028:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
 9029:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
 9030:     } elsif ($env{'request.course.id'}) {
 9031:         my $expiretime=600;
 9032:         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
 9033:             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
 9034:         }
 9035:         my ($deeplinkmenu,$menuref);
 9036:         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
 9037:         if ($menucoll) {
 9038:             if (ref($menuref) eq 'HASH') {
 9039:                 %menu = %{$menuref};
 9040:             }
 9041:             if ($menu{'top'} eq 'n') {
 9042:                 $args->{'no_primary_menu'} = 1;
 9043:             }
 9044:             if ($menu{'inline'} eq 'n') {
 9045:                 unless (&Apache::lonnet::allowed('opa')) {
 9046:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9047:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9048:                     my $crstype = &course_type();
 9049:                     my $now = time;
 9050:                     my $ccrole;
 9051:                     if ($crstype eq 'Community') {
 9052:                         $ccrole = 'co';
 9053:                     } else {
 9054:                         $ccrole = 'cc';
 9055:                     }
 9056:                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
 9057:                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
 9058:                         if ((($start) && ($start<0)) ||
 9059:                             (($end) && ($end<$now))  ||
 9060:                             (($start) && ($now<$start))) {
 9061:                             $args->{'no_inline_menu'} = 1;
 9062:                         }
 9063:                     } else {
 9064:                         $args->{'no_inline_menu'} = 1;
 9065:                     }
 9066:                 }
 9067:             }
 9068:         }
 9069:     }
 9070: 
 9071:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 9072: 	if ($args->{'frameset'}) {
 9073: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 9074: 						$args->{'add_entries'});
 9075: 	    $result .= "\n<frameset $attr_string>\n";
 9076:         } else {
 9077:             $result .=
 9078:                 &bodytag($title, 
 9079:                          $args->{'function'},       $args->{'add_entries'},
 9080:                          $args->{'only_body'},      $args->{'domain'},
 9081:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 9082:                          $args->{'bgcolor'},        $args,
 9083:                          \@advtools,$ltiscope,$ltiuri,\%ltimenu,$menucoll,\%menu);
 9084:         }
 9085:     }
 9086: 
 9087:     if ($args->{'js_ready'}) {
 9088: 		$result = &js_ready($result);
 9089:     }
 9090:     if ($args->{'html_encode'}) {
 9091: 		$result = &html_encode($result);
 9092:     }
 9093: 
 9094:     # Preparation for new and consistent functionlist at top of screen
 9095:     # if ($args->{'functionlist'}) {
 9096:     #            $result .= &build_functionlist();
 9097:     #}
 9098: 
 9099:     # Don't add anything more if only_body wanted or in const space
 9100:     return $result if    $args->{'only_body'} 
 9101:                       || $env{'request.state'} eq 'construct';
 9102: 
 9103:     #Breadcrumbs
 9104:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 9105: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 9106: 		#if any br links exists, add them to the breadcrumbs
 9107: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 9108: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 9109: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 9110: 			}
 9111: 		}
 9112:                 # if @advtools array contains items add then to the breadcrumbs
 9113:                 if (@advtools > 0) {
 9114:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 9115:                 }
 9116:                 my $menulink;
 9117:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
 9118:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
 9119:                      ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
 9120:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
 9121:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
 9122:                      (!$env{'request.role.adv'}))) {
 9123:                     $menulink = 0;
 9124:                 } else {
 9125:                     undef($menulink);
 9126:                 }
 9127: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 9128: 		if(exists($args->{'bread_crumbs_component'})){
 9129: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
 9130:                 } else {
 9131: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
 9132: 		}
 9133:     }
 9134:     return $result;
 9135: }
 9136: 
 9137: sub end_page {
 9138:     my ($args) = @_;
 9139:     $env{'internal.end_page'}++;
 9140:     my $result;
 9141:     if ($args->{'discussion'}) {
 9142: 	my ($target,$parser);
 9143: 	if (ref($args->{'discussion'})) {
 9144: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 9145: 				$args->{'discussion'}{'parser'});
 9146: 	}
 9147: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 9148:     }
 9149:     if ($args->{'frameset'}) {
 9150: 	$result .= '</frameset>';
 9151:     } else {
 9152: 	$result .= &endbodytag($args);
 9153:     }
 9154:     unless ($args->{'notbody'}) {
 9155:         $result .= "\n</html>";
 9156:     }
 9157: 
 9158:     if ($args->{'js_ready'}) {
 9159: 	$result = &js_ready($result);
 9160:     }
 9161: 
 9162:     if ($args->{'html_encode'}) {
 9163: 	$result = &html_encode($result);
 9164:     }
 9165: 
 9166:     return $result;
 9167: }
 9168: 
 9169: sub menucoll_in_effect {
 9170:     my ($menucoll,$deeplinkmenu,%menu);
 9171:     if ($env{'request.course.id'}) {
 9172:         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
 9173:         if ($env{'request.deeplink.login'}) {
 9174:             my ($deeplink_symb,$deeplink,$check_login_symb);
 9175:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9176:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9177:             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
 9178:                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
 9179:                     my $navmap = Apache::lonnavmaps::navmap->new();
 9180:                     if (ref($navmap)) {
 9181:                         $deeplink = $navmap->get_mapparam(undef,
 9182:                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
 9183:                                                           '0.deeplink');
 9184:                     } else {
 9185:                         $check_login_symb = 1;
 9186:                     }
 9187:                 } else {
 9188:                     my $symb = &Apache::lonnet::symbread();
 9189:                     if ($symb) {
 9190:                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
 9191:                     } else {
 9192:                         $check_login_symb = 1;
 9193:                     }
 9194:                 }
 9195:             } else {
 9196:                 $check_login_symb = 1;
 9197:             }
 9198:             if ($check_login_symb) {
 9199:                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
 9200:                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
 9201:                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
 9202:                     my $navmap = Apache::lonnavmaps::navmap->new();
 9203:                     if (ref($navmap)) {
 9204:                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
 9205:                     }
 9206:                 } else {
 9207:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
 9208:                 }
 9209:             }
 9210:             if ($deeplink ne '') {
 9211:                 my ($state,$others,$listed,$scope,$protect,$display) = split(/,/,$deeplink);
 9212:                 if ($display =~ /^\d+$/) {
 9213:                     $deeplinkmenu = 1;
 9214:                     $menucoll = $display;
 9215:                 }
 9216:             }
 9217:         }
 9218:         if ($menucoll) {
 9219:             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
 9220:         }
 9221:     }
 9222:     return ($menucoll,$deeplinkmenu,\%menu);
 9223: }
 9224: 
 9225: sub deeplink_login_symb {
 9226:     my ($cnum,$cdom) = @_;
 9227:     my $login_symb;
 9228:     if ($env{'request.deeplink.login'}) {
 9229:         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
 9230:     }
 9231:     return $login_symb;
 9232: }
 9233: 
 9234: sub symb_from_tinyurl {
 9235:     my ($url,$cnum,$cdom) = @_;
 9236:     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
 9237:         my $key = $1;
 9238:         my ($tinyurl,$login);
 9239:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
 9240:         if (defined($cached)) {
 9241:             $tinyurl = $result;
 9242:         } else {
 9243:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
 9244:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
 9245:             if ($currtiny{$key} ne '') {
 9246:                 $tinyurl = $currtiny{$key};
 9247:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
 9248:             }
 9249:         }
 9250:         if ($tinyurl ne '') {
 9251:             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
 9252:             if (wantarray) {
 9253:                 return ($cnumreq,$symb);
 9254:             } elsif ($cnumreq eq $cnum) {
 9255:                 return $symb;
 9256:             }
 9257:         }
 9258:     }
 9259:     if (wantarray) {
 9260:         return ();
 9261:     } else {
 9262:         return;
 9263:     }
 9264: }
 9265: 
 9266: sub wishlist_window {
 9267:     return(<<'ENDWISHLIST');
 9268: <script type="text/javascript">
 9269: // <![CDATA[
 9270: // <!-- BEGIN LON-CAPA Internal
 9271: function set_wishlistlink(title, path) {
 9272:     if (!title) {
 9273:         title = document.title;
 9274:         title = title.replace(/^LON-CAPA /,'');
 9275:     }
 9276:     title = encodeURIComponent(title);
 9277:     title = title.replace("'","\\\'");
 9278:     if (!path) {
 9279:         path = location.pathname;
 9280:     }
 9281:     path = encodeURIComponent(path);
 9282:     path = path.replace("'","\\\'");
 9283:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 9284:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 9285: }
 9286: // END LON-CAPA Internal -->
 9287: // ]]>
 9288: </script>
 9289: ENDWISHLIST
 9290: }
 9291: 
 9292: sub modal_window {
 9293:     return(<<'ENDMODAL');
 9294: <script type="text/javascript">
 9295: // <![CDATA[
 9296: // <!-- BEGIN LON-CAPA Internal
 9297: var modalWindow = {
 9298: 	parent:"body",
 9299: 	windowId:null,
 9300: 	content:null,
 9301: 	width:null,
 9302: 	height:null,
 9303: 	close:function()
 9304: 	{
 9305: 	        $(".LCmodal-window").remove();
 9306: 	        $(".LCmodal-overlay").remove();
 9307: 	},
 9308: 	open:function()
 9309: 	{
 9310: 		var modal = "";
 9311: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 9312: 		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;\">";
 9313: 		modal += this.content;
 9314: 		modal += "</div>";	
 9315: 
 9316: 		$(this.parent).append(modal);
 9317: 
 9318: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 9319: 		$(".LCclose-window").click(function(){modalWindow.close();});
 9320: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 9321: 	}
 9322: };
 9323: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
 9324: 	{
 9325:                 source = source.replace(/'/g,"&#39;");
 9326: 		modalWindow.windowId = "myModal";
 9327: 		modalWindow.width = width;
 9328: 		modalWindow.height = height;
 9329: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
 9330: 		modalWindow.open();
 9331: 	};
 9332: // END LON-CAPA Internal -->
 9333: // ]]>
 9334: </script>
 9335: ENDMODAL
 9336: }
 9337: 
 9338: sub modal_link {
 9339:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
 9340:     unless ($width) { $width=480; }
 9341:     unless ($height) { $height=400; }
 9342:     unless ($scrolling) { $scrolling='yes'; }
 9343:     unless ($transparency) { $transparency='true'; }
 9344: 
 9345:     my $target_attr;
 9346:     if (defined($target)) {
 9347:         $target_attr = 'target="'.$target.'"';
 9348:     }
 9349:     return <<"ENDLINK";
 9350: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
 9351: ENDLINK
 9352: }
 9353: 
 9354: sub modal_adhoc_script {
 9355:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
 9356:     my $mathjax;
 9357:     if ($possmathjax) {
 9358:         $mathjax = <<'ENDJAX';
 9359:                if (typeof MathJax == 'object') {
 9360:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
 9361:                }
 9362: ENDJAX
 9363:     }
 9364:     return (<<ENDADHOC);
 9365: <script type="text/javascript">
 9366: // <![CDATA[
 9367:         var $funcname = function()
 9368:         {
 9369:                 modalWindow.windowId = "myModal";
 9370:                 modalWindow.width = $width;
 9371:                 modalWindow.height = $height;
 9372:                 modalWindow.content = '$content';
 9373:                 modalWindow.open();
 9374:                 $mathjax
 9375:         };  
 9376: // ]]>
 9377: </script>
 9378: ENDADHOC
 9379: }
 9380: 
 9381: sub modal_adhoc_inner {
 9382:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
 9383:     my $innerwidth=$width-20;
 9384:     $content=&js_ready(
 9385:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 9386:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
 9387:                  $content.
 9388:                  &end_scrollbox().
 9389:                  &end_page()
 9390:              );
 9391:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
 9392: }
 9393: 
 9394: sub modal_adhoc_window {
 9395:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
 9396:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
 9397:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 9398: }
 9399: 
 9400: sub modal_adhoc_launch {
 9401:     my ($funcname,$width,$height,$content)=@_;
 9402:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 9403: <script type="text/javascript">
 9404: // <![CDATA[
 9405: $funcname();
 9406: // ]]>
 9407: </script>
 9408: ENDLAUNCH
 9409: }
 9410: 
 9411: sub modal_adhoc_close {
 9412:     return (<<ENDCLOSE);
 9413: <script type="text/javascript">
 9414: // <![CDATA[
 9415: modalWindow.close();
 9416: // ]]>
 9417: </script>
 9418: ENDCLOSE
 9419: }
 9420: 
 9421: sub togglebox_script {
 9422:    return(<<ENDTOGGLE);
 9423: <script type="text/javascript"> 
 9424: // <![CDATA[
 9425: function LCtoggleDisplay(id,hidetext,showtext) {
 9426:    link = document.getElementById(id + "link").childNodes[0];
 9427:    with (document.getElementById(id).style) {
 9428:       if (display == "none" ) {
 9429:           display = "inline";
 9430:           link.nodeValue = hidetext;
 9431:         } else {
 9432:           display = "none";
 9433:           link.nodeValue = showtext;
 9434:        }
 9435:    }
 9436: }
 9437: // ]]>
 9438: </script>
 9439: ENDTOGGLE
 9440: }
 9441: 
 9442: sub start_togglebox {
 9443:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 9444:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 9445:     unless ($showtext) { $showtext=&mt('show'); }
 9446:     unless ($hidetext) { $hidetext=&mt('hide'); }
 9447:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 9448:     return &start_data_table().
 9449:            &start_data_table_header_row().
 9450:            '<td bgcolor="'.$headerbg.'">'.$heading.
 9451:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 9452:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 9453:            &end_data_table_header_row().
 9454:            '<tr id="'.$id.'" style="display:none""><td>';
 9455: }
 9456: 
 9457: sub end_togglebox {
 9458:     return '</td></tr>'.&end_data_table();
 9459: }
 9460: 
 9461: sub LCprogressbar_script {
 9462:    my ($id,$number_to_do)=@_;
 9463:    if ($number_to_do) {
 9464:        return(<<ENDPROGRESS);
 9465: <script type="text/javascript">
 9466: // <![CDATA[
 9467: \$('#progressbar$id').progressbar({
 9468:   value: 0,
 9469:   change: function(event, ui) {
 9470:     var newVal = \$(this).progressbar('option', 'value');
 9471:     \$('.pblabel', this).text(LCprogressTxt);
 9472:   }
 9473: });
 9474: // ]]>
 9475: </script>
 9476: ENDPROGRESS
 9477:    } else {
 9478:        return(<<ENDPROGRESS);
 9479: <script type="text/javascript">
 9480: // <![CDATA[
 9481: \$('#progressbar$id').progressbar({
 9482:   value: false,
 9483:   create: function(event, ui) {
 9484:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
 9485:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
 9486:   }
 9487: });
 9488: // ]]>
 9489: </script>
 9490: ENDPROGRESS
 9491:    }
 9492: }
 9493: 
 9494: sub LCprogressbarUpdate_script {
 9495:    return(<<ENDPROGRESSUPDATE);
 9496: <style type="text/css">
 9497: .ui-progressbar { position:relative; }
 9498: .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%; }
 9499: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 9500: </style>
 9501: <script type="text/javascript">
 9502: // <![CDATA[
 9503: var LCprogressTxt='---';
 9504: 
 9505: function LCupdateProgress(percent,progresstext,id,maxnum) {
 9506:    LCprogressTxt=progresstext;
 9507:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
 9508:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
 9509:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
 9510:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
 9511:    } else {
 9512:        \$('#progressbar'+id).progressbar('value',percent);
 9513:    }
 9514: }
 9515: // ]]>
 9516: </script>
 9517: ENDPROGRESSUPDATE
 9518: }
 9519: 
 9520: my $LClastpercent;
 9521: my $LCidcnt;
 9522: my $LCcurrentid;
 9523: 
 9524: sub LCprogressbar {
 9525:     my ($r,$number_to_do,$preamble)=@_;
 9526:     $LClastpercent=0;
 9527:     $LCidcnt++;
 9528:     $LCcurrentid=$$.'_'.$LCidcnt;
 9529:     my ($starting,$content);
 9530:     if ($number_to_do) {
 9531:         $starting=&mt('Starting');
 9532:         $content=(<<ENDPROGBAR);
 9533: $preamble
 9534:   <div id="progressbar$LCcurrentid">
 9535:     <span class="pblabel">$starting</span>
 9536:   </div>
 9537: ENDPROGBAR
 9538:     } else {
 9539:         $starting=&mt('Loading...');
 9540:         $LClastpercent='false';
 9541:         $content=(<<ENDPROGBAR);
 9542: $preamble
 9543:   <div id="progressbar$LCcurrentid">
 9544:       <div class="progress-label">$starting</div>
 9545:   </div>
 9546: ENDPROGBAR
 9547:     }
 9548:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
 9549: }
 9550: 
 9551: sub LCprogressbarUpdate {
 9552:     my ($r,$val,$text,$number_to_do)=@_;
 9553:     if ($number_to_do) {
 9554:         unless ($val) { 
 9555:             if ($LClastpercent) {
 9556:                 $val=$LClastpercent;
 9557:             } else {
 9558:                 $val=0;
 9559:             }
 9560:         }
 9561:         if ($val<0) { $val=0; }
 9562:         if ($val>100) { $val=0; }
 9563:         $LClastpercent=$val;
 9564:         unless ($text) { $text=$val.'%'; }
 9565:     } else {
 9566:         $val = 'false';
 9567:     }
 9568:     $text=&js_ready($text);
 9569:     &r_print($r,<<ENDUPDATE);
 9570: <script type="text/javascript">
 9571: // <![CDATA[
 9572: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
 9573: // ]]>
 9574: </script>
 9575: ENDUPDATE
 9576: }
 9577: 
 9578: sub LCprogressbarClose {
 9579:     my ($r)=@_;
 9580:     $LClastpercent=0;
 9581:     &r_print($r,<<ENDCLOSE);
 9582: <script type="text/javascript">
 9583: // <![CDATA[
 9584: \$("#progressbar$LCcurrentid").hide('slow'); 
 9585: // ]]>
 9586: </script>
 9587: ENDCLOSE
 9588: }
 9589: 
 9590: sub r_print {
 9591:     my ($r,$to_print)=@_;
 9592:     if ($r) {
 9593:       $r->print($to_print);
 9594:       $r->rflush();
 9595:     } else {
 9596:       print($to_print);
 9597:     }
 9598: }
 9599: 
 9600: sub html_encode {
 9601:     my ($result) = @_;
 9602: 
 9603:     $result = &HTML::Entities::encode($result,'<>&"');
 9604:     
 9605:     return $result;
 9606: }
 9607: 
 9608: sub js_ready {
 9609:     my ($result) = @_;
 9610: 
 9611:     $result =~ s/[\n\r]/ /xmsg;
 9612:     $result =~ s/\\/\\\\/xmsg;
 9613:     $result =~ s/'/\\'/xmsg;
 9614:     $result =~ s{</}{<\\/}xmsg;
 9615:     
 9616:     return $result;
 9617: }
 9618: 
 9619: sub validate_page {
 9620:     if (  exists($env{'internal.start_page'})
 9621: 	  &&     $env{'internal.start_page'} > 1) {
 9622: 	&Apache::lonnet::logthis('start_page called multiple times '.
 9623: 				 $env{'internal.start_page'}.' '.
 9624: 				 $ENV{'request.filename'});
 9625:     }
 9626:     if (  exists($env{'internal.end_page'})
 9627: 	  &&     $env{'internal.end_page'} > 1) {
 9628: 	&Apache::lonnet::logthis('end_page called multiple times '.
 9629: 				 $env{'internal.end_page'}.' '.
 9630: 				 $env{'request.filename'});
 9631:     }
 9632:     if (     exists($env{'internal.start_page'})
 9633: 	&& ! exists($env{'internal.end_page'})) {
 9634: 	&Apache::lonnet::logthis('start_page called without end_page '.
 9635: 				 $env{'request.filename'});
 9636:     }
 9637:     if (   ! exists($env{'internal.start_page'})
 9638: 	&&   exists($env{'internal.end_page'})) {
 9639: 	&Apache::lonnet::logthis('end_page called without start_page'.
 9640: 				 $env{'request.filename'});
 9641:     }
 9642: }
 9643: 
 9644: 
 9645: sub start_scrollbox {
 9646:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
 9647:     unless ($outerwidth) { $outerwidth='520px'; }
 9648:     unless ($width) { $width='500px'; }
 9649:     unless ($height) { $height='200px'; }
 9650:     my ($table_id,$div_id,$tdcol);
 9651:     if ($id ne '') {
 9652:         $table_id = ' id="table_'.$id.'"';
 9653:         $div_id = ' id="div_'.$id.'"';
 9654:     }
 9655:     if ($bgcolor ne '') {
 9656:         $tdcol = "background-color: $bgcolor;";
 9657:     }
 9658:     my $nicescroll_js;
 9659:     if ($env{'browser.mobile'}) {
 9660:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
 9661:     }
 9662:     return <<"END";
 9663: $nicescroll_js
 9664: 
 9665: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
 9666: <div style="overflow:auto; width:$width; height:$height;"$div_id>
 9667: END
 9668: }
 9669: 
 9670: sub end_scrollbox {
 9671:     return '</div></td></tr></table>';
 9672: }
 9673: 
 9674: sub nicescroll_javascript {
 9675:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
 9676:     my %options;
 9677:     if (ref($cursor) eq 'HASH') {
 9678:         %options = %{$cursor};
 9679:     }
 9680:     unless ($options{'railalign'} =~ /^left|right$/) {
 9681:         $options{'railalign'} = 'left';
 9682:     }
 9683:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 9684:         my $function  = &get_users_function();
 9685:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
 9686:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 9687:             $options{'cursorcolor'} = '#00F';
 9688:         }
 9689:     }
 9690:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
 9691:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
 9692:             $options{'cursoropacity'}='1.0';
 9693:         }
 9694:     } else {
 9695:         $options{'cursoropacity'}='1.0';
 9696:     }
 9697:     if ($options{'cursorfixedheight'} eq 'none') {
 9698:         delete($options{'cursorfixedheight'});
 9699:     } else {
 9700:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
 9701:     }
 9702:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
 9703:         delete($options{'railoffset'});
 9704:     }
 9705:     my @niceoptions;
 9706:     while (my($key,$value) = each(%options)) {
 9707:         if ($value =~ /^\{.+\}$/) {
 9708:             push(@niceoptions,$key.':'.$value);
 9709:         } else {
 9710:             push(@niceoptions,$key.':"'.$value.'"');
 9711:         }
 9712:     }
 9713:     my $nicescroll_js = '
 9714: $(document).ready(
 9715:       function() {
 9716:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
 9717:       }
 9718: );
 9719: ';
 9720:     if ($framecheck) {
 9721:         $nicescroll_js .= '
 9722: function expand_div(caller) {
 9723:     if (top === self) {
 9724:         document.getElementById("'.$id.'").style.width = "auto";
 9725:         document.getElementById("'.$id.'").style.height = "auto";
 9726:     } else {
 9727:         try {
 9728:             if (parent.frames) {
 9729:                 if (parent.frames.length > 1) {
 9730:                     var framesrc = parent.frames[1].location.href;
 9731:                     var currsrc = framesrc.replace(/\#.*$/,"");
 9732:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
 9733:                         document.getElementById("'.$id.'").style.width = "auto";
 9734:                         document.getElementById("'.$id.'").style.height = "auto";
 9735:                     }
 9736:                 }
 9737:             }
 9738:         } catch (e) {
 9739:             return;
 9740:         }
 9741:     }
 9742:     return;
 9743: }
 9744: ';
 9745:     }
 9746:     if ($needjsready) {
 9747:         $nicescroll_js = '
 9748: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
 9749:     } else {
 9750:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
 9751:     }
 9752:     return $nicescroll_js;
 9753: }
 9754: 
 9755: sub simple_error_page {
 9756:     my ($r,$title,$msg,$args) = @_;
 9757:     my %displayargs;
 9758:     if (ref($args) eq 'HASH') {
 9759:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
 9760:         if ($args->{'only_body'}) {
 9761:             $displayargs{'only_body'} = 1;
 9762:         }
 9763:         if ($args->{'no_nav_bar'}) {
 9764:             $displayargs{'no_nav_bar'} = 1;
 9765:         }
 9766:     } else {
 9767:         $msg = &mt($msg);
 9768:     }
 9769: 
 9770:     my $page =
 9771: 	&Apache::loncommon::start_page($title,'',\%displayargs).
 9772: 	'<p class="LC_error">'.$msg.'</p>'.
 9773: 	&Apache::loncommon::end_page();
 9774:     if (ref($r)) {
 9775: 	$r->print($page);
 9776: 	return;
 9777:     }
 9778:     return $page;
 9779: }
 9780: 
 9781: {
 9782:     my @row_count;
 9783: 
 9784:     sub start_data_table_count {
 9785:         unshift(@row_count, 0);
 9786:         return;
 9787:     }
 9788: 
 9789:     sub end_data_table_count {
 9790:         shift(@row_count);
 9791:         return;
 9792:     }
 9793: 
 9794:     sub start_data_table {
 9795: 	my ($add_class,$id) = @_;
 9796: 	my $css_class = (join(' ','LC_data_table',$add_class));
 9797:         my $table_id;
 9798:         if (defined($id)) {
 9799:             $table_id = ' id="'.$id.'"';
 9800:         }
 9801: 	&start_data_table_count();
 9802: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 9803:     }
 9804: 
 9805:     sub end_data_table {
 9806: 	&end_data_table_count();
 9807: 	return '</table>'."\n";;
 9808:     }
 9809: 
 9810:     sub start_data_table_row {
 9811: 	my ($add_class, $id) = @_;
 9812: 	$row_count[0]++;
 9813: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 9814: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 9815:         $id = (' id="'.$id.'"') unless ($id eq '');
 9816:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 9817:     }
 9818:     
 9819:     sub continue_data_table_row {
 9820: 	my ($add_class, $id) = @_;
 9821: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 9822: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 9823:         $id = (' id="'.$id.'"') unless ($id eq '');
 9824:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 9825:     }
 9826: 
 9827:     sub end_data_table_row {
 9828: 	return '</tr>'."\n";;
 9829:     }
 9830: 
 9831:     sub start_data_table_empty_row {
 9832: #	$row_count[0]++;
 9833: 	return  '<tr class="LC_empty_row" >'."\n";;
 9834:     }
 9835: 
 9836:     sub end_data_table_empty_row {
 9837: 	return '</tr>'."\n";;
 9838:     }
 9839: 
 9840:     sub start_data_table_header_row {
 9841: 	return  '<tr class="LC_header_row">'."\n";;
 9842:     }
 9843: 
 9844:     sub end_data_table_header_row {
 9845: 	return '</tr>'."\n";;
 9846:     }
 9847: 
 9848:     sub data_table_caption {
 9849:         my $caption = shift;
 9850:         return "<caption class=\"LC_caption\">$caption</caption>";
 9851:     }
 9852: }
 9853: 
 9854: =pod
 9855: 
 9856: =item * &inhibit_menu_check($arg)
 9857: 
 9858: Checks for a inhibitmenu state and generates output to preserve it
 9859: 
 9860: Inputs:         $arg - can be any of
 9861:                      - undef - in which case the return value is a string 
 9862:                                to add  into arguments list of a uri
 9863:                      - 'input' - in which case the return value is a HTML
 9864:                                  <form> <input> field of type hidden to
 9865:                                  preserve the value
 9866:                      - a url - in which case the return value is the url with
 9867:                                the neccesary cgi args added to preserve the
 9868:                                inhibitmenu state
 9869:                      - a ref to a url - no return value, but the string is
 9870:                                         updated to include the neccessary cgi
 9871:                                         args to preserve the inhibitmenu state
 9872: 
 9873: =cut
 9874: 
 9875: sub inhibit_menu_check {
 9876:     my ($arg) = @_;
 9877:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 9878:     if ($arg eq 'input') {
 9879: 	if ($env{'form.inhibitmenu'}) {
 9880: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 9881: 	} else {
 9882: 	    return
 9883: 	}
 9884:     }
 9885:     if ($env{'form.inhibitmenu'}) {
 9886: 	if (ref($arg)) {
 9887: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 9888: 	} elsif ($arg eq '') {
 9889: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 9890: 	} else {
 9891: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 9892: 	}
 9893:     }
 9894:     if (!ref($arg)) {
 9895: 	return $arg;
 9896:     }
 9897: }
 9898: 
 9899: ###############################################
 9900: 
 9901: =pod
 9902: 
 9903: =back
 9904: 
 9905: =head1 User Information Routines
 9906: 
 9907: =over 4
 9908: 
 9909: =item * &get_users_function()
 9910: 
 9911: Used by &bodytag to determine the current users primary role.
 9912: Returns either 'student','coordinator','admin', or 'author'.
 9913: 
 9914: =cut
 9915: 
 9916: ###############################################
 9917: sub get_users_function {
 9918:     my $function = 'norole';
 9919:     if ($env{'request.role'}=~/^(st)/) {
 9920:         $function='student';
 9921:     }
 9922:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 9923:         $function='coordinator';
 9924:     }
 9925:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 9926:         $function='admin';
 9927:     }
 9928:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 9929:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 9930:         $function='author';
 9931:     }
 9932:     return $function;
 9933: }
 9934: 
 9935: ###############################################
 9936: 
 9937: =pod
 9938: 
 9939: =item * &show_course()
 9940: 
 9941: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 9942: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 9943: 
 9944: Inputs:
 9945: None
 9946: 
 9947: Outputs:
 9948: Scalar: 1 if 'Course' to be used, 0 otherwise.
 9949: 
 9950: =cut
 9951: 
 9952: ###############################################
 9953: sub show_course {
 9954:     my $course = !$env{'user.adv'};
 9955:     if (!$env{'user.adv'}) {
 9956:         foreach my $env (keys(%env)) {
 9957:             next if ($env !~ m/^user\.priv\./);
 9958:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 9959:                 $course = 0;
 9960:                 last;
 9961:             }
 9962:         }
 9963:     }
 9964:     return $course;
 9965: }
 9966: 
 9967: ###############################################
 9968: 
 9969: =pod
 9970: 
 9971: =item * &check_user_status()
 9972: 
 9973: Determines current status of supplied role for a
 9974: specific user. Roles can be active, previous or future.
 9975: 
 9976: Inputs: 
 9977: user's domain, user's username, course's domain,
 9978: course's number, optional section ID.
 9979: 
 9980: Outputs:
 9981: role status: active, previous or future. 
 9982: 
 9983: =cut
 9984: 
 9985: sub check_user_status {
 9986:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 9987:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 9988:     my @uroles = keys(%userinfo);
 9989:     my $srchstr;
 9990:     my $active_chk = 'none';
 9991:     my $now = time;
 9992:     if (@uroles > 0) {
 9993:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 9994:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 9995:         } else {
 9996:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 9997:         }
 9998:         if (grep/^\Q$srchstr\E$/,@uroles) {
 9999:             my $role_end = 0;
10000:             my $role_start = 0;
10001:             $active_chk = 'active';
10002:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
10003:                 $role_end = $1;
10004:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
10005:                     $role_start = $1;
10006:                 }
10007:             }
10008:             if ($role_start > 0) {
10009:                 if ($now < $role_start) {
10010:                     $active_chk = 'future';
10011:                 }
10012:             }
10013:             if ($role_end > 0) {
10014:                 if ($now > $role_end) {
10015:                     $active_chk = 'previous';
10016:                 }
10017:             }
10018:         }
10019:     }
10020:     return $active_chk;
10021: }
10022: 
10023: ###############################################
10024: 
10025: =pod
10026: 
10027: =item * &get_sections()
10028: 
10029: Determines all the sections for a course including
10030: sections with students and sections containing other roles.
10031: Incoming parameters: 
10032: 
10033: 1. domain
10034: 2. course number 
10035: 3. reference to array containing roles for which sections should 
10036: be gathered (optional).
10037: 4. reference to array containing status types for which sections 
10038: should be gathered (optional).
10039: 
10040: If the third argument is undefined, sections are gathered for any role. 
10041: If the fourth argument is undefined, sections are gathered for any status.
10042: Permissible values are 'active' or 'future' or 'previous'.
10043:  
10044: Returns section hash (keys are section IDs, values are
10045: number of users in each section), subject to the
10046: optional roles filter, optional status filter 
10047: 
10048: =cut
10049: 
10050: ###############################################
10051: sub get_sections {
10052:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
10053:     if (!defined($cdom) || !defined($cnum)) {
10054:         my $cid =  $env{'request.course.id'};
10055: 
10056: 	return if (!defined($cid));
10057: 
10058:         $cdom = $env{'course.'.$cid.'.domain'};
10059:         $cnum = $env{'course.'.$cid.'.num'};
10060:     }
10061: 
10062:     my %sectioncount;
10063:     my $now = time;
10064: 
10065:     my $check_students = 1;
10066:     my $only_students = 0;
10067:     if (ref($possible_roles) eq 'ARRAY') {
10068:         if (grep(/^st$/,@{$possible_roles})) {
10069:             if (@{$possible_roles} == 1) {
10070:                 $only_students = 1;
10071:             }
10072:         } else {
10073:             $check_students = 0;
10074:         }
10075:     }
10076: 
10077:     if ($check_students) { 
10078: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
10079: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
10080: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
10081:         my $start_index = &Apache::loncoursedata::CL_START();
10082:         my $end_index = &Apache::loncoursedata::CL_END();
10083:         my $status;
10084: 	while (my ($student,$data) = each(%$classlist)) {
10085: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
10086: 				                     $data->[$status_index],
10087:                                                      $data->[$start_index],
10088:                                                      $data->[$end_index]);
10089:             if ($stu_status eq 'Active') {
10090:                 $status = 'active';
10091:             } elsif ($end < $now) {
10092:                 $status = 'previous';
10093:             } elsif ($start > $now) {
10094:                 $status = 'future';
10095:             } 
10096: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
10097:                 if ((!defined($possible_status)) || (($status ne '') && 
10098:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
10099: 		    $sectioncount{$section}++;
10100:                 }
10101: 	    }
10102: 	}
10103:     }
10104:     if ($only_students) {
10105:         return %sectioncount;
10106:     }
10107:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10108:     foreach my $user (sort(keys(%courseroles))) {
10109: 	if ($user !~ /^(\w{2})/) { next; }
10110: 	my ($role) = ($user =~ /^(\w{2})/);
10111: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
10112: 	my ($section,$status);
10113: 	if ($role eq 'cr' &&
10114: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
10115: 	    $section=$1;
10116: 	}
10117: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
10118: 	if (!defined($section) || $section eq '-1') { next; }
10119:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
10120:         if ($end == -1 && $start == -1) {
10121:             next; #deleted role
10122:         }
10123:         if (!defined($possible_status)) { 
10124:             $sectioncount{$section}++;
10125:         } else {
10126:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
10127:                 $status = 'active';
10128:             } elsif ($end < $now) {
10129:                 $status = 'future';
10130:             } elsif ($start > $now) {
10131:                 $status = 'previous';
10132:             }
10133:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
10134:                 $sectioncount{$section}++;
10135:             }
10136:         }
10137:     }
10138:     return %sectioncount;
10139: }
10140: 
10141: ###############################################
10142: 
10143: =pod
10144: 
10145: =item * &get_course_users()
10146: 
10147: Retrieves usernames:domains for users in the specified course
10148: with specific role(s), and access status. 
10149: 
10150: Incoming parameters:
10151: 1. course domain
10152: 2. course number
10153: 3. access status: users must have - either active, 
10154: previous, future, or all.
10155: 4. reference to array of permissible roles
10156: 5. reference to array of section restrictions (optional)
10157: 6. reference to results object (hash of hashes).
10158: 7. reference to optional userdata hash
10159: 8. reference to optional statushash
10160: 9. flag if privileged users (except those set to unhide in
10161:    course settings) should be excluded    
10162: Keys of top level results hash are roles.
10163: Keys of inner hashes are username:domain, with 
10164: values set to access type.
10165: Optional userdata hash returns an array with arguments in the 
10166: same order as loncoursedata::get_classlist() for student data.
10167: 
10168: Optional statushash returns
10169: 
10170: Entries for end, start, section and status are blank because
10171: of the possibility of multiple values for non-student roles.
10172: 
10173: =cut
10174: 
10175: ###############################################
10176: 
10177: sub get_course_users {
10178:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
10179:     my %idx = ();
10180:     my %seclists;
10181: 
10182:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
10183:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
10184:     $idx{end} = &Apache::loncoursedata::CL_END();
10185:     $idx{start} = &Apache::loncoursedata::CL_START();
10186:     $idx{id} = &Apache::loncoursedata::CL_ID();
10187:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
10188:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
10189:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
10190: 
10191:     if (grep(/^st$/,@{$roles})) {
10192:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
10193:         my $now = time;
10194:         foreach my $student (keys(%{$classlist})) {
10195:             my $match = 0;
10196:             my $secmatch = 0;
10197:             my $section = $$classlist{$student}[$idx{section}];
10198:             my $status = $$classlist{$student}[$idx{status}];
10199:             if ($section eq '') {
10200:                 $section = 'none';
10201:             }
10202:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
10203:                 if (grep(/^all$/,@{$sections})) {
10204:                     $secmatch = 1;
10205:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
10206:                     if (grep(/^none$/,@{$sections})) {
10207:                         $secmatch = 1;
10208:                     }
10209:                 } else {  
10210: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
10211: 		        $secmatch = 1;
10212:                     }
10213: 		}
10214:                 if (!$secmatch) {
10215:                     next;
10216:                 }
10217:             }
10218:             if (defined($$types{'active'})) {
10219:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
10220:                     push(@{$$users{st}{$student}},'active');
10221:                     $match = 1;
10222:                 }
10223:             }
10224:             if (defined($$types{'previous'})) {
10225:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
10226:                     push(@{$$users{st}{$student}},'previous');
10227:                     $match = 1;
10228:                 }
10229:             }
10230:             if (defined($$types{'future'})) {
10231:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
10232:                     push(@{$$users{st}{$student}},'future');
10233:                     $match = 1;
10234:                 }
10235:             }
10236:             if ($match) {
10237:                 push(@{$seclists{$student}},$section);
10238:                 if (ref($userdata) eq 'HASH') {
10239:                     $$userdata{$student} = $$classlist{$student};
10240:                 }
10241:                 if (ref($statushash) eq 'HASH') {
10242:                     $statushash->{$student}{'st'}{$section} = $status;
10243:                 }
10244:             }
10245:         }
10246:     }
10247:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
10248:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10249:         my $now = time;
10250:         my %displaystatus = ( previous => 'Expired',
10251:                               active   => 'Active',
10252:                               future   => 'Future',
10253:                             );
10254:         my (%nothide,@possdoms);
10255:         if ($hidepriv) {
10256:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
10257:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
10258:                 if ($user !~ /:/) {
10259:                     $nothide{join(':',split(/[\@]/,$user))}=1;
10260:                 } else {
10261:                     $nothide{$user} = 1;
10262:                 }
10263:             }
10264:             my @possdoms = ($cdom);
10265:             if ($coursehash{'checkforpriv'}) {
10266:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
10267:             }
10268:         }
10269:         foreach my $person (sort(keys(%coursepersonnel))) {
10270:             my $match = 0;
10271:             my $secmatch = 0;
10272:             my $status;
10273:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
10274:             $user =~ s/:$//;
10275:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
10276:             if ($end == -1 || $start == -1) {
10277:                 next;
10278:             }
10279:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
10280:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
10281:                 my ($uname,$udom) = split(/:/,$user);
10282:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
10283:                     if (grep(/^all$/,@{$sections})) {
10284:                         $secmatch = 1;
10285:                     } elsif ($usec eq '') {
10286:                         if (grep(/^none$/,@{$sections})) {
10287:                             $secmatch = 1;
10288:                         }
10289:                     } else {
10290:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
10291:                             $secmatch = 1;
10292:                         }
10293:                     }
10294:                     if (!$secmatch) {
10295:                         next;
10296:                     }
10297:                 }
10298:                 if ($usec eq '') {
10299:                     $usec = 'none';
10300:                 }
10301:                 if ($uname ne '' && $udom ne '') {
10302:                     if ($hidepriv) {
10303:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
10304:                             (!$nothide{$uname.':'.$udom})) {
10305:                             next;
10306:                         }
10307:                     }
10308:                     if ($end > 0 && $end < $now) {
10309:                         $status = 'previous';
10310:                     } elsif ($start > $now) {
10311:                         $status = 'future';
10312:                     } else {
10313:                         $status = 'active';
10314:                     }
10315:                     foreach my $type (keys(%{$types})) { 
10316:                         if ($status eq $type) {
10317:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
10318:                                 push(@{$$users{$role}{$user}},$type);
10319:                             }
10320:                             $match = 1;
10321:                         }
10322:                     }
10323:                     if (($match) && (ref($userdata) eq 'HASH')) {
10324:                         if (!exists($$userdata{$uname.':'.$udom})) {
10325: 			    &get_user_info($udom,$uname,\%idx,$userdata);
10326:                         }
10327:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
10328:                             push(@{$seclists{$uname.':'.$udom}},$usec);
10329:                         }
10330:                         if (ref($statushash) eq 'HASH') {
10331:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
10332:                         }
10333:                     }
10334:                 }
10335:             }
10336:         }
10337:         if (grep(/^ow$/,@{$roles})) {
10338:             if ((defined($cdom)) && (defined($cnum))) {
10339:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
10340:                 if ( defined($csettings{'internal.courseowner'}) ) {
10341:                     my $owner = $csettings{'internal.courseowner'};
10342:                     next if ($owner eq '');
10343:                     my ($ownername,$ownerdom);
10344:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
10345:                         $ownername = $1;
10346:                         $ownerdom = $2;
10347:                     } else {
10348:                         $ownername = $owner;
10349:                         $ownerdom = $cdom;
10350:                         $owner = $ownername.':'.$ownerdom;
10351:                     }
10352:                     @{$$users{'ow'}{$owner}} = 'any';
10353:                     if (defined($userdata) && 
10354: 			!exists($$userdata{$owner})) {
10355: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
10356:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
10357:                             push(@{$seclists{$owner}},'none');
10358:                         }
10359:                         if (ref($statushash) eq 'HASH') {
10360:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
10361:                         }
10362: 		    }
10363:                 }
10364:             }
10365:         }
10366:         foreach my $user (keys(%seclists)) {
10367:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
10368:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
10369:         }
10370:     }
10371:     return;
10372: }
10373: 
10374: sub get_user_info {
10375:     my ($udom,$uname,$idx,$userdata) = @_;
10376:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
10377: 	&plainname($uname,$udom,'lastname');
10378:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
10379:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
10380:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
10381:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
10382:     return;
10383: }
10384: 
10385: ###############################################
10386: 
10387: =pod
10388: 
10389: =item * &get_user_quota()
10390: 
10391: Retrieves quota assigned for storage of user files.
10392: Default is to report quota for portfolio files.
10393: 
10394: Incoming parameters:
10395: 1. user's username
10396: 2. user's domain
10397: 3. quota name - portfolio, author, or course
10398:    (if no quota name provided, defaults to portfolio).
10399: 4. crstype - official, unofficial, textbook, placement or community, 
10400:    if quota name is course
10401: 
10402: Returns:
10403: 1. Disk quota (in MB) assigned to student.
10404: 2. (Optional) Type of setting: custom or default
10405:    (individually assigned or default for user's 
10406:    institutional status).
10407: 3. (Optional) - User's institutional status (e.g., faculty, staff
10408:    or student - types as defined in localenroll::inst_usertypes 
10409:    for user's domain, which determines default quota for user.
10410: 4. (Optional) - Default quota which would apply to the user.
10411: 
10412: If a value has been stored in the user's environment, 
10413: it will return that, otherwise it returns the maximal default
10414: defined for the user's institutional status(es) in the domain.
10415: 
10416: =cut
10417: 
10418: ###############################################
10419: 
10420: 
10421: sub get_user_quota {
10422:     my ($uname,$udom,$quotaname,$crstype) = @_;
10423:     my ($quota,$quotatype,$settingstatus,$defquota);
10424:     if (!defined($udom)) {
10425:         $udom = $env{'user.domain'};
10426:     }
10427:     if (!defined($uname)) {
10428:         $uname = $env{'user.name'};
10429:     }
10430:     if (($udom eq '' || $uname eq '') ||
10431:         ($udom eq 'public') && ($uname eq 'public')) {
10432:         $quota = 0;
10433:         $quotatype = 'default';
10434:         $defquota = 0; 
10435:     } else {
10436:         my $inststatus;
10437:         if ($quotaname eq 'course') {
10438:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
10439:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
10440:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
10441:             } else {
10442:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
10443:                 $quota = $cenv{'internal.uploadquota'};
10444:             }
10445:         } else {
10446:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
10447:                 if ($quotaname eq 'author') {
10448:                     $quota = $env{'environment.authorquota'};
10449:                 } else {
10450:                     $quota = $env{'environment.portfolioquota'};
10451:                 }
10452:                 $inststatus = $env{'environment.inststatus'};
10453:             } else {
10454:                 my %userenv = 
10455:                     &Apache::lonnet::get('environment',['portfolioquota',
10456:                                          'authorquota','inststatus'],$udom,$uname);
10457:                 my ($tmp) = keys(%userenv);
10458:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10459:                     if ($quotaname eq 'author') {
10460:                         $quota = $userenv{'authorquota'};
10461:                     } else {
10462:                         $quota = $userenv{'portfolioquota'};
10463:                     }
10464:                     $inststatus = $userenv{'inststatus'};
10465:                 } else {
10466:                     undef(%userenv);
10467:                 }
10468:             }
10469:         }
10470:         if ($quota eq '' || wantarray) {
10471:             if ($quotaname eq 'course') {
10472:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
10473:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
10474:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
10475:                     ($crstype eq 'placement')) { 
10476:                     $defquota = $domdefs{$crstype.'quota'};
10477:                 }
10478:                 if ($defquota eq '') {
10479:                     $defquota = 500;
10480:                 }
10481:             } else {
10482:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
10483:             }
10484:             if ($quota eq '') {
10485:                 $quota = $defquota;
10486:                 $quotatype = 'default';
10487:             } else {
10488:                 $quotatype = 'custom';
10489:             }
10490:         }
10491:     }
10492:     if (wantarray) {
10493:         return ($quota,$quotatype,$settingstatus,$defquota);
10494:     } else {
10495:         return $quota;
10496:     }
10497: }
10498: 
10499: ###############################################
10500: 
10501: =pod
10502: 
10503: =item * &default_quota()
10504: 
10505: Retrieves default quota assigned for storage of user portfolio files,
10506: given an (optional) user's institutional status.
10507: 
10508: Incoming parameters:
10509: 
10510: 1. domain
10511: 2. (Optional) institutional status(es).  This is a : separated list of 
10512:    status types (e.g., faculty, staff, student etc.)
10513:    which apply to the user for whom the default is being retrieved.
10514:    If the institutional status string in undefined, the domain
10515:    default quota will be returned.
10516: 3.  quota name - portfolio, author, or course
10517:    (if no quota name provided, defaults to portfolio).
10518: 
10519: Returns:
10520: 
10521: 1. Default disk quota (in MB) for user portfolios in the domain.
10522: 2. (Optional) institutional type which determined the value of the
10523:    default quota.
10524: 
10525: If a value has been stored in the domain's configuration db,
10526: it will return that, otherwise it returns 20 (for backwards 
10527: compatibility with domains which have not set up a configuration
10528: db file; the original statically defined portfolio quota was 20 MB). 
10529: 
10530: If the user's status includes multiple types (e.g., staff and student),
10531: the largest default quota which applies to the user determines the
10532: default quota returned.
10533: 
10534: =cut
10535: 
10536: ###############################################
10537: 
10538: 
10539: sub default_quota {
10540:     my ($udom,$inststatus,$quotaname) = @_;
10541:     my ($defquota,$settingstatus);
10542:     my %quotahash = &Apache::lonnet::get_dom('configuration',
10543:                                             ['quotas'],$udom);
10544:     my $key = 'defaultquota';
10545:     if ($quotaname eq 'author') {
10546:         $key = 'authorquota';
10547:     }
10548:     if (ref($quotahash{'quotas'}) eq 'HASH') {
10549:         if ($inststatus ne '') {
10550:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
10551:             foreach my $item (@statuses) {
10552:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
10553:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
10554:                         if ($defquota eq '') {
10555:                             $defquota = $quotahash{'quotas'}{$key}{$item};
10556:                             $settingstatus = $item;
10557:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
10558:                             $defquota = $quotahash{'quotas'}{$key}{$item};
10559:                             $settingstatus = $item;
10560:                         }
10561:                     }
10562:                 } elsif ($key eq 'defaultquota') {
10563:                     if ($quotahash{'quotas'}{$item} ne '') {
10564:                         if ($defquota eq '') {
10565:                             $defquota = $quotahash{'quotas'}{$item};
10566:                             $settingstatus = $item;
10567:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
10568:                             $defquota = $quotahash{'quotas'}{$item};
10569:                             $settingstatus = $item;
10570:                         }
10571:                     }
10572:                 }
10573:             }
10574:         }
10575:         if ($defquota eq '') {
10576:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
10577:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
10578:             } elsif ($key eq 'defaultquota') {
10579:                 $defquota = $quotahash{'quotas'}{'default'};
10580:             }
10581:             $settingstatus = 'default';
10582:             if ($defquota eq '') {
10583:                 if ($quotaname eq 'author') {
10584:                     $defquota = 500;
10585:                 }
10586:             }
10587:         }
10588:     } else {
10589:         $settingstatus = 'default';
10590:         if ($quotaname eq 'author') {
10591:             $defquota = 500;
10592:         } else {
10593:             $defquota = 20;
10594:         }
10595:     }
10596:     if (wantarray) {
10597:         return ($defquota,$settingstatus);
10598:     } else {
10599:         return $defquota;
10600:     }
10601: }
10602: 
10603: ###############################################
10604: 
10605: =pod
10606: 
10607: =item * &excess_filesize_warning()
10608: 
10609: Returns warning message if upload of file to authoring space, or copying
10610: of existing file within authoring space will cause quota for the authoring
10611: space to be exceeded.
10612: 
10613: Same, if upload of a file directly to a course/community via Course Editor
10614: will cause quota for uploaded content for the course to be exceeded.
10615: 
10616: Inputs: 7 
10617: 1. username or coursenum
10618: 2. domain
10619: 3. context ('author' or 'course')
10620: 4. filename of file for which action is being requested
10621: 5. filesize (kB) of file
10622: 6. action being taken: copy or upload.
10623: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
10624: 
10625: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
10626:          otherwise return null.
10627: 
10628: =back
10629: 
10630: =cut
10631: 
10632: sub excess_filesize_warning {
10633:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
10634:     my $current_disk_usage = 0;
10635:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
10636:     if ($context eq 'author') {
10637:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
10638:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
10639:     } else {
10640:         foreach my $subdir ('docs','supplemental') {
10641:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
10642:         }
10643:     }
10644:     $disk_quota = int($disk_quota * 1000);
10645:     if (($current_disk_usage + $filesize) > $disk_quota) {
10646:         return '<p class="LC_warning">'.
10647:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
10648:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
10649:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
10650:                             $disk_quota,$current_disk_usage).
10651:                '</p>';
10652:     }
10653:     return;
10654: }
10655: 
10656: ###############################################
10657: 
10658: 
10659: 
10660: 
10661: sub get_secgrprole_info {
10662:     my ($cdom,$cnum,$needroles,$type)  = @_;
10663:     my %sections_count = &get_sections($cdom,$cnum);
10664:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
10665:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
10666:     my @groups = sort(keys(%curr_groups));
10667:     my $allroles = [];
10668:     my $rolehash;
10669:     my $accesshash = {
10670:                      active => 'Currently has access',
10671:                      future => 'Will have future access',
10672:                      previous => 'Previously had access',
10673:                   };
10674:     if ($needroles) {
10675:         $rolehash = {'all' => 'all'};
10676:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10677: 	if (&Apache::lonnet::error(%user_roles)) {
10678: 	    undef(%user_roles);
10679: 	}
10680:         foreach my $item (keys(%user_roles)) {
10681:             my ($role)=split(/\:/,$item,2);
10682:             if ($role eq 'cr') { next; }
10683:             if ($role =~ /^cr/) {
10684:                 $$rolehash{$role} = (split('/',$role))[3];
10685:             } else {
10686:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
10687:             }
10688:         }
10689:         foreach my $key (sort(keys(%{$rolehash}))) {
10690:             push(@{$allroles},$key);
10691:         }
10692:         push (@{$allroles},'st');
10693:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
10694:     }
10695:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
10696: }
10697: 
10698: sub user_picker {
10699:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
10700:     my $currdom = $dom;
10701:     my @alldoms = &Apache::lonnet::all_domains();
10702:     if (@alldoms == 1) {
10703:         my %domsrch = &Apache::lonnet::get_dom('configuration',
10704:                                                ['directorysrch'],$alldoms[0]);
10705:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
10706:         my $showdom = $domdesc;
10707:         if ($showdom eq '') {
10708:             $showdom = $dom;
10709:         }
10710:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
10711:             if ((!$domsrch{'directorysrch'}{'available'}) &&
10712:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
10713:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
10714:             }
10715:         }
10716:     }
10717:     my %curr_selected = (
10718:                         srchin => 'dom',
10719:                         srchby => 'lastname',
10720:                       );
10721:     my $srchterm;
10722:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
10723:         if ($srch->{'srchby'} ne '') {
10724:             $curr_selected{'srchby'} = $srch->{'srchby'};
10725:         }
10726:         if ($srch->{'srchin'} ne '') {
10727:             $curr_selected{'srchin'} = $srch->{'srchin'};
10728:         }
10729:         if ($srch->{'srchtype'} ne '') {
10730:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
10731:         }
10732:         if ($srch->{'srchdomain'} ne '') {
10733:             $currdom = $srch->{'srchdomain'};
10734:         }
10735:         $srchterm = $srch->{'srchterm'};
10736:     }
10737:     my %html_lt=&Apache::lonlocal::texthash(
10738:                     'usr'       => 'Search criteria',
10739:                     'doma'      => 'Domain/institution to search',
10740:                     'uname'     => 'username',
10741:                     'lastname'  => 'last name',
10742:                     'lastfirst' => 'last name, first name',
10743:                     'crs'       => 'in this course',
10744:                     'dom'       => 'in selected LON-CAPA domain', 
10745:                     'alc'       => 'all LON-CAPA',
10746:                     'instd'     => 'in institutional directory for selected domain',
10747:                     'exact'     => 'is',
10748:                     'contains'  => 'contains',
10749:                     'begins'    => 'begins with',
10750:                                        );
10751:     my %js_lt=&Apache::lonlocal::texthash(
10752:                     'youm'      => "You must include some text to search for.",
10753:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
10754:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
10755:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
10756:                     'ymcd'      => "You must choose a domain when using a domain search.",
10757:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
10758:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
10759:                      'thfo'     => "The following need to be corrected before the search can be run:",
10760:                                        );
10761:     &html_escape(\%html_lt);
10762:     &js_escape(\%js_lt);
10763:     my $domform;
10764:     my $allow_blank = 1;
10765:     if ($fixeddom) {
10766:         $allow_blank = 0;
10767:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
10768:     } else {
10769:         my $defdom = $env{'request.role.domain'};
10770:         my ($trusted,$untrusted);
10771:         if (($context eq 'requestcrs') || ($context eq 'course')) {
10772:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
10773:         } elsif ($context eq 'author') {
10774:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
10775:         } elsif ($context eq 'domain') {
10776:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
10777:         }
10778:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
10779:     }
10780:     my $srchinsel = ' <select name="srchin">';
10781: 
10782:     my @srchins = ('crs','dom','alc','instd');
10783: 
10784:     foreach my $option (@srchins) {
10785:         # FIXME 'alc' option unavailable until 
10786:         #       loncreateuser::print_user_query_page()
10787:         #       has been completed.
10788:         next if ($option eq 'alc');
10789:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
10790:         next if ($option eq 'crs' && !$env{'request.course.id'});
10791:         next if (($option eq 'instd') && ($noinstd));
10792:         if ($curr_selected{'srchin'} eq $option) {
10793:             $srchinsel .= ' 
10794:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10795:         } else {
10796:             $srchinsel .= '
10797:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10798:         }
10799:     }
10800:     $srchinsel .= "\n  </select>\n";
10801: 
10802:     my $srchbysel =  ' <select name="srchby">';
10803:     foreach my $option ('lastname','lastfirst','uname') {
10804:         if ($curr_selected{'srchby'} eq $option) {
10805:             $srchbysel .= '
10806:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10807:         } else {
10808:             $srchbysel .= '
10809:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10810:          }
10811:     }
10812:     $srchbysel .= "\n  </select>\n";
10813: 
10814:     my $srchtypesel = ' <select name="srchtype">';
10815:     foreach my $option ('begins','contains','exact') {
10816:         if ($curr_selected{'srchtype'} eq $option) {
10817:             $srchtypesel .= '
10818:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10819:         } else {
10820:             $srchtypesel .= '
10821:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10822:         }
10823:     }
10824:     $srchtypesel .= "\n  </select>\n";
10825: 
10826:     my ($newuserscript,$new_user_create);
10827:     my $context_dom = $env{'request.role.domain'};
10828:     if ($context eq 'requestcrs') {
10829:         if ($env{'form.coursedom'} ne '') { 
10830:             $context_dom = $env{'form.coursedom'};
10831:         }
10832:     }
10833:     if ($forcenewuser) {
10834:         if (ref($srch) eq 'HASH') {
10835:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
10836:                 if ($cancreate) {
10837:                     $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>';
10838:                 } else {
10839:                     my $helplink = 'javascript:helpMenu('."'display'".')';
10840:                     my %usertypetext = (
10841:                         official   => 'institutional',
10842:                         unofficial => 'non-institutional',
10843:                     );
10844:                     $new_user_create = '<p class="LC_warning">'
10845:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
10846:                                       .' '
10847:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
10848:                                           ,'<a href="'.$helplink.'">','</a>')
10849:                                       .'</p><br />';
10850:                 }
10851:             }
10852:         }
10853: 
10854:         $newuserscript = <<"ENDSCRIPT";
10855: 
10856: function setSearch(createnew,callingForm) {
10857:     if (createnew == 1) {
10858:         for (var i=0; i<callingForm.srchby.length; i++) {
10859:             if (callingForm.srchby.options[i].value == 'uname') {
10860:                 callingForm.srchby.selectedIndex = i;
10861:             }
10862:         }
10863:         for (var i=0; i<callingForm.srchin.length; i++) {
10864:             if ( callingForm.srchin.options[i].value == 'dom') {
10865: 		callingForm.srchin.selectedIndex = i;
10866:             }
10867:         }
10868:         for (var i=0; i<callingForm.srchtype.length; i++) {
10869:             if (callingForm.srchtype.options[i].value == 'exact') {
10870:                 callingForm.srchtype.selectedIndex = i;
10871:             }
10872:         }
10873:         for (var i=0; i<callingForm.srchdomain.length; i++) {
10874:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
10875:                 callingForm.srchdomain.selectedIndex = i;
10876:             }
10877:         }
10878:     }
10879: }
10880: ENDSCRIPT
10881: 
10882:     }
10883: 
10884:     my $output = <<"END_BLOCK";
10885: <script type="text/javascript">
10886: // <![CDATA[
10887: function validateEntry(callingForm) {
10888: 
10889:     var checkok = 1;
10890:     var srchin;
10891:     for (var i=0; i<callingForm.srchin.length; i++) {
10892: 	if ( callingForm.srchin[i].checked ) {
10893: 	    srchin = callingForm.srchin[i].value;
10894: 	}
10895:     }
10896: 
10897:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
10898:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
10899:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
10900:     var srchterm =  callingForm.srchterm.value;
10901:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
10902:     var msg = "";
10903: 
10904:     if (srchterm == "") {
10905:         checkok = 0;
10906:         msg += "$js_lt{'youm'}\\n";
10907:     }
10908: 
10909:     if (srchtype== 'begins') {
10910:         if (srchterm.length < 2) {
10911:             checkok = 0;
10912:             msg += "$js_lt{'thte'}\\n";
10913:         }
10914:     }
10915: 
10916:     if (srchtype== 'contains') {
10917:         if (srchterm.length < 3) {
10918:             checkok = 0;
10919:             msg += "$js_lt{'thet'}\\n";
10920:         }
10921:     }
10922:     if (srchin == 'instd') {
10923:         if (srchdomain == '') {
10924:             checkok = 0;
10925:             msg += "$js_lt{'yomc'}\\n";
10926:         }
10927:     }
10928:     if (srchin == 'dom') {
10929:         if (srchdomain == '') {
10930:             checkok = 0;
10931:             msg += "$js_lt{'ymcd'}\\n";
10932:         }
10933:     }
10934:     if (srchby == 'lastfirst') {
10935:         if (srchterm.indexOf(",") == -1) {
10936:             checkok = 0;
10937:             msg += "$js_lt{'whus'}\\n";
10938:         }
10939:         if (srchterm.indexOf(",") == srchterm.length -1) {
10940:             checkok = 0;
10941:             msg += "$js_lt{'whse'}\\n";
10942:         }
10943:     }
10944:     if (checkok == 0) {
10945:         alert("$js_lt{'thfo'}\\n"+msg);
10946:         return;
10947:     }
10948:     if (checkok == 1) {
10949:         callingForm.submit();
10950:     }
10951: }
10952: 
10953: $newuserscript
10954: 
10955: // ]]>
10956: </script>
10957: 
10958: $new_user_create
10959: 
10960: END_BLOCK
10961: 
10962:     $output .= &Apache::lonhtmlcommon::start_pick_box().
10963:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
10964:                $domform.
10965:                &Apache::lonhtmlcommon::row_closure().
10966:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
10967:                $srchbysel.
10968:                $srchtypesel. 
10969:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
10970:                $srchinsel.
10971:                &Apache::lonhtmlcommon::row_closure(1). 
10972:                &Apache::lonhtmlcommon::end_pick_box().
10973:                '<br />';
10974:     return ($output,1);
10975: }
10976: 
10977: sub user_rule_check {
10978:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
10979:     my ($response,%inst_response);
10980:     if (ref($usershash) eq 'HASH') {
10981:         if (keys(%{$usershash}) > 1) {
10982:             my (%by_username,%by_id,%userdoms);
10983:             my $checkid; 
10984:             if (ref($checks) eq 'HASH') {
10985:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
10986:                     $checkid = 1;
10987:                 }
10988:             }
10989:             foreach my $user (keys(%{$usershash})) {
10990:                 my ($uname,$udom) = split(/:/,$user);
10991:                 if ($checkid) {
10992:                     if (ref($usershash->{$user}) eq 'HASH') {
10993:                         if ($usershash->{$user}->{'id'} ne '') {
10994:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
10995:                             $userdoms{$udom} = 1;
10996:                             if (ref($inst_results) eq 'HASH') {
10997:                                 $inst_results->{$uname.':'.$udom} = {};
10998:                             }
10999:                         }
11000:                     }
11001:                 } else {
11002:                     $by_username{$udom}{$uname} = 1;
11003:                     $userdoms{$udom} = 1;
11004:                     if (ref($inst_results) eq 'HASH') {
11005:                         $inst_results->{$uname.':'.$udom} = {};
11006:                     }
11007:                 }
11008:             }
11009:             foreach my $udom (keys(%userdoms)) {
11010:                 if (!$got_rules->{$udom}) {
11011:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
11012:                                                              ['usercreation'],$udom);
11013:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
11014:                         foreach my $item ('username','id') {
11015:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
11016:                                 $$curr_rules{$udom}{$item} =
11017:                                     $domconfig{'usercreation'}{$item.'_rule'};
11018:                             }
11019:                         }
11020:                     }
11021:                     $got_rules->{$udom} = 1;
11022:                 }
11023:             }
11024:             if ($checkid) {
11025:                 foreach my $udom (keys(%by_id)) {
11026:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
11027:                     if ($outcome eq 'ok') {
11028:                         foreach my $id (keys(%{$by_id{$udom}})) {
11029:                             my $uname = $by_id{$udom}{$id};
11030:                             $inst_response{$uname.':'.$udom} = $outcome;
11031:                         }
11032:                         if (ref($results) eq 'HASH') {
11033:                             foreach my $uname (keys(%{$results})) {
11034:                                 if (exists($inst_response{$uname.':'.$udom})) {
11035:                                     $inst_response{$uname.':'.$udom} = $outcome;
11036:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
11037:                                 }
11038:                             }
11039:                         }
11040:                     }
11041:                 }
11042:             } else {
11043:                 foreach my $udom (keys(%by_username)) {
11044:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
11045:                     if ($outcome eq 'ok') {
11046:                         foreach my $uname (keys(%{$by_username{$udom}})) {
11047:                             $inst_response{$uname.':'.$udom} = $outcome;
11048:                         }
11049:                         if (ref($results) eq 'HASH') {
11050:                             foreach my $uname (keys(%{$results})) {
11051:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
11052:                             }
11053:                         }
11054:                     }
11055:                 }
11056:             }
11057:         } elsif (keys(%{$usershash}) == 1) {
11058:             my $user = (keys(%{$usershash}))[0];
11059:             my ($uname,$udom) = split(/:/,$user);
11060:             if (($udom ne '') && ($uname ne '')) {
11061:                 if (ref($usershash->{$user}) eq 'HASH') {
11062:                     if (ref($checks) eq 'HASH') {
11063:                         if (defined($checks->{'username'})) {
11064:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
11065:                                 &Apache::lonnet::get_instuser($udom,$uname);
11066:                         } elsif (defined($checks->{'id'})) {
11067:                             if ($usershash->{$user}->{'id'} ne '') {
11068:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
11069:                                     &Apache::lonnet::get_instuser($udom,undef,
11070:                                                                   $usershash->{$user}->{'id'});
11071:                             } else {
11072:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
11073:                                     &Apache::lonnet::get_instuser($udom,$uname);
11074:                             }
11075:                         }
11076:                     } else {
11077:                        ($inst_response{$user},%{$inst_results->{$user}}) =
11078:                             &Apache::lonnet::get_instuser($udom,$uname);
11079:                        return;
11080:                     }
11081:                     if (!$got_rules->{$udom}) {
11082:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
11083:                                                                  ['usercreation'],$udom);
11084:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
11085:                             foreach my $item ('username','id') {
11086:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
11087:                                    $$curr_rules{$udom}{$item} = 
11088:                                        $domconfig{'usercreation'}{$item.'_rule'};
11089:                                 }
11090:                             }
11091:                         }
11092:                         $got_rules->{$udom} = 1;
11093:                     }
11094:                 }
11095:             } else {
11096:                 return;
11097:             }
11098:         } else {
11099:             return;
11100:         }
11101:         foreach my $user (keys(%{$usershash})) {
11102:             my ($uname,$udom) = split(/:/,$user);
11103:             next if (($udom eq '') || ($uname eq ''));
11104:             my $id;
11105:             if (ref($inst_results) eq 'HASH') {
11106:                 if (ref($inst_results->{$user}) eq 'HASH') {
11107:                     $id = $inst_results->{$user}->{'id'};
11108:                 }
11109:             }
11110:             if ($id eq '') { 
11111:                 if (ref($usershash->{$user})) {
11112:                     $id = $usershash->{$user}->{'id'};
11113:                 }
11114:             }
11115:             foreach my $item (keys(%{$checks})) {
11116:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
11117:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
11118:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
11119:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
11120:                                                                              $$curr_rules{$udom}{$item});
11121:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
11122:                                 if ($rule_check{$rule}) {
11123:                                     $$rulematch{$user}{$item} = $rule;
11124:                                     if ($inst_response{$user} eq 'ok') {
11125:                                         if (ref($inst_results) eq 'HASH') {
11126:                                             if (ref($inst_results->{$user}) eq 'HASH') {
11127:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
11128:                                                     $$alerts{$item}{$udom}{$uname} = 1;
11129:                                                 } elsif ($item eq 'id') {
11130:                                                     if ($inst_results->{$user}->{'id'} eq '') {
11131:                                                         $$alerts{$item}{$udom}{$uname} = 1;
11132:                                                     }
11133:                                                 }
11134:                                             }
11135:                                         }
11136:                                     }
11137:                                     last;
11138:                                 }
11139:                             }
11140:                         }
11141:                     }
11142:                 }
11143:             }
11144:         }
11145:     }
11146:     return;
11147: }
11148: 
11149: sub user_rule_formats {
11150:     my ($domain,$domdesc,$curr_rules,$check) = @_;
11151:     my %text = ( 
11152:                  'username' => 'Usernames',
11153:                  'id'       => 'IDs',
11154:                );
11155:     my $output;
11156:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
11157:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
11158:         if (@{$ruleorder} > 0) {
11159:             $output = '<br />'.
11160:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
11161:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
11162:                       ' <ul>';
11163:             foreach my $rule (@{$ruleorder}) {
11164:                 if (ref($curr_rules) eq 'ARRAY') {
11165:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
11166:                         if (ref($rules->{$rule}) eq 'HASH') {
11167:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
11168:                                         $rules->{$rule}{'desc'}.'</li>';
11169:                         }
11170:                     }
11171:                 }
11172:             }
11173:             $output .= '</ul>';
11174:         }
11175:     }
11176:     return $output;
11177: }
11178: 
11179: sub instrule_disallow_msg {
11180:     my ($checkitem,$domdesc,$count,$mode) = @_;
11181:     my $response;
11182:     my %text = (
11183:                   item   => 'username',
11184:                   items  => 'usernames',
11185:                   match  => 'matches',
11186:                   do     => 'does',
11187:                   action => 'a username',
11188:                   one    => 'one',
11189:                );
11190:     if ($count > 1) {
11191:         $text{'item'} = 'usernames';
11192:         $text{'match'} ='match';
11193:         $text{'do'} = 'do';
11194:         $text{'action'} = 'usernames',
11195:         $text{'one'} = 'ones';
11196:     }
11197:     if ($checkitem eq 'id') {
11198:         $text{'items'} = 'IDs';
11199:         $text{'item'} = 'ID';
11200:         $text{'action'} = 'an ID';
11201:         if ($count > 1) {
11202:             $text{'item'} = 'IDs';
11203:             $text{'action'} = 'IDs';
11204:         }
11205:     }
11206:     $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 />';
11207:     if ($mode eq 'upload') {
11208:         if ($checkitem eq 'username') {
11209:             $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'}.");
11210:         } elsif ($checkitem eq 'id') {
11211:             $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.");
11212:         }
11213:     } elsif ($mode eq 'selfcreate') {
11214:         if ($checkitem eq 'id') {
11215:             $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.");
11216:         }
11217:     } else {
11218:         if ($checkitem eq 'username') {
11219:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
11220:         } elsif ($checkitem eq 'id') {
11221:             $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.");
11222:         }
11223:     }
11224:     return $response;
11225: }
11226: 
11227: sub personal_data_fieldtitles {
11228:     my %fieldtitles = &Apache::lonlocal::texthash (
11229:                         id => 'Student/Employee ID',
11230:                         permanentemail => 'E-mail address',
11231:                         lastname => 'Last Name',
11232:                         firstname => 'First Name',
11233:                         middlename => 'Middle Name',
11234:                         generation => 'Generation',
11235:                         gen => 'Generation',
11236:                         inststatus => 'Affiliation',
11237:                    );
11238:     return %fieldtitles;
11239: }
11240: 
11241: sub sorted_inst_types {
11242:     my ($dom) = @_;
11243:     my ($usertypes,$order);
11244:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
11245:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
11246:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
11247:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
11248:     } else {
11249:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
11250:     }
11251:     my $othertitle = &mt('All users');
11252:     if ($env{'request.course.id'}) {
11253:         $othertitle  = &mt('Any users');
11254:     }
11255:     my @types;
11256:     if (ref($order) eq 'ARRAY') {
11257:         @types = @{$order};
11258:     }
11259:     if (@types == 0) {
11260:         if (ref($usertypes) eq 'HASH') {
11261:             @types = sort(keys(%{$usertypes}));
11262:         }
11263:     }
11264:     if (keys(%{$usertypes}) > 0) {
11265:         $othertitle = &mt('Other users');
11266:     }
11267:     return ($othertitle,$usertypes,\@types);
11268: }
11269: 
11270: sub get_institutional_codes {
11271:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
11272: # Get complete list of course sections to update
11273:     my @currsections = ();
11274:     my @currxlists = ();
11275:     my (%unclutteredsec,%unclutteredlcsec);
11276:     my $coursecode = $$settings{'internal.coursecode'};
11277:     my $crskey = $crs.':'.$coursecode;
11278:     @{$unclutteredsec{$crskey}} = ();
11279:     @{$unclutteredlcsec{$crskey}} = ();
11280: 
11281:     if ($$settings{'internal.sectionnums'} ne '') {
11282:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
11283:     }
11284: 
11285:     if ($$settings{'internal.crosslistings'} ne '') {
11286:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
11287:     }
11288: 
11289:     if (@currxlists > 0) {
11290:         foreach my $xl (@currxlists) {
11291:             if ($xl =~ /^([^:]+):(\w*)$/) {
11292:                 unless (grep/^$1$/,@{$allcourses}) {
11293:                     push(@{$allcourses},$1);
11294:                     $$LC_code{$1} = $2;
11295:                 }
11296:             }
11297:         }
11298:     }
11299: 
11300:     if (@currsections > 0) {
11301:         foreach my $sec (@currsections) {
11302:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
11303:                 my $instsec = $1;
11304:                 my $lc_sec = $2;
11305:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
11306:                     push(@{$unclutteredsec{$crskey}},$instsec);
11307:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
11308:                 }
11309:             }
11310:         }
11311:     }
11312: 
11313:     if (@{$unclutteredsec{$crskey}} > 0) {
11314:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
11315:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
11316:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
11317:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
11318:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
11319:                     push(@{$allcourses},$sec);
11320:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
11321:                 }
11322:             }
11323:         }
11324:     }
11325:     return;
11326: }
11327: 
11328: sub get_standard_codeitems {
11329:     return ('Year','Semester','Department','Number','Section');
11330: }
11331: 
11332: =pod
11333: 
11334: =head1 Slot Helpers
11335: 
11336: =over 4
11337: 
11338: =item * sorted_slots()
11339: 
11340: Sorts an array of slot names in order of an optional sort key,
11341: default sort is by slot start time (earliest first). 
11342: 
11343: Inputs:
11344: 
11345: =over 4
11346: 
11347: slotsarr  - Reference to array of unsorted slot names.
11348: 
11349: slots     - Reference to hash of hash, where outer hash keys are slot names.
11350: 
11351: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
11352: 
11353: =back
11354: 
11355: Returns:
11356: 
11357: =over 4
11358: 
11359: sorted   - An array of slot names sorted by a specified sort key 
11360:            (default sort key is start time of the slot).
11361: 
11362: =back
11363: 
11364: =cut
11365: 
11366: 
11367: sub sorted_slots {
11368:     my ($slotsarr,$slots,$sortkey) = @_;
11369:     if ($sortkey eq '') {
11370:         $sortkey = 'starttime';
11371:     }
11372:     my @sorted;
11373:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
11374:         @sorted =
11375:             sort {
11376:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
11377:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
11378:                      }
11379:                      if (ref($slots->{$a})) { return -1;}
11380:                      if (ref($slots->{$b})) { return 1;}
11381:                      return 0;
11382:                  } @{$slotsarr};
11383:     }
11384:     return @sorted;
11385: }
11386: 
11387: =pod
11388: 
11389: =item * get_future_slots()
11390: 
11391: Inputs:
11392: 
11393: =over 4
11394: 
11395: cnum - course number
11396: 
11397: cdom - course domain
11398: 
11399: now - current UNIX time
11400: 
11401: symb - optional symb
11402: 
11403: =back
11404: 
11405: Returns:
11406: 
11407: =over 4
11408: 
11409: sorted_reservable - ref to array of student_schedulable slots currently 
11410:                     reservable, ordered by end date of reservation period.
11411: 
11412: reservable_now - ref to hash of student_schedulable slots currently
11413:                  reservable.
11414: 
11415:     Keys in inner hash are:
11416:     (a) symb: either blank or symb to which slot use is restricted.
11417:     (b) endreserve: end date of reservation period.
11418:     (c) uniqueperiod: start,end dates when slot is to be uniquely
11419:         selected.
11420: 
11421: sorted_future - ref to array of student_schedulable slots reservable in
11422:                 the future, ordered by start date of reservation period.
11423: 
11424: future_reservable - ref to hash of student_schedulable slots reservable
11425:                     in the future.
11426: 
11427:     Keys in inner hash are:
11428:     (a) symb: either blank or symb to which slot use is restricted.
11429:     (b) startreserve: start date of reservation period.
11430:     (c) uniqueperiod: start,end dates when slot is to be uniquely
11431:         selected.
11432: 
11433: =back
11434: 
11435: =cut
11436: 
11437: sub get_future_slots {
11438:     my ($cnum,$cdom,$now,$symb) = @_;
11439:     my $map;
11440:     if ($symb) {
11441:         ($map) = &Apache::lonnet::decode_symb($symb);
11442:     }
11443:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
11444:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
11445:     foreach my $slot (keys(%slots)) {
11446:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
11447:         if ($symb) {
11448:             if ($slots{$slot}->{'symb'} ne '') {
11449:                 my $canuse;
11450:                 my %oksymbs;
11451:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
11452:                 map { $oksymbs{$_} = 1; } @slotsymbs;
11453:                 if ($oksymbs{$symb}) {
11454:                     $canuse = 1;
11455:                 } else {
11456:                     foreach my $item (@slotsymbs) {
11457:                         if ($item =~ /\.(page|sequence)$/) {
11458:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
11459:                             if (($map ne '') && ($map eq $sloturl)) {
11460:                                 $canuse = 1;
11461:                                 last;
11462:                             }
11463:                         }
11464:                     }
11465:                 }
11466:                 next unless ($canuse);
11467:             }
11468:         }
11469:         if (($slots{$slot}->{'starttime'} > $now) &&
11470:             ($slots{$slot}->{'endtime'} > $now)) {
11471:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
11472:                 my $userallowed = 0;
11473:                 if ($slots{$slot}->{'allowedsections'}) {
11474:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
11475:                     if (!defined($env{'request.role.sec'})
11476:                         && grep(/^No section assigned$/,@allowed_sec)) {
11477:                         $userallowed=1;
11478:                     } else {
11479:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
11480:                             $userallowed=1;
11481:                         }
11482:                     }
11483:                     unless ($userallowed) {
11484:                         if (defined($env{'request.course.groups'})) {
11485:                             my @groups = split(/:/,$env{'request.course.groups'});
11486:                             foreach my $group (@groups) {
11487:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
11488:                                     $userallowed=1;
11489:                                     last;
11490:                                 }
11491:                             }
11492:                         }
11493:                     }
11494:                 }
11495:                 if ($slots{$slot}->{'allowedusers'}) {
11496:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
11497:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
11498:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
11499:                         $userallowed = 1;
11500:                     }
11501:                 }
11502:                 next unless($userallowed);
11503:             }
11504:             my $startreserve = $slots{$slot}->{'startreserve'};
11505:             my $endreserve = $slots{$slot}->{'endreserve'};
11506:             my $symb = $slots{$slot}->{'symb'};
11507:             my $uniqueperiod;
11508:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
11509:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
11510:             }
11511:             if (($startreserve < $now) &&
11512:                 (!$endreserve || $endreserve > $now)) {
11513:                 my $lastres = $endreserve;
11514:                 if (!$lastres) {
11515:                     $lastres = $slots{$slot}->{'starttime'};
11516:                 }
11517:                 $reservable_now{$slot} = {
11518:                                            symb       => $symb,
11519:                                            endreserve => $lastres,
11520:                                            uniqueperiod => $uniqueperiod,
11521:                                          };
11522:             } elsif (($startreserve > $now) &&
11523:                      (!$endreserve || $endreserve > $startreserve)) {
11524:                 $future_reservable{$slot} = {
11525:                                               symb         => $symb,
11526:                                               startreserve => $startreserve,
11527:                                               uniqueperiod => $uniqueperiod,
11528:                                             };
11529:             }
11530:         }
11531:     }
11532:     my @unsorted_reservable = keys(%reservable_now);
11533:     if (@unsorted_reservable > 0) {
11534:         @sorted_reservable = 
11535:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
11536:     }
11537:     my @unsorted_future = keys(%future_reservable);
11538:     if (@unsorted_future > 0) {
11539:         @sorted_future =
11540:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
11541:     }
11542:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
11543: }
11544: 
11545: =pod
11546: 
11547: =back
11548: 
11549: =head1 HTTP Helpers
11550: 
11551: =over 4
11552: 
11553: =item * &get_unprocessed_cgi($query,$possible_names)
11554: 
11555: Modify the %env hash to contain unprocessed CGI form parameters held in
11556: $query.  The parameters listed in $possible_names (an array reference),
11557: will be set in $env{'form.name'} if they do not already exist.
11558: 
11559: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
11560: $possible_names is an ref to an array of form element names.  As an example:
11561: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
11562: will result in $env{'form.uname'} and $env{'form.udom'} being set.
11563: 
11564: =cut
11565: 
11566: sub get_unprocessed_cgi {
11567:   my ($query,$possible_names)= @_;
11568:   # $Apache::lonxml::debug=1;
11569:   foreach my $pair (split(/&/,$query)) {
11570:     my ($name, $value) = split(/=/,$pair);
11571:     $name = &unescape($name);
11572:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
11573:       $value =~ tr/+/ /;
11574:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
11575:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
11576:     }
11577:   }
11578: }
11579: 
11580: =pod
11581: 
11582: =item * &cacheheader() 
11583: 
11584: returns cache-controlling header code
11585: 
11586: =cut
11587: 
11588: sub cacheheader {
11589:     unless ($env{'request.method'} eq 'GET') { return ''; }
11590:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
11591:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
11592:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
11593:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
11594:     return $output;
11595: }
11596: 
11597: =pod
11598: 
11599: =item * &no_cache($r) 
11600: 
11601: specifies header code to not have cache
11602: 
11603: =cut
11604: 
11605: sub no_cache {
11606:     my ($r) = @_;
11607:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
11608: 	$env{'request.method'} ne 'GET') { return ''; }
11609:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
11610:     $r->no_cache(1);
11611:     $r->header_out("Expires" => $date);
11612:     $r->header_out("Pragma" => "no-cache");
11613: }
11614: 
11615: sub content_type {
11616:     my ($r,$type,$charset) = @_;
11617:     if ($r) {
11618: 	#  Note that printout.pl calls this with undef for $r.
11619: 	&no_cache($r);
11620:     }
11621:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
11622:     unless ($charset) {
11623: 	$charset=&Apache::lonlocal::current_encoding;
11624:     }
11625:     if ($charset) { $type.='; charset='.$charset; }
11626:     if ($r) {
11627: 	$r->content_type($type);
11628:     } else {
11629: 	print("Content-type: $type\n\n");
11630:     }
11631: }
11632: 
11633: =pod
11634: 
11635: =item * &add_to_env($name,$value) 
11636: 
11637: adds $name to the %env hash with value
11638: $value, if $name already exists, the entry is converted to an array
11639: reference and $value is added to the array.
11640: 
11641: =cut
11642: 
11643: sub add_to_env {
11644:   my ($name,$value)=@_;
11645:   if (defined($env{$name})) {
11646:     if (ref($env{$name})) {
11647:       #already have multiple values
11648:       push(@{ $env{$name} },$value);
11649:     } else {
11650:       #first time seeing multiple values, convert hash entry to an arrayref
11651:       my $first=$env{$name};
11652:       undef($env{$name});
11653:       push(@{ $env{$name} },$first,$value);
11654:     }
11655:   } else {
11656:     $env{$name}=$value;
11657:   }
11658: }
11659: 
11660: =pod
11661: 
11662: =item * &get_env_multiple($name) 
11663: 
11664: gets $name from the %env hash, it seemlessly handles the cases where multiple
11665: values may be defined and end up as an array ref.
11666: 
11667: returns an array of values
11668: 
11669: =cut
11670: 
11671: sub get_env_multiple {
11672:     my ($name) = @_;
11673:     my @values;
11674:     if (defined($env{$name})) {
11675:         # exists is it an array
11676:         if (ref($env{$name})) {
11677:             @values=@{ $env{$name} };
11678:         } else {
11679:             $values[0]=$env{$name};
11680:         }
11681:     }
11682:     return(@values);
11683: }
11684: 
11685: # Looks at given dependencies, and returns something depending on the context.
11686: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
11687: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
11688: # For all other contexts, returns ($output, $counter, $numpathchg).
11689: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
11690: # $counter: integer with the number of existing dependencies when no HTML output is returned, and the number of missing dependencies when an HTML output is returned.
11691: # $numpathchg: integer with the number of cleaned up dependency paths.
11692: # \%existing: hash reference clean path -> 1 only for existing dependencies.
11693: # \%mapping: hash reference clean path -> original path for all dependencies.
11694: # @param {string} actionurl - The path to the handler, indicative of the context.
11695: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
11696: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
11697: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
11698: # @param {hash reference} args - More parameters ! Possible keys: error_on_invalid_names (boolean), ignore_remote_references (boolean), current_path (string), docs_url (string), docs_title (string), context (string)
11699: # @return {Array} - array depending on the context (not a reference)
11700: sub ask_for_embedded_content {
11701:     # NOTE: documentation was added afterwards, it could be wrong
11702:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
11703:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
11704:         %currsubfile,%unused,$rem);
11705:     my $counter = 0;
11706:     my $numnew = 0;
11707:     my $numremref = 0;
11708:     my $numinvalid = 0;
11709:     my $numpathchg = 0;
11710:     my $numexisting = 0;
11711:     my $numunused = 0;
11712:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
11713:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
11714:     my $heading = &mt('Upload embedded files');
11715:     my $buttontext = &mt('Upload');
11716: 
11717:     # fills these variables based on the context:
11718:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
11719:     # $path, $fileloc, $title, $rem, $filename
11720:     if ($env{'request.course.id'}) {
11721:         if ($actionurl eq '/adm/dependencies') {
11722:             $navmap = Apache::lonnavmaps::navmap->new();
11723:         }
11724:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11725:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11726:     }
11727:     if (($actionurl eq '/adm/portfolio') || 
11728:         ($actionurl eq '/adm/coursegrp_portfolio')) {
11729:         my $current_path='/';
11730:         if ($env{'form.currentpath'}) {
11731:             $current_path = $env{'form.currentpath'};
11732:         }
11733:         if ($actionurl eq '/adm/coursegrp_portfolio') {
11734:             $udom = $cdom;
11735:             $uname = $cnum;
11736:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
11737:         } else {
11738:             $udom = $env{'user.domain'};
11739:             $uname = $env{'user.name'};
11740:             $url = '/userfiles/portfolio';
11741:         }
11742:         $toplevel = $url.'/';
11743:         $url .= $current_path;
11744:         $getpropath = 1;
11745:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
11746:              ($actionurl eq '/adm/imsimport')) { 
11747:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
11748:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
11749:         $toplevel = $url;
11750:         if ($rest ne '') {
11751:             $url .= $rest;
11752:         }
11753:     } elsif ($actionurl eq '/adm/coursedocs') {
11754:         if (ref($args) eq 'HASH') {
11755:             $url = $args->{'docs_url'};
11756:             $toplevel = $url;
11757:             if ($args->{'context'} eq 'paste') {
11758:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
11759:                 ($path) = 
11760:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
11761:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
11762:                 $fileloc =~ s{^/}{};
11763:             }
11764:         }
11765:     } elsif ($actionurl eq '/adm/dependencies')  {
11766:         if ($env{'request.course.id'} ne '') {
11767:             if (ref($args) eq 'HASH') {
11768:                 $url = $args->{'docs_url'};
11769:                 $title = $args->{'docs_title'};
11770:                 $toplevel = $url; 
11771:                 unless ($toplevel =~ m{^/}) {
11772:                     $toplevel = "/$url";
11773:                 }
11774:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
11775:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
11776:                     $path = $1;
11777:                 } else {
11778:                     ($path) =
11779:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
11780:                 }
11781:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
11782:                     $fileloc = $toplevel;
11783:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
11784:                     my ($udom,$uname,$fname) =
11785:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
11786:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
11787:                 } else {
11788:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
11789:                 }
11790:                 $fileloc =~ s{^/}{};
11791:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
11792:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
11793:             }
11794:         }
11795:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
11796:         $udom = $cdom;
11797:         $uname = $cnum;
11798:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
11799:         $toplevel = $url;
11800:         $path = $url;
11801:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
11802:         $fileloc =~ s{^/}{};
11803:     }
11804:     
11805:     # parses the dependency paths to get some info
11806:     # fills $newfiles, $mapping, $subdependencies, $dependencies
11807:     # $newfiles: hash URL -> 1 for new files or external URLs
11808:     # (will be completed later)
11809:     # $mapping:
11810:     #   for external URLs: external URL -> external URL
11811:     #   for relative paths: clean path -> original path
11812:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
11813:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
11814:     foreach my $file (keys(%{$allfiles})) {
11815:         my $embed_file;
11816:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
11817:             $embed_file = $1;
11818:         } else {
11819:             $embed_file = $file;
11820:         }
11821:         my ($absolutepath,$cleaned_file);
11822:         if ($embed_file =~ m{^\w+://}) {
11823:             $cleaned_file = $embed_file;
11824:             $newfiles{$cleaned_file} = 1;
11825:             $mapping{$cleaned_file} = $embed_file;
11826:         } else {
11827:             $cleaned_file = &clean_path($embed_file);
11828:             if ($embed_file =~ m{^/}) {
11829:                 $absolutepath = $embed_file;
11830:             }
11831:             if ($cleaned_file =~ m{/}) {
11832:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
11833:                 $path = &check_for_traversal($path,$url,$toplevel);
11834:                 my $item = $fname;
11835:                 if ($path ne '') {
11836:                     $item = $path.'/'.$fname;
11837:                     $subdependencies{$path}{$fname} = 1;
11838:                 } else {
11839:                     $dependencies{$item} = 1;
11840:                 }
11841:                 if ($absolutepath) {
11842:                     $mapping{$item} = $absolutepath;
11843:                 } else {
11844:                     $mapping{$item} = $embed_file;
11845:                 }
11846:             } else {
11847:                 $dependencies{$embed_file} = 1;
11848:                 if ($absolutepath) {
11849:                     $mapping{$cleaned_file} = $absolutepath;
11850:                 } else {
11851:                     $mapping{$cleaned_file} = $embed_file;
11852:                 }
11853:             }
11854:         }
11855:     }
11856:     
11857:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
11858:     # and lists
11859:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
11860:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
11861:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
11862:     #                                    the path had to be cleaned up
11863:     # $existing: hash clean path -> 1 if the file exists
11864:     # $numexisting: number of keys in $existing
11865:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
11866:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
11867:     #                                      dependency subdirectories that are
11868:     #                                      not listed as dependencies, with some exceptions using $rem
11869:     my $dirptr = 16384;
11870:     foreach my $path (keys(%subdependencies)) {
11871:         $currsubfile{$path} = {};
11872:         if (($actionurl eq '/adm/portfolio') || 
11873:             ($actionurl eq '/adm/coursegrp_portfolio')) {
11874:             my ($sublistref,$listerror) =
11875:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
11876:             if (ref($sublistref) eq 'ARRAY') {
11877:                 foreach my $line (@{$sublistref}) {
11878:                     my ($file_name,$rest) = split(/\&/,$line,2);
11879:                     $currsubfile{$path}{$file_name} = 1;
11880:                 }
11881:             }
11882:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11883:             if (opendir(my $dir,$url.'/'.$path)) {
11884:                 my @subdir_list = grep(!/^\./,readdir($dir));
11885:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
11886:             }
11887:         } elsif (($actionurl eq '/adm/dependencies') ||
11888:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11889:                   ($args->{'context'} eq 'paste')) ||
11890:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
11891:             if ($env{'request.course.id'} ne '') {
11892:                 my $dir;
11893:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
11894:                     $dir = $fileloc;
11895:                 } else {
11896:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
11897:                 }
11898:                 if ($dir ne '') {
11899:                     my ($sublistref,$listerror) =
11900:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
11901:                     if (ref($sublistref) eq 'ARRAY') {
11902:                         foreach my $line (@{$sublistref}) {
11903:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
11904:                                 undef,$mtime)=split(/\&/,$line,12);
11905:                             unless (($testdir&$dirptr) ||
11906:                                     ($file_name =~ /^\.\.?$/)) {
11907:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
11908:                             }
11909:                         }
11910:                     }
11911:                 }
11912:             }
11913:         }
11914:         foreach my $file (keys(%{$subdependencies{$path}})) {
11915:             if (exists($currsubfile{$path}{$file})) {
11916:                 my $item = $path.'/'.$file;
11917:                 unless ($mapping{$item} eq $item) {
11918:                     $pathchanges{$item} = 1;
11919:                 }
11920:                 $existing{$item} = 1;
11921:                 $numexisting ++;
11922:             } else {
11923:                 $newfiles{$path.'/'.$file} = 1;
11924:             }
11925:         }
11926:         if ($actionurl eq '/adm/dependencies') {
11927:             foreach my $path (keys(%currsubfile)) {
11928:                 if (ref($currsubfile{$path}) eq 'HASH') {
11929:                     foreach my $file (keys(%{$currsubfile{$path}})) {
11930:                          unless ($subdependencies{$path}{$file}) {
11931:                              next if (($rem ne '') &&
11932:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
11933:                                        (ref($navmap) &&
11934:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
11935:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
11936:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
11937:                              $unused{$path.'/'.$file} = 1; 
11938:                          }
11939:                     }
11940:                 }
11941:             }
11942:         }
11943:     }
11944:     
11945:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
11946:     # for files in $url or $fileloc (target directory) in some contexts
11947:     my %currfile;
11948:     if (($actionurl eq '/adm/portfolio') ||
11949:         ($actionurl eq '/adm/coursegrp_portfolio')) {
11950:         my ($dirlistref,$listerror) =
11951:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
11952:         if (ref($dirlistref) eq 'ARRAY') {
11953:             foreach my $line (@{$dirlistref}) {
11954:                 my ($file_name,$rest) = split(/\&/,$line,2);
11955:                 $currfile{$file_name} = 1;
11956:             }
11957:         }
11958:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11959:         if (opendir(my $dir,$url)) {
11960:             my @dir_list = grep(!/^\./,readdir($dir));
11961:             map {$currfile{$_} = 1;} @dir_list;
11962:         }
11963:     } elsif (($actionurl eq '/adm/dependencies') ||
11964:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11965:               ($args->{'context'} eq 'paste')) ||
11966:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
11967:         if ($env{'request.course.id'} ne '') {
11968:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
11969:             if ($dir ne '') {
11970:                 my ($dirlistref,$listerror) =
11971:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
11972:                 if (ref($dirlistref) eq 'ARRAY') {
11973:                     foreach my $line (@{$dirlistref}) {
11974:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
11975:                             $size,undef,$mtime)=split(/\&/,$line,12);
11976:                         unless (($testdir&$dirptr) ||
11977:                                 ($file_name =~ /^\.\.?$/)) {
11978:                             $currfile{$file_name} = [$size,$mtime];
11979:                         }
11980:                     }
11981:                 }
11982:             }
11983:         }
11984:     }
11985:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
11986:     # are not in subdirectories, using $currfile
11987:     foreach my $file (keys(%dependencies)) {
11988:         if (exists($currfile{$file})) {
11989:             unless ($mapping{$file} eq $file) {
11990:                 $pathchanges{$file} = 1;
11991:             }
11992:             $existing{$file} = 1;
11993:             $numexisting ++;
11994:         } else {
11995:             $newfiles{$file} = 1;
11996:         }
11997:     }
11998:     foreach my $file (keys(%currfile)) {
11999:         unless (($file eq $filename) ||
12000:                 ($file eq $filename.'.bak') ||
12001:                 ($dependencies{$file})) {
12002:             if ($actionurl eq '/adm/dependencies') {
12003:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
12004:                     next if (($rem ne '') &&
12005:                              (($env{"httpref.$rem".$file} ne '') ||
12006:                               (ref($navmap) &&
12007:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
12008:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
12009:                                 ($navmap->getResourceByUrl($rem.$1)))))));
12010:                 }
12011:             }
12012:             $unused{$file} = 1;
12013:         }
12014:     }
12015:     
12016:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
12017:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
12018:         ($args->{'context'} eq 'paste')) {
12019:         $counter = scalar(keys(%existing));
12020:         $numpathchg = scalar(keys(%pathchanges));
12021:         return ($output,$counter,$numpathchg,\%existing);
12022:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
12023:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
12024:         $counter = scalar(keys(%existing));
12025:         $numpathchg = scalar(keys(%pathchanges));
12026:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
12027:     }
12028:     
12029:     # returns HTML otherwise, with dependency results and to ask for more uploads
12030:     
12031:     # $upload_output: missing dependencies (with upload form)
12032:     # $modify_output: uploaded dependencies (in use)
12033:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
12034:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
12035:         if ($actionurl eq '/adm/dependencies') {
12036:             next if ($embed_file =~ m{^\w+://});
12037:         }
12038:         $upload_output .= &start_data_table_row().
12039:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
12040:                           '<span class="LC_filename">'.$embed_file.'</span>';
12041:         unless ($mapping{$embed_file} eq $embed_file) {
12042:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
12043:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
12044:         }
12045:         $upload_output .= '</td>';
12046:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
12047:             $upload_output.='<td align="right">'.
12048:                             '<span class="LC_info LC_fontsize_medium">'.
12049:                             &mt("URL points to web address").'</span>';
12050:             $numremref++;
12051:         } elsif ($args->{'error_on_invalid_names'}
12052:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
12053:             $upload_output.='<td align="right"><span class="LC_warning">'.
12054:                             &mt('Invalid characters').'</span>';
12055:             $numinvalid++;
12056:         } else {
12057:             $upload_output .= '<td>'.
12058:                               &embedded_file_element('upload_embedded',$counter,
12059:                                                      $embed_file,\%mapping,
12060:                                                      $allfiles,$codebase,'upload');
12061:             $counter ++;
12062:             $numnew ++;
12063:         }
12064:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
12065:     }
12066:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
12067:         if ($actionurl eq '/adm/dependencies') {
12068:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
12069:             $modify_output .= &start_data_table_row().
12070:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
12071:                               '<img src="'.&icon($embed_file).'" border="0" />'.
12072:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
12073:                               '<td>'.$size.'</td>'.
12074:                               '<td>'.$mtime.'</td>'.
12075:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
12076:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
12077:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
12078:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
12079:                               &embedded_file_element('upload_embedded',$counter,
12080:                                                      $embed_file,\%mapping,
12081:                                                      $allfiles,$codebase,'modify').
12082:                               '</div></td>'.
12083:                               &end_data_table_row()."\n";
12084:             $counter ++;
12085:         } else {
12086:             $upload_output .= &start_data_table_row().
12087:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
12088:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
12089:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
12090:                               &Apache::loncommon::end_data_table_row()."\n";
12091:         }
12092:     }
12093:     my $delidx = $counter;
12094:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
12095:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
12096:         $delete_output .= &start_data_table_row().
12097:                           '<td><img src="'.&icon($oldfile).'" />'.
12098:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
12099:                           '<td>'.$size.'</td>'.
12100:                           '<td>'.$mtime.'</td>'.
12101:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
12102:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
12103:                           &embedded_file_element('upload_embedded',$delidx,
12104:                                                  $oldfile,\%mapping,$allfiles,
12105:                                                  $codebase,'delete').'</td>'.
12106:                           &end_data_table_row()."\n"; 
12107:         $numunused ++;
12108:         $delidx ++;
12109:     }
12110:     if ($upload_output) {
12111:         $upload_output = &start_data_table().
12112:                          $upload_output.
12113:                          &end_data_table()."\n";
12114:     }
12115:     if ($modify_output) {
12116:         $modify_output = &start_data_table().
12117:                          &start_data_table_header_row().
12118:                          '<th>'.&mt('File').'</th>'.
12119:                          '<th>'.&mt('Size (KB)').'</th>'.
12120:                          '<th>'.&mt('Modified').'</th>'.
12121:                          '<th>'.&mt('Upload replacement?').'</th>'.
12122:                          &end_data_table_header_row().
12123:                          $modify_output.
12124:                          &end_data_table()."\n";
12125:     }
12126:     if ($delete_output) {
12127:         $delete_output = &start_data_table().
12128:                          &start_data_table_header_row().
12129:                          '<th>'.&mt('File').'</th>'.
12130:                          '<th>'.&mt('Size (KB)').'</th>'.
12131:                          '<th>'.&mt('Modified').'</th>'.
12132:                          '<th>'.&mt('Delete?').'</th>'.
12133:                          &end_data_table_header_row().
12134:                          $delete_output.
12135:                          &end_data_table()."\n";
12136:     }
12137:     my $applies = 0;
12138:     if ($numremref) {
12139:         $applies ++;
12140:     }
12141:     if ($numinvalid) {
12142:         $applies ++;
12143:     }
12144:     if ($numexisting) {
12145:         $applies ++;
12146:     }
12147:     if ($counter || $numunused) {
12148:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
12149:                   ' method="post" enctype="multipart/form-data">'."\n".
12150:                   $state.'<h3>'.$heading.'</h3>'; 
12151:         if ($actionurl eq '/adm/dependencies') {
12152:             if ($numnew) {
12153:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
12154:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
12155:                            $upload_output.'<br />'."\n";
12156:             }
12157:             if ($numexisting) {
12158:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
12159:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
12160:                            $modify_output.'<br />'."\n";
12161:                            $buttontext = &mt('Save changes');
12162:             }
12163:             if ($numunused) {
12164:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
12165:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
12166:                            $delete_output.'<br />'."\n";
12167:                            $buttontext = &mt('Save changes');
12168:             }
12169:         } else {
12170:             $output .= $upload_output.'<br />'."\n";
12171:         }
12172:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
12173:                    $counter.'" />'."\n";
12174:         if ($actionurl eq '/adm/dependencies') { 
12175:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
12176:                        $numnew.'" />'."\n";
12177:         } elsif ($actionurl eq '') {
12178:             $output .=  '<input type="hidden" name="phase" value="three" />';
12179:         }
12180:     } elsif ($applies) {
12181:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
12182:         if ($applies > 1) {
12183:             $output .=  
12184:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
12185:             if ($numremref) {
12186:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
12187:             }
12188:             if ($numinvalid) {
12189:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
12190:             }
12191:             if ($numexisting) {
12192:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
12193:             }
12194:             $output .= '</ul><br />';
12195:         } elsif ($numremref) {
12196:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
12197:         } elsif ($numinvalid) {
12198:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
12199:         } elsif ($numexisting) {
12200:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
12201:         }
12202:         $output .= $upload_output.'<br />';
12203:     }
12204:     my ($pathchange_output,$chgcount);
12205:     $chgcount = $counter;
12206:     if (keys(%pathchanges) > 0) {
12207:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
12208:             if ($counter) {
12209:                 $output .= &embedded_file_element('pathchange',$chgcount,
12210:                                                   $embed_file,\%mapping,
12211:                                                   $allfiles,$codebase,'change');
12212:             } else {
12213:                 $pathchange_output .= 
12214:                     &start_data_table_row().
12215:                     '<td><input type ="checkbox" name="namechange" value="'.
12216:                     $chgcount.'" checked="checked" /></td>'.
12217:                     '<td>'.$mapping{$embed_file}.'</td>'.
12218:                     '<td>'.$embed_file.
12219:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
12220:                                            \%mapping,$allfiles,$codebase,'change').
12221:                     '</td>'.&end_data_table_row();
12222:             }
12223:             $numpathchg ++;
12224:             $chgcount ++;
12225:         }
12226:     }
12227:     if (($counter) || ($numunused)) {
12228:         if ($numpathchg) {
12229:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
12230:                        $numpathchg.'" />'."\n";
12231:         }
12232:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
12233:             ($actionurl eq '/adm/imsimport')) {
12234:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
12235:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
12236:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
12237:         } elsif ($actionurl eq '/adm/dependencies') {
12238:             $output .= '<input type="hidden" name="action" value="process_changes" />';
12239:         }
12240:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
12241:     } elsif ($numpathchg) {
12242:         my %pathchange = ();
12243:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
12244:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
12245:             $output .= '<p>'.&mt('or').'</p>'; 
12246:         }
12247:     }
12248:     return ($output,$counter,$numpathchg);
12249: }
12250: 
12251: =pod
12252: 
12253: =item * clean_path($name)
12254: 
12255: Performs clean-up of directories, subdirectories and filename in an
12256: embedded object, referenced in an HTML file which is being uploaded
12257: to a course or portfolio, where 
12258: "Upload embedded images/multimedia files if HTML file" checkbox was
12259: checked.
12260: 
12261: Clean-up is similar to replacements in lonnet::clean_filename()
12262: except each / between sub-directory and next level is preserved.
12263: 
12264: =cut
12265: 
12266: sub clean_path {
12267:     my ($embed_file) = @_;
12268:     $embed_file =~s{^/+}{};
12269:     my @contents;
12270:     if ($embed_file =~ m{/}) {
12271:         @contents = split(/\//,$embed_file);
12272:     } else {
12273:         @contents = ($embed_file);
12274:     }
12275:     my $lastidx = scalar(@contents)-1;
12276:     for (my $i=0; $i<=$lastidx; $i++) { 
12277:         $contents[$i]=~s{\\}{/}g;
12278:         $contents[$i]=~s/\s+/\_/g;
12279:         $contents[$i]=~s{[^/\w\.\-]}{}g;
12280:         if ($i == $lastidx) {
12281:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
12282:         }
12283:     }
12284:     if ($lastidx > 0) {
12285:         return join('/',@contents);
12286:     } else {
12287:         return $contents[0];
12288:     }
12289: }
12290: 
12291: sub embedded_file_element {
12292:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
12293:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
12294:                    (ref($codebase) eq 'HASH'));
12295:     my $output;
12296:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
12297:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
12298:     }
12299:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
12300:                &escape($embed_file).'" />';
12301:     unless (($context eq 'upload_embedded') && 
12302:             ($mapping->{$embed_file} eq $embed_file)) {
12303:         $output .='
12304:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
12305:     }
12306:     my $attrib;
12307:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
12308:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
12309:     }
12310:     $output .=
12311:         "\n\t\t".
12312:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
12313:         $attrib.'" />';
12314:     if (exists($codebase->{$mapping->{$embed_file}})) {
12315:         $output .=
12316:             "\n\t\t".
12317:             '<input name="codebase_'.$num.'" type="hidden" value="'.
12318:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
12319:     }
12320:     return $output;
12321: }
12322: 
12323: sub get_dependency_details {
12324:     my ($currfile,$currsubfile,$embed_file) = @_;
12325:     my ($size,$mtime,$showsize,$showmtime);
12326:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
12327:         if ($embed_file =~ m{/}) {
12328:             my ($path,$fname) = split(/\//,$embed_file);
12329:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
12330:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
12331:             }
12332:         } else {
12333:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
12334:                 ($size,$mtime) = @{$currfile->{$embed_file}};
12335:             }
12336:         }
12337:         $showsize = $size/1024.0;
12338:         $showsize = sprintf("%.1f",$showsize);
12339:         if ($mtime > 0) {
12340:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
12341:         }
12342:     }
12343:     return ($showsize,$showmtime);
12344: }
12345: 
12346: sub ask_embedded_js {
12347:     return <<"END";
12348: <script type="text/javascript"">
12349: // <![CDATA[
12350: function toggleBrowse(counter) {
12351:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
12352:     var fileid = document.getElementById('embedded_item_'+counter);
12353:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
12354:     if (chkboxid.checked == true) {
12355:         uploaddivid.style.display='block';
12356:     } else {
12357:         uploaddivid.style.display='none';
12358:         fileid.value = '';
12359:     }
12360: }
12361: // ]]>
12362: </script>
12363: 
12364: END
12365: }
12366: 
12367: sub upload_embedded {
12368:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
12369:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
12370:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
12371:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
12372:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
12373:         my $orig_uploaded_filename =
12374:             $env{'form.embedded_item_'.$i.'.filename'};
12375:         foreach my $type ('orig','ref','attrib','codebase') {
12376:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
12377:                 $env{'form.embedded_'.$type.'_'.$i} =
12378:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
12379:             }
12380:         }
12381:         my ($path,$fname) =
12382:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
12383:         # no path, whole string is fname
12384:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
12385:         $fname = &Apache::lonnet::clean_filename($fname);
12386:         # See if there is anything left
12387:         next if ($fname eq '');
12388: 
12389:         # Check if file already exists as a file or directory.
12390:         my ($state,$msg);
12391:         if ($context eq 'portfolio') {
12392:             my $port_path = $dirpath;
12393:             if ($group ne '') {
12394:                 $port_path = "groups/$group/$port_path";
12395:             }
12396:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
12397:                                               $fname,$group,'embedded_item_'.$i,
12398:                                               $dir_root,$port_path,$disk_quota,
12399:                                               $current_disk_usage,$uname,$udom);
12400:             if ($state eq 'will_exceed_quota'
12401:                 || $state eq 'file_locked') {
12402:                 $output .= $msg;
12403:                 next;
12404:             }
12405:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
12406:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
12407:             if ($state eq 'exists') {
12408:                 $output .= $msg;
12409:                 next;
12410:             }
12411:         }
12412:         # Check if extension is valid
12413:         if (($fname =~ /\.(\w+)$/) &&
12414:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
12415:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
12416:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
12417:             next;
12418:         } elsif (($fname =~ /\.(\w+)$/) &&
12419:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
12420:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
12421:             next;
12422:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
12423:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
12424:             next;
12425:         }
12426:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
12427:         my $subdir = $path;
12428:         $subdir =~ s{/+$}{};
12429:         if ($context eq 'portfolio') {
12430:             my $result;
12431:             if ($state eq 'existingfile') {
12432:                 $result=
12433:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
12434:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
12435:             } else {
12436:                 $result=
12437:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
12438:                                                     $dirpath.
12439:                                                     $env{'form.currentpath'}.$subdir);
12440:                 if ($result !~ m|^/uploaded/|) {
12441:                     $output .= '<span class="LC_error">'
12442:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
12443:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
12444:                                .'</span><br />';
12445:                     next;
12446:                 } else {
12447:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
12448:                                $path.$fname.'</span>').'<br />';     
12449:                 }
12450:             }
12451:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
12452:             my $extendedsubdir = $dirpath.'/'.$subdir;
12453:             $extendedsubdir =~ s{/+$}{};
12454:             my $result =
12455:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
12456:             if ($result !~ m|^/uploaded/|) {
12457:                 $output .= '<span class="LC_error">'
12458:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
12459:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
12460:                            .'</span><br />';
12461:                     next;
12462:             } else {
12463:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
12464:                            $path.$fname.'</span>').'<br />';
12465:                 if ($context eq 'syllabus') {
12466:                     &Apache::lonnet::make_public_indefinitely($result);
12467:                 }
12468:             }
12469:         } else {
12470: # Save the file
12471:             my $target = $env{'form.embedded_item_'.$i};
12472:             my $fullpath = $dir_root.$dirpath.'/'.$path;
12473:             my $dest = $fullpath.$fname;
12474:             my $url = $url_root.$dirpath.'/'.$path.$fname;
12475:             my @parts=split(/\//,"$dirpath/$path");
12476:             my $count;
12477:             my $filepath = $dir_root;
12478:             foreach my $subdir (@parts) {
12479:                 $filepath .= "/$subdir";
12480:                 if (!-e $filepath) {
12481:                     mkdir($filepath,0770);
12482:                 }
12483:             }
12484:             my $fh;
12485:             if (!open($fh,'>'.$dest)) {
12486:                 &Apache::lonnet::logthis('Failed to create '.$dest);
12487:                 $output .= '<span class="LC_error">'.
12488:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
12489:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
12490:                            '</span><br />';
12491:             } else {
12492:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
12493:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
12494:                     $output .= '<span class="LC_error">'.
12495:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
12496:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
12497:                               '</span><br />';
12498:                 } else {
12499:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
12500:                                $url.'</span>').'<br />';
12501:                     unless ($context eq 'testbank') {
12502:                         $footer .= &mt('View embedded file: [_1]',
12503:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
12504:                     }
12505:                 }
12506:                 close($fh);
12507:             }
12508:         }
12509:         if ($env{'form.embedded_ref_'.$i}) {
12510:             $pathchange{$i} = 1;
12511:         }
12512:     }
12513:     if ($output) {
12514:         $output = '<p>'.$output.'</p>';
12515:     }
12516:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
12517:     $returnflag = 'ok';
12518:     my $numpathchgs = scalar(keys(%pathchange));
12519:     if ($numpathchgs > 0) {
12520:         if ($context eq 'portfolio') {
12521:             $output .= '<p>'.&mt('or').'</p>';
12522:         } elsif ($context eq 'testbank') {
12523:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
12524:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
12525:             $returnflag = 'modify_orightml';
12526:         }
12527:     }
12528:     return ($output.$footer,$returnflag,$numpathchgs);
12529: }
12530: 
12531: sub modify_html_form {
12532:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
12533:     my $end = 0;
12534:     my $modifyform;
12535:     if ($context eq 'upload_embedded') {
12536:         return unless (ref($pathchange) eq 'HASH');
12537:         if ($env{'form.number_embedded_items'}) {
12538:             $end += $env{'form.number_embedded_items'};
12539:         }
12540:         if ($env{'form.number_pathchange_items'}) {
12541:             $end += $env{'form.number_pathchange_items'};
12542:         }
12543:         if ($end) {
12544:             for (my $i=0; $i<$end; $i++) {
12545:                 if ($i < $env{'form.number_embedded_items'}) {
12546:                     next unless($pathchange->{$i});
12547:                 }
12548:                 $modifyform .=
12549:                     &start_data_table_row().
12550:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
12551:                     'checked="checked" /></td>'.
12552:                     '<td>'.$env{'form.embedded_ref_'.$i}.
12553:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
12554:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
12555:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
12556:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
12557:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
12558:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
12559:                     '<td>'.$env{'form.embedded_orig_'.$i}.
12560:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
12561:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
12562:                     &end_data_table_row();
12563:             }
12564:         }
12565:     } else {
12566:         $modifyform = $pathchgtable;
12567:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12568:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
12569:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
12570:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
12571:         }
12572:     }
12573:     if ($modifyform) {
12574:         if ($actionurl eq '/adm/dependencies') {
12575:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
12576:         }
12577:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
12578:                '<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".
12579:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
12580:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
12581:                '</ol></p>'."\n".'<p>'.
12582:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
12583:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
12584:                &start_data_table()."\n".
12585:                &start_data_table_header_row().
12586:                '<th>'.&mt('Change?').'</th>'.
12587:                '<th>'.&mt('Current reference').'</th>'.
12588:                '<th>'.&mt('Required reference').'</th>'.
12589:                &end_data_table_header_row()."\n".
12590:                $modifyform.
12591:                &end_data_table().'<br />'."\n".$hiddenstate.
12592:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
12593:                '</form>'."\n";
12594:     }
12595:     return;
12596: }
12597: 
12598: sub modify_html_refs {
12599:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
12600:     my $container;
12601:     if ($context eq 'portfolio') {
12602:         $container = $env{'form.container'};
12603:     } elsif ($context eq 'coursedoc') {
12604:         $container = $env{'form.primaryurl'};
12605:     } elsif ($context eq 'manage_dependencies') {
12606:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
12607:         $container = "/$container";
12608:     } elsif ($context eq 'syllabus') {
12609:         $container = $url;
12610:     } else {
12611:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
12612:     }
12613:     my (%allfiles,%codebase,$output,$content);
12614:     my @changes = &get_env_multiple('form.namechange');
12615:     unless ((@changes > 0) || ($context eq 'syllabus')) {
12616:         if (wantarray) {
12617:             return ('',0,0); 
12618:         } else {
12619:             return;
12620:         }
12621:     }
12622:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
12623:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
12624:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
12625:             if (wantarray) {
12626:                 return ('',0,0);
12627:             } else {
12628:                 return;
12629:             }
12630:         } 
12631:         $content = &Apache::lonnet::getfile($container);
12632:         if ($content eq '-1') {
12633:             if (wantarray) {
12634:                 return ('',0,0);
12635:             } else {
12636:                 return;
12637:             }
12638:         }
12639:     } else {
12640:         unless ($container =~ /^\Q$dir_root\E/) {
12641:             if (wantarray) {
12642:                 return ('',0,0);
12643:             } else {
12644:                 return;
12645:             }
12646:         } 
12647:         if (open(my $fh,'<',$container)) {
12648:             $content = join('', <$fh>);
12649:             close($fh);
12650:         } else {
12651:             if (wantarray) {
12652:                 return ('',0,0);
12653:             } else {
12654:                 return;
12655:             }
12656:         }
12657:     }
12658:     my ($count,$codebasecount) = (0,0);
12659:     my $mm = new File::MMagic;
12660:     my $mime_type = $mm->checktype_contents($content);
12661:     if ($mime_type eq 'text/html') {
12662:         my $parse_result = 
12663:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
12664:                                                     \%codebase,\$content);
12665:         if ($parse_result eq 'ok') {
12666:             foreach my $i (@changes) {
12667:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
12668:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
12669:                 if ($allfiles{$ref}) {
12670:                     my $newname =  $orig;
12671:                     my ($attrib_regexp,$codebase);
12672:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
12673:                     if ($attrib_regexp =~ /:/) {
12674:                         $attrib_regexp =~ s/\:/|/g;
12675:                     }
12676:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
12677:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
12678:                         $count += $numchg;
12679:                         $allfiles{$newname} = $allfiles{$ref};
12680:                         delete($allfiles{$ref});
12681:                     }
12682:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
12683:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
12684:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
12685:                         $codebasecount ++;
12686:                     }
12687:                 }
12688:             }
12689:             my $skiprewrites;
12690:             if ($count || $codebasecount) {
12691:                 my $saveresult;
12692:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
12693:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
12694:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
12695:                     if ($url eq $container) {
12696:                         my ($fname) = ($container =~ m{/([^/]+)$});
12697:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
12698:                                             $count,'<span class="LC_filename">'.
12699:                                             $fname.'</span>').'</p>';
12700:                     } else {
12701:                          $output = '<p class="LC_error">'.
12702:                                    &mt('Error: update failed for: [_1].',
12703:                                    '<span class="LC_filename">'.
12704:                                    $container.'</span>').'</p>';
12705:                     }
12706:                     if ($context eq 'syllabus') {
12707:                         unless ($saveresult eq 'ok') {
12708:                             $skiprewrites = 1;
12709:                         }
12710:                     }
12711:                 } else {
12712:                     if (open(my $fh,'>',$container)) {
12713:                         print $fh $content;
12714:                         close($fh);
12715:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
12716:                                   $count,'<span class="LC_filename">'.
12717:                                   $container.'</span>').'</p>';
12718:                     } else {
12719:                          $output = '<p class="LC_error">'.
12720:                                    &mt('Error: could not update [_1].',
12721:                                    '<span class="LC_filename">'.
12722:                                    $container.'</span>').'</p>';
12723:                     }
12724:                 }
12725:             }
12726:             if (($context eq 'syllabus') && (!$skiprewrites)) {
12727:                 my ($actionurl,$state);
12728:                 $actionurl = "/public/$udom/$uname/syllabus";
12729:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
12730:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
12731:                                               \%codebase,
12732:                                               {'context' => 'rewrites',
12733:                                                'ignore_remote_references' => 1,});
12734:                 if (ref($mapping) eq 'HASH') {
12735:                     my $rewrites = 0;
12736:                     foreach my $key (keys(%{$mapping})) {
12737:                         next if ($key =~ m{^https?://});
12738:                         my $ref = $mapping->{$key};
12739:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
12740:                         my $attrib;
12741:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
12742:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
12743:                         }
12744:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
12745:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
12746:                             $rewrites += $numchg;
12747:                         }
12748:                     }
12749:                     if ($rewrites) {
12750:                         my $saveresult; 
12751:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
12752:                         if ($url eq $container) {
12753:                             my ($fname) = ($container =~ m{/([^/]+)$});
12754:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
12755:                                             $count,'<span class="LC_filename">'.
12756:                                             $fname.'</span>').'</p>';
12757:                         } else {
12758:                             $output .= '<p class="LC_error">'.
12759:                                        &mt('Error: could not update links in [_1].',
12760:                                        '<span class="LC_filename">'.
12761:                                        $container.'</span>').'</p>';
12762: 
12763:                         }
12764:                     }
12765:                 }
12766:             }
12767:         } else {
12768:             &logthis('Failed to parse '.$container.
12769:                      ' to modify references: '.$parse_result);
12770:         }
12771:     }
12772:     if (wantarray) {
12773:         return ($output,$count,$codebasecount);
12774:     } else {
12775:         return $output;
12776:     }
12777: }
12778: 
12779: sub check_for_existing {
12780:     my ($path,$fname,$element) = @_;
12781:     my ($state,$msg);
12782:     if (-d $path.'/'.$fname) {
12783:         $state = 'exists';
12784:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
12785:     } elsif (-e $path.'/'.$fname) {
12786:         $state = 'exists';
12787:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
12788:     }
12789:     if ($state eq 'exists') {
12790:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
12791:     }
12792:     return ($state,$msg);
12793: }
12794: 
12795: sub check_for_upload {
12796:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
12797:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
12798:     my $filesize = length($env{'form.'.$element});
12799:     if (!$filesize) {
12800:         my $msg = '<span class="LC_error">'.
12801:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
12802:                       '<span class="LC_filename">'.$fname.'</span>',
12803:                       $filesize).'<br />'.
12804:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
12805:                   '</span>';
12806:         return ('zero_bytes',$msg);
12807:     }
12808:     $filesize =  $filesize/1000; #express in k (1024?)
12809:     my $getpropath = 1;
12810:     my ($dirlistref,$listerror) =
12811:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
12812:     my $found_file = 0;
12813:     my $locked_file = 0;
12814:     my @lockers;
12815:     my $navmap;
12816:     if ($env{'request.course.id'}) {
12817:         $navmap = Apache::lonnavmaps::navmap->new();
12818:     }
12819:     if (ref($dirlistref) eq 'ARRAY') {
12820:         foreach my $line (@{$dirlistref}) {
12821:             my ($file_name,$rest)=split(/\&/,$line,2);
12822:             if ($file_name eq $fname){
12823:                 $file_name = $path.$file_name;
12824:                 if ($group ne '') {
12825:                     $file_name = $group.$file_name;
12826:                 }
12827:                 $found_file = 1;
12828:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
12829:                     foreach my $lock (@lockers) {
12830:                         if (ref($lock) eq 'ARRAY') {
12831:                             my ($symb,$crsid) = @{$lock};
12832:                             if ($crsid eq $env{'request.course.id'}) {
12833:                                 if (ref($navmap)) {
12834:                                     my $res = $navmap->getBySymb($symb);
12835:                                     foreach my $part (@{$res->parts()}) { 
12836:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
12837:                                         unless (($slot_status == $res->RESERVED) ||
12838:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
12839:                                             $locked_file = 1;
12840:                                         }
12841:                                     }
12842:                                 } else {
12843:                                     $locked_file = 1;
12844:                                 }
12845:                             } else {
12846:                                 $locked_file = 1;
12847:                             }
12848:                         }
12849:                    }
12850:                 } else {
12851:                     my @info = split(/\&/,$rest);
12852:                     my $currsize = $info[6]/1000;
12853:                     if ($currsize < $filesize) {
12854:                         my $extra = $filesize - $currsize;
12855:                         if (($current_disk_usage + $extra) > $disk_quota) {
12856:                             my $msg = '<p class="LC_warning">'.
12857:                                       &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.',
12858:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
12859:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
12860:                                                    $disk_quota,$current_disk_usage).'</p>';
12861:                             return ('will_exceed_quota',$msg);
12862:                         }
12863:                     }
12864:                 }
12865:             }
12866:         }
12867:     }
12868:     if (($current_disk_usage + $filesize) > $disk_quota){
12869:         my $msg = '<p class="LC_warning">'.
12870:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
12871:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
12872:         return ('will_exceed_quota',$msg);
12873:     } elsif ($found_file) {
12874:         if ($locked_file) {
12875:             my $msg = '<p class="LC_warning">';
12876:             $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>');
12877:             $msg .= '</p>';
12878:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
12879:             return ('file_locked',$msg);
12880:         } else {
12881:             my $msg = '<p class="LC_error">';
12882:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
12883:             $msg .= '</p>';
12884:             return ('existingfile',$msg);
12885:         }
12886:     }
12887: }
12888: 
12889: sub check_for_traversal {
12890:     my ($path,$url,$toplevel) = @_;
12891:     my @parts=split(/\//,$path);
12892:     my $cleanpath;
12893:     my $fullpath = $url;
12894:     for (my $i=0;$i<@parts;$i++) {
12895:         next if ($parts[$i] eq '.');
12896:         if ($parts[$i] eq '..') {
12897:             $fullpath =~ s{([^/]+/)$}{};
12898:         } else {
12899:             $fullpath .= $parts[$i].'/';
12900:         }
12901:     }
12902:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
12903:         $cleanpath = $1;
12904:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
12905:         my $curr_toprel = $1;
12906:         my @parts = split(/\//,$curr_toprel);
12907:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
12908:         my @urlparts = split(/\//,$url_toprel);
12909:         my $doubledots;
12910:         my $startdiff = -1;
12911:         for (my $i=0; $i<@urlparts; $i++) {
12912:             if ($startdiff == -1) {
12913:                 unless ($urlparts[$i] eq $parts[$i]) {
12914:                     $startdiff = $i;
12915:                     $doubledots .= '../';
12916:                 }
12917:             } else {
12918:                 $doubledots .= '../';
12919:             }
12920:         }
12921:         if ($startdiff > -1) {
12922:             $cleanpath = $doubledots;
12923:             for (my $i=$startdiff; $i<@parts; $i++) {
12924:                 $cleanpath .= $parts[$i].'/';
12925:             }
12926:         }
12927:     }
12928:     $cleanpath =~ s{(/)$}{};
12929:     return $cleanpath;
12930: }
12931: 
12932: sub is_archive_file {
12933:     my ($mimetype) = @_;
12934:     if (($mimetype eq 'application/octet-stream') ||
12935:         ($mimetype eq 'application/x-stuffit') ||
12936:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
12937:         return 1;
12938:     }
12939:     return;
12940: }
12941: 
12942: sub decompress_form {
12943:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
12944:     my %lt = &Apache::lonlocal::texthash (
12945:         this => 'This file is an archive file.',
12946:         camt => 'This file is a Camtasia archive file.',
12947:         itsc => 'Its contents are as follows:',
12948:         youm => 'You may wish to extract its contents.',
12949:         extr => 'Extract contents',
12950:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
12951:         proa => 'Process automatically?',
12952:         yes  => 'Yes',
12953:         no   => 'No',
12954:         fold => 'Title for folder containing movie',
12955:         movi => 'Title for page containing embedded movie', 
12956:     );
12957:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
12958:     my ($is_camtasia,$topdir,%toplevel,@paths);
12959:     my $info = &list_archive_contents($fileloc,\@paths);
12960:     if (@paths) {
12961:         foreach my $path (@paths) {
12962:             $path =~ s{^/}{};
12963:             if ($path =~ m{^([^/]+)/$}) {
12964:                 $topdir = $1;
12965:             }
12966:             if ($path =~ m{^([^/]+)/}) {
12967:                 $toplevel{$1} = $path;
12968:             } else {
12969:                 $toplevel{$path} = $path;
12970:             }
12971:         }
12972:     }
12973:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
12974:         my @camtasia6 = ("$topdir/","$topdir/index.html",
12975:                         "$topdir/media/",
12976:                         "$topdir/media/$topdir.mp4",
12977:                         "$topdir/media/FirstFrame.png",
12978:                         "$topdir/media/player.swf",
12979:                         "$topdir/media/swfobject.js",
12980:                         "$topdir/media/expressInstall.swf");
12981:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
12982:                          "$topdir/$topdir.mp4",
12983:                          "$topdir/$topdir\_config.xml",
12984:                          "$topdir/$topdir\_controller.swf",
12985:                          "$topdir/$topdir\_embed.css",
12986:                          "$topdir/$topdir\_First_Frame.png",
12987:                          "$topdir/$topdir\_player.html",
12988:                          "$topdir/$topdir\_Thumbnails.png",
12989:                          "$topdir/playerProductInstall.swf",
12990:                          "$topdir/scripts/",
12991:                          "$topdir/scripts/config_xml.js",
12992:                          "$topdir/scripts/handlebars.js",
12993:                          "$topdir/scripts/jquery-1.7.1.min.js",
12994:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
12995:                          "$topdir/scripts/modernizr.js",
12996:                          "$topdir/scripts/player-min.js",
12997:                          "$topdir/scripts/swfobject.js",
12998:                          "$topdir/skins/",
12999:                          "$topdir/skins/configuration_express.xml",
13000:                          "$topdir/skins/express_show/",
13001:                          "$topdir/skins/express_show/player-min.css",
13002:                          "$topdir/skins/express_show/spritesheet.png");
13003:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
13004:                          "$topdir/$topdir.mp4",
13005:                          "$topdir/$topdir\_config.xml",
13006:                          "$topdir/$topdir\_controller.swf",
13007:                          "$topdir/$topdir\_embed.css",
13008:                          "$topdir/$topdir\_First_Frame.png",
13009:                          "$topdir/$topdir\_player.html",
13010:                          "$topdir/$topdir\_Thumbnails.png",
13011:                          "$topdir/playerProductInstall.swf",
13012:                          "$topdir/scripts/",
13013:                          "$topdir/scripts/config_xml.js",
13014:                          "$topdir/scripts/techsmith-smart-player.min.js",
13015:                          "$topdir/skins/",
13016:                          "$topdir/skins/configuration_express.xml",
13017:                          "$topdir/skins/express_show/",
13018:                          "$topdir/skins/express_show/spritesheet.min.css",
13019:                          "$topdir/skins/express_show/spritesheet.png",
13020:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
13021:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
13022:         if (@diffs == 0) {
13023:             $is_camtasia = 6;
13024:         } else {
13025:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
13026:             if (@diffs == 0) {
13027:                 $is_camtasia = 8;
13028:             } else {
13029:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
13030:                 if (@diffs == 0) {
13031:                     $is_camtasia = 8;
13032:                 }
13033:             }
13034:         }
13035:     }
13036:     my $output;
13037:     if ($is_camtasia) {
13038:         $output = <<"ENDCAM";
13039: <script type="text/javascript" language="Javascript">
13040: // <![CDATA[
13041: 
13042: function camtasiaToggle() {
13043:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
13044:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
13045:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
13046:                 document.getElementById('camtasia_titles').style.display='block';
13047:             } else {
13048:                 document.getElementById('camtasia_titles').style.display='none';
13049:             }
13050:         }
13051:     }
13052:     return;
13053: }
13054: 
13055: // ]]>
13056: </script>
13057: <p>$lt{'camt'}</p>
13058: ENDCAM
13059:     } else {
13060:         $output = '<p>'.$lt{'this'};
13061:         if ($info eq '') {
13062:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
13063:         } else {
13064:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
13065:                        '<div><pre>'.$info.'</pre></div>';
13066:         }
13067:     }
13068:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
13069:     my $duplicates;
13070:     my $num = 0;
13071:     if (ref($dirlist) eq 'ARRAY') {
13072:         foreach my $item (@{$dirlist}) {
13073:             if (ref($item) eq 'ARRAY') {
13074:                 if (exists($toplevel{$item->[0]})) {
13075:                     $duplicates .= 
13076:                         &start_data_table_row().
13077:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
13078:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
13079:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
13080:                         'value="1" />'.&mt('Yes').'</label>'.
13081:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
13082:                         '<td>'.$item->[0].'</td>';
13083:                     if ($item->[2]) {
13084:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
13085:                     } else {
13086:                         $duplicates .= '<td>'.&mt('File').'</td>';
13087:                     }
13088:                     $duplicates .= '<td>'.$item->[3].'</td>'.
13089:                                    '<td>'.
13090:                                    &Apache::lonlocal::locallocaltime($item->[4]).
13091:                                    '</td>'.
13092:                                    &end_data_table_row();
13093:                     $num ++;
13094:                 }
13095:             }
13096:         }
13097:     }
13098:     my $itemcount;
13099:     if (@paths > 0) {
13100:         $itemcount = scalar(@paths);
13101:     } else {
13102:         $itemcount = 1;
13103:     }
13104:     if ($is_camtasia) {
13105:         $output .= $lt{'auto'}.'<br />'.
13106:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
13107:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
13108:                    $lt{'yes'}.'</label>&nbsp;<label>'.
13109:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
13110:                    $lt{'no'}.'</label></span><br />'.
13111:                    '<div id="camtasia_titles" style="display:block">'.
13112:                    &Apache::lonhtmlcommon::start_pick_box().
13113:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
13114:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
13115:                    &Apache::lonhtmlcommon::row_closure().
13116:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
13117:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
13118:                    &Apache::lonhtmlcommon::row_closure(1).
13119:                    &Apache::lonhtmlcommon::end_pick_box().
13120:                    '</div>';
13121:     }
13122:     $output .= 
13123:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
13124:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
13125:         "\n";
13126:     if ($duplicates ne '') {
13127:         $output .= '<p><span class="LC_warning">'.
13128:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
13129:                    &start_data_table().
13130:                    &start_data_table_header_row().
13131:                    '<th>'.&mt('Overwrite?').'</th>'.
13132:                    '<th>'.&mt('Name').'</th>'.
13133:                    '<th>'.&mt('Type').'</th>'.
13134:                    '<th>'.&mt('Size').'</th>'.
13135:                    '<th>'.&mt('Last modified').'</th>'.
13136:                    &end_data_table_header_row().
13137:                    $duplicates.
13138:                    &end_data_table().
13139:                    '</p>';
13140:     }
13141:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
13142:     if (ref($hiddenelements) eq 'HASH') {
13143:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
13144:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
13145:         }
13146:     }
13147:     $output .= <<"END";
13148: <br />
13149: <input type="submit" name="decompress" value="$lt{'extr'}" />
13150: </form>
13151: $noextract
13152: END
13153:     return $output;
13154: }
13155: 
13156: sub decompression_utility {
13157:     my ($program) = @_;
13158:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
13159:     my $location;
13160:     if (grep(/^\Q$program\E$/,@utilities)) { 
13161:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
13162:                          '/usr/sbin/') {
13163:             if (-x $dir.$program) {
13164:                 $location = $dir.$program;
13165:                 last;
13166:             }
13167:         }
13168:     }
13169:     return $location;
13170: }
13171: 
13172: sub list_archive_contents {
13173:     my ($file,$pathsref) = @_;
13174:     my (@cmd,$output);
13175:     my $needsregexp;
13176:     if ($file =~ /\.zip$/) {
13177:         @cmd = (&decompression_utility('unzip'),"-l");
13178:         $needsregexp = 1;
13179:     } elsif (($file =~ m/\.tar\.gz$/) ||
13180:              ($file =~ /\.tgz$/)) {
13181:         @cmd = (&decompression_utility('tar'),"-ztf");
13182:     } elsif ($file =~ /\.tar\.bz2$/) {
13183:         @cmd = (&decompression_utility('tar'),"-jtf");
13184:     } elsif ($file =~ m|\.tar$|) {
13185:         @cmd = (&decompression_utility('tar'),"-tf");
13186:     }
13187:     if (@cmd) {
13188:         undef($!);
13189:         undef($@);
13190:         if (open(my $fh,"-|", @cmd, $file)) {
13191:             while (my $line = <$fh>) {
13192:                 $output .= $line;
13193:                 chomp($line);
13194:                 my $item;
13195:                 if ($needsregexp) {
13196:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
13197:                 } else {
13198:                     $item = $line;
13199:                 }
13200:                 if ($item ne '') {
13201:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
13202:                         push(@{$pathsref},$item);
13203:                     } 
13204:                 }
13205:             }
13206:             close($fh);
13207:         }
13208:     }
13209:     return $output;
13210: }
13211: 
13212: sub decompress_uploaded_file {
13213:     my ($file,$dir) = @_;
13214:     &Apache::lonnet::appenv({'cgi.file' => $file});
13215:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
13216:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
13217:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
13218:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
13219:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
13220:     my $decompressed = $env{'cgi.decompressed'};
13221:     &Apache::lonnet::delenv('cgi.file');
13222:     &Apache::lonnet::delenv('cgi.dir');
13223:     &Apache::lonnet::delenv('cgi.decompressed');
13224:     return ($decompressed,$result);
13225: }
13226: 
13227: sub process_decompression {
13228:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
13229:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
13230:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13231:                &mt('Unexpected file path.').'</p>'."\n";
13232:     }
13233:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
13234:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13235:                &mt('Unexpected course context.').'</p>'."\n";
13236:     }
13237:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
13238:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13239:                &mt('Filename contained unexpected characters.').'</p>'."\n";
13240:     }
13241:     my ($dir,$error,$warning,$output);
13242:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
13243:         $error = &mt('Filename not a supported archive file type.').
13244:                  '<br />'.&mt('Filename should end with one of: [_1].',
13245:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
13246:     } else {
13247:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
13248:         if ($docuhome eq 'no_host') {
13249:             $error = &mt('Could not determine home server for course.');
13250:         } else {
13251:             my @ids=&Apache::lonnet::current_machine_ids();
13252:             my $currdir = "$dir_root/$destination";
13253:             if (grep(/^\Q$docuhome\E$/,@ids)) {
13254:                 $dir = &LONCAPA::propath($docudom,$docuname).
13255:                        "$dir_root/$destination";
13256:             } else {
13257:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
13258:                        "$dir_root/$docudom/$docuname/$destination";
13259:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
13260:                     $error = &mt('Archive file not found.');
13261:                 }
13262:             }
13263:             my (@to_overwrite,@to_skip);
13264:             if ($env{'form.archive_overwrite_total'} > 0) {
13265:                 my $total = $env{'form.archive_overwrite_total'};
13266:                 for (my $i=0; $i<$total; $i++) {
13267:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
13268:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
13269:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
13270:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
13271:                     }
13272:                 }
13273:             }
13274:             my $numskip = scalar(@to_skip);
13275:             my $numoverwrite = scalar(@to_overwrite);
13276:             if (($numskip) && (!$numoverwrite)) { 
13277:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
13278:             } elsif ($dir eq '') {
13279:                 $error = &mt('Directory containing archive file unavailable.');
13280:             } elsif (!$error) {
13281:                 my ($decompressed,$display);
13282:                 if (($numskip) || ($numoverwrite)) {
13283:                     my $tempdir = time.'_'.$$.int(rand(10000));
13284:                     mkdir("$dir/$tempdir",0755);
13285:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
13286:                         ($decompressed,$display) = 
13287:                             &decompress_uploaded_file($file,"$dir/$tempdir");
13288:                         foreach my $item (@to_skip) {
13289:                             if (($item ne '') && ($item !~ /\.\./)) {
13290:                                 if (-f "$dir/$tempdir/$item") { 
13291:                                     unlink("$dir/$tempdir/$item");
13292:                                 } elsif (-d "$dir/$tempdir/$item") {
13293:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
13294:                                 }
13295:                             }
13296:                         }
13297:                         foreach my $item (@to_overwrite) {
13298:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
13299:                                 if (($item ne '') && ($item !~ /\.\./)) {
13300:                                     if (-f "$dir/$item") {
13301:                                         unlink("$dir/$item");
13302:                                     } elsif (-d "$dir/$item") {
13303:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
13304:                                     }
13305:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
13306:                                 }
13307:                             }
13308:                         }
13309:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
13310:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
13311:                         }
13312:                     }
13313:                 } else {
13314:                     ($decompressed,$display) = 
13315:                         &decompress_uploaded_file($file,$dir);
13316:                 }
13317:                 if ($decompressed eq 'ok') {
13318:                     $output = '<p class="LC_info">'.
13319:                               &mt('Files extracted successfully from archive.').
13320:                               '</p>'."\n";
13321:                     my ($warning,$result,@contents);
13322:                     my ($newdirlistref,$newlisterror) =
13323:                         &Apache::lonnet::dirlist($currdir,$docudom,
13324:                                                  $docuname,1);
13325:                     my (%is_dir,%changes,@newitems);
13326:                     my $dirptr = 16384;
13327:                     if (ref($newdirlistref) eq 'ARRAY') {
13328:                         foreach my $dir_line (@{$newdirlistref}) {
13329:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
13330:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
13331:                                 push(@newitems,$item);
13332:                                 if ($dirptr&$testdir) {
13333:                                     $is_dir{$item} = 1;
13334:                                 }
13335:                                 $changes{$item} = 1;
13336:                             }
13337:                         }
13338:                     }
13339:                     if (keys(%changes) > 0) {
13340:                         foreach my $item (sort(@newitems)) {
13341:                             if ($changes{$item}) {
13342:                                 push(@contents,$item);
13343:                             }
13344:                         }
13345:                     }
13346:                     if (@contents > 0) {
13347:                         my $wantform;
13348:                         unless ($env{'form.autoextract_camtasia'}) {
13349:                             $wantform = 1;
13350:                         }
13351:                         my (%children,%parent,%dirorder,%titles);
13352:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
13353:                                                                 $currdir,\%is_dir,
13354:                                                                 \%children,\%parent,
13355:                                                                 \@contents,\%dirorder,
13356:                                                                 \%titles,$wantform);
13357:                         if ($datatable ne '') {
13358:                             $output .= &archive_options_form('decompressed',$datatable,
13359:                                                              $count,$hiddenelem);
13360:                             my $startcount = 6;
13361:                             $output .= &archive_javascript($startcount,$count,
13362:                                                            \%titles,\%children);
13363:                         }
13364:                         if ($env{'form.autoextract_camtasia'}) {
13365:                             my $version = $env{'form.autoextract_camtasia'};
13366:                             my %displayed;
13367:                             my $total = 1;
13368:                             $env{'form.archive_directory'} = [];
13369:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
13370:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
13371:                                 $path =~ s{/$}{};
13372:                                 my $item;
13373:                                 if ($path ne '') {
13374:                                     $item = "$path/$titles{$i}";
13375:                                 } else {
13376:                                     $item = $titles{$i};
13377:                                 }
13378:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
13379:                                 if ($item eq $contents[0]) {
13380:                                     push(@{$env{'form.archive_directory'}},$i);
13381:                                     $env{'form.archive_'.$i} = 'display';
13382:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
13383:                                     $displayed{'folder'} = $i;
13384:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
13385:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
13386:                                     $env{'form.archive_'.$i} = 'display';
13387:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
13388:                                     $displayed{'web'} = $i;
13389:                                 } else {
13390:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
13391:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
13392:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
13393:                                         push(@{$env{'form.archive_directory'}},$i);
13394:                                     }
13395:                                     $env{'form.archive_'.$i} = 'dependency';
13396:                                 }
13397:                                 $total ++;
13398:                             }
13399:                             for (my $i=1; $i<$total; $i++) {
13400:                                 next if ($i == $displayed{'web'});
13401:                                 next if ($i == $displayed{'folder'});
13402:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
13403:                             }
13404:                             $env{'form.phase'} = 'decompress_cleanup';
13405:                             $env{'form.archivedelete'} = 1;
13406:                             $env{'form.archive_count'} = $total-1;
13407:                             $output .=
13408:                                 &process_extracted_files('coursedocs',$docudom,
13409:                                                          $docuname,$destination,
13410:                                                          $dir_root,$hiddenelem);
13411:                         }
13412:                     } else {
13413:                         $warning = &mt('No new items extracted from archive file.');
13414:                     }
13415:                 } else {
13416:                     $output = $display;
13417:                     $error = &mt('An error occurred during extraction from the archive file.');
13418:                 }
13419:             }
13420:         }
13421:     }
13422:     if ($error) {
13423:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13424:                    $error.'</p>'."\n";
13425:     }
13426:     if ($warning) {
13427:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
13428:     }
13429:     return $output;
13430: }
13431: 
13432: sub get_extracted {
13433:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
13434:         $titles,$wantform) = @_;
13435:     my $count = 0;
13436:     my $depth = 0;
13437:     my $datatable;
13438:     my @hierarchy;
13439:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
13440:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
13441:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
13442:     foreach my $item (@{$contents}) {
13443:         $count ++;
13444:         @{$dirorder->{$count}} = @hierarchy;
13445:         $titles->{$count} = $item;
13446:         &archive_hierarchy($depth,$count,$parent,$children);
13447:         if ($wantform) {
13448:             $datatable .= &archive_row($is_dir->{$item},$item,
13449:                                        $currdir,$depth,$count);
13450:         }
13451:         if ($is_dir->{$item}) {
13452:             $depth ++;
13453:             push(@hierarchy,$count);
13454:             $parent->{$depth} = $count;
13455:             $datatable .=
13456:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
13457:                                            \$depth,\$count,\@hierarchy,$dirorder,
13458:                                            $children,$parent,$titles,$wantform);
13459:             $depth --;
13460:             pop(@hierarchy);
13461:         }
13462:     }
13463:     return ($count,$datatable);
13464: }
13465: 
13466: sub recurse_extracted_archive {
13467:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
13468:         $children,$parent,$titles,$wantform) = @_;
13469:     my $result='';
13470:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
13471:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
13472:             (ref($dirorder) eq 'HASH')) {
13473:         return $result;
13474:     }
13475:     my $dirptr = 16384;
13476:     my ($newdirlistref,$newlisterror) =
13477:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
13478:     if (ref($newdirlistref) eq 'ARRAY') {
13479:         foreach my $dir_line (@{$newdirlistref}) {
13480:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
13481:             unless ($item =~ /^\.+$/) {
13482:                 $$count ++;
13483:                 @{$dirorder->{$$count}} = @{$hierarchy};
13484:                 $titles->{$$count} = $item;
13485:                 &archive_hierarchy($$depth,$$count,$parent,$children);
13486: 
13487:                 my $is_dir;
13488:                 if ($dirptr&$testdir) {
13489:                     $is_dir = 1;
13490:                 }
13491:                 if ($wantform) {
13492:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
13493:                 }
13494:                 if ($is_dir) {
13495:                     $$depth ++;
13496:                     push(@{$hierarchy},$$count);
13497:                     $parent->{$$depth} = $$count;
13498:                     $result .=
13499:                         &recurse_extracted_archive("$currdir/$item",$docudom,
13500:                                                    $docuname,$depth,$count,
13501:                                                    $hierarchy,$dirorder,$children,
13502:                                                    $parent,$titles,$wantform);
13503:                     $$depth --;
13504:                     pop(@{$hierarchy});
13505:                 }
13506:             }
13507:         }
13508:     }
13509:     return $result;
13510: }
13511: 
13512: sub archive_hierarchy {
13513:     my ($depth,$count,$parent,$children) =@_;
13514:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
13515:         if (exists($parent->{$depth})) {
13516:              $children->{$parent->{$depth}} .= $count.':';
13517:         }
13518:     }
13519:     return;
13520: }
13521: 
13522: sub archive_row {
13523:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
13524:     my ($name) = ($item =~ m{([^/]+)$});
13525:     my %choices = &Apache::lonlocal::texthash (
13526:                                        'display'    => 'Add as file',
13527:                                        'dependency' => 'Include as dependency',
13528:                                        'discard'    => 'Discard',
13529:                                       );
13530:     if ($is_dir) {
13531:         $choices{'display'} = &mt('Add as folder'); 
13532:     }
13533:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
13534:     my $offset = 0;
13535:     foreach my $action ('display','dependency','discard') {
13536:         $offset ++;
13537:         if ($action ne 'display') {
13538:             $offset ++;
13539:         }  
13540:         $output .= '<td><span class="LC_nobreak">'.
13541:                    '<label><input type="radio" name="archive_'.$count.
13542:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
13543:         my $text = $choices{$action};
13544:         if ($is_dir) {
13545:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
13546:             if ($action eq 'display') {
13547:                 $text = &mt('Add as folder');
13548:             }
13549:         } else {
13550:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
13551: 
13552:         }
13553:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
13554:         if ($action eq 'dependency') {
13555:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
13556:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
13557:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
13558:                        '<option value=""></option>'."\n".
13559:                        '</select>'."\n".
13560:                        '</div>';
13561:         } elsif ($action eq 'display') {
13562:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
13563:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
13564:                        '</div>';
13565:         }
13566:         $output .= '</td>';
13567:     }
13568:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
13569:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
13570:     for (my $i=0; $i<$depth; $i++) {
13571:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
13572:     }
13573:     if ($is_dir) {
13574:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
13575:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
13576:     } else {
13577:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
13578:     }
13579:     $output .= '&nbsp;'.$name.'</td>'."\n".
13580:                &end_data_table_row();
13581:     return $output;
13582: }
13583: 
13584: sub archive_options_form {
13585:     my ($form,$display,$count,$hiddenelem) = @_;
13586:     my %lt = &Apache::lonlocal::texthash(
13587:                perm => 'Permanently remove archive file?',
13588:                hows => 'How should each extracted item be incorporated in the course?',
13589:                cont => 'Content actions for all',
13590:                addf => 'Add as folder/file',
13591:                incd => 'Include as dependency for a displayed file',
13592:                disc => 'Discard',
13593:                no   => 'No',
13594:                yes  => 'Yes',
13595:                save => 'Save',
13596:     );
13597:     my $output = <<"END";
13598: <form name="$form" method="post" action="">
13599: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
13600: <label>
13601:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
13602: </label>
13603: &nbsp;
13604: <label>
13605:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
13606: </span>
13607: </p>
13608: <input type="hidden" name="phase" value="decompress_cleanup" />
13609: <br />$lt{'hows'}
13610: <div class="LC_columnSection">
13611:   <fieldset>
13612:     <legend>$lt{'cont'}</legend>
13613:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
13614:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
13615:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
13616:   </fieldset>
13617: </div>
13618: END
13619:     return $output.
13620:            &start_data_table()."\n".
13621:            $display."\n".
13622:            &end_data_table()."\n".
13623:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
13624:            $hiddenelem.
13625:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
13626:            '</form>';
13627: }
13628: 
13629: sub archive_javascript {
13630:     my ($startcount,$numitems,$titles,$children) = @_;
13631:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
13632:     my $maintitle = $env{'form.comment'};
13633:     my $scripttag = <<START;
13634: <script type="text/javascript">
13635: // <![CDATA[
13636: 
13637: function checkAll(form,prefix) {
13638:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
13639:     for (var i=0; i < form.elements.length; i++) {
13640:         var id = form.elements[i].id;
13641:         if ((id != '') && (id != undefined)) {
13642:             if (idstr.test(id)) {
13643:                 if (form.elements[i].type == 'radio') {
13644:                     form.elements[i].checked = true;
13645:                     var nostart = i-$startcount;
13646:                     var offset = nostart%7;
13647:                     var count = (nostart-offset)/7;    
13648:                     dependencyCheck(form,count,offset);
13649:                 }
13650:             }
13651:         }
13652:     }
13653: }
13654: 
13655: function propagateCheck(form,count) {
13656:     if (count > 0) {
13657:         var startelement = $startcount + ((count-1) * 7);
13658:         for (var j=1; j<6; j++) {
13659:             if ((j != 2) && (j != 4)) {
13660:                 var item = startelement + j; 
13661:                 if (form.elements[item].type == 'radio') {
13662:                     if (form.elements[item].checked) {
13663:                         containerCheck(form,count,j);
13664:                         break;
13665:                     }
13666:                 }
13667:             }
13668:         }
13669:     }
13670: }
13671: 
13672: numitems = $numitems
13673: var titles = new Array(numitems);
13674: var parents = new Array(numitems);
13675: for (var i=0; i<numitems; i++) {
13676:     parents[i] = new Array;
13677: }
13678: var maintitle = '$maintitle';
13679: 
13680: START
13681: 
13682:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
13683:         my @contents = split(/:/,$children->{$container});
13684:         for (my $i=0; $i<@contents; $i ++) {
13685:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
13686:         }
13687:     }
13688: 
13689:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
13690:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
13691:     }
13692: 
13693:     $scripttag .= <<END;
13694: 
13695: function containerCheck(form,count,offset) {
13696:     if (count > 0) {
13697:         dependencyCheck(form,count,offset);
13698:         var item = (offset+$startcount)+7*(count-1);
13699:         form.elements[item].checked = true;
13700:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
13701:             if (parents[count].length > 0) {
13702:                 for (var j=0; j<parents[count].length; j++) {
13703:                     containerCheck(form,parents[count][j],offset);
13704:                 }
13705:             }
13706:         }
13707:     }
13708: }
13709: 
13710: function dependencyCheck(form,count,offset) {
13711:     if (count > 0) {
13712:         var chosen = (offset+$startcount)+7*(count-1);
13713:         var depitem = $startcount + ((count-1) * 7) + 4;
13714:         var currtype = form.elements[depitem].type;
13715:         if (form.elements[chosen].value == 'dependency') {
13716:             document.getElementById('arc_depon_'+count).style.display='block'; 
13717:             form.elements[depitem].options.length = 0;
13718:             form.elements[depitem].options[0] = new Option('Select','',true,true);
13719:             for (var i=1; i<=numitems; i++) {
13720:                 if (i == count) {
13721:                     continue;
13722:                 }
13723:                 var startelement = $startcount + (i-1) * 7;
13724:                 for (var j=1; j<6; j++) {
13725:                     if ((j != 2) && (j!= 4)) {
13726:                         var item = startelement + j;
13727:                         if (form.elements[item].type == 'radio') {
13728:                             if (form.elements[item].checked) {
13729:                                 if (form.elements[item].value == 'display') {
13730:                                     var n = form.elements[depitem].options.length;
13731:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
13732:                                 }
13733:                             }
13734:                         }
13735:                     }
13736:                 }
13737:             }
13738:         } else {
13739:             document.getElementById('arc_depon_'+count).style.display='none';
13740:             form.elements[depitem].options.length = 0;
13741:             form.elements[depitem].options[0] = new Option('Select','',true,true);
13742:         }
13743:         titleCheck(form,count,offset);
13744:     }
13745: }
13746: 
13747: function propagateSelect(form,count,offset) {
13748:     if (count > 0) {
13749:         var item = (1+offset+$startcount)+7*(count-1);
13750:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
13751:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
13752:             if (parents[count].length > 0) {
13753:                 for (var j=0; j<parents[count].length; j++) {
13754:                     containerSelect(form,parents[count][j],offset,picked);
13755:                 }
13756:             }
13757:         }
13758:     }
13759: }
13760: 
13761: function containerSelect(form,count,offset,picked) {
13762:     if (count > 0) {
13763:         var item = (offset+$startcount)+7*(count-1);
13764:         if (form.elements[item].type == 'radio') {
13765:             if (form.elements[item].value == 'dependency') {
13766:                 if (form.elements[item+1].type == 'select-one') {
13767:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
13768:                         if (form.elements[item+1].options[i].value == picked) {
13769:                             form.elements[item+1].selectedIndex = i;
13770:                             break;
13771:                         }
13772:                     }
13773:                 }
13774:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
13775:                     if (parents[count].length > 0) {
13776:                         for (var j=0; j<parents[count].length; j++) {
13777:                             containerSelect(form,parents[count][j],offset,picked);
13778:                         }
13779:                     }
13780:                 }
13781:             }
13782:         }
13783:     }
13784: }
13785: 
13786: function titleCheck(form,count,offset) {
13787:     if (count > 0) {
13788:         var chosen = (offset+$startcount)+7*(count-1);
13789:         var depitem = $startcount + ((count-1) * 7) + 2;
13790:         var currtype = form.elements[depitem].type;
13791:         if (form.elements[chosen].value == 'display') {
13792:             document.getElementById('arc_title_'+count).style.display='block';
13793:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
13794:                 document.getElementById('archive_title_'+count).value=maintitle;
13795:             }
13796:         } else {
13797:             document.getElementById('arc_title_'+count).style.display='none';
13798:             if (currtype == 'text') { 
13799:                 document.getElementById('archive_title_'+count).value='';
13800:             }
13801:         }
13802:     }
13803:     return;
13804: }
13805: 
13806: // ]]>
13807: </script>
13808: END
13809:     return $scripttag;
13810: }
13811: 
13812: sub process_extracted_files {
13813:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
13814:     my $numitems = $env{'form.archive_count'};
13815:     return if ((!$numitems) || ($numitems =~ /\D/));
13816:     my @ids=&Apache::lonnet::current_machine_ids();
13817:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
13818:         %folders,%containers,%mapinner,%prompttofetch);
13819:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
13820:     if (grep(/^\Q$docuhome\E$/,@ids)) {
13821:         $prefix = &LONCAPA::propath($docudom,$docuname);
13822:         $pathtocheck = "$dir_root/$destination";
13823:         $dir = $dir_root;
13824:         $ishome = 1;
13825:     } else {
13826:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
13827:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
13828:         $dir = "$dir_root/$docudom/$docuname";
13829:     }
13830:     my $currdir = "$dir_root/$destination";
13831:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
13832:     if ($env{'form.folderpath'}) {
13833:         my @items = split('&',$env{'form.folderpath'});
13834:         $folders{'0'} = $items[-2];
13835:         if ($env{'form.folderpath'} =~ /\:1$/) {
13836:             $containers{'0'}='page';
13837:         } else {  
13838:             $containers{'0'}='sequence';
13839:         }
13840:     }
13841:     my @archdirs = &get_env_multiple('form.archive_directory');
13842:     if ($numitems) {
13843:         for (my $i=1; $i<=$numitems; $i++) {
13844:             my $path = $env{'form.archive_content_'.$i};
13845:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
13846:                 my $item = $1;
13847:                 $toplevelitems{$item} = $i;
13848:                 if (grep(/^\Q$i\E$/,@archdirs)) {
13849:                     $is_dir{$item} = 1;
13850:                 }
13851:             }
13852:         }
13853:     }
13854:     my ($output,%children,%parent,%titles,%dirorder,$result);
13855:     if (keys(%toplevelitems) > 0) {
13856:         my @contents = sort(keys(%toplevelitems));
13857:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
13858:                                            \%parent,\@contents,\%dirorder,\%titles);
13859:     }
13860:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
13861:     if ($numitems) {
13862:         for (my $i=1; $i<=$numitems; $i++) {
13863:             next if ($env{'form.archive_'.$i} eq 'dependency');
13864:             my $path = $env{'form.archive_content_'.$i};
13865:             if ($path =~ /^\Q$pathtocheck\E/) {
13866:                 if ($env{'form.archive_'.$i} eq 'discard') {
13867:                     if ($prefix ne '' && $path ne '') {
13868:                         if (-e $prefix.$path) {
13869:                             if ((@archdirs > 0) && 
13870:                                 (grep(/^\Q$i\E$/,@archdirs))) {
13871:                                 $todeletedir{$prefix.$path} = 1;
13872:                             } else {
13873:                                 $todelete{$prefix.$path} = 1;
13874:                             }
13875:                         }
13876:                     }
13877:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
13878:                     my ($docstitle,$title,$url,$outer);
13879:                     ($title) = ($path =~ m{/([^/]+)$});
13880:                     $docstitle = $env{'form.archive_title_'.$i};
13881:                     if ($docstitle eq '') {
13882:                         $docstitle = $title;
13883:                     }
13884:                     $outer = 0;
13885:                     if (ref($dirorder{$i}) eq 'ARRAY') {
13886:                         if (@{$dirorder{$i}} > 0) {
13887:                             foreach my $item (reverse(@{$dirorder{$i}})) {
13888:                                 if ($env{'form.archive_'.$item} eq 'display') {
13889:                                     $outer = $item;
13890:                                     last;
13891:                                 }
13892:                             }
13893:                         }
13894:                     }
13895:                     my ($errtext,$fatal) = 
13896:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
13897:                                                '/'.$folders{$outer}.'.'.
13898:                                                $containers{$outer});
13899:                     next if ($fatal);
13900:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
13901:                         if ($context eq 'coursedocs') {
13902:                             $mapinner{$i} = time;
13903:                             $folders{$i} = 'default_'.$mapinner{$i};
13904:                             $containers{$i} = 'sequence';
13905:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
13906:                                       $folders{$i}.'.'.$containers{$i};
13907:                             my $newidx = &LONCAPA::map::getresidx();
13908:                             $LONCAPA::map::resources[$newidx]=
13909:                                 $docstitle.':'.$url.':false:normal:res';
13910:                             push(@LONCAPA::map::order,$newidx);
13911:                             my ($outtext,$errtext) =
13912:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
13913:                                                         $docuname.'/'.$folders{$outer}.
13914:                                                         '.'.$containers{$outer},1,1);
13915:                             $newseqid{$i} = $newidx;
13916:                             unless ($errtext) {
13917:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
13918:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
13919:                                             '</li>'."\n";
13920:                             }
13921:                         }
13922:                     } else {
13923:                         if ($context eq 'coursedocs') {
13924:                             my $newidx=&LONCAPA::map::getresidx();
13925:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
13926:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
13927:                                       $title;
13928:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
13929:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
13930:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
13931:                                 }
13932:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
13933:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
13934:                                 }
13935:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
13936:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
13937:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
13938:                                         unless ($ishome) {
13939:                                             my $fetch = "$newdest{$i}/$title";
13940:                                             $fetch =~ s/^\Q$prefix$dir\E//;
13941:                                             $prompttofetch{$fetch} = 1;
13942:                                         }
13943:                                     }
13944:                                 }
13945:                                 $LONCAPA::map::resources[$newidx]=
13946:                                     $docstitle.':'.$url.':false:normal:res';
13947:                                 push(@LONCAPA::map::order, $newidx);
13948:                                 my ($outtext,$errtext)=
13949:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
13950:                                                             $docuname.'/'.$folders{$outer}.
13951:                                                             '.'.$containers{$outer},1,1);
13952:                                 unless ($errtext) {
13953:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
13954:                                         $result .= '<li>'.&mt('File: [_1] added to course',
13955:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
13956:                                                    '</li>'."\n";
13957:                                     }
13958:                                 }
13959:                             } else {
13960:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13961:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
13962:                             }
13963:                         }
13964:                     }
13965:                 }
13966:             } else {
13967:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13968:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
13969:             }
13970:         }
13971:         for (my $i=1; $i<=$numitems; $i++) {
13972:             next unless ($env{'form.archive_'.$i} eq 'dependency');
13973:             my $path = $env{'form.archive_content_'.$i};
13974:             if ($path =~ /^\Q$pathtocheck\E/) {
13975:                 my ($title) = ($path =~ m{/([^/]+)$});
13976:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
13977:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
13978:                     if (ref($dirorder{$i}) eq 'ARRAY') {
13979:                         my ($itemidx,$fullpath,$relpath);
13980:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
13981:                             my $container = $dirorder{$referrer{$i}}->[-1];
13982:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
13983:                                 if ($dirorder{$i}->[$j] eq $container) {
13984:                                     $itemidx = $j;
13985:                                 }
13986:                             }
13987:                         }
13988:                         if ($itemidx eq '') {
13989:                             $itemidx =  0;
13990:                         } 
13991:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
13992:                             if ($mapinner{$referrer{$i}}) {
13993:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
13994:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
13995:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
13996:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
13997:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
13998:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
13999:                                             if (!-e $fullpath) {
14000:                                                 mkdir($fullpath,0755);
14001:                                             }
14002:                                         }
14003:                                     } else {
14004:                                         last;
14005:                                     }
14006:                                 }
14007:                             }
14008:                         } elsif ($newdest{$referrer{$i}}) {
14009:                             $fullpath = $newdest{$referrer{$i}};
14010:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
14011:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
14012:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
14013:                                     last;
14014:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
14015:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
14016:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
14017:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
14018:                                         if (!-e $fullpath) {
14019:                                             mkdir($fullpath,0755);
14020:                                         }
14021:                                     }
14022:                                 } else {
14023:                                     last;
14024:                                 }
14025:                             }
14026:                         }
14027:                         if ($fullpath ne '') {
14028:                             if (-e "$prefix$path") {
14029:                                 unless (rename("$prefix$path","$fullpath/$title")) {
14030:                                      $warning .= &mt('Failed to rename dependency').'<br />';
14031:                                 }
14032:                             }
14033:                             if (-e "$fullpath/$title") {
14034:                                 my $showpath;
14035:                                 if ($relpath ne '') {
14036:                                     $showpath = "$relpath/$title";
14037:                                 } else {
14038:                                     $showpath = "/$title";
14039:                                 } 
14040:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
14041:                                                       &HTML::Entities::encode($showpath,'<>&"')).
14042:                                            '</li>'."\n";
14043:                                 unless ($ishome) {
14044:                                     my $fetch = "$fullpath/$title";
14045:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
14046:                                     $prompttofetch{$fetch} = 1;
14047:                                 }
14048:                             }
14049:                         }
14050:                     }
14051:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
14052:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
14053:                                     &HTML::Entities::encode($path,'<>&"'),
14054:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
14055:                                 '<br />';
14056:                 }
14057:             } else {
14058:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
14059:                                 &HTML::Entities::encode($path)).'<br />';
14060:             }
14061:         }
14062:         if (keys(%todelete)) {
14063:             foreach my $key (keys(%todelete)) {
14064:                 unlink($key);
14065:             }
14066:         }
14067:         if (keys(%todeletedir)) {
14068:             foreach my $key (keys(%todeletedir)) {
14069:                 rmdir($key);
14070:             }
14071:         }
14072:         foreach my $dir (sort(keys(%is_dir))) {
14073:             if (($pathtocheck ne '') && ($dir ne ''))  {
14074:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
14075:             }
14076:         }
14077:         if ($result ne '') {
14078:             $output .= '<ul>'."\n".
14079:                        $result."\n".
14080:                        '</ul>';
14081:         }
14082:         unless ($ishome) {
14083:             my $replicationfail;
14084:             foreach my $item (keys(%prompttofetch)) {
14085:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
14086:                 unless ($fetchresult eq 'ok') {
14087:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
14088:                 }
14089:             }
14090:             if ($replicationfail) {
14091:                 $output .= '<p class="LC_error">'.
14092:                            &mt('Course home server failed to retrieve:').'<ul>'.
14093:                            $replicationfail.
14094:                            '</ul></p>';
14095:             }
14096:         }
14097:     } else {
14098:         $warning = &mt('No items found in archive.');
14099:     }
14100:     if ($error) {
14101:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
14102:                    $error.'</p>'."\n";
14103:     }
14104:     if ($warning) {
14105:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
14106:     }
14107:     return $output;
14108: }
14109: 
14110: sub cleanup_empty_dirs {
14111:     my ($path) = @_;
14112:     if (($path ne '') && (-d $path)) {
14113:         if (opendir(my $dirh,$path)) {
14114:             my @dircontents = grep(!/^\./,readdir($dirh));
14115:             my $numitems = 0;
14116:             foreach my $item (@dircontents) {
14117:                 if (-d "$path/$item") {
14118:                     &cleanup_empty_dirs("$path/$item");
14119:                     if (-e "$path/$item") {
14120:                         $numitems ++;
14121:                     }
14122:                 } else {
14123:                     $numitems ++;
14124:                 }
14125:             }
14126:             if ($numitems == 0) {
14127:                 rmdir($path);
14128:             }
14129:             closedir($dirh);
14130:         }
14131:     }
14132:     return;
14133: }
14134: 
14135: =pod
14136: 
14137: =item * &get_folder_hierarchy()
14138: 
14139: Provides hierarchy of names of folders/sub-folders containing the current
14140: item,
14141: 
14142: Inputs: 3
14143:      - $navmap - navmaps object
14144: 
14145:      - $map - url for map (either the trigger itself, or map containing
14146:                            the resource, which is the trigger).
14147: 
14148:      - $showitem - 1 => show title for map itself; 0 => do not show.
14149: 
14150: Outputs: 1 @pathitems - array of folder/subfolder names.
14151: 
14152: =cut
14153: 
14154: sub get_folder_hierarchy {
14155:     my ($navmap,$map,$showitem) = @_;
14156:     my @pathitems;
14157:     if (ref($navmap)) {
14158:         my $mapres = $navmap->getResourceByUrl($map);
14159:         if (ref($mapres)) {
14160:             my $pcslist = $mapres->map_hierarchy();
14161:             if ($pcslist ne '') {
14162:                 my @pcs = split(/,/,$pcslist);
14163:                 foreach my $pc (@pcs) {
14164:                     if ($pc == 1) {
14165:                         push(@pathitems,&mt('Main Content'));
14166:                     } else {
14167:                         my $res = $navmap->getByMapPc($pc);
14168:                         if (ref($res)) {
14169:                             my $title = $res->compTitle();
14170:                             $title =~ s/\W+/_/g;
14171:                             if ($title ne '') {
14172:                                 push(@pathitems,$title);
14173:                             }
14174:                         }
14175:                     }
14176:                 }
14177:             }
14178:             if ($showitem) {
14179:                 if ($mapres->{ID} eq '0.0') {
14180:                     push(@pathitems,&mt('Main Content'));
14181:                 } else {
14182:                     my $maptitle = $mapres->compTitle();
14183:                     $maptitle =~ s/\W+/_/g;
14184:                     if ($maptitle ne '') {
14185:                         push(@pathitems,$maptitle);
14186:                     }
14187:                 }
14188:             }
14189:         }
14190:     }
14191:     return @pathitems;
14192: }
14193: 
14194: =pod
14195: 
14196: =item * &get_turnedin_filepath()
14197: 
14198: Determines path in a user's portfolio file for storage of files uploaded
14199: to a specific essayresponse or dropbox item.
14200: 
14201: Inputs: 3 required + 1 optional.
14202: $symb is symb for resource, $uname and $udom are for current user (required).
14203: $caller is optional (can be "submission", if routine is called when storing
14204: an upoaded file when "Submit Answer" button was pressed).
14205: 
14206: Returns array containing $path and $multiresp. 
14207: $path is path in portfolio.  $multiresp is 1 if this resource contains more
14208: than one file upload item.  Callers of routine should append partid as a 
14209: subdirectory to $path in cases where $multiresp is 1.
14210: 
14211: Called by: homework/essayresponse.pm and homework/structuretags.pm
14212: 
14213: =cut
14214: 
14215: sub get_turnedin_filepath {
14216:     my ($symb,$uname,$udom,$caller) = @_;
14217:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
14218:     my $turnindir;
14219:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
14220:     $turnindir = $userhash{'turnindir'};
14221:     my ($path,$multiresp);
14222:     if ($turnindir eq '') {
14223:         if ($caller eq 'submission') {
14224:             $turnindir = &mt('turned in');
14225:             $turnindir =~ s/\W+/_/g;
14226:             my %newhash = (
14227:                             'turnindir' => $turnindir,
14228:                           );
14229:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
14230:         }
14231:     }
14232:     if ($turnindir ne '') {
14233:         $path = '/'.$turnindir.'/';
14234:         my ($multipart,$turnin,@pathitems);
14235:         my $navmap = Apache::lonnavmaps::navmap->new();
14236:         if (defined($navmap)) {
14237:             my $mapres = $navmap->getResourceByUrl($map);
14238:             if (ref($mapres)) {
14239:                 my $pcslist = $mapres->map_hierarchy();
14240:                 if ($pcslist ne '') {
14241:                     foreach my $pc (split(/,/,$pcslist)) {
14242:                         my $res = $navmap->getByMapPc($pc);
14243:                         if (ref($res)) {
14244:                             my $title = $res->compTitle();
14245:                             $title =~ s/\W+/_/g;
14246:                             if ($title ne '') {
14247:                                 if (($pc > 1) && (length($title) > 12)) {
14248:                                     $title = substr($title,0,12);
14249:                                 }
14250:                                 push(@pathitems,$title);
14251:                             }
14252:                         }
14253:                     }
14254:                 }
14255:                 my $maptitle = $mapres->compTitle();
14256:                 $maptitle =~ s/\W+/_/g;
14257:                 if ($maptitle ne '') {
14258:                     if (length($maptitle) > 12) {
14259:                         $maptitle = substr($maptitle,0,12);
14260:                     }
14261:                     push(@pathitems,$maptitle);
14262:                 }
14263:                 unless ($env{'request.state'} eq 'construct') {
14264:                     my $res = $navmap->getBySymb($symb);
14265:                     if (ref($res)) {
14266:                         my $partlist = $res->parts();
14267:                         my $totaluploads = 0;
14268:                         if (ref($partlist) eq 'ARRAY') {
14269:                             foreach my $part (@{$partlist}) {
14270:                                 my @types = $res->responseType($part);
14271:                                 my @ids = $res->responseIds($part);
14272:                                 for (my $i=0; $i < scalar(@ids); $i++) {
14273:                                     if ($types[$i] eq 'essay') {
14274:                                         my $partid = $part.'_'.$ids[$i];
14275:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
14276:                                             $totaluploads ++;
14277:                                         }
14278:                                     }
14279:                                 }
14280:                             }
14281:                             if ($totaluploads > 1) {
14282:                                 $multiresp = 1;
14283:                             }
14284:                         }
14285:                     }
14286:                 }
14287:             } else {
14288:                 return;
14289:             }
14290:         } else {
14291:             return;
14292:         }
14293:         my $restitle=&Apache::lonnet::gettitle($symb);
14294:         $restitle =~ s/\W+/_/g;
14295:         if ($restitle eq '') {
14296:             $restitle = ($resurl =~ m{/[^/]+$});
14297:             if ($restitle eq '') {
14298:                 $restitle = time;
14299:             }
14300:         }
14301:         if (length($restitle) > 12) {
14302:             $restitle = substr($restitle,0,12);
14303:         }
14304:         push(@pathitems,$restitle);
14305:         $path .= join('/',@pathitems);
14306:     }
14307:     return ($path,$multiresp);
14308: }
14309: 
14310: =pod
14311: 
14312: =back
14313: 
14314: =head1 CSV Upload/Handling functions
14315: 
14316: =over 4
14317: 
14318: =item * &upfile_store($r)
14319: 
14320: Store uploaded file, $r should be the HTTP Request object,
14321: needs $env{'form.upfile'}
14322: returns $datatoken to be put into hidden field
14323: 
14324: =cut
14325: 
14326: sub upfile_store {
14327:     my $r=shift;
14328:     $env{'form.upfile'}=~s/\r/\n/gs;
14329:     $env{'form.upfile'}=~s/\f/\n/gs;
14330:     $env{'form.upfile'}=~s/\n+/\n/gs;
14331:     $env{'form.upfile'}=~s/\n+$//gs;
14332: 
14333:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
14334:                                      '_enroll_'.$env{'request.course.id'}.'_'.
14335:                                      time.'_'.$$);
14336:     return if ($datatoken eq '');
14337: 
14338:     {
14339:         my $datafile = $r->dir_config('lonDaemons').
14340:                            '/tmp/'.$datatoken.'.tmp';
14341:         if ( open(my $fh,'>',$datafile) ) {
14342:             print $fh $env{'form.upfile'};
14343:             close($fh);
14344:         }
14345:     }
14346:     return $datatoken;
14347: }
14348: 
14349: =pod
14350: 
14351: =item * &load_tmp_file($r,$datatoken)
14352: 
14353: Load uploaded file from tmp, $r should be the HTTP Request object,
14354: $datatoken is the name to assign to the temporary file.
14355: sets $env{'form.upfile'} to the contents of the file
14356: 
14357: =cut
14358: 
14359: sub load_tmp_file {
14360:     my ($r,$datatoken) = @_;
14361:     return if ($datatoken eq '');
14362:     my @studentdata=();
14363:     {
14364:         my $studentfile = $r->dir_config('lonDaemons').
14365:                               '/tmp/'.$datatoken.'.tmp';
14366:         if ( open(my $fh,'<',$studentfile) ) {
14367:             @studentdata=<$fh>;
14368:             close($fh);
14369:         }
14370:     }
14371:     $env{'form.upfile'}=join('',@studentdata);
14372: }
14373: 
14374: sub valid_datatoken {
14375:     my ($datatoken) = @_;
14376:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
14377:         return $datatoken;
14378:     }
14379:     return;
14380: }
14381: 
14382: =pod
14383: 
14384: =item * &upfile_record_sep()
14385: 
14386: Separate uploaded file into records
14387: returns array of records,
14388: needs $env{'form.upfile'} and $env{'form.upfiletype'}
14389: 
14390: =cut
14391: 
14392: sub upfile_record_sep {
14393:     if ($env{'form.upfiletype'} eq 'xml') {
14394:     } else {
14395: 	my @records;
14396: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
14397: 	    if ($line=~/^\s*$/) { next; }
14398: 	    push(@records,$line);
14399: 	}
14400: 	return @records;
14401:     }
14402: }
14403: 
14404: =pod
14405: 
14406: =item * &record_sep($record)
14407: 
14408: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
14409: 
14410: =cut
14411: 
14412: sub takeleft {
14413:     my $index=shift;
14414:     return substr('0000'.$index,-4,4);
14415: }
14416: 
14417: sub record_sep {
14418:     my $record=shift;
14419:     my %components=();
14420:     if ($env{'form.upfiletype'} eq 'xml') {
14421:     } elsif ($env{'form.upfiletype'} eq 'space') {
14422:         my $i=0;
14423:         foreach my $field (split(/\s+/,$record)) {
14424:             $field=~s/^(\"|\')//;
14425:             $field=~s/(\"|\')$//;
14426:             $components{&takeleft($i)}=$field;
14427:             $i++;
14428:         }
14429:     } elsif ($env{'form.upfiletype'} eq 'tab') {
14430:         my $i=0;
14431:         foreach my $field (split(/\t/,$record)) {
14432:             $field=~s/^(\"|\')//;
14433:             $field=~s/(\"|\')$//;
14434:             $components{&takeleft($i)}=$field;
14435:             $i++;
14436:         }
14437:     } else {
14438:         my $separator=',';
14439:         if ($env{'form.upfiletype'} eq 'semisv') {
14440:             $separator=';';
14441:         }
14442:         my $i=0;
14443: # the character we are looking for to indicate the end of a quote or a record 
14444:         my $looking_for=$separator;
14445: # do not add the characters to the fields
14446:         my $ignore=0;
14447: # we just encountered a separator (or the beginning of the record)
14448:         my $just_found_separator=1;
14449: # store the field we are working on here
14450:         my $field='';
14451: # work our way through all characters in record
14452:         foreach my $character ($record=~/(.)/g) {
14453:             if ($character eq $looking_for) {
14454:                if ($character ne $separator) {
14455: # Found the end of a quote, again looking for separator
14456:                   $looking_for=$separator;
14457:                   $ignore=1;
14458:                } else {
14459: # Found a separator, store away what we got
14460:                   $components{&takeleft($i)}=$field;
14461: 	          $i++;
14462:                   $just_found_separator=1;
14463:                   $ignore=0;
14464:                   $field='';
14465:                }
14466:                next;
14467:             }
14468: # single or double quotation marks after a separator indicate beginning of a quote
14469: # we are now looking for the end of the quote and need to ignore separators
14470:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
14471:                $looking_for=$character;
14472:                next;
14473:             }
14474: # ignore would be true after we reached the end of a quote
14475:             if ($ignore) { next; }
14476:             if (($just_found_separator) && ($character=~/\s/)) { next; }
14477:             $field.=$character;
14478:             $just_found_separator=0; 
14479:         }
14480: # catch the very last entry, since we never encountered the separator
14481:         $components{&takeleft($i)}=$field;
14482:     }
14483:     return %components;
14484: }
14485: 
14486: ######################################################
14487: ######################################################
14488: 
14489: =pod
14490: 
14491: =item * &upfile_select_html()
14492: 
14493: Return HTML code to select a file from the users machine and specify 
14494: the file type.
14495: 
14496: =cut
14497: 
14498: ######################################################
14499: ######################################################
14500: sub upfile_select_html {
14501:     my %Types = (
14502:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
14503:                  semisv => &mt('Semicolon separated values'),
14504:                  space => &mt('Space separated'),
14505:                  tab   => &mt('Tabulator separated'),
14506: #                 xml   => &mt('HTML/XML'),
14507:                  );
14508:     my $Str = '<input type="file" name="upfile" size="50" />'.
14509:         '<br />'.&mt('Type').': <select name="upfiletype">';
14510:     foreach my $type (sort(keys(%Types))) {
14511:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
14512:     }
14513:     $Str .= "</select>\n";
14514:     return $Str;
14515: }
14516: 
14517: sub get_samples {
14518:     my ($records,$toget) = @_;
14519:     my @samples=({});
14520:     my $got=0;
14521:     foreach my $rec (@$records) {
14522: 	my %temp = &record_sep($rec);
14523: 	if (! grep(/\S/, values(%temp))) { next; }
14524: 	if (%temp) {
14525: 	    $samples[$got]=\%temp;
14526: 	    $got++;
14527: 	    if ($got == $toget) { last; }
14528: 	}
14529:     }
14530:     return \@samples;
14531: }
14532: 
14533: ######################################################
14534: ######################################################
14535: 
14536: =pod
14537: 
14538: =item * &csv_print_samples($r,$records)
14539: 
14540: Prints a table of sample values from each column uploaded $r is an
14541: Apache Request ref, $records is an arrayref from
14542: &Apache::loncommon::upfile_record_sep
14543: 
14544: =cut
14545: 
14546: ######################################################
14547: ######################################################
14548: sub csv_print_samples {
14549:     my ($r,$records) = @_;
14550:     my $samples = &get_samples($records,5);
14551: 
14552:     $r->print(&mt('Samples').'<br />'.&start_data_table().
14553:               &start_data_table_header_row());
14554:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
14555:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
14556:     $r->print(&end_data_table_header_row());
14557:     foreach my $hash (@$samples) {
14558: 	$r->print(&start_data_table_row());
14559: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
14560: 	    $r->print('<td>');
14561: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
14562: 	    $r->print('</td>');
14563: 	}
14564: 	$r->print(&end_data_table_row());
14565:     }
14566:     $r->print(&end_data_table().'<br />'."\n");
14567: }
14568: 
14569: ######################################################
14570: ######################################################
14571: 
14572: =pod
14573: 
14574: =item * &csv_print_select_table($r,$records,$d)
14575: 
14576: Prints a table to create associations between values and table columns.
14577: 
14578: $r is an Apache Request ref,
14579: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
14580: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
14581: 
14582: =cut
14583: 
14584: ######################################################
14585: ######################################################
14586: sub csv_print_select_table {
14587:     my ($r,$records,$d) = @_;
14588:     my $i=0;
14589:     my $samples = &get_samples($records,1);
14590:     $r->print(&mt('Associate columns with student attributes.')."\n".
14591: 	      &start_data_table().&start_data_table_header_row().
14592:               '<th>'.&mt('Attribute').'</th>'.
14593:               '<th>'.&mt('Column').'</th>'.
14594:               &end_data_table_header_row()."\n");
14595:     foreach my $array_ref (@$d) {
14596: 	my ($value,$display,$defaultcol)=@{ $array_ref };
14597: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
14598: 
14599: 	$r->print('<td><select name="f'.$i.'"'.
14600: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
14601: 	$r->print('<option value="none"></option>');
14602: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
14603: 	    $r->print('<option value="'.$sample.'"'.
14604:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
14605:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
14606: 	}
14607: 	$r->print('</select></td>'.&end_data_table_row()."\n");
14608: 	$i++;
14609:     }
14610:     $r->print(&end_data_table());
14611:     $i--;
14612:     return $i;
14613: }
14614: 
14615: ######################################################
14616: ######################################################
14617: 
14618: =pod
14619: 
14620: =item * &csv_samples_select_table($r,$records,$d)
14621: 
14622: Prints a table of sample values from the upload and can make associate samples to internal names.
14623: 
14624: $r is an Apache Request ref,
14625: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
14626: $d is an array of 2 element arrays (internal name, displayed name)
14627: 
14628: =cut
14629: 
14630: ######################################################
14631: ######################################################
14632: sub csv_samples_select_table {
14633:     my ($r,$records,$d) = @_;
14634:     my $i=0;
14635:     #
14636:     my $max_samples = 5;
14637:     my $samples = &get_samples($records,$max_samples);
14638:     $r->print(&start_data_table().
14639:               &start_data_table_header_row().'<th>'.
14640:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
14641:               &end_data_table_header_row());
14642: 
14643:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
14644: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
14645: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
14646: 	foreach my $option (@$d) {
14647: 	    my ($value,$display,$defaultcol)=@{ $option };
14648: 	    $r->print('<option value="'.$value.'"'.
14649:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
14650:                       $display.'</option>');
14651: 	}
14652: 	$r->print('</select></td><td>');
14653: 	foreach my $line (0..($max_samples-1)) {
14654: 	    if (defined($samples->[$line]{$key})) { 
14655: 		$r->print($samples->[$line]{$key}."<br />\n"); 
14656: 	    }
14657: 	}
14658: 	$r->print('</td>'.&end_data_table_row());
14659: 	$i++;
14660:     }
14661:     $r->print(&end_data_table());
14662:     $i--;
14663:     return($i);
14664: }
14665: 
14666: ######################################################
14667: ######################################################
14668: 
14669: =pod
14670: 
14671: =item * &clean_excel_name($name)
14672: 
14673: Returns a replacement for $name which does not contain any illegal characters.
14674: 
14675: =cut
14676: 
14677: ######################################################
14678: ######################################################
14679: sub clean_excel_name {
14680:     my ($name) = @_;
14681:     $name =~ s/[:\*\?\/\\]//g;
14682:     if (length($name) > 31) {
14683:         $name = substr($name,0,31);
14684:     }
14685:     return $name;
14686: }
14687: 
14688: =pod
14689: 
14690: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
14691: 
14692: Returns either 1 or undef
14693: 
14694: 1 if the part is to be hidden, undef if it is to be shown
14695: 
14696: Arguments are:
14697: 
14698: $id the id of the part to be checked
14699: $symb, optional the symb of the resource to check
14700: $udom, optional the domain of the user to check for
14701: $uname, optional the username of the user to check for
14702: 
14703: =cut
14704: 
14705: sub check_if_partid_hidden {
14706:     my ($id,$symb,$udom,$uname) = @_;
14707:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
14708: 					 $symb,$udom,$uname);
14709:     my $truth=1;
14710:     #if the string starts with !, then the list is the list to show not hide
14711:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
14712:     my @hiddenlist=split(/,/,$hiddenparts);
14713:     foreach my $checkid (@hiddenlist) {
14714: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
14715:     }
14716:     return !$truth;
14717: }
14718: 
14719: 
14720: ############################################################
14721: ############################################################
14722: 
14723: =pod
14724: 
14725: =back 
14726: 
14727: =head1 cgi-bin script and graphing routines
14728: 
14729: =over 4
14730: 
14731: =item * &get_cgi_id()
14732: 
14733: Inputs: none
14734: 
14735: Returns an id which can be used to pass environment variables
14736: to various cgi-bin scripts.  These environment variables will
14737: be removed from the users environment after a given time by
14738: the routine &Apache::lonnet::transfer_profile_to_env.
14739: 
14740: =cut
14741: 
14742: ############################################################
14743: ############################################################
14744: my $uniq=0;
14745: sub get_cgi_id {
14746:     $uniq=($uniq+1)%100000;
14747:     return (time.'_'.$$.'_'.$uniq);
14748: }
14749: 
14750: ############################################################
14751: ############################################################
14752: 
14753: =pod
14754: 
14755: =item * &DrawBarGraph()
14756: 
14757: Facilitates the plotting of data in a (stacked) bar graph.
14758: Puts plot definition data into the users environment in order for 
14759: graph.png to plot it.  Returns an <img> tag for the plot.
14760: The bars on the plot are labeled '1','2',...,'n'.
14761: 
14762: Inputs:
14763: 
14764: =over 4
14765: 
14766: =item $Title: string, the title of the plot
14767: 
14768: =item $xlabel: string, text describing the X-axis of the plot
14769: 
14770: =item $ylabel: string, text describing the Y-axis of the plot
14771: 
14772: =item $Max: scalar, the maximum Y value to use in the plot
14773: If $Max is < any data point, the graph will not be rendered.
14774: 
14775: =item $colors: array ref holding the colors to be used for the data sets when
14776: they are plotted.  If undefined, default values will be used.
14777: 
14778: =item $labels: array ref holding the labels to use on the x-axis for the bars.
14779: 
14780: =item @Values: An array of array references.  Each array reference holds data
14781: to be plotted in a stacked bar chart.
14782: 
14783: =item If the final element of @Values is a hash reference the key/value
14784: pairs will be added to the graph definition.
14785: 
14786: =back
14787: 
14788: Returns:
14789: 
14790: An <img> tag which references graph.png and the appropriate identifying
14791: information for the plot.
14792: 
14793: =cut
14794: 
14795: ############################################################
14796: ############################################################
14797: sub DrawBarGraph {
14798:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
14799:     #
14800:     if (! defined($colors)) {
14801:         $colors = ['#33ff00', 
14802:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
14803:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
14804:                   ]; 
14805:     }
14806:     my $extra_settings = {};
14807:     if (ref($Values[-1]) eq 'HASH') {
14808:         $extra_settings = pop(@Values);
14809:     }
14810:     #
14811:     my $identifier = &get_cgi_id();
14812:     my $id = 'cgi.'.$identifier;        
14813:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
14814:         return '';
14815:     }
14816:     #
14817:     my @Labels;
14818:     if (defined($labels)) {
14819:         @Labels = @$labels;
14820:     } else {
14821:         for (my $i=0;$i<@{$Values[0]};$i++) {
14822:             push(@Labels,$i+1);
14823:         }
14824:     }
14825:     #
14826:     my $NumBars = scalar(@{$Values[0]});
14827:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
14828:     my %ValuesHash;
14829:     my $NumSets=1;
14830:     foreach my $array (@Values) {
14831:         next if (! ref($array));
14832:         $ValuesHash{$id.'.data.'.$NumSets++} = 
14833:             join(',',@$array);
14834:     }
14835:     #
14836:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
14837:     if ($NumBars < 3) {
14838:         $width = 120+$NumBars*32;
14839:         $xskip = 1;
14840:         $bar_width = 30;
14841:     } elsif ($NumBars < 5) {
14842:         $width = 120+$NumBars*20;
14843:         $xskip = 1;
14844:         $bar_width = 20;
14845:     } elsif ($NumBars < 10) {
14846:         $width = 120+$NumBars*15;
14847:         $xskip = 1;
14848:         $bar_width = 15;
14849:     } elsif ($NumBars <= 25) {
14850:         $width = 120+$NumBars*11;
14851:         $xskip = 5;
14852:         $bar_width = 8;
14853:     } elsif ($NumBars <= 50) {
14854:         $width = 120+$NumBars*8;
14855:         $xskip = 5;
14856:         $bar_width = 4;
14857:     } else {
14858:         $width = 120+$NumBars*8;
14859:         $xskip = 5;
14860:         $bar_width = 4;
14861:     }
14862:     #
14863:     $Max = 1 if ($Max < 1);
14864:     if ( int($Max) < $Max ) {
14865:         $Max++;
14866:         $Max = int($Max);
14867:     }
14868:     $Title  = '' if (! defined($Title));
14869:     $xlabel = '' if (! defined($xlabel));
14870:     $ylabel = '' if (! defined($ylabel));
14871:     $ValuesHash{$id.'.title'}    = &escape($Title);
14872:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
14873:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
14874:     $ValuesHash{$id.'.y_max_value'} = $Max;
14875:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
14876:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
14877:     $ValuesHash{$id.'.PlotType'} = 'bar';
14878:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14879:     $ValuesHash{$id.'.height'}   = $height;
14880:     $ValuesHash{$id.'.width'}    = $width;
14881:     $ValuesHash{$id.'.xskip'}    = $xskip;
14882:     $ValuesHash{$id.'.bar_width'} = $bar_width;
14883:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
14884:     #
14885:     # Deal with other parameters
14886:     while (my ($key,$value) = each(%$extra_settings)) {
14887:         $ValuesHash{$id.'.'.$key} = $value;
14888:     }
14889:     #
14890:     &Apache::lonnet::appenv(\%ValuesHash);
14891:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14892: }
14893: 
14894: ############################################################
14895: ############################################################
14896: 
14897: =pod
14898: 
14899: =item * &DrawXYGraph()
14900: 
14901: Facilitates the plotting of data in an XY graph.
14902: Puts plot definition data into the users environment in order for 
14903: graph.png to plot it.  Returns an <img> tag for the plot.
14904: 
14905: Inputs:
14906: 
14907: =over 4
14908: 
14909: =item $Title: string, the title of the plot
14910: 
14911: =item $xlabel: string, text describing the X-axis of the plot
14912: 
14913: =item $ylabel: string, text describing the Y-axis of the plot
14914: 
14915: =item $Max: scalar, the maximum Y value to use in the plot
14916: If $Max is < any data point, the graph will not be rendered.
14917: 
14918: =item $colors: Array ref containing the hex color codes for the data to be 
14919: plotted in.  If undefined, default values will be used.
14920: 
14921: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
14922: 
14923: =item $Ydata: Array ref containing Array refs.  
14924: Each of the contained arrays will be plotted as a separate curve.
14925: 
14926: =item %Values: hash indicating or overriding any default values which are 
14927: passed to graph.png.  
14928: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
14929: 
14930: =back
14931: 
14932: Returns:
14933: 
14934: An <img> tag which references graph.png and the appropriate identifying
14935: information for the plot.
14936: 
14937: =cut
14938: 
14939: ############################################################
14940: ############################################################
14941: sub DrawXYGraph {
14942:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
14943:     #
14944:     # Create the identifier for the graph
14945:     my $identifier = &get_cgi_id();
14946:     my $id = 'cgi.'.$identifier;
14947:     #
14948:     $Title  = '' if (! defined($Title));
14949:     $xlabel = '' if (! defined($xlabel));
14950:     $ylabel = '' if (! defined($ylabel));
14951:     my %ValuesHash = 
14952:         (
14953:          $id.'.title'  => &escape($Title),
14954:          $id.'.xlabel' => &escape($xlabel),
14955:          $id.'.ylabel' => &escape($ylabel),
14956:          $id.'.y_max_value'=> $Max,
14957:          $id.'.labels'     => join(',',@$Xlabels),
14958:          $id.'.PlotType'   => 'XY',
14959:          );
14960:     #
14961:     if (defined($colors) && ref($colors) eq 'ARRAY') {
14962:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14963:     }
14964:     #
14965:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
14966:         return '';
14967:     }
14968:     my $NumSets=1;
14969:     foreach my $array (@{$Ydata}){
14970:         next if (! ref($array));
14971:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
14972:     }
14973:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
14974:     #
14975:     # Deal with other parameters
14976:     while (my ($key,$value) = each(%Values)) {
14977:         $ValuesHash{$id.'.'.$key} = $value;
14978:     }
14979:     #
14980:     &Apache::lonnet::appenv(\%ValuesHash);
14981:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14982: }
14983: 
14984: ############################################################
14985: ############################################################
14986: 
14987: =pod
14988: 
14989: =item * &DrawXYYGraph()
14990: 
14991: Facilitates the plotting of data in an XY graph with two Y axes.
14992: Puts plot definition data into the users environment in order for 
14993: graph.png to plot it.  Returns an <img> tag for the plot.
14994: 
14995: Inputs:
14996: 
14997: =over 4
14998: 
14999: =item $Title: string, the title of the plot
15000: 
15001: =item $xlabel: string, text describing the X-axis of the plot
15002: 
15003: =item $ylabel: string, text describing the Y-axis of the plot
15004: 
15005: =item $colors: Array ref containing the hex color codes for the data to be 
15006: plotted in.  If undefined, default values will be used.
15007: 
15008: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
15009: 
15010: =item $Ydata1: The first data set
15011: 
15012: =item $Min1: The minimum value of the left Y-axis
15013: 
15014: =item $Max1: The maximum value of the left Y-axis
15015: 
15016: =item $Ydata2: The second data set
15017: 
15018: =item $Min2: The minimum value of the right Y-axis
15019: 
15020: =item $Max2: The maximum value of the left Y-axis
15021: 
15022: =item %Values: hash indicating or overriding any default values which are 
15023: passed to graph.png.  
15024: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
15025: 
15026: =back
15027: 
15028: Returns:
15029: 
15030: An <img> tag which references graph.png and the appropriate identifying
15031: information for the plot.
15032: 
15033: =cut
15034: 
15035: ############################################################
15036: ############################################################
15037: sub DrawXYYGraph {
15038:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
15039:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
15040:     #
15041:     # Create the identifier for the graph
15042:     my $identifier = &get_cgi_id();
15043:     my $id = 'cgi.'.$identifier;
15044:     #
15045:     $Title  = '' if (! defined($Title));
15046:     $xlabel = '' if (! defined($xlabel));
15047:     $ylabel = '' if (! defined($ylabel));
15048:     my %ValuesHash = 
15049:         (
15050:          $id.'.title'  => &escape($Title),
15051:          $id.'.xlabel' => &escape($xlabel),
15052:          $id.'.ylabel' => &escape($ylabel),
15053:          $id.'.labels' => join(',',@$Xlabels),
15054:          $id.'.PlotType' => 'XY',
15055:          $id.'.NumSets' => 2,
15056:          $id.'.two_axes' => 1,
15057:          $id.'.y1_max_value' => $Max1,
15058:          $id.'.y1_min_value' => $Min1,
15059:          $id.'.y2_max_value' => $Max2,
15060:          $id.'.y2_min_value' => $Min2,
15061:          );
15062:     #
15063:     if (defined($colors) && ref($colors) eq 'ARRAY') {
15064:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
15065:     }
15066:     #
15067:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
15068:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
15069:         return '';
15070:     }
15071:     my $NumSets=1;
15072:     foreach my $array ($Ydata1,$Ydata2){
15073:         next if (! ref($array));
15074:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
15075:     }
15076:     #
15077:     # Deal with other parameters
15078:     while (my ($key,$value) = each(%Values)) {
15079:         $ValuesHash{$id.'.'.$key} = $value;
15080:     }
15081:     #
15082:     &Apache::lonnet::appenv(\%ValuesHash);
15083:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15084: }
15085: 
15086: ############################################################
15087: ############################################################
15088: 
15089: =pod
15090: 
15091: =back 
15092: 
15093: =head1 Statistics helper routines?  
15094: 
15095: Bad place for them but what the hell.
15096: 
15097: =over 4
15098: 
15099: =item * &chartlink()
15100: 
15101: Returns a link to the chart for a specific student.  
15102: 
15103: Inputs:
15104: 
15105: =over 4
15106: 
15107: =item $linktext: The text of the link
15108: 
15109: =item $sname: The students username
15110: 
15111: =item $sdomain: The students domain
15112: 
15113: =back
15114: 
15115: =back
15116: 
15117: =cut
15118: 
15119: ############################################################
15120: ############################################################
15121: sub chartlink {
15122:     my ($linktext, $sname, $sdomain) = @_;
15123:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
15124:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
15125:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
15126:        '">'.$linktext.'</a>';
15127: }
15128: 
15129: #######################################################
15130: #######################################################
15131: 
15132: =pod
15133: 
15134: =head1 Course Environment Routines
15135: 
15136: =over 4
15137: 
15138: =item * &restore_course_settings()
15139: 
15140: =item * &store_course_settings()
15141: 
15142: Restores/Store indicated form parameters from the course environment.
15143: Will not overwrite existing values of the form parameters.
15144: 
15145: Inputs: 
15146: a scalar describing the data (e.g. 'chart', 'problem_analysis')
15147: 
15148: a hash ref describing the data to be stored.  For example:
15149:    
15150: %Save_Parameters = ('Status' => 'scalar',
15151:     'chartoutputmode' => 'scalar',
15152:     'chartoutputdata' => 'scalar',
15153:     'Section' => 'array',
15154:     'Group' => 'array',
15155:     'StudentData' => 'array',
15156:     'Maps' => 'array');
15157: 
15158: Returns: both routines return nothing
15159: 
15160: =back
15161: 
15162: =cut
15163: 
15164: #######################################################
15165: #######################################################
15166: sub store_course_settings {
15167:     return &store_settings($env{'request.course.id'},@_);
15168: }
15169: 
15170: sub store_settings {
15171:     # save to the environment
15172:     # appenv the same items, just to be safe
15173:     my $udom  = $env{'user.domain'};
15174:     my $uname = $env{'user.name'};
15175:     my ($context,$prefix,$Settings) = @_;
15176:     my %SaveHash;
15177:     my %AppHash;
15178:     while (my ($setting,$type) = each(%$Settings)) {
15179:         my $basename = join('.','internal',$context,$prefix,$setting);
15180:         my $envname = 'environment.'.$basename;
15181:         if (exists($env{'form.'.$setting})) {
15182:             # Save this value away
15183:             if ($type eq 'scalar' &&
15184:                 (! exists($env{$envname}) || 
15185:                  $env{$envname} ne $env{'form.'.$setting})) {
15186:                 $SaveHash{$basename} = $env{'form.'.$setting};
15187:                 $AppHash{$envname}   = $env{'form.'.$setting};
15188:             } elsif ($type eq 'array') {
15189:                 my $stored_form;
15190:                 if (ref($env{'form.'.$setting})) {
15191:                     $stored_form = join(',',
15192:                                         map {
15193:                                             &escape($_);
15194:                                         } sort(@{$env{'form.'.$setting}}));
15195:                 } else {
15196:                     $stored_form = 
15197:                         &escape($env{'form.'.$setting});
15198:                 }
15199:                 # Determine if the array contents are the same.
15200:                 if ($stored_form ne $env{$envname}) {
15201:                     $SaveHash{$basename} = $stored_form;
15202:                     $AppHash{$envname}   = $stored_form;
15203:                 }
15204:             }
15205:         }
15206:     }
15207:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
15208:                                           $udom,$uname);
15209:     if ($put_result !~ /^(ok|delayed)/) {
15210:         &Apache::lonnet::logthis('unable to save form parameters, '.
15211:                                  'got error:'.$put_result);
15212:     }
15213:     # Make sure these settings stick around in this session, too
15214:     &Apache::lonnet::appenv(\%AppHash);
15215:     return;
15216: }
15217: 
15218: sub restore_course_settings {
15219:     return &restore_settings($env{'request.course.id'},@_);
15220: }
15221: 
15222: sub restore_settings {
15223:     my ($context,$prefix,$Settings) = @_;
15224:     while (my ($setting,$type) = each(%$Settings)) {
15225:         next if (exists($env{'form.'.$setting}));
15226:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
15227:             '.'.$setting;
15228:         if (exists($env{$envname})) {
15229:             if ($type eq 'scalar') {
15230:                 $env{'form.'.$setting} = $env{$envname};
15231:             } elsif ($type eq 'array') {
15232:                 $env{'form.'.$setting} = [ 
15233:                                            map { 
15234:                                                &unescape($_); 
15235:                                            } split(',',$env{$envname})
15236:                                            ];
15237:             }
15238:         }
15239:     }
15240: }
15241: 
15242: #######################################################
15243: #######################################################
15244: 
15245: =pod
15246: 
15247: =head1 Domain E-mail Routines  
15248: 
15249: =over 4
15250: 
15251: =item * &build_recipient_list()
15252: 
15253: Build recipient lists for following types of e-mail:
15254: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
15255: (d) Help requests, (e) Course requests needing approval, (f) loncapa
15256: module change checking, student/employee ID conflict checks, as
15257: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
15258: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
15259: 
15260: Inputs:
15261: defmail (scalar - email address of default recipient), 
15262: mailing type (scalar: errormail, packagesmail, helpdeskmail,
15263: requestsmail, updatesmail, or idconflictsmail).
15264: 
15265: defdom (domain for which to retrieve configuration settings),
15266: 
15267: origmail (scalar - email address of recipient from loncapa.conf, 
15268: i.e., predates configuration by DC via domainprefs.pm
15269: 
15270: $requname username of requester (if mailing type is helpdeskmail)
15271: 
15272: $requdom domain of requester (if mailing type is helpdeskmail)
15273: 
15274: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
15275: 
15276: 
15277: Returns: comma separated list of addresses to which to send e-mail.
15278: 
15279: =back
15280: 
15281: =cut
15282: 
15283: ############################################################
15284: ############################################################
15285: sub build_recipient_list {
15286:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
15287:     my @recipients;
15288:     my ($otheremails,$lastresort,$allbcc,$addtext);
15289:     my %domconfig =
15290:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
15291:     if (ref($domconfig{'contacts'}) eq 'HASH') {
15292:         if (exists($domconfig{'contacts'}{$mailing})) {
15293:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
15294:                 my @contacts = ('adminemail','supportemail');
15295:                 foreach my $item (@contacts) {
15296:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
15297:                         my $addr = $domconfig{'contacts'}{$item}; 
15298:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
15299:                             push(@recipients,$addr);
15300:                         }
15301:                     }
15302:                 }
15303:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
15304:                 if ($mailing eq 'helpdeskmail') {
15305:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
15306:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
15307:                         my @ok_bccs;
15308:                         foreach my $bcc (@bccs) {
15309:                             $bcc =~ s/^\s+//g;
15310:                             $bcc =~ s/\s+$//g;
15311:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15312:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15313:                                     push(@ok_bccs,$bcc);
15314:                                 }
15315:                             }
15316:                         }
15317:                         if (@ok_bccs > 0) {
15318:                             $allbcc = join(', ',@ok_bccs);
15319:                         }
15320:                     }
15321:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
15322:                 }
15323:             }
15324:         } elsif ($origmail ne '') {
15325:             $lastresort = $origmail;
15326:         }
15327:         if ($mailing eq 'helpdeskmail') {
15328:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
15329:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
15330:                 my ($inststatus,$inststatus_checked);
15331:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
15332:                     ($env{'user.domain'} ne 'public')) {
15333:                     $inststatus_checked = 1;
15334:                     $inststatus = $env{'environment.inststatus'};
15335:                 }
15336:                 unless ($inststatus_checked) {
15337:                     if (($requname ne '') && ($requdom ne '')) {
15338:                         if (($requname =~ /^$match_username$/) &&
15339:                             ($requdom =~ /^$match_domain$/) &&
15340:                             (&Apache::lonnet::domain($requdom))) {
15341:                             my $requhome = &Apache::lonnet::homeserver($requname,
15342:                                                                       $requdom);
15343:                             unless ($requhome eq 'no_host') {
15344:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
15345:                                 $inststatus = $userenv{'inststatus'};
15346:                                 $inststatus_checked = 1;
15347:                             }
15348:                         }
15349:                     }
15350:                 }
15351:                 unless ($inststatus_checked) {
15352:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
15353:                         my %srch = (srchby     => 'email',
15354:                                     srchdomain => $defdom,
15355:                                     srchterm   => $reqemail,
15356:                                     srchtype   => 'exact');
15357:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
15358:                         foreach my $uname (keys(%srch_results)) {
15359:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
15360:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
15361:                                 $inststatus_checked = 1;
15362:                                 last;
15363:                             }
15364:                         }
15365:                         unless ($inststatus_checked) {
15366:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
15367:                             if ($dirsrchres eq 'ok') {
15368:                                 foreach my $uname (keys(%srch_results)) {
15369:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
15370:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
15371:                                         $inststatus_checked = 1;
15372:                                         last;
15373:                                     }
15374:                                 }
15375:                             }
15376:                         }
15377:                     }
15378:                 }
15379:                 if ($inststatus ne '') {
15380:                     foreach my $status (split(/\:/,$inststatus)) {
15381:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
15382:                             my @contacts = ('adminemail','supportemail');
15383:                             foreach my $item (@contacts) {
15384:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
15385:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
15386:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
15387:                                         push(@recipients,$addr);
15388:                                     }
15389:                                 }
15390:                             }
15391:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
15392:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
15393:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
15394:                                 my @ok_bccs;
15395:                                 foreach my $bcc (@bccs) {
15396:                                     $bcc =~ s/^\s+//g;
15397:                                     $bcc =~ s/\s+$//g;
15398:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15399:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15400:                                             push(@ok_bccs,$bcc);
15401:                                         }
15402:                                     }
15403:                                 }
15404:                                 if (@ok_bccs > 0) {
15405:                                     $allbcc = join(', ',@ok_bccs);
15406:                                 }
15407:                             }
15408:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
15409:                             last;
15410:                         }
15411:                     }
15412:                 }
15413:             }
15414:         }
15415:     } elsif ($origmail ne '') {
15416:         $lastresort = $origmail;
15417:     }
15418:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
15419:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
15420:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
15421:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
15422:             my %what = (
15423:                           perlvar => 1,
15424:                        );
15425:             my $primary = &Apache::lonnet::domain($defdom,'primary');
15426:             if ($primary) {
15427:                 my $gotaddr;
15428:                 my ($result,$returnhash) =
15429:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
15430:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
15431:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
15432:                         $lastresort = $returnhash->{'lonSupportEMail'};
15433:                         $gotaddr = 1;
15434:                     }
15435:                 }
15436:                 unless ($gotaddr) {
15437:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
15438:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
15439:                     unless ($uintdom eq $intdom) {
15440:                         my %domconfig =
15441:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
15442:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
15443:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
15444:                                 my @contacts = ('adminemail','supportemail');
15445:                                 foreach my $item (@contacts) {
15446:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
15447:                                         my $addr = $domconfig{'contacts'}{$item};
15448:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
15449:                                             push(@recipients,$addr);
15450:                                         }
15451:                                     }
15452:                                 }
15453:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
15454:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
15455:                                 }
15456:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
15457:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
15458:                                     my @ok_bccs;
15459:                                     foreach my $bcc (@bccs) {
15460:                                         $bcc =~ s/^\s+//g;
15461:                                         $bcc =~ s/\s+$//g;
15462:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15463:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15464:                                                 push(@ok_bccs,$bcc);
15465:                                             }
15466:                                         }
15467:                                     }
15468:                                     if (@ok_bccs > 0) {
15469:                                         $allbcc = join(', ',@ok_bccs);
15470:                                     }
15471:                                 }
15472:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
15473:                             }
15474:                         }
15475:                     }
15476:                 }
15477:             }
15478:         }
15479:     }
15480:     if (defined($defmail)) {
15481:         if ($defmail ne '') {
15482:             push(@recipients,$defmail);
15483:         }
15484:     }
15485:     if ($otheremails) {
15486:         my @others;
15487:         if ($otheremails =~ /,/) {
15488:             @others = split(/,/,$otheremails);
15489:         } else {
15490:             push(@others,$otheremails);
15491:         }
15492:         foreach my $addr (@others) {
15493:             if (!grep(/^\Q$addr\E$/,@recipients)) {
15494:                 push(@recipients,$addr);
15495:             }
15496:         }
15497:     }
15498:     if ($mailing eq 'helpdeskmail') {
15499:         if ((!@recipients) && ($lastresort ne '')) {
15500:             push(@recipients,$lastresort);
15501:         }
15502:     } elsif ($lastresort ne '') {
15503:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
15504:             push(@recipients,$lastresort);
15505:         }
15506:     }
15507:     my $recipientlist = join(',',@recipients);
15508:     if (wantarray) {
15509:         return ($recipientlist,$allbcc,$addtext);
15510:     } else {
15511:         return $recipientlist;
15512:     }
15513: }
15514: 
15515: ############################################################
15516: ############################################################
15517: 
15518: =pod
15519: 
15520: =over 4
15521: 
15522: =item * &mime_email()
15523: 
15524: Sends an email with a possible attachment
15525: 
15526: Inputs:
15527: 
15528: =over 4
15529: 
15530: from -              Sender's email address
15531: 
15532: replyto -           Reply-To email address
15533: 
15534: to -                Email address of recipient
15535: 
15536: subject -           Subject of email
15537: 
15538: body -              Body of email
15539: 
15540: cc_string -         Carbon copy email address
15541: 
15542: bcc -               Blind carbon copy email address
15543: 
15544: attachment_path -   Path of file to be attached
15545: 
15546: file_name -         Name of file to be attached
15547: 
15548: attachment_text -   The body of an attachment of type "TEXT"
15549: 
15550: =back
15551: 
15552: =back
15553: 
15554: =cut
15555: 
15556: ############################################################
15557: ############################################################
15558: 
15559: sub mime_email {
15560:     my ($from,$replyto,$to,$subject,$body,$cc_string,$bcc,$attachment_path, 
15561:         $file_name,$attachment_text) = @_;
15562:  
15563:     my $msg = MIME::Lite->new(
15564:              From    => $from,
15565:              To      => $to,
15566:              Subject => $subject,
15567:              Type    =>'TEXT',
15568:              Data    => $body,
15569:              );
15570:     if ($replyto ne '') {
15571:         $msg->add("Reply-To" => $replyto);
15572:     }
15573:     if ($cc_string ne '') {
15574:         $msg->add("Cc" => $cc_string);
15575:     }
15576:     if ($bcc ne '') {
15577:         $msg->add("Bcc" => $bcc);
15578:     }
15579:     $msg->attr("content-type"         => "text/plain");
15580:     $msg->attr("content-type.charset" => "UTF-8");
15581:     # Attach file if given
15582:     if ($attachment_path) {
15583:         unless ($file_name) {
15584:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
15585:         }
15586:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
15587:         $msg->attach(Type     => $type,
15588:                      Path     => $attachment_path,
15589:                      Filename => $file_name
15590:                      );
15591:     # Otherwise attach text if given
15592:     } elsif ($attachment_text) {
15593:         $msg->attach(Type => 'TEXT',
15594:                      Data => $attachment_text);
15595:     }
15596:     # Send it
15597:     $msg->send('sendmail');
15598: }
15599: 
15600: ############################################################
15601: ############################################################
15602: 
15603: =pod
15604: 
15605: =head1 Course Catalog Routines
15606: 
15607: =over 4
15608: 
15609: =item * &gather_categories()
15610: 
15611: Converts category definitions - keys of categories hash stored in  
15612: coursecategories in configuration.db on the primary library server in a 
15613: domain - to an array.  Also generates javascript and idx hash used to 
15614: generate Domain Coordinator interface for editing Course Categories.
15615: 
15616: Inputs:
15617: 
15618: categories (reference to hash of category definitions).
15619: 
15620: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15621:       categories and subcategories).
15622: 
15623: idx (reference to hash of counters used in Domain Coordinator interface for 
15624:       editing Course Categories).
15625: 
15626: jsarray (reference to array of categories used to create Javascript arrays for
15627:          Domain Coordinator interface for editing Course Categories).
15628: 
15629: Returns: nothing
15630: 
15631: Side effects: populates cats, idx and jsarray. 
15632: 
15633: =cut
15634: 
15635: sub gather_categories {
15636:     my ($categories,$cats,$idx,$jsarray) = @_;
15637:     my %counters;
15638:     my $num = 0;
15639:     foreach my $item (keys(%{$categories})) {
15640:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
15641:         if ($container eq '' && $depth == 0) {
15642:             $cats->[$depth][$categories->{$item}] = $cat;
15643:         } else {
15644:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
15645:         }
15646:         my ($escitem,$tail) = split(/:/,$item,2);
15647:         if ($counters{$tail} eq '') {
15648:             $counters{$tail} = $num;
15649:             $num ++;
15650:         }
15651:         if (ref($idx) eq 'HASH') {
15652:             $idx->{$item} = $counters{$tail};
15653:         }
15654:         if (ref($jsarray) eq 'ARRAY') {
15655:             push(@{$jsarray->[$counters{$tail}]},$item);
15656:         }
15657:     }
15658:     return;
15659: }
15660: 
15661: =pod
15662: 
15663: =item * &extract_categories()
15664: 
15665: Used to generate breadcrumb trails for course categories.
15666: 
15667: Inputs:
15668: 
15669: categories (reference to hash of category definitions).
15670: 
15671: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15672:       categories and subcategories).
15673: 
15674: trails (reference to array of breacrumb trails for each category).
15675: 
15676: allitems (reference to hash - key is category key 
15677:          (format: escaped(name):escaped(parent category):depth in hierarchy).
15678: 
15679: idx (reference to hash of counters used in Domain Coordinator interface for
15680:       editing Course Categories).
15681: 
15682: jsarray (reference to array of categories used to create Javascript arrays for
15683:          Domain Coordinator interface for editing Course Categories).
15684: 
15685: subcats (reference to hash of arrays containing all subcategories within each 
15686:          category, -recursive)
15687: 
15688: maxd (reference to hash used to hold max depth for all top-level categories).
15689: 
15690: Returns: nothing
15691: 
15692: Side effects: populates trails and allitems hash references.
15693: 
15694: =cut
15695: 
15696: sub extract_categories {
15697:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
15698:     if (ref($categories) eq 'HASH') {
15699:         &gather_categories($categories,$cats,$idx,$jsarray);
15700:         if (ref($cats->[0]) eq 'ARRAY') {
15701:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
15702:                 my $name = $cats->[0][$i];
15703:                 my $item = &escape($name).'::0';
15704:                 my $trailstr;
15705:                 if ($name eq 'instcode') {
15706:                     $trailstr = &mt('Official courses (with institutional codes)');
15707:                 } elsif ($name eq 'communities') {
15708:                     $trailstr = &mt('Communities');
15709:                 } elsif ($name eq 'placement') {
15710:                     $trailstr = &mt('Placement Tests');
15711:                 } else {
15712:                     $trailstr = $name;
15713:                 }
15714:                 if ($allitems->{$item} eq '') {
15715:                     push(@{$trails},$trailstr);
15716:                     $allitems->{$item} = scalar(@{$trails})-1;
15717:                 }
15718:                 my @parents = ($name);
15719:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
15720:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
15721:                         my $category = $cats->[1]{$name}[$j];
15722:                         if (ref($subcats) eq 'HASH') {
15723:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
15724:                         }
15725:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
15726:                     }
15727:                 } else {
15728:                     if (ref($subcats) eq 'HASH') {
15729:                         $subcats->{$item} = [];
15730:                     }
15731:                     if (ref($maxd) eq 'HASH') {
15732:                         $maxd->{$name} = 1;
15733:                     }
15734:                 }
15735:             }
15736:         }
15737:     }
15738:     return;
15739: }
15740: 
15741: =pod
15742: 
15743: =item * &recurse_categories()
15744: 
15745: Recursively used to generate breadcrumb trails for course categories.
15746: 
15747: Inputs:
15748: 
15749: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15750:       categories and subcategories).
15751: 
15752: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
15753: 
15754: category (current course category, for which breadcrumb trail is being generated).
15755: 
15756: trails (reference to array of breadcrumb trails for each category).
15757: 
15758: allitems (reference to hash - key is category key
15759:          (format: escaped(name):escaped(parent category):depth in hierarchy).
15760: 
15761: parents (array containing containers directories for current category, 
15762:          back to top level). 
15763: 
15764: Returns: nothing
15765: 
15766: Side effects: populates trails and allitems hash references
15767: 
15768: =cut
15769: 
15770: sub recurse_categories {
15771:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
15772:     my $shallower = $depth - 1;
15773:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
15774:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
15775:             my $name = $cats->[$depth]{$category}[$k];
15776:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
15777:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
15778:             if ($allitems->{$item} eq '') {
15779:                 push(@{$trails},$trailstr);
15780:                 $allitems->{$item} = scalar(@{$trails})-1;
15781:             }
15782:             my $deeper = $depth+1;
15783:             push(@{$parents},$category);
15784:             if (ref($subcats) eq 'HASH') {
15785:                 my $subcat = &escape($name).':'.$category.':'.$depth;
15786:                 for (my $j=@{$parents}; $j>=0; $j--) {
15787:                     my $higher;
15788:                     if ($j > 0) {
15789:                         $higher = &escape($parents->[$j]).':'.
15790:                                   &escape($parents->[$j-1]).':'.$j;
15791:                     } else {
15792:                         $higher = &escape($parents->[$j]).'::'.$j;
15793:                     }
15794:                     push(@{$subcats->{$higher}},$subcat);
15795:                 }
15796:             }
15797:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
15798:                                 $subcats,$maxd);
15799:             pop(@{$parents});
15800:         }
15801:     } else {
15802:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
15803:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
15804:         if ($allitems->{$item} eq '') {
15805:             push(@{$trails},$trailstr);
15806:             $allitems->{$item} = scalar(@{$trails})-1;
15807:         }
15808:         if (ref($maxd) eq 'HASH') {
15809:             if ($depth > $maxd->{$parents->[0]}) {
15810:                 $maxd->{$parents->[0]} = $depth;
15811:             }
15812:         }
15813:     }
15814:     return;
15815: }
15816: 
15817: =pod
15818: 
15819: =item * &assign_categories_table()
15820: 
15821: Create a datatable for display of hierarchical categories in a domain,
15822: with checkboxes to allow a course to be categorized. 
15823: 
15824: Inputs:
15825: 
15826: cathash - reference to hash of categories defined for the domain (from
15827:           configuration.db)
15828: 
15829: currcat - scalar with an & separated list of categories assigned to a course. 
15830: 
15831: type    - scalar contains course type (Course or Community).
15832: 
15833: disabled - scalar (optional) contains disabled="disabled" if input elements are
15834:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
15835: 
15836: Returns: $output (markup to be displayed) 
15837: 
15838: =cut
15839: 
15840: sub assign_categories_table {
15841:     my ($cathash,$currcat,$type,$disabled) = @_;
15842:     my $output;
15843:     if (ref($cathash) eq 'HASH') {
15844:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
15845:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
15846:         $maxdepth = scalar(@cats);
15847:         if (@cats > 0) {
15848:             my $itemcount = 0;
15849:             if (ref($cats[0]) eq 'ARRAY') {
15850:                 my @currcategories;
15851:                 if ($currcat ne '') {
15852:                     @currcategories = split('&',$currcat);
15853:                 }
15854:                 my $table;
15855:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
15856:                     my $parent = $cats[0][$i];
15857:                     next if ($parent eq 'instcode');
15858:                     if ($type eq 'Community') {
15859:                         next unless ($parent eq 'communities');
15860:                     } elsif ($type eq 'Placement') {
15861:                         next unless ($parent eq 'placement');
15862:                     } else {
15863:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
15864:                     }
15865:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
15866:                     my $item = &escape($parent).'::0';
15867:                     my $checked = '';
15868:                     if (@currcategories > 0) {
15869:                         if (grep(/^\Q$item\E$/,@currcategories)) {
15870:                             $checked = ' checked="checked"';
15871:                         }
15872:                     }
15873:                     my $parent_title = $parent;
15874:                     if ($parent eq 'communities') {
15875:                         $parent_title = &mt('Communities');
15876:                     } elsif ($parent eq 'placement') {
15877:                         $parent_title = &mt('Placement Tests');
15878:                     }
15879:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
15880:                               '<input type="checkbox" name="usecategory" value="'.
15881:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
15882:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
15883:                     my $depth = 1;
15884:                     push(@path,$parent);
15885:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
15886:                     pop(@path);
15887:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
15888:                     $itemcount ++;
15889:                 }
15890:                 if ($itemcount) {
15891:                     $output = &Apache::loncommon::start_data_table().
15892:                               $table.
15893:                               &Apache::loncommon::end_data_table();
15894:                 }
15895:             }
15896:         }
15897:     }
15898:     return $output;
15899: }
15900: 
15901: =pod
15902: 
15903: =item * &assign_category_rows()
15904: 
15905: Create a datatable row for display of nested categories in a domain,
15906: with checkboxes to allow a course to be categorized,called recursively.
15907: 
15908: Inputs:
15909: 
15910: itemcount - track row number for alternating colors
15911: 
15912: cats - reference to array of arrays/hashes which encapsulates hierarchy of
15913:       categories and subcategories.
15914: 
15915: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
15916: 
15917: parent - parent of current category item
15918: 
15919: path - Array containing all categories back up through the hierarchy from the
15920:        current category to the top level.
15921: 
15922: currcategories - reference to array of current categories assigned to the course
15923: 
15924: disabled - scalar (optional) contains disabled="disabled" if input elements are
15925:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
15926: 
15927: Returns: $output (markup to be displayed).
15928: 
15929: =cut
15930: 
15931: sub assign_category_rows {
15932:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
15933:     my ($text,$name,$item,$chgstr);
15934:     if (ref($cats) eq 'ARRAY') {
15935:         my $maxdepth = scalar(@{$cats});
15936:         if (ref($cats->[$depth]) eq 'HASH') {
15937:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
15938:                 my $numchildren = @{$cats->[$depth]{$parent}};
15939:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
15940:                 $text .= '<td><table class="LC_data_table">';
15941:                 for (my $j=0; $j<$numchildren; $j++) {
15942:                     $name = $cats->[$depth]{$parent}[$j];
15943:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
15944:                     my $deeper = $depth+1;
15945:                     my $checked = '';
15946:                     if (ref($currcategories) eq 'ARRAY') {
15947:                         if (@{$currcategories} > 0) {
15948:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
15949:                                 $checked = ' checked="checked"';
15950:                             }
15951:                         }
15952:                     }
15953:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
15954:                              '<input type="checkbox" name="usecategory" value="'.
15955:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
15956:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
15957:                              '</td><td>';
15958:                     if (ref($path) eq 'ARRAY') {
15959:                         push(@{$path},$name);
15960:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
15961:                         pop(@{$path});
15962:                     }
15963:                     $text .= '</td></tr>';
15964:                 }
15965:                 $text .= '</table></td>';
15966:             }
15967:         }
15968:     }
15969:     return $text;
15970: }
15971: 
15972: =pod
15973: 
15974: =back
15975: 
15976: =cut
15977: 
15978: ############################################################
15979: ############################################################
15980: 
15981: 
15982: sub commit_customrole {
15983:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
15984:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
15985:                          ($start?', '.&mt('starting').' '.localtime($start):'').
15986:                          ($end?', ending '.localtime($end):'').': <b>'.
15987:               &Apache::lonnet::assigncustomrole(
15988:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
15989:                  '</b><br />';
15990:     return $output;
15991: }
15992: 
15993: sub commit_standardrole {
15994:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
15995:     my ($output,$logmsg,$linefeed);
15996:     if ($context eq 'auto') {
15997:         $linefeed = "\n";
15998:     } else {
15999:         $linefeed = "<br />\n";
16000:     }  
16001:     if ($three eq 'st') {
16002:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
16003:                                          $one,$two,$sec,$context,$credits);
16004:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
16005:             ($result eq 'unknown_course') || ($result eq 'refused')) {
16006:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
16007:         } else {
16008:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
16009:                ($start?', '.&mt('starting').' '.localtime($start):'').
16010:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
16011:             if ($context eq 'auto') {
16012:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
16013:             } else {
16014:                $output .= '<b>'.$result.'</b>'.$linefeed.
16015:                &mt('Add to classlist').': <b>ok</b>';
16016:             }
16017:             $output .= $linefeed;
16018:         }
16019:     } else {
16020:         $output = &mt('Assigning').' '.$three.' in '.$url.
16021:                ($start?', '.&mt('starting').' '.localtime($start):'').
16022:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
16023:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
16024:         if ($context eq 'auto') {
16025:             $output .= $result.$linefeed;
16026:         } else {
16027:             $output .= '<b>'.$result.'</b>'.$linefeed;
16028:         }
16029:     }
16030:     return $output;
16031: }
16032: 
16033: sub commit_studentrole {
16034:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
16035:         $credits) = @_;
16036:     my ($result,$linefeed,$oldsecurl,$newsecurl);
16037:     if ($context eq 'auto') {
16038:         $linefeed = "\n";
16039:     } else {
16040:         $linefeed = '<br />'."\n";
16041:     }
16042:     if (defined($one) && defined($two)) {
16043:         my $cid=$one.'_'.$two;
16044:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
16045:         my $secchange = 0;
16046:         my $expire_role_result;
16047:         my $modify_section_result;
16048:         if ($oldsec ne '-1') { 
16049:             if ($oldsec ne $sec) {
16050:                 $secchange = 1;
16051:                 my $now = time;
16052:                 my $uurl='/'.$cid;
16053:                 $uurl=~s/\_/\//g;
16054:                 if ($oldsec) {
16055:                     $uurl.='/'.$oldsec;
16056:                 }
16057:                 $oldsecurl = $uurl;
16058:                 $expire_role_result = 
16059:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
16060:                 if ($env{'request.course.sec'} ne '') { 
16061:                     if ($expire_role_result eq 'refused') {
16062:                         my @roles = ('st');
16063:                         my @statuses = ('previous');
16064:                         my @roledoms = ($one);
16065:                         my $withsec = 1;
16066:                         my %roleshash = 
16067:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
16068:                                               \@statuses,\@roles,\@roledoms,$withsec);
16069:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
16070:                             my ($oldstart,$oldend) = 
16071:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
16072:                             if ($oldend > 0 && $oldend <= $now) {
16073:                                 $expire_role_result = 'ok';
16074:                             }
16075:                         }
16076:                     }
16077:                 }
16078:                 $result = $expire_role_result;
16079:             }
16080:         }
16081:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
16082:             $modify_section_result = 
16083:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
16084:                                                            undef,undef,undef,$sec,
16085:                                                            $end,$start,'','',$cid,
16086:                                                            '',$context,$credits);
16087:             if ($modify_section_result =~ /^ok/) {
16088:                 if ($secchange == 1) {
16089:                     if ($sec eq '') {
16090:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
16091:                     } else {
16092:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
16093:                     }
16094:                 } elsif ($oldsec eq '-1') {
16095:                     if ($sec eq '') {
16096:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
16097:                     } else {
16098:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
16099:                     }
16100:                 } else {
16101:                     if ($sec eq '') {
16102:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
16103:                     } else {
16104:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
16105:                     }
16106:                 }
16107:             } else {
16108:                 if ($secchange) { 
16109:                     $$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;
16110:                 } else {
16111:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
16112:                 }
16113:             }
16114:             $result = $modify_section_result;
16115:         } elsif ($secchange == 1) {
16116:             if ($oldsec eq '') {
16117:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
16118:             } else {
16119:                 $$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;
16120:             }
16121:             if ($expire_role_result eq 'refused') {
16122:                 my $newsecurl = '/'.$cid;
16123:                 $newsecurl =~ s/\_/\//g;
16124:                 if ($sec ne '') {
16125:                     $newsecurl.='/'.$sec;
16126:                 }
16127:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
16128:                     if ($sec eq '') {
16129:                         $$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;
16130:                     } else {
16131:                         $$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;
16132:                     }
16133:                 }
16134:             }
16135:         }
16136:     } else {
16137:         $$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;
16138:         $result = "error: incomplete course id\n";
16139:     }
16140:     return $result;
16141: }
16142: 
16143: sub show_role_extent {
16144:     my ($scope,$context,$role) = @_;
16145:     $scope =~ s{^/}{};
16146:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
16147:     push(@courseroles,'co');
16148:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
16149:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
16150:         $scope =~ s{/}{_};
16151:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
16152:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
16153:         my ($audom,$auname) = split(/\//,$scope);
16154:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
16155:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
16156:     } else {
16157:         $scope =~ s{/$}{};
16158:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
16159:                    &Apache::lonnet::domain($scope,'description').'</span>');
16160:     }
16161: }
16162: 
16163: ############################################################
16164: ############################################################
16165: 
16166: sub check_clone {
16167:     my ($args,$linefeed) = @_;
16168:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
16169:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
16170:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
16171:     my $clonetitle;
16172:     my @clonemsg;
16173:     my $can_clone = 0;
16174:     my $lctype = lc($args->{'crstype'});
16175:     if ($lctype ne 'community') {
16176:         $lctype = 'course';
16177:     }
16178:     if ($clonehome eq 'no_host') {
16179:         if ($args->{'crstype'} eq 'Community') {
16180:             push(@clonemsg,({
16181:                               mt => 'No new community created.',
16182:                               args => [],
16183:                             },
16184:                             {
16185:                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
16186:                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
16187:                             }));
16188:         } else {
16189:             push(@clonemsg,({
16190:                               mt => 'No new course created.',
16191:                               args => [],
16192:                             },
16193:                             {
16194:                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
16195:                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
16196:                             }));
16197:         }
16198:     } else {
16199: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
16200:         $clonetitle = $clonedesc{'description'};
16201:         if ($args->{'crstype'} eq 'Community') {
16202:             if ($clonedesc{'type'} ne 'Community') {
16203:                 push(@clonemsg,({
16204:                                   mt => 'No new community created.',
16205:                                   args => [],
16206:                                 },
16207:                                 {
16208:                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
16209:                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
16210:                                 }));
16211:                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
16212:             }
16213:         }
16214: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
16215:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
16216: 	    $can_clone = 1;
16217: 	} else {
16218: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
16219: 						 $args->{'clonedomain'},$args->{'clonecourse'});
16220:             if ($clonehash{'cloners'} eq '') {
16221:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
16222:                 if ($domdefs{'canclone'}) {
16223:                     unless ($domdefs{'canclone'} eq 'none') {
16224:                         if ($domdefs{'canclone'} eq 'domain') {
16225:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
16226:                                 $can_clone = 1;
16227:                             }
16228:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
16229:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
16230:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
16231:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
16232:                                 $can_clone = 1;
16233:                             }
16234:                         }
16235:                     }
16236:                 }
16237:             } else {
16238: 	        my @cloners = split(/,/,$clonehash{'cloners'});
16239:                 if (grep(/^\*$/,@cloners)) {
16240:                     $can_clone = 1;
16241:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
16242:                     $can_clone = 1;
16243:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
16244:                     $can_clone = 1;
16245:                 }
16246:                 unless ($can_clone) {
16247:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
16248:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
16249:                         my (%gotdomdefaults,%gotcodedefaults);
16250:                         foreach my $cloner (@cloners) {
16251:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
16252:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
16253:                                 my (%codedefaults,@code_order);
16254:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
16255:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
16256:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
16257:                                     }
16258:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
16259:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
16260:                                     }
16261:                                 } else {
16262:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
16263:                                                                             \%codedefaults,
16264:                                                                             \@code_order);
16265:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
16266:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
16267:                                 }
16268:                                 if (@code_order > 0) {
16269:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
16270:                                                                                 $cloner,$clonehash{'internal.coursecode'},
16271:                                                                                 $args->{'crscode'})) {
16272:                                         $can_clone = 1;
16273:                                         last;
16274:                                     }
16275:                                 }
16276:                             }
16277:                         }
16278:                     }
16279:                 }
16280:             }
16281:             unless ($can_clone) {
16282:                 my $ccrole = 'cc';
16283:                 if ($args->{'crstype'} eq 'Community') {
16284:                     $ccrole = 'co';
16285:                 }
16286: 	        my %roleshash =
16287: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
16288: 					          $args->{'ccdomain'},
16289:                                                   'userroles',['active'],[$ccrole],
16290: 					          [$args->{'clonedomain'}]);
16291: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
16292:                     $can_clone = 1;
16293:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
16294:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
16295:                     $can_clone = 1;
16296:                 }
16297:             }
16298:             unless ($can_clone) {
16299:                 if ($args->{'crstype'} eq 'Community') {
16300:                     push(@clonemsg,({
16301:                                       mt => 'No new community created.',
16302:                                       args => [],
16303:                                     },
16304:                                     {
16305:                                       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]).',
16306:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
16307:                                     }));
16308:                 } else {
16309:                     push(@clonemsg,({
16310:                                       mt => 'No new course created.',
16311:                                       args => [],
16312:                                     },
16313:                                     {
16314:                                       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]).',
16315:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
16316:                                     }));
16317:                 }
16318: 	    }
16319:         }
16320:     }
16321:     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
16322: }
16323: 
16324: sub construct_course {
16325:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
16326:         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
16327:     my ($outcome,$msgref,$clonemsgref);
16328:     my $linefeed =  '<br />'."\n";
16329:     if ($context eq 'auto') {
16330:         $linefeed = "\n";
16331:     }
16332: 
16333: #
16334: # Are we cloning?
16335: #
16336:     my ($can_clone,$cloneid,$clonehome,$clonetitle);
16337:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
16338: 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
16339:         if (!$can_clone) {
16340: 	    return (0,$outcome,$clonemsgref);
16341: 	}
16342:     }
16343: 
16344: #
16345: # Open course
16346: #
16347:     my $showncrstype;
16348:     if ($args->{'crstype'} eq 'Placement') {
16349:         $showncrstype = 'placement test'; 
16350:     } else {  
16351:         $showncrstype = lc($args->{'crstype'});
16352:     }
16353:     my %cenv=();
16354:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
16355:                                              $args->{'cdescr'},
16356:                                              $args->{'curl'},
16357:                                              $args->{'course_home'},
16358:                                              $args->{'nonstandard'},
16359:                                              $args->{'crscode'},
16360:                                              $args->{'ccuname'}.':'.
16361:                                              $args->{'ccdomain'},
16362:                                              $args->{'crstype'},
16363:                                              $cnum,$context,$category,
16364:                                              $callercontext);
16365: 
16366:     # Note: The testing routines depend on this being output; see 
16367:     # Utils::Course. This needs to at least be output as a comment
16368:     # if anyone ever decides to not show this, and Utils::Course::new
16369:     # will need to be suitably modified.
16370:     if (($callercontext eq 'auto') && ($user_lh ne '')) {
16371:         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
16372:     } else {
16373:         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
16374:     }
16375:     if ($$courseid =~ /^error:/) {
16376:         return (0,$outcome,$clonemsgref);
16377:     }
16378: 
16379: #
16380: # Check if created correctly
16381: #
16382:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
16383:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
16384:     if ($crsuhome eq 'no_host') {
16385:         if (($callercontext eq 'auto') && ($user_lh ne '')) {
16386:             $outcome .= &mt_user($user_lh,
16387:                             'Course creation failed, unrecognized course home server.');
16388:         } else {
16389:             $outcome .= &mt('Course creation failed, unrecognized course home server.');
16390:         }
16391:         $outcome .= $linefeed;
16392:         return (0,$outcome,$clonemsgref);
16393:     }
16394:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
16395: 
16396: #
16397: # Do the cloning
16398: #   
16399:     my @clonemsg;
16400:     if ($can_clone && $cloneid) {
16401:         push(@clonemsg,
16402:                       {
16403:                           mt => 'Created [_1] by cloning from [_2]',
16404:                           args => [$showncrstype,$clonetitle],
16405:                       });
16406: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
16407: # Copy all files
16408:         my @info =
16409: 	    &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
16410: 	                                             $args->{'dateshift'},$args->{'crscode'},
16411:                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
16412:                                                      $args->{'tinyurls'});
16413:         if (@info) {
16414:             push(@clonemsg,@info);
16415:         }
16416: # Restore URL
16417: 	$cenv{'url'}=$oldcenv{'url'};
16418: # Restore title
16419: 	$cenv{'description'}=$oldcenv{'description'};
16420: # Restore creation date, creator and creation context.
16421:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
16422:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
16423:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
16424: # Mark as cloned
16425: 	$cenv{'clonedfrom'}=$cloneid;
16426: # Need to clone grading mode
16427:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
16428:         $cenv{'grading'}=$newenv{'grading'};
16429: # Do not clone these environment entries
16430:         &Apache::lonnet::del('environment',
16431:                   ['default_enrollment_start_date',
16432:                    'default_enrollment_end_date',
16433:                    'question.email',
16434:                    'policy.email',
16435:                    'comment.email',
16436:                    'pch.users.denied',
16437:                    'plc.users.denied',
16438:                    'hidefromcat',
16439:                    'checkforpriv',
16440:                    'categories'],
16441:                    $$crsudom,$$crsunum);
16442:         if ($args->{'textbook'}) {
16443:             $cenv{'internal.textbook'} = $args->{'textbook'};
16444:         }
16445:     }
16446: 
16447: #
16448: # Set environment (will override cloned, if existing)
16449: #
16450:     my @sections = ();
16451:     my @xlists = ();
16452:     if ($args->{'crstype'}) {
16453:         $cenv{'type'}=$args->{'crstype'};
16454:     }
16455:     if ($args->{'crsid'}) {
16456:         $cenv{'courseid'}=$args->{'crsid'};
16457:     }
16458:     if ($args->{'crscode'}) {
16459:         $cenv{'internal.coursecode'}=$args->{'crscode'};
16460:     }
16461:     if ($args->{'crsquota'} ne '') {
16462:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
16463:     } else {
16464:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
16465:     }
16466:     if ($args->{'ccuname'}) {
16467:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
16468:                                         ':'.$args->{'ccdomain'};
16469:     } else {
16470:         $cenv{'internal.courseowner'} = $args->{'curruser'};
16471:     }
16472:     if ($args->{'defaultcredits'}) {
16473:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
16474:     }
16475:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
16476:     if ($args->{'crssections'}) {
16477:         $cenv{'internal.sectionnums'} = '';
16478:         if ($args->{'crssections'} =~ m/,/) {
16479:             @sections = split/,/,$args->{'crssections'};
16480:         } else {
16481:             $sections[0] = $args->{'crssections'};
16482:         }
16483:         if (@sections > 0) {
16484:             foreach my $item (@sections) {
16485:                 my ($sec,$gp) = split/:/,$item;
16486:                 my $class = $args->{'crscode'}.$sec;
16487:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
16488:                 $cenv{'internal.sectionnums'} .= $item.',';
16489:                 unless ($addcheck eq 'ok') {
16490:                     push(@badclasses,$class);
16491:                 }
16492:             }
16493:             $cenv{'internal.sectionnums'} =~ s/,$//;
16494:         }
16495:     }
16496: # do not hide course coordinator from staff listing, 
16497: # even if privileged
16498:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16499: # add course coordinator's domain to domains to check for privileged users
16500: # if different to course domain
16501:     if ($$crsudom ne $args->{'ccdomain'}) {
16502:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
16503:     }
16504: # add crosslistings
16505:     if ($args->{'crsxlist'}) {
16506:         $cenv{'internal.crosslistings'}='';
16507:         if ($args->{'crsxlist'} =~ m/,/) {
16508:             @xlists = split/,/,$args->{'crsxlist'};
16509:         } else {
16510:             $xlists[0] = $args->{'crsxlist'};
16511:         }
16512:         if (@xlists > 0) {
16513:             foreach my $item (@xlists) {
16514:                 my ($xl,$gp) = split/:/,$item;
16515:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
16516:                 $cenv{'internal.crosslistings'} .= $item.',';
16517:                 unless ($addcheck eq 'ok') {
16518:                     push(@badclasses,$xl);
16519:                 }
16520:             }
16521:             $cenv{'internal.crosslistings'} =~ s/,$//;
16522:         }
16523:     }
16524:     if ($args->{'autoadds'}) {
16525:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
16526:     }
16527:     if ($args->{'autodrops'}) {
16528:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
16529:     }
16530: # check for notification of enrollment changes
16531:     my @notified = ();
16532:     if ($args->{'notify_owner'}) {
16533:         if ($args->{'ccuname'} ne '') {
16534:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
16535:         }
16536:     }
16537:     if ($args->{'notify_dc'}) {
16538:         if ($uname ne '') { 
16539:             push(@notified,$uname.':'.$udom);
16540:         }
16541:     }
16542:     if (@notified > 0) {
16543:         my $notifylist;
16544:         if (@notified > 1) {
16545:             $notifylist = join(',',@notified);
16546:         } else {
16547:             $notifylist = $notified[0];
16548:         }
16549:         $cenv{'internal.notifylist'} = $notifylist;
16550:     }
16551:     if (@badclasses > 0) {
16552:         my %lt=&Apache::lonlocal::texthash(
16553:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
16554:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
16555:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
16556:         );
16557:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
16558:                            &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'};
16559:         if ($context eq 'auto') {
16560:             $outcome .= $badclass_msg.$linefeed;
16561:         } else {
16562:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
16563:         }
16564:         foreach my $item (@badclasses) {
16565:             if ($context eq 'auto') {
16566:                 $outcome .= " - $item\n";
16567:             } else {
16568:                 $outcome .= "<li>$item</li>\n";
16569:             }
16570:         }
16571:         if ($context eq 'auto') {
16572:             $outcome .= $linefeed;
16573:         } else {
16574:             $outcome .= "</ul><br /><br /></div>\n";
16575:         } 
16576:     }
16577:     if ($args->{'no_end_date'}) {
16578:         $args->{'endaccess'} = 0;
16579:     }
16580:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
16581:     $cenv{'internal.autoend'}=$args->{'enrollend'};
16582:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
16583:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
16584:     if ($args->{'showphotos'}) {
16585:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
16586:     }
16587:     $cenv{'internal.authtype'} = $args->{'authtype'};
16588:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
16589:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
16590:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
16591:             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'); 
16592:             if ($context eq 'auto') {
16593:                 $outcome .= $krb_msg;
16594:             } else {
16595:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
16596:             }
16597:             $outcome .= $linefeed;
16598:         }
16599:     }
16600:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
16601:        if ($args->{'setpolicy'}) {
16602:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16603:        }
16604:        if ($args->{'setcontent'}) {
16605:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16606:        }
16607:        if ($args->{'setcomment'}) {
16608:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16609:        }
16610:     }
16611:     if ($args->{'reshome'}) {
16612: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
16613: 	$cenv{'reshome'}=~s/\/+$/\//;
16614:     }
16615: #
16616: # course has keyed access
16617: #
16618:     if ($args->{'setkeys'}) {
16619:        $cenv{'keyaccess'}='yes';
16620:     }
16621: # if specified, key authority is not course, but user
16622: # only active if keyaccess is yes
16623:     if ($args->{'keyauth'}) {
16624: 	my ($user,$domain) = split(':',$args->{'keyauth'});
16625: 	$user = &LONCAPA::clean_username($user);
16626: 	$domain = &LONCAPA::clean_username($domain);
16627: 	if ($user ne '' && $domain ne '') {
16628: 	    $cenv{'keyauth'}=$user.':'.$domain;
16629: 	}
16630:     }
16631: 
16632: #
16633: #  generate and store uniquecode (available to course requester), if course should have one.
16634: #
16635:     if ($args->{'uniquecode'}) {
16636:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
16637:         if ($code) {
16638:             $cenv{'internal.uniquecode'} = $code;
16639:             my %crsinfo =
16640:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
16641:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
16642:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
16643:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
16644:             } 
16645:             if (ref($coderef)) {
16646:                 $$coderef = $code;
16647:             }
16648:         }
16649:     }
16650: 
16651:     if ($args->{'disresdis'}) {
16652:         $cenv{'pch.roles.denied'}='st';
16653:     }
16654:     if ($args->{'disablechat'}) {
16655:         $cenv{'plc.roles.denied'}='st';
16656:     }
16657: 
16658:     # Record we've not yet viewed the Course Initialization Helper for this 
16659:     # course
16660:     $cenv{'course.helper.not.run'} = 1;
16661:     #
16662:     # Use new Randomseed
16663:     #
16664:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
16665:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
16666:     #
16667:     # The encryption code and receipt prefix for this course
16668:     #
16669:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
16670:     $cenv{'internal.encpref'}=100+int(9*rand(99));
16671:     #
16672:     # By default, use standard grading
16673:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
16674: 
16675:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
16676:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
16677: #
16678: # Open all assignments
16679: #
16680:     if ($args->{'openall'}) {
16681:        my $opendate = time;
16682:        if ($args->{'openallfrom'} =~ /^\d+$/) {
16683:            $opendate = $args->{'openallfrom'};
16684:        }
16685:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
16686:        my %storecontent = ($storeunder         => $opendate,
16687:                            $storeunder.'.type' => 'date_start');
16688:        $outcome .= &mt('All assignments open starting [_1]',
16689:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
16690:                    &Apache::lonnet::cput
16691:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
16692:    }
16693: #
16694: # Set first page
16695: #
16696:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
16697: 	    || ($cloneid)) {
16698: 	use LONCAPA::map;
16699: 	$outcome .= &mt('Setting first resource').': ';
16700: 
16701: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
16702:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
16703: 
16704:         $outcome .= ($fatal?$errtext:'read ok').' - ';
16705:         my $title; my $url;
16706:         if ($args->{'firstres'} eq 'syl') {
16707: 	    $title=&mt('Syllabus');
16708:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
16709:         } else {
16710:             $title=&mt('Table of Contents');
16711:             $url='/adm/navmaps';
16712:         }
16713: 
16714:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
16715: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
16716: 
16717: 	if ($errtext) { $fatal=2; }
16718:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
16719:     }
16720: 
16721: # 
16722: # Set params for Placement Tests
16723: #
16724:     if ($args->{'crstype'} eq 'Placement') {
16725:        my %storecontent; 
16726:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
16727:        my %defaults = (
16728:                         buttonshide   => { value => 'yes',
16729:                                            type => 'string_yesno',},
16730:                         type          => { value => 'randomizetry',
16731:                                            type  => 'string_questiontype',},
16732:                         maxtries      => { value => 1,
16733:                                            type => 'int_pos',},
16734:                         problemstatus => { value => 'no',
16735:                                            type  => 'string_problemstatus',},
16736:                       );
16737:        foreach my $key (keys(%defaults)) {
16738:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
16739:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
16740:        }
16741:        &Apache::lonnet::cput
16742:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
16743:     }
16744: 
16745:     return (1,$outcome,\@clonemsg);
16746: }
16747: 
16748: sub make_unique_code {
16749:     my ($cdom,$cnum) = @_;
16750:     # get lock on uniquecodes db
16751:     my $lockhash = {
16752:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
16753:                                                   ':'.$env{'user.domain'},
16754:                    };
16755:     my $tries = 0;
16756:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
16757:     my ($code,$error);
16758:   
16759:     while (($gotlock ne 'ok') && ($tries<3)) {
16760:         $tries ++;
16761:         sleep 1;
16762:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
16763:     }
16764:     if ($gotlock eq 'ok') {
16765:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
16766:         my $gotcode;
16767:         my $attempts = 0;
16768:         while ((!$gotcode) && ($attempts < 100)) {
16769:             $code = &generate_code();
16770:             if (!exists($currcodes{$code})) {
16771:                 $gotcode = 1;
16772:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
16773:                     $error = 'nostore';
16774:                 }
16775:             }
16776:             $attempts ++;
16777:         }
16778:         my @del_lock = ($cnum."\0".'uniquecodes');
16779:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
16780:     } else {
16781:         $error = 'nolock';
16782:     }
16783:     return ($code,$error);
16784: }
16785: 
16786: sub generate_code {
16787:     my $code;
16788:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
16789:     for (my $i=0; $i<6; $i++) {
16790:         my $lettnum = int (rand 2);
16791:         my $item = '';
16792:         if ($lettnum) {
16793:             $item = $letts[int( rand(18) )];
16794:         } else {
16795:             $item = 1+int( rand(8) );
16796:         }
16797:         $code .= $item;
16798:     }
16799:     return $code;
16800: }
16801: 
16802: ############################################################
16803: ############################################################
16804: 
16805: # Community, Course and Placement Test
16806: sub course_type {
16807:     my ($cid) = @_;
16808:     if (!defined($cid)) {
16809:         $cid = $env{'request.course.id'};
16810:     }
16811:     if (defined($env{'course.'.$cid.'.type'})) {
16812:         return $env{'course.'.$cid.'.type'};
16813:     } else {
16814:         return 'Course';
16815:     }
16816: }
16817: 
16818: sub group_term {
16819:     my $crstype = &course_type();
16820:     my %names = (
16821:                   'Course' => 'group',
16822:                   'Community' => 'group',
16823:                   'Placement' => 'group',
16824:                 );
16825:     return $names{$crstype};
16826: }
16827: 
16828: sub course_types {
16829:     my @types = ('official','unofficial','community','textbook','placement','lti');
16830:     my %typename = (
16831:                          official   => 'Official course',
16832:                          unofficial => 'Unofficial course',
16833:                          community  => 'Community',
16834:                          textbook   => 'Textbook course',
16835:                          placement  => 'Placement test',
16836:                          lti        => 'LTI provider',
16837:                    );
16838:     return (\@types,\%typename);
16839: }
16840: 
16841: sub icon {
16842:     my ($file)=@_;
16843:     my $curfext = lc((split(/\./,$file))[-1]);
16844:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
16845:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
16846:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
16847: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
16848: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
16849: 	            $curfext.".gif") {
16850: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
16851: 		$curfext.".gif";
16852: 	}
16853:     }
16854:     return &lonhttpdurl($iconname);
16855: } 
16856: 
16857: sub lonhttpdurl {
16858: #
16859: # Had been used for "small fry" static images on separate port 8080.
16860: # Modify here if lightweight http functionality desired again.
16861: # Currently eliminated due to increasing firewall issues.
16862: #
16863:     my ($url)=@_;
16864:     return $url;
16865: }
16866: 
16867: sub connection_aborted {
16868:     my ($r)=@_;
16869:     $r->print(" ");$r->rflush();
16870:     my $c = $r->connection;
16871:     return $c->aborted();
16872: }
16873: 
16874: #    Escapes strings that may have embedded 's that will be put into
16875: #    strings as 'strings'.
16876: sub escape_single {
16877:     my ($input) = @_;
16878:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
16879:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
16880:     return $input;
16881: }
16882: 
16883: #  Same as escape_single, but escape's "'s  This 
16884: #  can be used for  "strings"
16885: sub escape_double {
16886:     my ($input) = @_;
16887:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
16888:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
16889:     return $input;
16890: }
16891:  
16892: #   Escapes the last element of a full URL.
16893: sub escape_url {
16894:     my ($url)   = @_;
16895:     my @urlslices = split(/\//, $url,-1);
16896:     my $lastitem = &escape(pop(@urlslices));
16897:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
16898: }
16899: 
16900: sub compare_arrays {
16901:     my ($arrayref1,$arrayref2) = @_;
16902:     my (@difference,%count);
16903:     @difference = ();
16904:     %count = ();
16905:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
16906:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
16907:         foreach my $element (keys(%count)) {
16908:             if ($count{$element} == 1) {
16909:                 push(@difference,$element);
16910:             }
16911:         }
16912:     }
16913:     return @difference;
16914: }
16915: 
16916: sub lon_status_items {
16917:     my %defaults = (
16918:                      E         => 100,
16919:                      W         => 4,
16920:                      N         => 1,
16921:                      U         => 5,
16922:                      threshold => 200,
16923:                      sysmail   => 2500,
16924:                    );
16925:     my %names = (
16926:                    E => 'Errors',
16927:                    W => 'Warnings',
16928:                    N => 'Notices',
16929:                    U => 'Unsent',
16930:                 );
16931:     return (\%defaults,\%names);
16932: }
16933: 
16934: # -------------------------------------------------------- Initialize user login
16935: sub init_user_environment {
16936:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
16937:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
16938: 
16939:     my $public=($username eq 'public' && $domain eq 'public');
16940: 
16941:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
16942:     my $now=time;
16943: 
16944:     if ($public) {
16945: 	my $max_public=100;
16946: 	my $oldest;
16947: 	my $oldest_time=0;
16948: 	for(my $next=1;$next<=$max_public;$next++) {
16949: 	    if (-e $lonids."/publicuser_$next.id") {
16950: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
16951: 		if ($mtime<$oldest_time || !$oldest_time) {
16952: 		    $oldest_time=$mtime;
16953: 		    $oldest=$next;
16954: 		}
16955: 	    } else {
16956: 		$cookie="publicuser_$next";
16957: 		last;
16958: 	    }
16959: 	}
16960: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
16961:     } else {
16962: 	# See if old ID present, if so, remove if this isn't a robot,
16963: 	# killing any existing non-robot sessions
16964: 	if (!$args->{'robot'}) {
16965: 	    opendir(DIR,$lonids);
16966: 	    while ($filename=readdir(DIR)) {
16967: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
16968:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
16969:                             &GDBM_READER(),0640)) {
16970:                         my $linkedfile;
16971:                         if (exists($oldenv{'user.linkedenv'})) {
16972:                             $linkedfile = $oldenv{'user.linkedenv'};
16973:                         }
16974:                         untie(%oldenv);
16975:                         if (unlink("$lonids/$filename")) {
16976:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
16977:                                 if (-l "$lonids/$linkedfile.id") {
16978:                                     unlink("$lonids/$linkedfile.id");
16979:                                 }
16980:                             }
16981:                         }
16982:                     } else {
16983:                         unlink($lonids.'/'.$filename);
16984:                     }
16985: 		}
16986: 	    }
16987: 	    closedir(DIR);
16988: # If there is a undeleted lockfile for the user's paste buffer remove it.
16989:             my $namespace = 'nohist_courseeditor';
16990:             my $lockingkey = 'paste'."\0".'locked_num';
16991:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
16992:                                                 $domain,$username);
16993:             if (exists($lockhash{$lockingkey})) {
16994:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
16995:                 unless ($delresult eq 'ok') {
16996:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
16997:                 }
16998:             }
16999: 	}
17000: # Give them a new cookie
17001: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
17002: 		                   : $now.$$.int(rand(10000)));
17003: 	$cookie="$username\_$id\_$domain\_$authhost";
17004:     
17005: # Initialize roles
17006: 
17007: 	($userroles,$firstaccenv,$timerintenv) = 
17008:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
17009:     }
17010: # ------------------------------------ Check browser type and MathML capability
17011: 
17012:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
17013:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
17014: 
17015: # ------------------------------------------------------------- Get environment
17016: 
17017:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
17018:     my ($tmp) = keys(%userenv);
17019:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
17020: 	undef(%userenv);
17021:     }
17022:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
17023: 	$form->{'interface'}=$userenv{'interface'};
17024:     }
17025:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
17026: 
17027: # --------------- Do not trust query string to be put directly into environment
17028:     foreach my $option ('interface','localpath','localres') {
17029:         $form->{$option}=~s/[\n\r\=]//gs;
17030:     }
17031: # --------------------------------------------------------- Write first profile
17032: 
17033:     {
17034:         my $ip = &Apache::lonnet::get_requestor_ip($r);
17035: 	my %initial_env = 
17036: 	    ("user.name"          => $username,
17037: 	     "user.domain"        => $domain,
17038: 	     "user.home"          => $authhost,
17039: 	     "browser.type"       => $clientbrowser,
17040: 	     "browser.version"    => $clientversion,
17041: 	     "browser.mathml"     => $clientmathml,
17042: 	     "browser.unicode"    => $clientunicode,
17043: 	     "browser.os"         => $clientos,
17044:              "browser.mobile"     => $clientmobile,
17045:              "browser.info"       => $clientinfo,
17046:              "browser.osversion"  => $clientosversion,
17047: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
17048: 	     "request.course.fn"  => '',
17049: 	     "request.course.uri" => '',
17050: 	     "request.course.sec" => '',
17051: 	     "request.role"       => 'cm',
17052: 	     "request.role.adv"   => $env{'user.adv'},
17053: 	     "request.host"       => $ip,);
17054: 
17055:         if ($form->{'localpath'}) {
17056: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
17057: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
17058:         }
17059: 	
17060: 	if ($form->{'interface'}) {
17061: 	    $form->{'interface'}=~s/\W//gs;
17062: 	    $initial_env{"browser.interface"} = $form->{'interface'};
17063: 	    $env{'browser.interface'}=$form->{'interface'};
17064: 	}
17065: 
17066:         if ($form->{'iptoken'}) {
17067:             my $lonhost = $r->dir_config('lonHostID');
17068:             $initial_env{"user.noloadbalance"} = $lonhost;
17069:             $env{'user.noloadbalance'} = $lonhost;
17070:         }
17071: 
17072:         if ($form->{'noloadbalance'}) {
17073:             my @hosts = &Apache::lonnet::current_machine_ids();
17074:             my $hosthere = $form->{'noloadbalance'};
17075:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
17076:                 $initial_env{"user.noloadbalance"} = $hosthere;
17077:                 $env{'user.noloadbalance'} = $hosthere;
17078:             }
17079:         }
17080: 
17081:         unless ($domain eq 'public') {
17082:             my %is_adv = ( is_adv => $env{'user.adv'} );
17083:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
17084: 
17085:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
17086:                 $userenv{'availabletools.'.$tool} = 
17087:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
17088:                                                       undef,\%userenv,\%domdef,\%is_adv);
17089:             }
17090: 
17091:             foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
17092:                 $userenv{'canrequest.'.$crstype} =
17093:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
17094:                                                       'reload','requestcourses',
17095:                                                       \%userenv,\%domdef,\%is_adv);
17096:             }
17097: 
17098:             $userenv{'canrequest.author'} =
17099:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
17100:                                                   'reload','requestauthor',
17101:                                                   \%userenv,\%domdef,\%is_adv);
17102:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
17103:                                                  $domain,$username);
17104:             my $reqstatus = $reqauthor{'author_status'};
17105:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
17106:                 if (ref($reqauthor{'author'}) eq 'HASH') {
17107:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
17108:                                                       $reqauthor{'author'}{'timestamp'};
17109:                 }
17110:             }
17111:             my ($types,$typename) = &course_types();
17112:             if (ref($types) eq 'ARRAY') {
17113:                 my @options = ('approval','validate','autolimit');
17114:                 my $optregex = join('|',@options);
17115:                 my (%willtrust,%trustchecked);
17116:                 foreach my $type (@{$types}) {
17117:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
17118:                     if ($dom_str ne '') {
17119:                         my $updatedstr = '';
17120:                         my @possdomains = split(',',$dom_str);
17121:                         foreach my $entry (@possdomains) {
17122:                             my ($extdom,$extopt) = split(':',$entry);
17123:                             unless ($trustchecked{$extdom}) {
17124:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
17125:                                 $trustchecked{$extdom} = 1;
17126:                             }
17127:                             if ($willtrust{$extdom}) {
17128:                                 $updatedstr .= $entry.',';
17129:                             }
17130:                         }
17131:                         $updatedstr =~ s/,$//;
17132:                         if ($updatedstr) {
17133:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
17134:                         } else {
17135:                             delete($userenv{'reqcrsotherdom.'.$type});
17136:                         }
17137:                     }
17138:                 }
17139:             }
17140:         }
17141: 	$env{'user.environment'} = "$lonids/$cookie.id";
17142: 
17143: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
17144: 		 &GDBM_WRCREAT(),0640)) {
17145: 	    &_add_to_env(\%disk_env,\%initial_env);
17146: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
17147: 	    &_add_to_env(\%disk_env,$userroles);
17148:             if (ref($firstaccenv) eq 'HASH') {
17149:                 &_add_to_env(\%disk_env,$firstaccenv);
17150:             }
17151:             if (ref($timerintenv) eq 'HASH') {
17152:                 &_add_to_env(\%disk_env,$timerintenv);
17153:             }
17154: 	    if (ref($args->{'extra_env'})) {
17155: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
17156: 	    }
17157: 	    untie(%disk_env);
17158: 	} else {
17159: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
17160: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
17161: 	    return 'error: '.$!;
17162: 	}
17163:     }
17164:     $env{'request.role'}='cm';
17165:     $env{'request.role.adv'}=$env{'user.adv'};
17166:     $env{'browser.type'}=$clientbrowser;
17167: 
17168:     return $cookie;
17169: 
17170: }
17171: 
17172: sub _add_to_env {
17173:     my ($idf,$env_data,$prefix) = @_;
17174:     if (ref($env_data) eq 'HASH') {
17175:         while (my ($key,$value) = each(%$env_data)) {
17176: 	    $idf->{$prefix.$key} = $value;
17177: 	    $env{$prefix.$key}   = $value;
17178:         }
17179:     }
17180: }
17181: 
17182: # --- Get the symbolic name of a problem and the url
17183: sub get_symb {
17184:     my ($request,$silent) = @_;
17185:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
17186:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
17187:     if ($symb eq '') {
17188:         if (!$silent) {
17189:             if (ref($request)) { 
17190:                 $request->print("Unable to handle ambiguous references:$url:.");
17191:             }
17192:             return ();
17193:         }
17194:     }
17195:     &Apache::lonenc::check_decrypt(\$symb);
17196:     return ($symb);
17197: }
17198: 
17199: # --------------------------------------------------------------Get annotation
17200: 
17201: sub get_annotation {
17202:     my ($symb,$enc) = @_;
17203: 
17204:     my $key = $symb;
17205:     if (!$enc) {
17206:         $key =
17207:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
17208:     }
17209:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
17210:     return $annotation{$key};
17211: }
17212: 
17213: sub clean_symb {
17214:     my ($symb,$delete_enc) = @_;
17215: 
17216:     &Apache::lonenc::check_decrypt(\$symb);
17217:     my $enc = $env{'request.enc'};
17218:     if ($delete_enc) {
17219:         delete($env{'request.enc'});
17220:     }
17221: 
17222:     return ($symb,$enc);
17223: }
17224: 
17225: ############################################################
17226: ############################################################
17227: 
17228: =pod
17229: 
17230: =head1 Routines for building display used to search for courses
17231: 
17232: 
17233: =over 4
17234: 
17235: =item * &build_filters()
17236: 
17237: Create markup for a table used to set filters to use when selecting
17238: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
17239: and quotacheck.pl
17240: 
17241: 
17242: Inputs:
17243: 
17244: filterlist - anonymous array of fields to include as potential filters 
17245: 
17246: crstype - course type
17247: 
17248: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
17249:               to pop-open a course selector (will contain "extra element"). 
17250: 
17251: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
17252: 
17253: filter - anonymous hash of criteria and their values
17254: 
17255: action - form action
17256: 
17257: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
17258: 
17259: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
17260: 
17261: cloneruname - username of owner of new course who wants to clone
17262: 
17263: clonerudom - domain of owner of new course who wants to clone
17264: 
17265: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
17266: 
17267: codetitlesref - reference to array of titles of components in institutional codes (official courses)
17268: 
17269: codedom - domain
17270: 
17271: formname - value of form element named "form". 
17272: 
17273: fixeddom - domain, if fixed.
17274: 
17275: prevphase - value to assign to form element named "phase" when going back to the previous screen  
17276: 
17277: cnameelement - name of form element in form on opener page which will receive title of selected course 
17278: 
17279: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
17280: 
17281: cdomelement - name of form element in form on opener page which will receive domain of selected course
17282: 
17283: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
17284: 
17285: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
17286: 
17287: clonewarning - warning message about missing information for intended course owner when DC creates a course
17288: 
17289: 
17290: Returns: $output - HTML for display of search criteria, and hidden form elements.
17291: 
17292: 
17293: Side Effects: None
17294: 
17295: =cut
17296: 
17297: # ---------------------------------------------- search for courses based on last activity etc.
17298: 
17299: sub build_filters {
17300:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
17301:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
17302:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
17303:         $cnameelement,$cnumelement,$cdomelement,$setroles,
17304:         $clonetext,$clonewarning) = @_;
17305:     my ($list,$jscript);
17306:     my $onchange = 'javascript:updateFilters(this)';
17307:     my ($domainselectform,$sincefilterform,$createdfilterform,
17308:         $ownerdomselectform,$persondomselectform,$instcodeform,
17309:         $typeselectform,$instcodetitle);
17310:     if ($formname eq '') {
17311:         $formname = $caller;
17312:     }
17313:     foreach my $item (@{$filterlist}) {
17314:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
17315:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
17316:             if ($item eq 'domainfilter') {
17317:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
17318:             } elsif ($item eq 'coursefilter') {
17319:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
17320:             } elsif ($item eq 'ownerfilter') {
17321:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
17322:             } elsif ($item eq 'ownerdomfilter') {
17323:                 $filter->{'ownerdomfilter'} =
17324:                     &LONCAPA::clean_domain($filter->{$item});
17325:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
17326:                                                        'ownerdomfilter',1);
17327:             } elsif ($item eq 'personfilter') {
17328:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
17329:             } elsif ($item eq 'persondomfilter') {
17330:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
17331:                                                         'persondomfilter',1);
17332:             } else {
17333:                 $filter->{$item} =~ s/\W//g;
17334:             }
17335:             if (!$filter->{$item}) {
17336:                 $filter->{$item} = '';
17337:             }
17338:         }
17339:         if ($item eq 'domainfilter') {
17340:             my $allow_blank = 1;
17341:             if ($formname eq 'portform') {
17342:                 $allow_blank=0;
17343:             } elsif ($formname eq 'studentform') {
17344:                 $allow_blank=0;
17345:             }
17346:             if ($fixeddom) {
17347:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
17348:                                     ' value="'.$codedom.'" />'.
17349:                                     &Apache::lonnet::domain($codedom,'description');
17350:             } else {
17351:                 $domainselectform = &select_dom_form($filter->{$item},
17352:                                                      'domainfilter',
17353:                                                       $allow_blank,'',$onchange);
17354:             }
17355:         } else {
17356:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
17357:         }
17358:     }
17359: 
17360:     # last course activity filter and selection
17361:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
17362: 
17363:     # course created filter and selection
17364:     if (exists($filter->{'createdfilter'})) {
17365:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
17366:     }
17367: 
17368:     my $prefix = $crstype;
17369:     if ($crstype eq 'Placement') {
17370:         $prefix = 'Placement Test'
17371:     }
17372:     my %lt = &Apache::lonlocal::texthash(
17373:                 'cac' => "$prefix Activity",
17374:                 'ccr' => "$prefix Created",
17375:                 'cde' => "$prefix Title",
17376:                 'cdo' => "$prefix Domain",
17377:                 'ins' => 'Institutional Code',
17378:                 'inc' => 'Institutional Categorization',
17379:                 'cow' => "$prefix Owner/Co-owner",
17380:                 'cop' => "$prefix Personnel Includes",
17381:                 'cog' => 'Type',
17382:              );
17383: 
17384:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
17385:         my $typeval = 'Course';
17386:         if ($crstype eq 'Community') {
17387:             $typeval = 'Community';
17388:         } elsif ($crstype eq 'Placement') {
17389:             $typeval = 'Placement';
17390:         }
17391:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
17392:     } else {
17393:         $typeselectform =  '<select name="type" size="1"';
17394:         if ($onchange) {
17395:             $typeselectform .= ' onchange="'.$onchange.'"';
17396:         }
17397:         $typeselectform .= '>'."\n";
17398:         foreach my $posstype ('Course','Community','Placement') {
17399:             my $shown;
17400:             if ($posstype eq 'Placement') {
17401:                 $shown = &mt('Placement Test');
17402:             } else {
17403:                 $shown = &mt($posstype);
17404:             }
17405:             $typeselectform.='<option value="'.$posstype.'"'.
17406:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
17407:         }
17408:         $typeselectform.="</select>";
17409:     }
17410: 
17411:     my ($cloneableonlyform,$cloneabletitle);
17412:     if (exists($filter->{'cloneableonly'})) {
17413:         my $cloneableon = '';
17414:         my $cloneableoff = ' checked="checked"';
17415:         if ($filter->{'cloneableonly'}) {
17416:             $cloneableon = $cloneableoff;
17417:             $cloneableoff = '';
17418:         }
17419:         $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>';
17420:         if ($formname eq 'ccrs') {
17421:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
17422:         } else {
17423:             $cloneabletitle = &mt('Cloneable by you');
17424:         }
17425:     }
17426:     my $officialjs;
17427:     if ($crstype eq 'Course') {
17428:         if (exists($filter->{'instcodefilter'})) {
17429: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
17430: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
17431:             if ($codedom) { 
17432:                 $officialjs = 1;
17433:                 ($instcodeform,$jscript,$$numtitlesref) =
17434:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
17435:                                                                   $officialjs,$codetitlesref);
17436:                 if ($jscript) {
17437:                     $jscript = '<script type="text/javascript">'."\n".
17438:                                '// <![CDATA['."\n".
17439:                                $jscript."\n".
17440:                                '// ]]>'."\n".
17441:                                '</script>'."\n";
17442:                 }
17443:             }
17444:             if ($instcodeform eq '') {
17445:                 $instcodeform =
17446:                     '<input type="text" name="instcodefilter" size="10" value="'.
17447:                     $list->{'instcodefilter'}.'" />';
17448:                 $instcodetitle = $lt{'ins'};
17449:             } else {
17450:                 $instcodetitle = $lt{'inc'};
17451:             }
17452:             if ($fixeddom) {
17453:                 $instcodetitle .= '<br />('.$codedom.')';
17454:             }
17455:         }
17456:     }
17457:     my $output = qq|
17458: <form method="post" name="filterpicker" action="$action">
17459: <input type="hidden" name="form" value="$formname" />
17460: |;
17461:     if ($formname eq 'modifycourse') {
17462:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
17463:                    '<input type="hidden" name="prevphase" value="'.
17464:                    $prevphase.'" />'."\n";
17465:     } elsif ($formname eq 'quotacheck') {
17466:         $output .= qq|
17467: <input type="hidden" name="sortby" value="" />
17468: <input type="hidden" name="sortorder" value="" />
17469: |;
17470:     } else {
17471:         my $name_input;
17472:         if ($cnameelement ne '') {
17473:             $name_input = '<input type="hidden" name="cnameelement" value="'.
17474:                           $cnameelement.'" />';
17475:         }
17476:         $output .= qq|
17477: <input type="hidden" name="cnumelement" value="$cnumelement" />
17478: <input type="hidden" name="cdomelement" value="$cdomelement" />
17479: $name_input
17480: $roleelement
17481: $multelement
17482: $typeelement
17483: |;
17484:         if ($formname eq 'portform') {
17485:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
17486:         }
17487:     }
17488:     if ($fixeddom) {
17489:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
17490:     }
17491:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
17492:     if ($sincefilterform) {
17493:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
17494:                   .$sincefilterform
17495:                   .&Apache::lonhtmlcommon::row_closure();
17496:     }
17497:     if ($createdfilterform) {
17498:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
17499:                   .$createdfilterform
17500:                   .&Apache::lonhtmlcommon::row_closure();
17501:     }
17502:     if ($domainselectform) {
17503:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
17504:                   .$domainselectform
17505:                   .&Apache::lonhtmlcommon::row_closure();
17506:     }
17507:     if ($typeselectform) {
17508:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
17509:             $output .= $typeselectform;
17510:         } else {
17511:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
17512:                       .$typeselectform
17513:                       .&Apache::lonhtmlcommon::row_closure();
17514:         }
17515:     }
17516:     if ($instcodeform) {
17517:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
17518:                   .$instcodeform
17519:                   .&Apache::lonhtmlcommon::row_closure();
17520:     }
17521:     if (exists($filter->{'ownerfilter'})) {
17522:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
17523:                    '<table><tr><td>'.&mt('Username').'<br />'.
17524:                    '<input type="text" name="ownerfilter" size="20" value="'.
17525:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
17526:                    $ownerdomselectform.'</td></tr></table>'.
17527:                    &Apache::lonhtmlcommon::row_closure();
17528:     }
17529:     if (exists($filter->{'personfilter'})) {
17530:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
17531:                    '<table><tr><td>'.&mt('Username').'<br />'.
17532:                    '<input type="text" name="personfilter" size="20" value="'.
17533:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
17534:                    $persondomselectform.'</td></tr></table>'.
17535:                    &Apache::lonhtmlcommon::row_closure();
17536:     }
17537:     if (exists($filter->{'coursefilter'})) {
17538:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
17539:                   .'<input type="text" name="coursefilter" size="25" value="'
17540:                   .$list->{'coursefilter'}.'" />'
17541:                   .&Apache::lonhtmlcommon::row_closure();
17542:     }
17543:     if ($cloneableonlyform) {
17544:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
17545:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
17546:     }
17547:     if (exists($filter->{'descriptfilter'})) {
17548:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
17549:                   .'<input type="text" name="descriptfilter" size="40" value="'
17550:                   .$list->{'descriptfilter'}.'" />'
17551:                   .&Apache::lonhtmlcommon::row_closure(1);
17552:     }
17553:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
17554:                '<input type="hidden" name="updater" value="" />'."\n".
17555:                '<input type="submit" name="gosearch" value="'.
17556:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
17557:     return $jscript.$clonewarning.$output;
17558: }
17559: 
17560: =pod 
17561: 
17562: =item * &timebased_select_form()
17563: 
17564: Create markup for a dropdown list used to select a time-based
17565: filter e.g., Course Activity, Course Created, when searching for courses
17566: or communities
17567: 
17568: Inputs:
17569: 
17570: item - name of form element (sincefilter or createdfilter)
17571: 
17572: filter - anonymous hash of criteria and their values
17573: 
17574: Returns: HTML for a select box contained a blank, then six time selections,
17575:          with value set in incoming form variables currently selected. 
17576: 
17577: Side Effects: None
17578: 
17579: =cut
17580: 
17581: sub timebased_select_form {
17582:     my ($item,$filter) = @_;
17583:     if (ref($filter) eq 'HASH') {
17584:         $filter->{$item} =~ s/[^\d-]//g;
17585:         if (!$filter->{$item}) { $filter->{$item}=-1; }
17586:         return &select_form(
17587:                             $filter->{$item},
17588:                             $item,
17589:                             {      '-1' => '',
17590:                                 '86400' => &mt('today'),
17591:                                '604800' => &mt('last week'),
17592:                               '2592000' => &mt('last month'),
17593:                               '7776000' => &mt('last three months'),
17594:                              '15552000' => &mt('last six months'),
17595:                              '31104000' => &mt('last year'),
17596:                     'select_form_order' =>
17597:                            ['-1','86400','604800','2592000','7776000',
17598:                             '15552000','31104000']});
17599:     }
17600: }
17601: 
17602: =pod
17603: 
17604: =item * &js_changer()
17605: 
17606: Create script tag containing Javascript used to submit course search form
17607: when course type or domain is changed, and also to hide 'Searching ...' on
17608: page load completion for page showing search result.
17609: 
17610: Inputs: None
17611: 
17612: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
17613: 
17614: Side Effects: None
17615: 
17616: =cut
17617: 
17618: sub js_changer {
17619:     return <<ENDJS;
17620: <script type="text/javascript">
17621: // <![CDATA[
17622: function updateFilters(caller) {
17623:     if (typeof(caller) != "undefined") {
17624:         document.filterpicker.updater.value = caller.name;
17625:     }
17626:     document.filterpicker.submit();
17627: }
17628: 
17629: function hideSearching() {
17630:     if (document.getElementById('searching')) {
17631:         document.getElementById('searching').style.display = 'none';
17632:     }
17633:     return;
17634: }
17635: 
17636: // ]]>
17637: </script>
17638: 
17639: ENDJS
17640: }
17641: 
17642: =pod
17643: 
17644: =item * &search_courses()
17645: 
17646: Process selected filters form course search form and pass to lonnet::courseiddump
17647: to retrieve a hash for which keys are courseIDs which match the selected filters.
17648: 
17649: Inputs:
17650: 
17651: dom - domain being searched 
17652: 
17653: type - course type ('Course' or 'Community' or '.' if any).
17654: 
17655: filter - anonymous hash of criteria and their values
17656: 
17657: numtitles - for institutional codes - number of categories
17658: 
17659: cloneruname - optional username of new course owner
17660: 
17661: clonerudom - optional domain of new course owner
17662: 
17663: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
17664:             (used when DC is using course creation form)
17665: 
17666: codetitles - reference to array of titles of components in institutional codes (official courses).
17667: 
17668: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
17669:            (and so can clone automatically)
17670: 
17671: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
17672: 
17673: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
17674:               courses to clone 
17675: 
17676: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
17677: 
17678: 
17679: Side Effects: None
17680: 
17681: =cut
17682: 
17683: 
17684: sub search_courses {
17685:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
17686:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
17687:     my (%courses,%showcourses,$cloner);
17688:     if (($filter->{'ownerfilter'} ne '') ||
17689:         ($filter->{'ownerdomfilter'} ne '')) {
17690:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
17691:                                        $filter->{'ownerdomfilter'};
17692:     }
17693:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
17694:         if (!$filter->{$item}) {
17695:             $filter->{$item}='.';
17696:         }
17697:     }
17698:     my $now = time;
17699:     my $timefilter =
17700:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
17701:     my ($createdbefore,$createdafter);
17702:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
17703:         $createdbefore = $now;
17704:         $createdafter = $now-$filter->{'createdfilter'};
17705:     }
17706:     my ($instcodefilter,$regexpok);
17707:     if ($numtitles) {
17708:         if ($env{'form.official'} eq 'on') {
17709:             $instcodefilter =
17710:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
17711:             $regexpok = 1;
17712:         } elsif ($env{'form.official'} eq 'off') {
17713:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
17714:             unless ($instcodefilter eq '') {
17715:                 $regexpok = -1;
17716:             }
17717:         }
17718:     } else {
17719:         $instcodefilter = $filter->{'instcodefilter'};
17720:     }
17721:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
17722:     if ($type eq '') { $type = '.'; }
17723: 
17724:     if (($clonerudom ne '') && ($cloneruname ne '')) {
17725:         $cloner = $cloneruname.':'.$clonerudom;
17726:     }
17727:     %courses = &Apache::lonnet::courseiddump($dom,
17728:                                              $filter->{'descriptfilter'},
17729:                                              $timefilter,
17730:                                              $instcodefilter,
17731:                                              $filter->{'combownerfilter'},
17732:                                              $filter->{'coursefilter'},
17733:                                              undef,undef,$type,$regexpok,undef,undef,
17734:                                              undef,undef,$cloner,$cc_clone,
17735:                                              $filter->{'cloneableonly'},
17736:                                              $createdbefore,$createdafter,undef,
17737:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
17738:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
17739:         my $ccrole;
17740:         if ($type eq 'Community') {
17741:             $ccrole = 'co';
17742:         } else {
17743:             $ccrole = 'cc';
17744:         }
17745:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
17746:                                                      $filter->{'persondomfilter'},
17747:                                                      'userroles',undef,
17748:                                                      [$ccrole,'in','ad','ep','ta','cr'],
17749:                                                      $dom);
17750:         foreach my $role (keys(%rolehash)) {
17751:             my ($cnum,$cdom,$courserole) = split(':',$role);
17752:             my $cid = $cdom.'_'.$cnum;
17753:             if (exists($courses{$cid})) {
17754:                 if (ref($courses{$cid}) eq 'HASH') {
17755:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
17756:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
17757:                             push(@{$courses{$cid}{roles}},$courserole);
17758:                         }
17759:                     } else {
17760:                         $courses{$cid}{roles} = [$courserole];
17761:                     }
17762:                     $showcourses{$cid} = $courses{$cid};
17763:                 }
17764:             }
17765:         }
17766:         %courses = %showcourses;
17767:     }
17768:     return %courses;
17769: }
17770: 
17771: =pod
17772: 
17773: =back
17774: 
17775: =head1 Routines for version requirements for current course.
17776: 
17777: =over 4
17778: 
17779: =item * &check_release_required()
17780: 
17781: Compares required LON-CAPA version with version on server, and
17782: if required version is newer looks for a server with the required version.
17783: 
17784: Looks first at servers in user's owen domain; if none suitable, looks at
17785: servers in course's domain are permitted to host sessions for user's domain.
17786: 
17787: Inputs:
17788: 
17789: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
17790: 
17791: $courseid - Course ID of current course
17792: 
17793: $rolecode - User's current role in course (for switchserver query string).
17794: 
17795: $required - LON-CAPA version needed by course (format: Major.Minor).
17796: 
17797: 
17798: Returns:
17799: 
17800: $switchserver - query string tp append to /adm/switchserver call (if 
17801:                 current server's LON-CAPA version is too old. 
17802: 
17803: $warning - Message is displayed if no suitable server could be found.
17804: 
17805: =cut
17806: 
17807: sub check_release_required {
17808:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
17809:     my ($switchserver,$warning);
17810:     if ($required ne '') {
17811:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
17812:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
17813:         if ($reqdmajor ne '' && $reqdminor ne '') {
17814:             my $otherserver;
17815:             if (($major eq '' && $minor eq '') ||
17816:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
17817:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
17818:                 my $switchlcrev =
17819:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
17820:                                                            $userdomserver);
17821:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
17822:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
17823:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
17824:                     my $cdom = $env{'course.'.$courseid.'.domain'};
17825:                     if ($cdom ne $env{'user.domain'}) {
17826:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
17827:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
17828:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
17829:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
17830:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
17831:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
17832:                         my $canhost =
17833:                             &Apache::lonnet::can_host_session($env{'user.domain'},
17834:                                                               $coursedomserver,
17835:                                                               $remoterev,
17836:                                                               $udomdefaults{'remotesessions'},
17837:                                                               $defdomdefaults{'hostedsessions'});
17838: 
17839:                         if ($canhost) {
17840:                             $otherserver = $coursedomserver;
17841:                         } else {
17842:                             $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.");
17843:                         }
17844:                     } else {
17845:                         $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).");
17846:                     }
17847:                 } else {
17848:                     $otherserver = $userdomserver;
17849:                 }
17850:             }
17851:             if ($otherserver ne '') {
17852:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
17853:             }
17854:         }
17855:     }
17856:     return ($switchserver,$warning);
17857: }
17858: 
17859: =pod
17860: 
17861: =item * &check_release_result()
17862: 
17863: Inputs:
17864: 
17865: $switchwarning - Warning message if no suitable server found to host session.
17866: 
17867: $switchserver - query string to append to /adm/switchserver containing lonHostID
17868:                 and current role.
17869: 
17870: Returns: HTML to display with information about requirement to switch server.
17871:          Either displaying warning with link to Roles/Courses screen or
17872:          display link to switchserver.
17873: 
17874: =cut
17875: 
17876: sub check_release_result {
17877:     my ($switchwarning,$switchserver) = @_;
17878:     my $output = &start_page('Selected course unavailable on this server').
17879:                  '<p class="LC_warning">';
17880:     if ($switchwarning) {
17881:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
17882:         if (&show_course()) {
17883:             $output .= &mt('Display courses');
17884:         } else {
17885:             $output .= &mt('Display roles');
17886:         }
17887:         $output .= '</a>';
17888:     } elsif ($switchserver) {
17889:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
17890:                    '<br />'.
17891:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
17892:                    &mt('Switch Server').
17893:                    '</a>';
17894:     }
17895:     $output .= '</p>'.&end_page();
17896:     return $output;
17897: }
17898: 
17899: =pod
17900: 
17901: =item * &needs_coursereinit()
17902: 
17903: Determine if course contents stored for user's session needs to be
17904: refreshed, because content has changed since "Big Hash" last tied.
17905: 
17906: Check for change is made if time last checked is more than 10 minutes ago
17907: (by default).
17908: 
17909: Inputs:
17910: 
17911: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
17912: 
17913: $interval (optional) - Time which may elapse (in s) between last check for content
17914:                        change in current course. (default: 600 s).  
17915: 
17916: Returns: an array; first element is:
17917: 
17918: =over 4
17919: 
17920: 'switch' - if content updates mean user's session
17921:            needs to be switched to a server running a newer LON-CAPA version
17922:  
17923: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
17924:            on current server hosting user's session                
17925: 
17926: ''       - if no action required.
17927: 
17928: =back
17929: 
17930: If first item element is 'switch':
17931: 
17932: second item is $switchwarning - Warning message if no suitable server found to host session. 
17933: 
17934: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
17935:                               and current role. 
17936: 
17937: otherwise: no other elements returned.
17938: 
17939: =back
17940: 
17941: =cut
17942: 
17943: sub needs_coursereinit {
17944:     my ($loncaparev,$interval) = @_;
17945:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
17946:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
17947:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
17948:     my $now = time;
17949:     if ($interval eq '') {
17950:         $interval = 600;
17951:     }
17952:     if (($now-$env{'request.course.timechecked'})>$interval) {
17953:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
17954:         my $blocked = &blocking_status('reinit',$cnum,$cdom,undef,1);
17955:         if ($blocked) {
17956:             return ();
17957:         }
17958:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
17959:         if ($lastchange > $env{'request.course.tied'}) {
17960:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
17961:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
17962:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
17963:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
17964:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
17965:                                              $curr_reqd_hash{'internal.releaserequired'}});
17966:                     my ($switchserver,$switchwarning) =
17967:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
17968:                                                 $curr_reqd_hash{'internal.releaserequired'});
17969:                     if ($switchwarning ne '' || $switchserver ne '') {
17970:                         return ('switch',$switchwarning,$switchserver);
17971:                     }
17972:                 }
17973:             }
17974:             return ('update');
17975:         }
17976:     }
17977:     return ();
17978: }
17979: 
17980: sub update_content_constraints {
17981:     my ($cdom,$cnum,$chome,$cid,$keeporder) = @_;
17982:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
17983:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
17984:     my (%checkresponsetypes,%checkcrsrestypes);
17985:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
17986:         my ($item,$name,$value) = split(/:/,$key);
17987:         if ($item eq 'resourcetag') {
17988:             if ($name eq 'responsetype') {
17989:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
17990:             }
17991:         } elsif ($item eq 'course') {
17992:             if ($name eq 'courserestype') {
17993:                 $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
17994:             }
17995:         }
17996:     }
17997:     my $navmap = Apache::lonnavmaps::navmap->new();
17998:     if (defined($navmap)) {
17999:         my (%allresponses,%allcrsrestypes);
18000:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
18001:             if ($res->is_tool()) {
18002:                 if ($allcrsrestypes{'exttool'}) {
18003:                     $allcrsrestypes{'exttool'} ++;
18004:                 } else {
18005:                     $allcrsrestypes{'exttool'} = 1;
18006:                 }
18007:                 next;
18008:             }
18009:             my %responses = $res->responseTypes();
18010:             foreach my $key (keys(%responses)) {
18011:                 next unless(exists($checkresponsetypes{$key}));
18012:                 $allresponses{$key} += $responses{$key};
18013:             }
18014:         }
18015:         foreach my $key (keys(%allresponses)) {
18016:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
18017:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
18018:                 ($reqdmajor,$reqdminor) = ($major,$minor);
18019:             }
18020:         }
18021:         foreach my $key (keys(%allcrsrestypes)) {
18022:             my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
18023:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
18024:                 ($reqdmajor,$reqdminor) = ($major,$minor);
18025:             }
18026:         }
18027:         undef($navmap);
18028:     }
18029:     my (@resources,@order,@resparms,@zombies);
18030:     if ($keeporder) {
18031:         use LONCAPA::map;
18032:         @resources = @LONCAPA::map::resources;
18033:         @order = @LONCAPA::map::order;
18034:         @resparms = @LONCAPA::map::resparms;
18035:         @zombies = @LONCAPA::map::zombies;
18036:     }
18037:     my $suppmap = 'supplemental.sequence';
18038:     my ($suppcount,$supptools,$errors) = (0,0,0);
18039:     ($suppcount,$supptools,$errors) = &recurse_supplemental($cnum,$cdom,$suppmap,
18040:                                                             $suppcount,$supptools,$errors);
18041:     if ($keeporder) {
18042:         @LONCAPA::map::resources = @resources;
18043:         @LONCAPA::map::order = @order;
18044:         @LONCAPA::map::resparms = @resparms;
18045:         @LONCAPA::map::zombies = @zombies;
18046:     }
18047:     if ($supptools) {
18048:         my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
18049:         if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
18050:             ($reqdmajor,$reqdminor) = ($major,$minor);
18051:         }
18052:     }
18053:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
18054:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
18055:     }
18056:     return;
18057: }
18058: 
18059: sub allmaps_incourse {
18060:     my ($cdom,$cnum,$chome,$cid) = @_;
18061:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
18062:         $cid = $env{'request.course.id'};
18063:         $cdom = $env{'course.'.$cid.'.domain'};
18064:         $cnum = $env{'course.'.$cid.'.num'};
18065:         $chome = $env{'course.'.$cid.'.home'};
18066:     }
18067:     my %allmaps = ();
18068:     my $lastchange =
18069:         &Apache::lonnet::get_coursechange($cdom,$cnum);
18070:     if ($lastchange > $env{'request.course.tied'}) {
18071:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
18072:         unless ($ferr) {
18073:             &update_content_constraints($cdom,$cnum,$chome,$cid,1);
18074:         }
18075:     }
18076:     my $navmap = Apache::lonnavmaps::navmap->new();
18077:     if (defined($navmap)) {
18078:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
18079:             $allmaps{$res->src()} = 1;
18080:         }
18081:     }
18082:     return \%allmaps;
18083: }
18084: 
18085: sub parse_supplemental_title {
18086:     my ($title) = @_;
18087: 
18088:     my ($foldertitle,$renametitle);
18089:     if ($title =~ /&amp;&amp;&amp;/) {
18090:         $title = &HTML::Entites::decode($title);
18091:     }
18092:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
18093:         $renametitle=$4;
18094:         my ($time,$uname,$udom) = ($1,$2,$3);
18095:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
18096:         my $name =  &plainname($uname,$udom);
18097:         $name = &HTML::Entities::encode($name,'"<>&\'');
18098:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
18099:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
18100:             $name.': <br />'.$foldertitle;
18101:     }
18102:     if (wantarray) {
18103:         return ($title,$foldertitle,$renametitle);
18104:     }
18105:     return $title;
18106: }
18107: 
18108: sub recurse_supplemental {
18109:     my ($cnum,$cdom,$suppmap,$numfiles,$numexttools,$errors) = @_;
18110:     if ($suppmap) {
18111:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
18112:         if ($fatal) {
18113:             $errors ++;
18114:         } else {
18115:             if ($#LONCAPA::map::resources > 0) {
18116:                 foreach my $res (@LONCAPA::map::resources) {
18117:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
18118:                     if (($src ne '') && ($status eq 'res')) {
18119:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
18120:                             ($numfiles,$numexttools,$errors) = &recurse_supplemental($cnum,$cdom,$1,
18121:                                                                    $numfiles,$numexttools,$errors);
18122:                         } else {
18123:                             if ($src =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
18124:                                 $numexttools ++;
18125:                             }
18126:                             $numfiles ++;
18127:                         }
18128:                     }
18129:                 }
18130:             }
18131:         }
18132:     }
18133:     return ($numfiles,$numexttools,$errors);
18134: }
18135: 
18136: sub symb_to_docspath {
18137:     my ($symb,$navmapref) = @_;
18138:     return unless ($symb && ref($navmapref));
18139:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
18140:     if ($resurl=~/\.(sequence|page)$/) {
18141:         $mapurl=$resurl;
18142:     } elsif ($resurl eq 'adm/navmaps') {
18143:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
18144:     }
18145:     my $mapresobj;
18146:     unless (ref($$navmapref)) {
18147:         $$navmapref = Apache::lonnavmaps::navmap->new();
18148:     }
18149:     if (ref($$navmapref)) {
18150:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
18151:     }
18152:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
18153:     my $type=$2;
18154:     my $path;
18155:     if (ref($mapresobj)) {
18156:         my $pcslist = $mapresobj->map_hierarchy();
18157:         if ($pcslist ne '') {
18158:             foreach my $pc (split(/,/,$pcslist)) {
18159:                 next if ($pc <= 1);
18160:                 my $res = $$navmapref->getByMapPc($pc);
18161:                 if (ref($res)) {
18162:                     my $thisurl = $res->src();
18163:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
18164:                     my $thistitle = $res->title();
18165:                     $path .= '&'.
18166:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
18167:                              &escape($thistitle).
18168:                              ':'.$res->randompick().
18169:                              ':'.$res->randomout().
18170:                              ':'.$res->encrypted().
18171:                              ':'.$res->randomorder().
18172:                              ':'.$res->is_page();
18173:                 }
18174:             }
18175:         }
18176:         $path =~ s/^\&//;
18177:         my $maptitle = $mapresobj->title();
18178:         if ($mapurl eq 'default') {
18179:             $maptitle = 'Main Content';
18180:         }
18181:         $path .= (($path ne '')? '&' : '').
18182:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
18183:                  &escape($maptitle).
18184:                  ':'.$mapresobj->randompick().
18185:                  ':'.$mapresobj->randomout().
18186:                  ':'.$mapresobj->encrypted().
18187:                  ':'.$mapresobj->randomorder().
18188:                  ':'.$mapresobj->is_page();
18189:     } else {
18190:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
18191:         my $ispage = (($type eq 'page')? 1 : '');
18192:         if ($mapurl eq 'default') {
18193:             $maptitle = 'Main Content';
18194:         }
18195:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
18196:                 &escape($maptitle).':::::'.$ispage;
18197:     }
18198:     unless ($mapurl eq 'default') {
18199:         $path = 'default&'.
18200:                 &escape('Main Content').
18201:                 ':::::&'.$path;
18202:     }
18203:     return $path;
18204: }
18205: 
18206: sub captcha_display {
18207:     my ($context,$lonhost,$defdom) = @_;
18208:     my ($output,$error);
18209:     my ($captcha,$pubkey,$privkey,$version) = 
18210:         &get_captcha_config($context,$lonhost,$defdom);
18211:     if ($captcha eq 'original') {
18212:         $output = &create_captcha();
18213:         unless ($output) {
18214:             $error = 'captcha';
18215:         }
18216:     } elsif ($captcha eq 'recaptcha') {
18217:         $output = &create_recaptcha($pubkey,$version);
18218:         unless ($output) {
18219:             $error = 'recaptcha';
18220:         }
18221:     }
18222:     return ($output,$error,$captcha,$version);
18223: }
18224: 
18225: sub captcha_response {
18226:     my ($context,$lonhost,$defdom) = @_;
18227:     my ($captcha_chk,$captcha_error);
18228:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
18229:     if ($captcha eq 'original') {
18230:         ($captcha_chk,$captcha_error) = &check_captcha();
18231:     } elsif ($captcha eq 'recaptcha') {
18232:         $captcha_chk = &check_recaptcha($privkey,$version);
18233:     } else {
18234:         $captcha_chk = 1;
18235:     }
18236:     return ($captcha_chk,$captcha_error);
18237: }
18238: 
18239: sub get_captcha_config {
18240:     my ($context,$lonhost,$dom_in_effect) = @_;
18241:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
18242:     my $hostname = &Apache::lonnet::hostname($lonhost);
18243:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
18244:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
18245:     if ($context eq 'usercreation') {
18246:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
18247:         if (ref($domconfig{$context}) eq 'HASH') {
18248:             $hashtocheck = $domconfig{$context}{'cancreate'};
18249:             if (ref($hashtocheck) eq 'HASH') {
18250:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
18251:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
18252:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
18253:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
18254:                     }
18255:                     if ($privkey && $pubkey) {
18256:                         $captcha = 'recaptcha';
18257:                         $version = $hashtocheck->{'recaptchaversion'};
18258:                         if ($version ne '2') {
18259:                             $version = 1;
18260:                         }
18261:                     } else {
18262:                         $captcha = 'original';
18263:                     }
18264:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
18265:                     $captcha = 'original';
18266:                 }
18267:             }
18268:         } else {
18269:             $captcha = 'captcha';
18270:         }
18271:     } elsif ($context eq 'login') {
18272:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
18273:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
18274:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
18275:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
18276:             if ($privkey && $pubkey) {
18277:                 $captcha = 'recaptcha';
18278:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
18279:                 if ($version ne '2') {
18280:                     $version = 1; 
18281:                 }
18282:             } else {
18283:                 $captcha = 'original';
18284:             }
18285:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
18286:             $captcha = 'original';
18287:         }
18288:     } elsif ($context eq 'passwords') {
18289:         if ($dom_in_effect) {
18290:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
18291:             if ($passwdconf{'captcha'} eq 'recaptcha') {
18292:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
18293:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
18294:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
18295:                 }
18296:                 if ($privkey && $pubkey) {
18297:                     $captcha = 'recaptcha';
18298:                     $version = $passwdconf{'recaptchaversion'};
18299:                     if ($version ne '2') {
18300:                         $version = 1;
18301:                     }
18302:                 } else {
18303:                     $captcha = 'original';
18304:                 }
18305:             } elsif ($passwdconf{'captcha'} ne 'notused') {
18306:                 $captcha = 'original';
18307:             }
18308:         }
18309:     } 
18310:     return ($captcha,$pubkey,$privkey,$version);
18311: }
18312: 
18313: sub create_captcha {
18314:     my %captcha_params = &captcha_settings();
18315:     my ($output,$maxtries,$tries) = ('',10,0);
18316:     while ($tries < $maxtries) {
18317:         $tries ++;
18318:         my $captcha = Authen::Captcha->new (
18319:                                            output_folder => $captcha_params{'output_dir'},
18320:                                            data_folder   => $captcha_params{'db_dir'},
18321:                                           );
18322:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
18323: 
18324:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
18325:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
18326:                       '<span class="LC_nobreak">'.
18327:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
18328:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
18329:                       '</span><br />'.
18330:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
18331:             last;
18332:         }
18333:     }
18334:     if ($output eq '') {
18335:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
18336:     }
18337:     return $output;
18338: }
18339: 
18340: sub captcha_settings {
18341:     my %captcha_params = (
18342:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
18343:                            www_output_dir => "/captchaspool",
18344:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
18345:                            numchars       => '5',
18346:                          );
18347:     return %captcha_params;
18348: }
18349: 
18350: sub check_captcha {
18351:     my ($captcha_chk,$captcha_error);
18352:     my $code = $env{'form.code'};
18353:     my $md5sum = $env{'form.crypt'};
18354:     my %captcha_params = &captcha_settings();
18355:     my $captcha = Authen::Captcha->new(
18356:                       output_folder => $captcha_params{'output_dir'},
18357:                       data_folder   => $captcha_params{'db_dir'},
18358:                   );
18359:     $captcha_chk = $captcha->check_code($code,$md5sum);
18360:     my %captcha_hash = (
18361:                         0       => 'Code not checked (file error)',
18362:                        -1      => 'Failed: code expired',
18363:                        -2      => 'Failed: invalid code (not in database)',
18364:                        -3      => 'Failed: invalid code (code does not match crypt)',
18365:     );
18366:     if ($captcha_chk != 1) {
18367:         $captcha_error = $captcha_hash{$captcha_chk}
18368:     }
18369:     return ($captcha_chk,$captcha_error);
18370: }
18371: 
18372: sub create_recaptcha {
18373:     my ($pubkey,$version) = @_;
18374:     if ($version >= 2) {
18375:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
18376:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
18377:     } else {
18378:         my $use_ssl;
18379:         if ($ENV{'SERVER_PORT'} == 443) {
18380:             $use_ssl = 1;
18381:         }
18382:         my $captcha = Captcha::reCAPTCHA->new;
18383:         return $captcha->get_options_setter({theme => 'white'})."\n".
18384:                $captcha->get_html($pubkey,undef,$use_ssl).
18385:                &mt('If the text is hard to read, [_1] will replace them.',
18386:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
18387:                '<br /><br />';
18388:     }
18389: }
18390: 
18391: sub check_recaptcha {
18392:     my ($privkey,$version) = @_;
18393:     my $captcha_chk;
18394:     my $ip = &Apache::lonnet::get_requestor_ip();
18395:     if ($version >= 2) {
18396:         my %info = (
18397:                      secret   => $privkey, 
18398:                      response => $env{'form.g-recaptcha-response'},
18399:                      remoteip => $ip,
18400:                    );
18401:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
18402:         $request->content(join('&',map {
18403:                          my $name = escape($_);
18404:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
18405:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
18406:                          : &escape($info{$_}) );
18407:         } keys(%info)));
18408:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
18409:         if ($response->is_success)  {
18410:             my $data = JSON::DWIW->from_json($response->decoded_content);
18411:             if (ref($data) eq 'HASH') {
18412:                 if ($data->{'success'}) {
18413:                     $captcha_chk = 1;
18414:                 }
18415:             }
18416:         }
18417:     } else {
18418:         my $captcha = Captcha::reCAPTCHA->new;
18419:         my $captcha_result =
18420:             $captcha->check_answer(
18421:                                     $privkey,
18422:                                     $ip,
18423:                                     $env{'form.recaptcha_challenge_field'},
18424:                                     $env{'form.recaptcha_response_field'},
18425:                                   );
18426:         if ($captcha_result->{is_valid}) {
18427:             $captcha_chk = 1;
18428:         }
18429:     }
18430:     return $captcha_chk;
18431: }
18432: 
18433: sub emailusername_info {
18434:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
18435:     my %titles = &Apache::lonlocal::texthash (
18436:                      lastname      => 'Last Name',
18437:                      firstname     => 'First Name',
18438:                      institution   => 'School/college/university',
18439:                      location      => "School's city, state/province, country",
18440:                      web           => "School's web address",
18441:                      officialemail => 'E-mail address at institution (if different)',
18442:                      id            => 'Student/Employee ID',
18443:                  );
18444:     return (\@fields,\%titles);
18445: }
18446: 
18447: sub cleanup_html {
18448:     my ($incoming) = @_;
18449:     my $outgoing;
18450:     if ($incoming ne '') {
18451:         $outgoing = $incoming;
18452:         $outgoing =~ s/;/&#059;/g;
18453:         $outgoing =~ s/\#/&#035;/g;
18454:         $outgoing =~ s/\&/&#038;/g;
18455:         $outgoing =~ s/</&#060;/g;
18456:         $outgoing =~ s/>/&#062;/g;
18457:         $outgoing =~ s/\(/&#040/g;
18458:         $outgoing =~ s/\)/&#041;/g;
18459:         $outgoing =~ s/"/&#034;/g;
18460:         $outgoing =~ s/'/&#039;/g;
18461:         $outgoing =~ s/\$/&#036;/g;
18462:         $outgoing =~ s{/}{&#047;}g;
18463:         $outgoing =~ s/=/&#061;/g;
18464:         $outgoing =~ s/\\/&#092;/g
18465:     }
18466:     return $outgoing;
18467: }
18468: 
18469: # Checks for critical messages and returns a redirect url if one exists.
18470: # $interval indicates how often to check for messages.
18471: # $context is the calling context -- roles, grades, contents, menu or flip. 
18472: sub critical_redirect {
18473:     my ($interval,$context) = @_;
18474:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
18475:         return ();
18476:     }
18477:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
18478:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
18479:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
18480:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
18481:             my $blocked = &blocking_status('alert',$cnum,$cdom,undef,1);
18482:             if ($blocked) {
18483:                 my $checkrole = "cm./$cdom/$cnum";
18484:                 if ($env{'request.course.sec'} ne '') {
18485:                     $checkrole .= "/$env{'request.course.sec'}";
18486:                 }
18487:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
18488:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
18489:                     return;
18490:                 }
18491:             }
18492:         }
18493:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
18494:                                         $env{'user.name'});
18495:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
18496:         my $redirecturl;
18497:         if ($what[0]) {
18498: 	    if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
18499: 	        $redirecturl='/adm/email?critical=display';
18500: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
18501:                 return (1, $url);
18502:             }
18503:         }
18504:     } 
18505:     return ();
18506: }
18507: 
18508: # Use:
18509: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
18510: #
18511: ##################################################
18512: #          password associated functions         #
18513: ##################################################
18514: sub des_keys {
18515:     # Make a new key for DES encryption.
18516:     # Each key has two parts which are returned separately.
18517:     # Please note:  Each key must be passed through the &hex function
18518:     # before it is output to the web browser.  The hex versions cannot
18519:     # be used to decrypt.
18520:     my @hexstr=('0','1','2','3','4','5','6','7',
18521:                 '8','9','a','b','c','d','e','f');
18522:     my $lkey='';
18523:     for (0..7) {
18524:         $lkey.=$hexstr[rand(15)];
18525:     }
18526:     my $ukey='';
18527:     for (0..7) {
18528:         $ukey.=$hexstr[rand(15)];
18529:     }
18530:     return ($lkey,$ukey);
18531: }
18532: 
18533: sub des_decrypt {
18534:     my ($key,$cyphertext) = @_;
18535:     my $keybin=pack("H16",$key);
18536:     my $cypher;
18537:     if ($Crypt::DES::VERSION>=2.03) {
18538:         $cypher=new Crypt::DES $keybin;
18539:     } else {
18540:         $cypher=new DES $keybin;
18541:     }
18542:     my $plaintext='';
18543:     my $cypherlength = length($cyphertext);
18544:     my $numchunks = int($cypherlength/32);
18545:     for (my $j=0; $j<$numchunks; $j++) {
18546:         my $start = $j*32;
18547:         my $cypherblock = substr($cyphertext,$start,32);
18548:         my $chunk =
18549:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
18550:         $chunk .=
18551:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
18552:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
18553:         $plaintext .= $chunk;
18554:     }
18555:     return $plaintext;
18556: }
18557: 
18558: sub get_requested_shorturls {
18559:     my ($cdom,$cnum,$navmap) = @_;
18560:     return unless (ref($navmap));
18561:     my ($numnew,$errors);
18562:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
18563:     if (@toshorten) {
18564:         my (%maps,%resources,%titles);
18565:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
18566:                                                                'shorturls',$cdom,$cnum);
18567:         if (keys(%resources)) {
18568:             my %tocreate;
18569:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
18570:                 my $symb = $resources{$item};
18571:                 if ($symb) {
18572:                     $tocreate{$cnum.'&'.$symb} = 1;
18573:                 }
18574:             }
18575:             if (keys(%tocreate)) {
18576:                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
18577:                                                       \%tocreate);
18578:             }
18579:         }
18580:     }
18581:     return ($numnew,$errors);
18582: }
18583: 
18584: sub make_short_symbs {
18585:     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
18586:     my ($numnew,@errors);
18587:     if (ref($tocreateref) eq 'HASH') {
18588:         my %tocreate = %{$tocreateref};
18589:         if (keys(%tocreate)) {
18590:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
18591:             my $su = Short::URL->new(no_vowels => 1);
18592:             my $init = '';
18593:             my (%newunique,%addcourse,%courseonly,%failed);
18594:             # get lock on tiny db
18595:             my $now = time;
18596:             if ($lockuser eq '') {
18597:                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
18598:             }
18599:             my $lockhash = {
18600:                                 "lock\0$now" => $lockuser,
18601:                             };
18602:             my $tries = 0;
18603:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
18604:             my ($code,$error);
18605:             while (($gotlock ne 'ok') && ($tries<3)) {
18606:                 $tries ++;
18607:                 sleep 1;
18608:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
18609:             }
18610:             if ($gotlock eq 'ok') {
18611:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
18612:                                        \%addcourse,\%courseonly,\%failed);
18613:                 if (keys(%failed)) {
18614:                     my $numfailed = scalar(keys(%failed));
18615:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
18616:                 }
18617:                 if (keys(%newunique)) {
18618:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
18619:                     if ($putres eq 'ok') {
18620:                         $numnew = scalar(keys(%newunique));
18621:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
18622:                         unless ($newputres eq 'ok') {
18623:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
18624:                         }
18625:                     } else {
18626:                         push(@errors,&mt('error: could not store unique six character URLs'));
18627:                     }
18628:                 }
18629:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
18630:                 unless ($dellockres eq 'ok') {
18631:                     push(@errors,&mt('error: could not release lockfile'));
18632:                 }
18633:             } else {
18634:                 push(@errors,&mt('error: could not obtain lockfile'));
18635:             }
18636:             if (keys(%courseonly)) {
18637:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
18638:                 if ($result ne 'ok') {
18639:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
18640:                 }
18641:             }
18642:         }
18643:     }
18644:     return ($numnew,\@errors);
18645: }
18646: 
18647: sub shorten_symbs {
18648:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
18649:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
18650:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
18651:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
18652:     my (%possibles,%collisions);
18653:     foreach my $key (keys(%{$tocreate})) {
18654:         my $num = String::CRC32::crc32($key);
18655:         my $tiny = $su->encode($num,$init);
18656:         if ($tiny) {
18657:             $possibles{$tiny} = $key;
18658:         }
18659:     }
18660:     if (!$init) {
18661:         $init = 1;
18662:     } else {
18663:         $init ++;
18664:     }
18665:     if (keys(%possibles)) {
18666:         my @posstiny = keys(%possibles);
18667:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
18668:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
18669:         if (keys(%currtiny)) {
18670:             foreach my $key (keys(%currtiny)) {
18671:                 next if ($currtiny{$key} eq '');
18672:                 if ($currtiny{$key} eq $possibles{$key}) {
18673:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
18674:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
18675:                         $courseonly->{$tsymb} = $key;
18676:                     }
18677:                 } else {
18678:                     $collisions{$possibles{$key}} = 1;
18679:                 }
18680:                 delete($possibles{$key});
18681:             }
18682:         }
18683:         foreach my $key (keys(%possibles)) {
18684:             $newunique->{$key} = $possibles{$key};
18685:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
18686:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
18687:                 $addcourse->{$tsymb} = $key;
18688:             }
18689:         }
18690:     }
18691:     if (keys(%collisions)) {
18692:         if ($init <5) {
18693:             if (!$init) {
18694:                 $init = 1;
18695:             } else {
18696:                 $init ++;
18697:             }
18698:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
18699:                                    $newunique,$addcourse,$courseonly,$failed);
18700:         } else {
18701:             foreach my $key (keys(%collisions)) {
18702:                 $failed->{$key} = 1;
18703:             }
18704:         }
18705:     }
18706:     return $init;
18707: }
18708: 
18709: sub is_nonframeable {
18710:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
18711:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
18712:     return if (($remprotocol eq '') || ($remhost eq ''));
18713: 
18714:     $remprotocol = lc($remprotocol);
18715:     $remhost = lc($remhost);
18716:     my $remport = 80;
18717:     if ($remprotocol eq 'https') {
18718:         $remport = 443;
18719:     }
18720:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
18721:     if ($cached) {
18722:         unless ($nocache) {
18723:             if ($result) {
18724:                 return 1;
18725:             } else {
18726:                 return 0;
18727:             }
18728:         }
18729:     }
18730:     my $uselink;
18731:     my $request = new HTTP::Request('HEAD',$url);
18732:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
18733:     if ($response->is_success()) {
18734:         my $secpolicy = lc($response->header('content-security-policy'));
18735:         my $xframeop = lc($response->header('x-frame-options'));
18736:         $secpolicy =~ s/^\s+|\s+$//g;
18737:         $xframeop =~ s/^\s+|\s+$//g;
18738:         if (($secpolicy ne '') || ($xframeop ne '')) {
18739:             my $remotehost = $remprotocol.'://'.$remhost;
18740:             my ($origin,$protocol,$port);
18741:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
18742:                 $port = $ENV{'SERVER_PORT'};
18743:             } else {
18744:                 $port = 80;
18745:             }
18746:             if ($absolute eq '') {
18747:                 $protocol = 'http:';
18748:                 if ($port == 443) {
18749:                     $protocol = 'https:';
18750:                 }
18751:                 $origin = $protocol.'//'.lc($hostname);
18752:             } else {
18753:                 $origin = lc($absolute);
18754:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
18755:             }
18756:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
18757:                 my $framepolicy = $1;
18758:                 $framepolicy =~ s/^\s+|\s+$//g;
18759:                 my @policies = split(/\s+/,$framepolicy);
18760:                 if (@policies) {
18761:                     if (grep(/^\Q'none'\E$/,@policies)) {
18762:                         $uselink = 1;
18763:                     } else {
18764:                         $uselink = 1;
18765:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
18766:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
18767:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
18768:                             undef($uselink);
18769:                         }
18770:                         if ($uselink) {
18771:                             if (grep(/^\Q'self'\E$/,@policies)) {
18772:                                 if (($origin ne '') && ($remotehost eq $origin)) {
18773:                                     undef($uselink);
18774:                                 }
18775:                             }
18776:                         }
18777:                         if ($uselink) {
18778:                             my @possok;
18779:                             if ($ip ne '') {
18780:                                 push(@possok,$ip);
18781:                             }
18782:                             my $hoststr = '';
18783:                             foreach my $part (reverse(split(/\./,$hostname))) {
18784:                                 if ($hoststr eq '') {
18785:                                     $hoststr = $part;
18786:                                 } else {
18787:                                     $hoststr = "$part.$hoststr";
18788:                                 }
18789:                                 if ($hoststr eq $hostname) {
18790:                                     push(@possok,$hostname);
18791:                                 } else {
18792:                                     push(@possok,"*.$hoststr");
18793:                                 }
18794:                             }
18795:                             if (@possok) {
18796:                                 foreach my $poss (@possok) {
18797:                                     last if (!$uselink);
18798:                                     foreach my $policy (@policies) {
18799:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
18800:                                             undef($uselink);
18801:                                             last;
18802:                                         }
18803:                                     }
18804:                                 }
18805:                             }
18806:                         }
18807:                     }
18808:                 }
18809:             } elsif ($xframeop ne '') {
18810:                 $uselink = 1;
18811:                 my @policies = split(/\s*,\s*/,$xframeop);
18812:                 if (@policies) {
18813:                     unless (grep(/^deny$/,@policies)) {
18814:                         if ($origin ne '') {
18815:                             if (grep(/^sameorigin$/,@policies)) {
18816:                                 if ($remotehost eq $origin) {
18817:                                     undef($uselink);
18818:                                 }
18819:                             }
18820:                             if ($uselink) {
18821:                                 foreach my $policy (@policies) {
18822:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
18823:                                         my $allowfrom = $1;
18824:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
18825:                                             undef($uselink);
18826:                                             last;
18827:                                         }
18828:                                     }
18829:                                 }
18830:                             }
18831:                         }
18832:                     }
18833:                 }
18834:             }
18835:         }
18836:     }
18837:     if ($nocache) {
18838:         if ($cached) {
18839:             my $devalidate;
18840:             if ($uselink && !$result) {
18841:                 $devalidate = 1;
18842:             } elsif (!$uselink && $result) {
18843:                 $devalidate = 1;
18844:             }
18845:             if ($devalidate) {
18846:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
18847:             }
18848:         }
18849:     } else {
18850:         if ($uselink) {
18851:             $result = 1;
18852:         } else {
18853:             $result = 0;
18854:         }
18855:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
18856:     }
18857:     return $uselink;
18858: }
18859: 
18860: sub page_menu {
18861:     my ($menucolls,$menunum) = @_;
18862:     my %menu;
18863:     foreach my $item (split(/;/,$menucolls)) {
18864:         my ($num,$value) = split(/\%/,$item);
18865:         if ($num eq $menunum) {
18866:             my @entries = split(/\&/,$value);
18867:             foreach my $entry (@entries) {
18868:                 my ($name,$fields) = split(/=/,$entry);
18869:                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
18870:                     $menu{$name} = $fields;
18871:                 } else {
18872:                     my @shown;
18873:                     if ($fields =~ /,/) {
18874:                         @shown = split(/,/,$fields);
18875:                     } else {
18876:                         @shown = ($fields);
18877:                     }
18878:                     if (@shown) {
18879:                         foreach my $field (@shown) {
18880:                             next if ($field eq '');
18881:                             $menu{$field} = 1;
18882:                         }
18883:                     }
18884:                 }
18885:             }
18886:         }
18887:     }
18888:     return %menu;
18889: }
18890: 
18891: 1;
18892: __END__;
18893: 

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