File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1422: download - view: text, annotated - select for diffs
Sun Nov 26 20:47:16 2023 UTC (5 months, 3 weeks ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Support checking of available editors when saving in Daxe, when current
  role is a course role.
- Support localization.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1422 2023/11/26 20:47:16 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: # Makes a table out of the previous attempts
   30: # Inputs result_from_symbread, user, domain, course_id
   31: # Reads in non-network-related .tab files
   32: 
   33: # POD header:
   34: 
   35: =pod
   36: 
   37: =head1 NAME
   38: 
   39: Apache::loncommon - pile of common routines
   40: 
   41: =head1 SYNOPSIS
   42: 
   43: Common routines for manipulating connections, student answers,
   44:     domains, common Javascript fragments, etc.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: A collection of commonly used subroutines that don't have a natural
   49: home anywhere else. This collection helps remove
   50: redundancy from other modules and increase efficiency of memory usage.
   51: 
   52: =cut 
   53: 
   54: # End of POD header
   55: package Apache::loncommon;
   56: 
   57: use strict;
   58: use Apache::lonnet;
   59: use GDBM_File;
   60: use POSIX qw(strftime mktime);
   61: use Apache::lonmenu();
   62: use Apache::lonenc();
   63: use Apache::lonlocal;
   64: use Apache::lonnavmaps();
   65: use HTML::Entities;
   66: use Apache::lonhtmlcommon();
   67: use Apache::loncoursedata();
   68: use Apache::lontexconvert();
   69: use Apache::lonclonecourse();
   70: use Apache::lonuserutils();
   71: use Apache::lonuserstate();
   72: use Apache::courseclassifier();
   73: use LONCAPA qw(:DEFAULT :match);
   74: use LONCAPA::ltiutils;
   75: use LONCAPA::LWPReq;
   76: use LONCAPA::map();
   77: use HTTP::Request;
   78: use DateTime::TimeZone;
   79: use DateTime::Locale;
   80: use Encode();
   81: use Text::Aspell;
   82: use Authen::Captcha;
   83: use Captcha::reCAPTCHA;
   84: use JSON::DWIW;
   85: use Crypt::DES;
   86: use DynaLoader; # for Crypt::DES version
   87: use MIME::Lite;
   88: use MIME::Types;
   89: use File::Copy();
   90: use File::Path();
   91: use String::CRC32();
   92: use Short::URL();
   93: 
   94: # ---------------------------------------------- Designs
   95: use vars qw(%defaultdesign);
   96: 
   97: my $readit;
   98: 
   99: 
  100: ##
  101: ## Global Variables
  102: ##
  103: 
  104: 
  105: # ----------------------------------------------- SSI with retries:
  106: #
  107: 
  108: =pod
  109: 
  110: =head1 Server Side include with retries:
  111: 
  112: =over 4
  113: 
  114: =item * &ssi_with_retries(resource,retries form)
  115: 
  116: Performs an ssi with some number of retries.  Retries continue either
  117: until the result is ok or until the retry count supplied by the
  118: caller is exhausted.  
  119: 
  120: Inputs:
  121: 
  122: =over 4
  123: 
  124: resource   - Identifies the resource to insert.
  125: 
  126: retries    - Count of the number of retries allowed.
  127: 
  128: form       - Hash that identifies the rendering options.
  129: 
  130: =back
  131: 
  132: Returns:
  133: 
  134: =over 4
  135: 
  136: content    - The content of the response.  If retries were exhausted this is empty.
  137: 
  138: response   - The response from the last attempt (which may or may not have been successful.
  139: 
  140: =back
  141: 
  142: =back
  143: 
  144: =cut
  145: 
  146: sub ssi_with_retries {
  147:     my ($resource, $retries, %form) = @_;
  148: 
  149: 
  150:     my $ok = 0;			# True if we got a good response.
  151:     my $content;
  152:     my $response;
  153: 
  154:     # Try to get the ssi done. within the retries count:
  155: 
  156:     do {
  157: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  158: 	$ok      = $response->is_success;
  159:         if (!$ok) {
  160:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  161:         }
  162: 	$retries--;
  163:     } while (!$ok && ($retries > 0));
  164: 
  165:     if (!$ok) {
  166: 	$content = '';		# On error return an empty content.
  167:     }
  168:     return ($content, $response);
  169: 
  170: }
  171: 
  172: 
  173: 
  174: # ----------------------------------------------- Filetypes/Languages/Copyright
  175: my %language;
  176: my %supported_language;
  177: my %supported_codes;
  178: my %latex_language;		# For choosing hyphenation in <transl..>
  179: my %latex_language_bykey;	# for choosing hyphenation from metadata
  180: my %cprtag;
  181: my %scprtag;
  182: my %fe; my %fd; my %fm;
  183: my %category_extensions;
  184: 
  185: # ---------------------------------------------- Thesaurus variables
  186: #
  187: # %Keywords:
  188: #      A hash used by &keyword to determine if a word is considered a keyword.
  189: # $thesaurus_db_file 
  190: #      Scalar containing the full path to the thesaurus database.
  191: 
  192: my %Keywords;
  193: my $thesaurus_db_file;
  194: 
  195: #
  196: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  197: # thesaurus.tab, and filecategories.tab.
  198: #
  199: BEGIN {
  200:     # Variable initialization
  201:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  202:     #
  203:     unless ($readit) {
  204: # ------------------------------------------------------------------- languages
  205:     {
  206:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  207:                                    '/language.tab';
  208:         if ( open(my $fh,'<',$langtabfile) ) {
  209:             while (my $line = <$fh>) {
  210:                 next if ($line=~/^\#/);
  211:                 chomp($line);
  212:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  213:                 $language{$key}=$val.' - '.$enc;
  214:                 if ($sup) {
  215:                     $supported_language{$key}=$sup;
  216: 		    $supported_codes{$key}   = $code;
  217:                 }
  218: 		if ($latex) {
  219: 		    $latex_language_bykey{$key} = $latex;
  220: 		    $latex_language{$code} = $latex;
  221: 		}
  222:             }
  223:             close($fh);
  224:         }
  225:     }
  226: # ------------------------------------------------------------------ copyrights
  227:     {
  228:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  229:                                   '/copyright.tab';
  230:         if ( open (my $fh,'<',$copyrightfile) ) {
  231:             while (my $line = <$fh>) {
  232:                 next if ($line=~/^\#/);
  233:                 chomp($line);
  234:                 my ($key,$val)=(split(/\s+/,$line,2));
  235:                 $cprtag{$key}=$val;
  236:             }
  237:             close($fh);
  238:         }
  239:     }
  240: # ----------------------------------------------------------- source copyrights
  241:     {
  242:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  243:                                   '/source_copyright.tab';
  244:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
  245:             while (my $line = <$fh>) {
  246:                 next if ($line =~ /^\#/);
  247:                 chomp($line);
  248:                 my ($key,$val)=(split(/\s+/,$line,2));
  249:                 $scprtag{$key}=$val;
  250:             }
  251:             close($fh);
  252:         }
  253:     }
  254: 
  255: # -------------------------------------------------------------- default domain designs
  256:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  257:     my $designfile = $designdir.'/default.tab';
  258:     if ( open (my $fh,'<',$designfile) ) {
  259:         while (my $line = <$fh>) {
  260:             next if ($line =~ /^\#/);
  261:             chomp($line);
  262:             my ($key,$val)=(split(/\=/,$line));
  263:             if ($val) { $defaultdesign{$key}=$val; }
  264:         }
  265:         close($fh);
  266:     }
  267: 
  268: # ------------------------------------------------------------- file categories
  269:     {
  270:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  271:                                   '/filecategories.tab';
  272:         if ( open (my $fh,'<',$categoryfile) ) {
  273: 	    while (my $line = <$fh>) {
  274: 		next if ($line =~ /^\#/);
  275: 		chomp($line);
  276:                 my ($extension,$category)=(split(/\s+/,$line,2));
  277:                 push(@{$category_extensions{lc($category)}},$extension);
  278:             }
  279:             close($fh);
  280:         }
  281: 
  282:     }
  283: # ------------------------------------------------------------------ file types
  284:     {
  285:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  286:                '/filetypes.tab';
  287:         if ( open (my $fh,'<',$typesfile) ) {
  288:             while (my $line = <$fh>) {
  289: 		next if ($line =~ /^\#/);
  290: 		chomp($line);
  291:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  292:                 if ($descr ne '') {
  293:                     $fe{$ending}=lc($emb);
  294:                     $fd{$ending}=$descr;
  295:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  296:                 }
  297:             }
  298:             close($fh);
  299:         }
  300:     }
  301:     &Apache::lonnet::logthis(
  302:              "<span style='color:yellow;'>INFO: Read file types</span>");
  303:     $readit=1;
  304:     }  # end of unless($readit) 
  305:     
  306: }
  307: 
  308: ###############################################################
  309: ##           HTML and Javascript Helper Functions            ##
  310: ###############################################################
  311: 
  312: =pod 
  313: 
  314: =head1 HTML and Javascript Functions
  315: 
  316: =over 4
  317: 
  318: =item * &browser_and_searcher_javascript()
  319: 
  320: X<browsing, javascript>X<searching, javascript>Returns a string
  321: containing javascript with two functions, C<openbrowser> and
  322: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  323: tags.
  324: 
  325: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  326: 
  327: inputs: formname, elementname, only, omit
  328: 
  329: formname and elementname indicate the name of the html form and name of
  330: the element that the results of the browsing selection are to be placed in. 
  331: 
  332: Specifying 'only' will restrict the browser to displaying only files
  333: with the given extension.  Can be a comma separated list.
  334: 
  335: Specifying 'omit' will restrict the browser to NOT displaying files
  336: with the given extension.  Can be a comma separated list.
  337: 
  338: =item * &opensearcher(formname,elementname) [javascript]
  339: 
  340: Inputs: formname, elementname
  341: 
  342: formname and elementname specify the name of the html form and the name
  343: of the element the selection from the search results will be placed in.
  344: 
  345: =cut
  346: 
  347: sub browser_and_searcher_javascript {
  348:     my ($mode)=@_;
  349:     if (!defined($mode)) { $mode='edit'; }
  350:     my $resurl=&escape_single(&lastresurl());
  351:     return <<END;
  352: // <!-- BEGIN LON-CAPA Internal
  353:     var editbrowser = null;
  354:     function openbrowser(formname,elementname,only,omit,titleelement) {
  355:         var url = '$resurl/?';
  356:         if (editbrowser == null) {
  357:             url += 'launch=1&';
  358:         }
  359:         url += 'catalogmode=interactive&';
  360:         url += 'mode=$mode&';
  361:         url += 'inhibitmenu=yes&';
  362:         url += 'form=' + formname + '&';
  363:         if (only != null) {
  364:             url += 'only=' + only + '&';
  365:         } else {
  366:             url += 'only=&';
  367: 	}
  368:         if (omit != null) {
  369:             url += 'omit=' + omit + '&';
  370:         } else {
  371:             url += 'omit=&';
  372: 	}
  373:         if (titleelement != null) {
  374:             url += 'titleelement=' + titleelement + '&';
  375:         } else {
  376: 	    url += 'titleelement=&';
  377: 	}
  378:         url += 'element=' + elementname + '';
  379:         var title = 'Browser';
  380:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  381:         options += ',width=700,height=600';
  382:         editbrowser = open(url,title,options,'1');
  383:         editbrowser.focus();
  384:     }
  385:     var editsearcher;
  386:     function opensearcher(formname,elementname,titleelement) {
  387:         var url = '/adm/searchcat?';
  388:         if (editsearcher == null) {
  389:             url += 'launch=1&';
  390:         }
  391:         url += 'catalogmode=interactive&';
  392:         url += 'mode=$mode&';
  393:         url += 'form=' + formname + '&';
  394:         if (titleelement != null) {
  395:             url += 'titleelement=' + titleelement + '&';
  396:         } else {
  397: 	    url += 'titleelement=&';
  398: 	}
  399:         url += 'element=' + elementname + '';
  400:         var title = 'Search';
  401:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  402:         options += ',width=700,height=600';
  403:         editsearcher = open(url,title,options,'1');
  404:         editsearcher.focus();
  405:     }
  406: // END LON-CAPA Internal -->
  407: END
  408: }
  409: 
  410: sub lastresurl {
  411:     if ($env{'environment.lastresurl'}) {
  412: 	return $env{'environment.lastresurl'}
  413:     } else {
  414: 	return '/res';
  415:     }
  416: }
  417: 
  418: sub storeresurl {
  419:     my $resurl=&Apache::lonnet::clutter(shift);
  420:     unless ($resurl=~/^\/res/) { return 0; }
  421:     $resurl=~s/\/$//;
  422:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  423:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  424:     return 1;
  425: }
  426: 
  427: sub studentbrowser_javascript {
  428:    unless (
  429:             (($env{'request.course.id'}) && 
  430:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  431: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  432: 					  '/'.$env{'request.course.sec'})
  433: 	      ))
  434:          || ($env{'request.role'}=~/^(au|dc|su)/)
  435:           ) { return ''; }  
  436:    return (<<'ENDSTDBRW');
  437: <script type="text/javascript" language="Javascript">
  438: // <![CDATA[
  439:     var stdeditbrowser;
  440:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv,uident) {
  441:         var url = '/adm/pickstudent?';
  442:         var filter;
  443: 	if (!ignorefilter) {
  444: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  445: 	}
  446:         if (filter != null) {
  447:            if (filter != '') {
  448:                url += 'filter='+filter+'&';
  449: 	   }
  450:         }
  451:         url += 'form=' + formname + '&unameelement='+uname+
  452:                                     '&udomelement='+udom+
  453:                                     '&clicker='+clicker;
  454: 	if (roleflag) { url+="&roles=1"; }
  455:         if (courseadv == 'condition') {
  456:             if (document.getElementById('courseadv')) {
  457:                 courseadv = document.getElementById('courseadv').value;
  458:             }
  459:         }
  460:         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
  461:         if (uident !== '') { url+="&identelement="+uident; } 
  462:         var title = 'Student_Browser';
  463:         var options = 'scrollbars=1,resizable=1,menubar=0';
  464:         options += ',width=700,height=600';
  465:         stdeditbrowser = open(url,title,options,'1');
  466:         stdeditbrowser.focus();
  467:     }
  468: // ]]>
  469: </script>
  470: ENDSTDBRW
  471: }
  472: 
  473: sub resourcebrowser_javascript {
  474:    unless ($env{'request.course.id'}) { return ''; }
  475:    return (<<'ENDRESBRW');
  476: <script type="text/javascript" language="Javascript">
  477: // <![CDATA[
  478:     var reseditbrowser;
  479:     function openresbrowser(formname,reslink) {
  480:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  481:         var title = 'Resource_Browser';
  482:         var options = 'scrollbars=1,resizable=1,menubar=0';
  483:         options += ',width=700,height=500';
  484:         reseditbrowser = open(url,title,options,'1');
  485:         reseditbrowser.focus();
  486:     }
  487: // ]]>
  488: </script>
  489: ENDRESBRW
  490: }
  491: 
  492: sub selectstudent_link {
  493:    my ($form,$unameele,$udomele,$courseadv,$clickerid,$identelem)=@_;
  494:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  495:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  496:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  497:    if ($env{'request.course.id'}) {  
  498:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  499: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  500: 					'/'.$env{'request.course.sec'})) {
  501: 	   return '';
  502:        }
  503:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  504:        if ($courseadv eq 'only') {
  505:            $callargs .= ",'',1,'$courseadv'";
  506:        } elsif ($courseadv eq 'none') {
  507:            $callargs .= ",'','','$courseadv'";
  508:        } elsif ($courseadv eq 'condition') {
  509:            $callargs .= ",'','','$courseadv'";
  510:        } elsif ($identelem ne '') {
  511:            $callargs .= ",'','',''";
  512:        }
  513:        if ($identelem ne '') {
  514:            $callargs .= ",'".&Apache::lonhtmlcommon::entity_encode($identelem)."'";
  515:        }
  516:        return '<span class="LC_nobreak">'.
  517:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  518:               &mt('Select User').'</a></span>';
  519:    }
  520:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  521:        $callargs .= ",'',1"; 
  522:        return '<span class="LC_nobreak">'.
  523:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  524:               &mt('Select User').'</a></span>';
  525:    }
  526:    return '';
  527: }
  528: 
  529: sub selectresource_link {
  530:    my ($form,$reslink,$arg)=@_;
  531:    
  532:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  533:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  534:    unless ($env{'request.course.id'}) { return $arg; }
  535:    return '<span class="LC_nobreak">'.
  536:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  537:               $arg.'</a></span>';
  538: }
  539: 
  540: 
  541: 
  542: sub authorbrowser_javascript {
  543:     return <<"ENDAUTHORBRW";
  544: <script type="text/javascript" language="JavaScript">
  545: // <![CDATA[
  546: var stdeditbrowser;
  547: 
  548: function openauthorbrowser(formname,udom) {
  549:     var url = '/adm/pickauthor?';
  550:     url += 'form='+formname+'&roledom='+udom;
  551:     var title = 'Author_Browser';
  552:     var options = 'scrollbars=1,resizable=1,menubar=0';
  553:     options += ',width=700,height=600';
  554:     stdeditbrowser = open(url,title,options,'1');
  555:     stdeditbrowser.focus();
  556: }
  557: 
  558: // ]]>
  559: </script>
  560: ENDAUTHORBRW
  561: }
  562: 
  563: sub coursebrowser_javascript {
  564:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
  565:         $credits_element,$instcode) = @_;
  566:     my $wintitle = 'Course_Browser';
  567:     if ($crstype eq 'Community') {
  568:         $wintitle = 'Community_Browser';
  569:     }
  570:     my $id_functions = &javascript_index_functions();
  571:     my $output = '
  572: <script type="text/javascript" language="JavaScript">
  573: // <![CDATA[
  574:     var stdeditbrowser;'."\n";
  575: 
  576:     $output .= <<"ENDSTDBRW";
  577:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  578:         var url = '/adm/pickcourse?';
  579:         var formid = getFormIdByName(formname);
  580:         var domainfilter = getDomainFromSelectbox(formname,udom);
  581:         if (domainfilter != null) {
  582:            if (domainfilter != '') {
  583:                url += 'domainfilter='+domainfilter+'&';
  584: 	   }
  585:         }
  586:         url += 'form=' + formname + '&cnumelement='+uname+
  587: 	                            '&cdomelement='+udom+
  588:                                     '&cnameelement='+desc;
  589:         if (extra_element !=null && extra_element != '') {
  590:             if (formname == 'rolechoice' || formname == 'studentform') {
  591:                 url += '&roleelement='+extra_element;
  592:                 if (domainfilter == null || domainfilter == '') {
  593:                     url += '&domainfilter='+extra_element;
  594:                 }
  595:             }
  596:             else {
  597:                 if (formname == 'portform') {
  598:                     url += '&setroles='+extra_element;
  599:                 } else {
  600:                     if (formname == 'rules') {
  601:                         url += '&fixeddom='+extra_element; 
  602:                     }
  603:                 }
  604:             }     
  605:         }
  606:         if (type != null && type != '') {
  607:             url += '&type='+type;
  608:         }
  609:         if (type_elem != null && type_elem != '') {
  610:             url += '&typeelement='+type_elem;
  611:         }
  612:         if (formname == 'ccrs') {
  613:             var ownername = document.forms[formid].ccuname.value;
  614:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  615:             url += '&cloner='+ownername+':'+ownerdom;
  616:             if (type == 'Course') {
  617:                 url += '&crscode='+document.forms[formid].crscode.value;
  618:             }
  619:         }
  620:         if (formname == 'requestcrs') {
  621:             url += '&crsdom=$domainfilter&crscode=$instcode';
  622:         }
  623:         if (multflag !=null && multflag != '') {
  624:             url += '&multiple='+multflag;
  625:         }
  626:         var title = '$wintitle';
  627:         var options = 'scrollbars=1,resizable=1,menubar=0';
  628:         options += ',width=700,height=600';
  629:         stdeditbrowser = open(url,title,options,'1');
  630:         stdeditbrowser.focus();
  631:     }
  632: $id_functions
  633: ENDSTDBRW
  634:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
  635:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
  636:                                       $credits_element);
  637:     }
  638:     $output .= '
  639: // ]]>
  640: </script>';
  641:     return $output;
  642: }
  643: 
  644: sub javascript_index_functions {
  645:     return <<"ENDJS";
  646: 
  647: function getFormIdByName(formname) {
  648:     for (var i=0;i<document.forms.length;i++) {
  649:         if (document.forms[i].name == formname) {
  650:             return i;
  651:         }
  652:     }
  653:     return -1;
  654: }
  655: 
  656: function getIndexByName(formid,item) {
  657:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  658:         if (document.forms[formid].elements[i].name == item) {
  659:             return i;
  660:         }
  661:     }
  662:     return -1;
  663: }
  664: 
  665: function getDomainFromSelectbox(formname,udom) {
  666:     var userdom;
  667:     var formid = getFormIdByName(formname);
  668:     if (formid > -1) {
  669:         var domid = getIndexByName(formid,udom);
  670:         if (domid > -1) {
  671:             if (document.forms[formid].elements[domid].type == 'select-one') {
  672:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  673:             }
  674:             if (document.forms[formid].elements[domid].type == 'hidden') {
  675:                 userdom=document.forms[formid].elements[domid].value;
  676:             }
  677:         }
  678:     }
  679:     return userdom;
  680: }
  681: 
  682: ENDJS
  683: 
  684: }
  685: 
  686: sub javascript_array_indexof {
  687:     return <<ENDJS;
  688: <script type="text/javascript" language="JavaScript">
  689: // <![CDATA[
  690: 
  691: if (!Array.prototype.indexOf) {
  692:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  693:         "use strict";
  694:         if (this === void 0 || this === null) {
  695:             throw new TypeError();
  696:         }
  697:         var t = Object(this);
  698:         var len = t.length >>> 0;
  699:         if (len === 0) {
  700:             return -1;
  701:         }
  702:         var n = 0;
  703:         if (arguments.length > 0) {
  704:             n = Number(arguments[1]);
  705:             if (n !== n) { // shortcut for verifying if it is NaN
  706:                 n = 0;
  707:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  708:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  709:             }
  710:         }
  711:         if (n >= len) {
  712:             return -1;
  713:         }
  714:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  715:         for (; k < len; k++) {
  716:             if (k in t && t[k] === searchElement) {
  717:                 return k;
  718:             }
  719:         }
  720:         return -1;
  721:     }
  722: }
  723: 
  724: // ]]>
  725: </script>
  726: 
  727: ENDJS
  728: 
  729: }
  730: 
  731: sub userbrowser_javascript {
  732:     my $id_functions = &javascript_index_functions();
  733:     return <<"ENDUSERBRW";
  734: 
  735: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  736:     var url = '/adm/pickuser?';
  737:     var userdom = getDomainFromSelectbox(formname,udom);
  738:     if (userdom != null) {
  739:        if (userdom != '') {
  740:            url += 'srchdom='+userdom+'&';
  741:        }
  742:     }
  743:     url += 'form=' + formname + '&unameelement='+uname+
  744:                                 '&udomelement='+udom+
  745:                                 '&ulastelement='+ulast+
  746:                                 '&ufirstelement='+ufirst+
  747:                                 '&uemailelement='+uemail+
  748:                                 '&hideudomelement='+hideudom+
  749:                                 '&coursedom='+crsdom;
  750:     if ((caller != null) && (caller != undefined)) {
  751:         url += '&caller='+caller;
  752:     }
  753:     var title = 'User_Browser';
  754:     var options = 'scrollbars=1,resizable=1,menubar=0';
  755:     options += ',width=700,height=600';
  756:     var stdeditbrowser = open(url,title,options,'1');
  757:     stdeditbrowser.focus();
  758: }
  759: 
  760: function fix_domain (formname,udom,origdom,uname) {
  761:     var formid = getFormIdByName(formname);
  762:     if (formid > -1) {
  763:         var unameid = getIndexByName(formid,uname);
  764:         var domid = getIndexByName(formid,udom);
  765:         var hidedomid = getIndexByName(formid,origdom);
  766:         if (hidedomid > -1) {
  767:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  768:             var unameval = document.forms[formid].elements[unameid].value;
  769:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  770:                 if (domid > -1) {
  771:                     var slct = document.forms[formid].elements[domid];
  772:                     if (slct.type == 'select-one') {
  773:                         var i;
  774:                         for (i=0;i<slct.length;i++) {
  775:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  776:                         }
  777:                     }
  778:                     if (slct.type == 'hidden') {
  779:                         slct.value = fixeddom;
  780:                     }
  781:                 }
  782:             }
  783:         }
  784:     }
  785:     return;
  786: }
  787: 
  788: $id_functions
  789: ENDUSERBRW
  790: }
  791: 
  792: sub setsec_javascript {
  793:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
  794:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  795:         $communityrolestr);
  796:     if ($role_element ne '') {
  797:         my @allroles = ('st','ta','ep','in','ad');
  798:         foreach my $crstype ('Course','Community') {
  799:             if ($crstype eq 'Community') {
  800:                 foreach my $role (@allroles) {
  801:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  802:                 }
  803:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  804:             } else {
  805:                 foreach my $role (@allroles) {
  806:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  807:                 }
  808:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  809:             }
  810:         }
  811:         $rolestr = '"'.join('","',@allroles).'"';
  812:         $courserolestr = '"'.join('","',@courserolenames).'"';
  813:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  814:     }
  815:     my $setsections = qq|
  816: function setSect(sectionlist) {
  817:     var sectionsArray = new Array();
  818:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  819:         sectionsArray = sectionlist.split(",");
  820:     }
  821:     var numSections = sectionsArray.length;
  822:     document.$formname.$sec_element.length = 0;
  823:     if (numSections == 0) {
  824:         document.$formname.$sec_element.multiple=false;
  825:         document.$formname.$sec_element.size=1;
  826:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  827:     } else {
  828:         if (numSections == 1) {
  829:             document.$formname.$sec_element.multiple=false;
  830:             document.$formname.$sec_element.size=1;
  831:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  832:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  833:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  834:         } else {
  835:             for (var i=0; i<numSections; i++) {
  836:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  837:             }
  838:             document.$formname.$sec_element.multiple=true
  839:             if (numSections < 3) {
  840:                 document.$formname.$sec_element.size=numSections;
  841:             } else {
  842:                 document.$formname.$sec_element.size=3;
  843:             }
  844:             document.$formname.$sec_element.options[0].selected = false
  845:         }
  846:     }
  847: }
  848: 
  849: function setRole(crstype) {
  850: |;
  851:     if ($role_element eq '') {
  852:         $setsections .= '    return;
  853: }
  854: ';
  855:     } else {
  856:         $setsections .= qq|
  857:     var elementLength = document.$formname.$role_element.length;
  858:     var allroles = Array($rolestr);
  859:     var courserolenames = Array($courserolestr);
  860:     var communityrolenames = Array($communityrolestr);
  861:     if (elementLength != undefined) {
  862:         if (document.$formname.$role_element.options[5].value == 'cc') {
  863:             if (crstype == 'Course') {
  864:                 return;
  865:             } else {
  866:                 allroles[5] = 'co';
  867:                 for (var i=0; i<6; i++) {
  868:                     document.$formname.$role_element.options[i].value = allroles[i];
  869:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  870:                 }
  871:             }
  872:         } else {
  873:             if (crstype == 'Community') {
  874:                 return;
  875:             } else {
  876:                 allroles[5] = 'cc';
  877:                 for (var i=0; i<6; i++) {
  878:                     document.$formname.$role_element.options[i].value = allroles[i];
  879:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  880:                 }
  881:             }
  882:         }
  883:     }
  884:     return;
  885: }
  886: |;
  887:     }
  888:     if ($credits_element) {
  889:         $setsections .= qq|
  890: function setCredits(defaultcredits) {
  891:     document.$formname.$credits_element.value = defaultcredits;
  892:     return;
  893: }
  894: |;
  895:     }
  896:     return $setsections;
  897: }
  898: 
  899: sub selectcourse_link {
  900:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  901:        $typeelement) = @_;
  902:    my $type = $selecttype;
  903:    my $linktext = &mt('Select Course');
  904:    if ($selecttype eq 'Community') {
  905:        $linktext = &mt('Select Community');
  906:    } elsif ($selecttype eq 'Placement') {
  907:        $linktext = &mt('Select Placement Test'); 
  908:    } elsif ($selecttype eq 'Course/Community') {
  909:        $linktext = &mt('Select Course/Community');
  910:        $type = '';
  911:    } elsif ($selecttype eq 'Select') {
  912:        $linktext = &mt('Select');
  913:        $type = '';
  914:    }
  915:    return '<span class="LC_nobreak">'
  916:          ."<a href='"
  917:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  918:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  919:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  920:          ."'>".$linktext.'</a>'
  921:          .'</span>';
  922: }
  923: 
  924: sub selectauthor_link {
  925:    my ($form,$udom)=@_;
  926:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  927:           &mt('Select Author').'</a>';
  928: }
  929: 
  930: sub selectuser_link {
  931:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  932:         $coursedom,$linktext,$caller) = @_;
  933:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  934:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  935:            ');">'.$linktext.'</a>';
  936: }
  937: 
  938: sub check_uncheck_jscript {
  939:     my $jscript = <<"ENDSCRT";
  940: function checkAll(field) {
  941:     if (field.length > 0) {
  942:         for (i = 0; i < field.length; i++) {
  943:             if (!field[i].disabled) { 
  944:                 field[i].checked = true;
  945:             }
  946:         }
  947:     } else {
  948:         if (!field.disabled) { 
  949:             field.checked = true;
  950:         }
  951:     }
  952: }
  953:  
  954: function uncheckAll(field) {
  955:     if (field.length > 0) {
  956:         for (i = 0; i < field.length; i++) {
  957:             field[i].checked = false ;
  958:         }
  959:     } else {
  960:         field.checked = false ;
  961:     }
  962: }
  963: ENDSCRT
  964:     return $jscript;
  965: }
  966: 
  967: sub select_timezone {
  968:    my ($name,$selected,$onchange,$includeempty,$id,$disabled)=@_;
  969:    my $output='<select name="'.$name.'" '.$id.$onchange.$disabled.'>'."\n";
  970:    if ($includeempty) {
  971:        $output .= '<option value=""';
  972:        if (($selected eq '') || ($selected eq 'local')) {
  973:            $output .= ' selected="selected" ';
  974:        }
  975:        $output .= '> </option>';
  976:    }
  977:    my @timezones = DateTime::TimeZone->all_names;
  978:    foreach my $tzone (@timezones) {
  979:        $output.= '<option value="'.$tzone.'"';
  980:        if ($tzone eq $selected) {
  981:            $output.=' selected="selected"';
  982:        }
  983:        $output.=">$tzone</option>\n";
  984:    }
  985:    $output.="</select>";
  986:    return $output;
  987: }
  988: 
  989: sub select_datelocale {
  990:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  991:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  992:     if ($includeempty) {
  993:         $output .= '<option value=""';
  994:         if ($selected eq '') {
  995:             $output .= ' selected="selected" ';
  996:         }
  997:         $output .= '> </option>';
  998:     }
  999:     my @languages = &Apache::lonlocal::preferred_languages();
 1000:     my (@possibles,%locale_names);
 1001:     my @locales = DateTime::Locale->ids();
 1002:     foreach my $id (@locales) {
 1003:         if ($id ne '') {
 1004:             my ($en_terr,$native_terr);
 1005:             my $loc = DateTime::Locale->load($id);
 1006:             if (ref($loc)) {
 1007:                 $en_terr = $loc->name();
 1008:                 $native_terr = $loc->native_name();
 1009:                 if (grep(/^en$/,@languages) || !@languages) {
 1010:                     if ($en_terr ne '') {
 1011:                         $locale_names{$id} = '('.$en_terr.')';
 1012:                     } elsif ($native_terr ne '') {
 1013:                         $locale_names{$id} = $native_terr;
 1014:                     }
 1015:                 } else {
 1016:                     if ($native_terr ne '') {
 1017:                         $locale_names{$id} = $native_terr.' ';
 1018:                     } elsif ($en_terr ne '') {
 1019:                         $locale_names{$id} = '('.$en_terr.')';
 1020:                     }
 1021:                 }
 1022:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
 1023:                 push(@possibles,$id);
 1024:             } 
 1025:         }
 1026:     }
 1027:     foreach my $item (sort(@possibles)) {
 1028:         $output.= '<option value="'.$item.'"';
 1029:         if ($item eq $selected) {
 1030:             $output.=' selected="selected"';
 1031:         }
 1032:         $output.=">$item";
 1033:         if ($locale_names{$item} ne '') {
 1034:             $output.='  '.$locale_names{$item};
 1035:         }
 1036:         $output.="</option>\n";
 1037:     }
 1038:     $output.="</select>";
 1039:     return $output;
 1040: }
 1041: 
 1042: sub select_language {
 1043:     my ($name,$selected,$includeempty,$noedit) = @_;
 1044:     my %langchoices;
 1045:     if ($includeempty) {
 1046:         %langchoices = ('' => 'No language preference');
 1047:     }
 1048:     foreach my $id (&languageids()) {
 1049:         my $code = &supportedlanguagecode($id);
 1050:         if ($code) {
 1051:             $langchoices{$code} = &plainlanguagedescription($id);
 1052:         }
 1053:     }
 1054:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
 1055:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
 1056: }
 1057: 
 1058: =pod
 1059: 
 1060: 
 1061: =item * &list_languages()
 1062: 
 1063: Returns an array reference that is suitable for use in language prompters.
 1064: Each array element is itself a two element array.  The first element
 1065: is the language code.  The second element a descsriptiuon of the 
 1066: language itself.  This is suitable for use in e.g.
 1067: &Apache::edit::select_arg (once dereferenced that is).
 1068: 
 1069: =cut 
 1070: 
 1071: sub list_languages {
 1072:     my @lang_choices;
 1073: 
 1074:     foreach my $id (&languageids()) {
 1075: 	my $code = &supportedlanguagecode($id);
 1076: 	if ($code) {
 1077: 	    my $selector    = $supported_codes{$id};
 1078: 	    my $description = &plainlanguagedescription($id);
 1079: 	    push(@lang_choices, [$selector, $description]);
 1080: 	}
 1081:     }
 1082:     return \@lang_choices;
 1083: }
 1084: 
 1085: =pod
 1086: 
 1087: =item * &linked_select_forms(...)
 1088: 
 1089: linked_select_forms returns a string containing a <script></script> block
 1090: and html for two <select> menus.  The select menus will be linked in that
 1091: changing the value of the first menu will result in new values being placed
 1092: in the second menu.  The values in the select menu will appear in alphabetical
 1093: order unless a defined order is provided.
 1094: 
 1095: linked_select_forms takes the following ordered inputs:
 1096: 
 1097: =over 4
 1098: 
 1099: =item * $formname, the name of the <form> tag
 1100: 
 1101: =item * $middletext, the text which appears between the <select> tags
 1102: 
 1103: =item * $firstdefault, the default value for the first menu
 1104: 
 1105: =item * $firstselectname, the name of the first <select> tag
 1106: 
 1107: =item * $secondselectname, the name of the second <select> tag
 1108: 
 1109: =item * $hashref, a reference to a hash containing the data for the menus.
 1110: 
 1111: =item * $menuorder, the order of values in the first menu
 1112: 
 1113: =item * $onchangefirst, additional javascript call to execute for an onchange
 1114:         event for the first <select> tag
 1115: 
 1116: =item * $onchangesecond, additional javascript call to execute for an onchange
 1117:         event for the second <select> tag
 1118: 
 1119: =item * $suffix, to differentiate separate uses of select2data javascript
 1120:         objects in a page.
 1121: 
 1122: =back 
 1123: 
 1124: Below is an example of such a hash.  Only the 'text', 'default', and 
 1125: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1126: values for the first select menu.  The text that coincides with the 
 1127: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1128: and text for the second menu are given in the hash pointed to by 
 1129: $menu{$choice1}->{'select2'}.  
 1130: 
 1131:  my %menu = ( A1 => { text =>"Choice A1" ,
 1132:                        default => "B3",
 1133:                        select2 => { 
 1134:                            B1 => "Choice B1",
 1135:                            B2 => "Choice B2",
 1136:                            B3 => "Choice B3",
 1137:                            B4 => "Choice B4"
 1138:                            },
 1139:                        order => ['B4','B3','B1','B2'],
 1140:                    },
 1141:                A2 => { text =>"Choice A2" ,
 1142:                        default => "C2",
 1143:                        select2 => { 
 1144:                            C1 => "Choice C1",
 1145:                            C2 => "Choice C2",
 1146:                            C3 => "Choice C3"
 1147:                            },
 1148:                        order => ['C2','C1','C3'],
 1149:                    },
 1150:                A3 => { text =>"Choice A3" ,
 1151:                        default => "D6",
 1152:                        select2 => { 
 1153:                            D1 => "Choice D1",
 1154:                            D2 => "Choice D2",
 1155:                            D3 => "Choice D3",
 1156:                            D4 => "Choice D4",
 1157:                            D5 => "Choice D5",
 1158:                            D6 => "Choice D6",
 1159:                            D7 => "Choice D7"
 1160:                            },
 1161:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1162:                    }
 1163:                );
 1164: 
 1165: =cut
 1166: 
 1167: sub linked_select_forms {
 1168:     my ($formname,
 1169:         $middletext,
 1170:         $firstdefault,
 1171:         $firstselectname,
 1172:         $secondselectname, 
 1173:         $hashref,
 1174:         $menuorder,
 1175:         $onchangefirst,
 1176:         $onchangesecond,
 1177:         $suffix
 1178:         ) = @_;
 1179:     my $second = "document.$formname.$secondselectname";
 1180:     my $first = "document.$formname.$firstselectname";
 1181:     # output the javascript to do the changing
 1182:     my $result = '';
 1183:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1184:     $result.="// <![CDATA[\n";
 1185:     $result.="var select2data${suffix} = new Object();\n";
 1186:     $" = '","';
 1187:     my $debug = '';
 1188:     foreach my $s1 (sort(keys(%$hashref))) {
 1189:         $result.="select2data${suffix}['d_$s1'] = new Object();\n";        
 1190:         $result.="select2data${suffix}['d_$s1'].def = new String('".
 1191:             $hashref->{$s1}->{'default'}."');\n";
 1192:         $result.="select2data${suffix}['d_$s1'].values = new Array(";
 1193:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1194:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1195:             @s2values = @{$hashref->{$s1}->{'order'}};
 1196:         }
 1197:         $result.="\"@s2values\");\n";
 1198:         $result.="select2data${suffix}['d_$s1'].texts = new Array(";        
 1199:         my @s2texts;
 1200:         foreach my $value (@s2values) {
 1201:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
 1202:         }
 1203:         $result.="\"@s2texts\");\n";
 1204:     }
 1205:     $"=' ';
 1206:     $result.= <<"END";
 1207: 
 1208: function select1${suffix}_changed() {
 1209:     // Determine new choice
 1210:     var newvalue = "d_" + $first.options[$first.selectedIndex].value;
 1211:     // update select2
 1212:     var values     = select2data${suffix}[newvalue].values;
 1213:     var texts      = select2data${suffix}[newvalue].texts;
 1214:     var select2def = select2data${suffix}[newvalue].def;
 1215:     var i;
 1216:     // out with the old
 1217:     $second.options.length = 0;
 1218:     // in with the new
 1219:     for (i=0;i<values.length; i++) {
 1220:         $second.options[i] = new Option(values[i]);
 1221:         $second.options[i].value = values[i];
 1222:         $second.options[i].text = texts[i];
 1223:         if (values[i] == select2def) {
 1224:             $second.options[i].selected = true;
 1225:         }
 1226:     }
 1227: }
 1228: // ]]>
 1229: </script>
 1230: END
 1231:     # output the initial values for the selection lists
 1232:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
 1233:     my @order = sort(keys(%{$hashref}));
 1234:     if (ref($menuorder) eq 'ARRAY') {
 1235:         @order = @{$menuorder};
 1236:     }
 1237:     foreach my $value (@order) {
 1238:         $result.="    <option value=\"$value\" ";
 1239:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1240:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1241:     }
 1242:     $result .= "</select>\n";
 1243:     my %select2;
 1244:     if (ref($hashref->{$firstdefault}) eq 'HASH') {
 1245:         if (ref($hashref->{$firstdefault}->{'select2'}) eq 'HASH') {
 1246:             %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1247:         }
 1248:     }
 1249:     $result .= $middletext;
 1250:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
 1251:     if ($onchangesecond) {
 1252:         $result .= ' onchange="'.$onchangesecond.'"';
 1253:     }
 1254:     $result .= ">\n";
 1255:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1256:     
 1257:     my @secondorder = sort(keys(%select2));
 1258:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1259:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1260:     }
 1261:     foreach my $value (@secondorder) {
 1262:         $result.="    <option value=\"$value\" ";        
 1263:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1264:         $result.=">".&mt($select2{$value})."</option>\n";
 1265:     }
 1266:     $result .= "</select>\n";
 1267:     #    return $debug;
 1268:     return $result;
 1269: }   #  end of sub linked_select_forms {
 1270: 
 1271: =pod
 1272: 
 1273: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid,$links_target)
 1274: 
 1275: Returns a string corresponding to an HTML link to the given help
 1276: $topic, where $topic corresponds to the name of a .tex file in
 1277: /home/httpd/html/adm/help/tex, with underscores replaced by
 1278: spaces. 
 1279: 
 1280: $text will optionally be linked to the same topic, allowing you to
 1281: link text in addition to the graphic. If you do not want to link
 1282: text, but wish to specify one of the later parameters, pass an
 1283: empty string. 
 1284: 
 1285: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1286: the link will not open a new window. If false, the link will open
 1287: a new window using Javascript. (Default is false.) 
 1288: 
 1289: $width and $height are optional numerical parameters that will
 1290: override the width and height of the popped up window, which may
 1291: be useful for certain help topics with big pictures included.
 1292: 
 1293: $imgid is the id of the img tag used for the help icon. This may be
 1294: used in a javascript call to switch the image src.  See 
 1295: lonhtmlcommon::htmlareaselectactive() for an example.
 1296: 
 1297: $links_target will optionally be set to a target (_top, _parent or _self).
 1298: 
 1299: =cut
 1300: 
 1301: sub help_open_topic {
 1302:     my ($topic, $text, $stayOnPage, $width, $height, $imgid, $links_target) = @_;
 1303:     $text = "" if (not defined $text);
 1304:     $stayOnPage = 0 if (not defined $stayOnPage);
 1305:     $width = 500 if (not defined $width);
 1306:     $height = 400 if (not defined $height);
 1307:     my $filename = $topic;
 1308:     $filename =~ s/ /_/g;
 1309: 
 1310:     my $template = "";
 1311:     my $link;
 1312:     
 1313:     $topic=~s/\W/\_/g;
 1314: 
 1315:     if (!$stayOnPage) {
 1316: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1317:     } elsif ($stayOnPage eq 'popup') {
 1318:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1319:     } else {
 1320: 	$link = "/adm/help/${filename}.hlp";
 1321:     }
 1322: 
 1323:     # Add the text
 1324:     my $target = ' target="_top"';
 1325:     if ($links_target) {
 1326:         $target = ' target="'.$links_target.'"';
 1327:     } elsif ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
 1328:              (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
 1329:         $target = '';
 1330:     }
 1331:     if ($text ne "") {
 1332: 	$template.='<span class="LC_help_open_topic">'
 1333:                   .'<a'.$target.' href="'.$link.'">'
 1334:                   .$text.'</a>';
 1335:     }
 1336: 
 1337:     # (Always) Add the graphic
 1338:     my $title = &mt('Online Help');
 1339:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1340:     if ($imgid ne '') {
 1341:         $imgid = ' id="'.$imgid.'"';
 1342:     }
 1343:     $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
 1344:               .'<img src="'.$helpicon.'" border="0"'
 1345:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1346:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1347:               .' /></a>';
 1348:     if ($text ne "") {	
 1349:         $template.='</span>';
 1350:     }
 1351:     return $template;
 1352: 
 1353: }
 1354: 
 1355: # This is a quicky function for Latex cheatsheet editing, since it 
 1356: # appears in at least four places
 1357: sub helpLatexCheatsheet {
 1358:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1359:     my $out;
 1360:     my $addOther = '';
 1361:     if ($topic) {
 1362: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1363:     }
 1364:     $out = '<span>' # Start cheatsheet
 1365: 	  .$addOther
 1366:           .'<span>'
 1367: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1368: 	  .'</span> <span>'
 1369: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1370: 	  .'</span>';
 1371:     unless ($not_author) {
 1372:         $out .= '<span>'
 1373:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1374:                .'</span> <span>'
 1375:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
 1376: 	       .'</span>';
 1377:     }
 1378:     $out .= '</span>'; # End cheatsheet
 1379:     return $out;
 1380: }
 1381: 
 1382: sub general_help {
 1383:     my $helptopic='Student_Intro';
 1384:     if ($env{'request.role'}=~/^(ca|au)/) {
 1385: 	$helptopic='Authoring_Intro';
 1386:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1387: 	$helptopic='Course_Coordination_Intro';
 1388:     } elsif ($env{'request.role'}=~/^dc/) {
 1389:         $helptopic='Domain_Coordination_Intro';
 1390:     }
 1391:     return $helptopic;
 1392: }
 1393: 
 1394: sub update_help_link {
 1395:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1396:     my $origurl = $ENV{'REQUEST_URI'};
 1397:     $origurl=~s|^/~|/priv/|;
 1398:     my $timestamp = time;
 1399:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1400:         $$datum = &escape($$datum);
 1401:     }
 1402: 
 1403:     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";
 1404:     my $output .= <<"ENDOUTPUT";
 1405: <script type="text/javascript">
 1406: // <![CDATA[
 1407: banner_link = '$banner_link';
 1408: // ]]>
 1409: </script>
 1410: ENDOUTPUT
 1411:     return $output;
 1412: }
 1413: 
 1414: # now just updates the help link and generates a blue icon
 1415: sub help_open_menu {
 1416:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text,$links_target) 
 1417: 	= @_;    
 1418:     $stayOnPage = 1;
 1419:     my $output;
 1420:     if ($component_help) {
 1421: 	if (!$text) {
 1422: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1423: 				       $width,$height,'',$links_target);
 1424: 	} else {
 1425: 	    my $help_text;
 1426: 	    $help_text=&unescape($topic);
 1427: 	    $output='<table><tr><td>'.
 1428: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1429: 				 $width,$height,'',$links_target).'</td></tr></table>';
 1430: 	}
 1431:     }
 1432:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1433:     return $output.$banner_link;
 1434: }
 1435: 
 1436: sub top_nav_help {
 1437:     my ($text,$linkattr) = @_;
 1438:     $text = &mt($text);
 1439:     my $stay_on_page = 1;
 1440: 
 1441:     my ($link,$banner_link);
 1442:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
 1443:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1444: 	                         : "javascript:helpMenu('open')";
 1445:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1446:     }
 1447:     my $title = &mt('Get help');
 1448:     if ($link) {
 1449:         return <<"END";
 1450: $banner_link
 1451: <a href="$link" title="$title" $linkattr>$text</a>
 1452: END
 1453:     } else {
 1454:         return '&nbsp;'.$text.'&nbsp;';
 1455:     }
 1456: }
 1457: 
 1458: sub help_menu_js {
 1459:     my ($httphost) = @_;
 1460:     my $stayOnPage = 1;
 1461:     my $width = 620;
 1462:     my $height = 600;
 1463:     my $helptopic=&general_help();
 1464:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
 1465:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1466:     my $start_page =
 1467:         &Apache::loncommon::start_page('Help Menu', undef,
 1468: 				       {'frameset'    => 1,
 1469: 					'js_ready'    => 1,
 1470:                                         'use_absolute' => $httphost,
 1471: 					'add_entries' => {
 1472: 					    'border' => '0', 
 1473: 					    'rows'   => "110,*",},});
 1474:     my $end_page =
 1475:         &Apache::loncommon::end_page({'frameset' => 1,
 1476: 				      'js_ready' => 1,});
 1477: 
 1478:     my $template .= <<"ENDTEMPLATE";
 1479: <script type="text/javascript">
 1480: // <![CDATA[
 1481: // <!-- BEGIN LON-CAPA Internal
 1482: var banner_link = '';
 1483: function helpMenu(target) {
 1484:     var caller = this;
 1485:     if (target == 'open') {
 1486:         var newWindow = null;
 1487:         try {
 1488:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1489:         }
 1490:         catch(error) {
 1491:             writeHelp(caller);
 1492:             return;
 1493:         }
 1494:         if (newWindow) {
 1495:             caller = newWindow;
 1496:         }
 1497:     }
 1498:     writeHelp(caller);
 1499:     return;
 1500: }
 1501: function writeHelp(caller) {
 1502:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
 1503:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
 1504:     caller.document.close();
 1505:     caller.focus();
 1506: }
 1507: // END LON-CAPA Internal -->
 1508: // ]]>
 1509: </script>
 1510: ENDTEMPLATE
 1511:     return $template;
 1512: }
 1513: 
 1514: sub help_open_bug {
 1515:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1516:     unless ($env{'user.adv'}) { return ''; }
 1517:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1518:     $text = "" if (not defined $text);
 1519: 	$stayOnPage=1;
 1520:     $width = 600 if (not defined $width);
 1521:     $height = 600 if (not defined $height);
 1522: 
 1523:     $topic=~s/\W+/\+/g;
 1524:     my $link='';
 1525:     my $template='';
 1526:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1527: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1528:     if (!$stayOnPage)
 1529:     {
 1530: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1531:     }
 1532:     else
 1533:     {
 1534: 	$link = $url;
 1535:     }
 1536: 
 1537:     my $target = '_top';
 1538:     if ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
 1539:         (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
 1540:         $target = '_blank';
 1541:     }
 1542: 
 1543:     # Add the text
 1544:     if ($text ne "")
 1545:     {
 1546: 	$template .= 
 1547:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1548:   "<td bgcolor='#FF5555'><a target=\"$target\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1549:     }
 1550: 
 1551:     # Add the graphic
 1552:     my $title = &mt('Report a Bug');
 1553:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1554:     $template .= <<"ENDTEMPLATE";
 1555:  <a target="$target" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1556: ENDTEMPLATE
 1557:     if ($text ne '') { $template.='</td></tr></table>' };
 1558:     return $template;
 1559: 
 1560: }
 1561: 
 1562: sub help_open_faq {
 1563:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1564:     unless ($env{'user.adv'}) { return ''; }
 1565:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1566:     $text = "" if (not defined $text);
 1567: 	$stayOnPage=1;
 1568:     $width = 350 if (not defined $width);
 1569:     $height = 400 if (not defined $height);
 1570: 
 1571:     $topic=~s/\W+/\+/g;
 1572:     my $link='';
 1573:     my $template='';
 1574:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1575:     if (!$stayOnPage)
 1576:     {
 1577: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1578:     }
 1579:     else
 1580:     {
 1581: 	$link = $url;
 1582:     }
 1583: 
 1584:     # Add the text
 1585:     if ($text ne "")
 1586:     {
 1587: 	$template .= 
 1588:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1589:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1590:     }
 1591: 
 1592:     # Add the graphic
 1593:     my $title = &mt('View the FAQ');
 1594:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1595:     $template .= <<"ENDTEMPLATE";
 1596:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1597: ENDTEMPLATE
 1598:     if ($text ne '') { $template.='</td></tr></table>' };
 1599:     return $template;
 1600: 
 1601: }
 1602: 
 1603: ###############################################################
 1604: ###############################################################
 1605: 
 1606: =pod
 1607: 
 1608: =item * &change_content_javascript():
 1609: 
 1610: This and the next function allow you to create small sections of an
 1611: otherwise static HTML page that you can update on the fly with
 1612: Javascript, even in Netscape 4.
 1613: 
 1614: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1615: must be written to the HTML page once. It will prove the Javascript
 1616: function "change(name, content)". Calling the change function with the
 1617: name of the section 
 1618: you want to update, matching the name passed to C<changable_area>, and
 1619: the new content you want to put in there, will put the content into
 1620: that area.
 1621: 
 1622: B<Note>: Netscape 4 only reserves enough space for the changable area
 1623: to contain room for the original contents. You need to "make space"
 1624: for whatever changes you wish to make, and be B<sure> to check your
 1625: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1626: it's adequate for updating a one-line status display, but little more.
 1627: This script will set the space to 100% width, so you only need to
 1628: worry about height in Netscape 4.
 1629: 
 1630: Modern browsers are much less limiting, and if you can commit to the
 1631: user not using Netscape 4, this feature may be used freely with
 1632: pretty much any HTML.
 1633: 
 1634: =cut
 1635: 
 1636: sub change_content_javascript {
 1637:     # If we're on Netscape 4, we need to use Layer-based code
 1638:     if ($env{'browser.type'} eq 'netscape' &&
 1639: 	$env{'browser.version'} =~ /^4\./) {
 1640: 	return (<<NETSCAPE4);
 1641: 	function change(name, content) {
 1642: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1643: 	    doc.open();
 1644: 	    doc.write(content);
 1645: 	    doc.close();
 1646: 	}
 1647: NETSCAPE4
 1648:     } else {
 1649: 	# Otherwise, we need to use semi-standards-compliant code
 1650: 	# (technically, "innerHTML" isn't standard but the equivalent
 1651: 	# is really scary, and every useful browser supports it
 1652: 	return (<<DOMBASED);
 1653: 	function change(name, content) {
 1654: 	    element = document.getElementById(name);
 1655: 	    element.innerHTML = content;
 1656: 	}
 1657: DOMBASED
 1658:     }
 1659: }
 1660: 
 1661: =pod
 1662: 
 1663: =item * &changable_area($name,$origContent):
 1664: 
 1665: This provides a "changable area" that can be modified on the fly via
 1666: the Javascript code provided in C<change_content_javascript>. $name is
 1667: the name you will use to reference the area later; do not repeat the
 1668: same name on a given HTML page more then once. $origContent is what
 1669: the area will originally contain, which can be left blank.
 1670: 
 1671: =cut
 1672: 
 1673: sub changable_area {
 1674:     my ($name, $origContent) = @_;
 1675: 
 1676:     if ($env{'browser.type'} eq 'netscape' &&
 1677: 	$env{'browser.version'} =~ /^4\./) {
 1678: 	# If this is netscape 4, we need to use the Layer tag
 1679: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1680:     } else {
 1681: 	return "<span id='$name'>$origContent</span>";
 1682:     }
 1683: }
 1684: 
 1685: =pod
 1686: 
 1687: =item * &viewport_geometry_js 
 1688: 
 1689: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1690: 
 1691: =cut
 1692: 
 1693: 
 1694: sub viewport_geometry_js { 
 1695:     return <<"GEOMETRY";
 1696: var Geometry = {};
 1697: function init_geometry() {
 1698:     if (Geometry.init) { return };
 1699:     Geometry.init=1;
 1700:     if (window.innerHeight) {
 1701:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1702:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1703:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1704:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1705:     }
 1706:     else if (document.documentElement && document.documentElement.clientHeight) {
 1707:         Geometry.getViewportHeight =
 1708:             function() { return document.documentElement.clientHeight; };
 1709:         Geometry.getViewportWidth =
 1710:             function() { return document.documentElement.clientWidth; };
 1711: 
 1712:         Geometry.getHorizontalScroll =
 1713:             function() { return document.documentElement.scrollLeft; };
 1714:         Geometry.getVerticalScroll =
 1715:             function() { return document.documentElement.scrollTop; };
 1716:     }
 1717:     else if (document.body.clientHeight) {
 1718:         Geometry.getViewportHeight =
 1719:             function() { return document.body.clientHeight; };
 1720:         Geometry.getViewportWidth =
 1721:             function() { return document.body.clientWidth; };
 1722:         Geometry.getHorizontalScroll =
 1723:             function() { return document.body.scrollLeft; };
 1724:         Geometry.getVerticalScroll =
 1725:             function() { return document.body.scrollTop; };
 1726:     }
 1727: }
 1728: 
 1729: GEOMETRY
 1730: }
 1731: 
 1732: =pod
 1733: 
 1734: =item * &viewport_size_js()
 1735: 
 1736: 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. 
 1737: 
 1738: =cut
 1739: 
 1740: sub viewport_size_js {
 1741:     my $geometry = &viewport_geometry_js();
 1742:     return <<"DIMS";
 1743: 
 1744: $geometry
 1745: 
 1746: function getViewportDims(width,height) {
 1747:     init_geometry();
 1748:     width.value = Geometry.getViewportWidth();
 1749:     height.value = Geometry.getViewportHeight();
 1750:     return;
 1751: }
 1752: 
 1753: DIMS
 1754: }
 1755: 
 1756: =pod
 1757: 
 1758: =item * &resize_textarea_js()
 1759: 
 1760: emits the needed javascript to resize a textarea to be as big as possible
 1761: 
 1762: creates a function resize_textrea that takes two IDs first should be
 1763: the id of the element to resize, second should be the id of a div that
 1764: surrounds everything that comes after the textarea, this routine needs
 1765: to be attached to the <body> for the onload and onresize events.
 1766: 
 1767: =back
 1768: 
 1769: =cut
 1770: 
 1771: sub resize_textarea_js {
 1772:     my $geometry = &viewport_geometry_js();
 1773:     return <<"RESIZE";
 1774:     <script type="text/javascript">
 1775: // <![CDATA[
 1776: $geometry
 1777: 
 1778: function getX(element) {
 1779:     var x = 0;
 1780:     while (element) {
 1781: 	x += element.offsetLeft;
 1782: 	element = element.offsetParent;
 1783:     }
 1784:     return x;
 1785: }
 1786: function getY(element) {
 1787:     var y = 0;
 1788:     while (element) {
 1789: 	y += element.offsetTop;
 1790: 	element = element.offsetParent;
 1791:     }
 1792:     return y;
 1793: }
 1794: 
 1795: 
 1796: function resize_textarea(textarea_id,bottom_id) {
 1797:     init_geometry();
 1798:     var textarea        = document.getElementById(textarea_id);
 1799:     //alert(textarea);
 1800: 
 1801:     var textarea_top    = getY(textarea);
 1802:     var textarea_height = textarea.offsetHeight;
 1803:     var bottom          = document.getElementById(bottom_id);
 1804:     var bottom_top      = getY(bottom);
 1805:     var bottom_height   = bottom.offsetHeight;
 1806:     var window_height   = Geometry.getViewportHeight();
 1807:     var fudge           = 23;
 1808:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1809:     if (new_height < 300) {
 1810: 	new_height = 300;
 1811:     }
 1812:     textarea.style.height=new_height+'px';
 1813: }
 1814: // ]]>
 1815: </script>
 1816: RESIZE
 1817: 
 1818: }
 1819: 
 1820: sub colorfuleditor_js {
 1821:     my $browse_or_search;
 1822:     my $respath;
 1823:     my ($cnum,$cdom) = &crsauthor_url();
 1824:     if ($cnum) {
 1825:         $respath = "/res/$cdom/$cnum/";
 1826:         my %js_lt = &Apache::lonlocal::texthash(
 1827:             sunm => 'Sub-directory name',
 1828:             save => 'Save page to make this permanent',
 1829:         );
 1830:         &js_escape(\%js_lt);
 1831:         my $showfile_js = &show_crsfiles_js();
 1832:         $browse_or_search = <<"END";
 1833: 
 1834:     $showfile_js
 1835: 
 1836:     function toggleChooser(form,element,titleid,only,search) {
 1837:         var disp = 'none';
 1838:         if (document.getElementById('chooser_'+element)) {
 1839:             var curr = document.getElementById('chooser_'+element).style.display;
 1840:             if (curr == 'none') {
 1841:                 disp='inline';
 1842:                 if (form.elements['chooser_'+element].length) {
 1843:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
 1844:                         form.elements['chooser_'+element][i].checked = false;
 1845:                     }
 1846:                 }
 1847:                 toggleResImport(form,element);
 1848:             }
 1849:             document.getElementById('chooser_'+element).style.display = disp;
 1850:             var dirsel = '';
 1851:             var filesel = '';
 1852:             if (document.getElementById('chooser_'+element+'_crsres')) {
 1853:                 var currcrsres = document.getElementById('chooser_'+element+'_crsres').style.display;
 1854:                 if (currcrsres == 'none') {
 1855:                     dirsel = 'coursepath_'+element;
 1856:                     var filesel = 'coursefile_'+element;
 1857:                     var include;
 1858:                     if (document.getElementById('crsres_include_'+element)) {
 1859:                         include = document.getElementById('crsres_include_'+element).value;
 1860:                     }
 1861:                     populateCrsSelects(form,dirsel,filesel,1,include,1,0,1,1,0);
 1862:                 }
 1863:             }
 1864:             if (document.getElementById('chooser_'+element+'_upload')) {
 1865:                 var currcrsupload = document.getElementById('chooser_'+element+'_upload').style.display;
 1866:                 if (currcrsupload == 'none') {
 1867:                     dirsel = 'crsauthorpath_'+element;
 1868:                     filesel = '';
 1869:                     populateCrsSelects(form,dirsel,filesel,0,'',1,0,1,0,1);
 1870:                 }
 1871:             }
 1872:         }
 1873:     }
 1874: 
 1875:     function toggleCrsFile(form,element) {
 1876:         if (document.getElementById('chooser_'+element+'_crsres')) {
 1877:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
 1878:             if (curr == 'none') {
 1879:                 if (document.getElementById('coursepath_'+element)) {
 1880:                     var numdirs;
 1881:                     if (document.getElementById('coursepath_'+element).length) {
 1882:                         numdirs = document.getElementById('coursepath_'+element).length;
 1883:                     }
 1884:                     if ((document.getElementById('hascrsres_'+element)) &&
 1885:                         (document.getElementById('nocrsres_'+element))) {
 1886:                         if (numdirs) {
 1887:                             document.getElementById('hascrsres_'+element).style.display='inline-block';
 1888:                             document.getElementById('nocrsres_'+element).style.display='none';
 1889:                         } else {
 1890:                             document.getElementById('hascrsres_'+element).style.display='none';
 1891:                             document.getElementById('nocrsres_'+element).style.display='inline-block';
 1892:                         }
 1893:                     }
 1894:                     form.elements['coursepath_'+element].selectedIndex = 0;
 1895:                     if (numdirs > 1) {
 1896:                         var selelem = form.elements['coursefile_'+element];
 1897:                         var i, len = selelem.options.length -1;
 1898:                         if (len >=0) {
 1899:                             for (i = len; i >= 0; i--) {
 1900:                                 selelem.remove(i);
 1901:                             }
 1902:                             selelem.options[0] = new Option('','');
 1903:                         }
 1904:                     }
 1905:                 }
 1906:             }
 1907:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
 1908:         }
 1909:         if (document.getElementById('chooser_'+element+'_upload')) {
 1910:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
 1911:             if (document.getElementById('uploadcrsres_'+element)) {
 1912:                 document.getElementById('uploadcrsres_'+element).value = '';
 1913:             }
 1914:         }
 1915:         return;
 1916:     }
 1917: 
 1918:     function toggleCrsUpload(form,element) {
 1919:         if (document.getElementById('chooser_'+element+'_crsres')) {
 1920:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
 1921:         }
 1922:         if (document.getElementById('chooser_'+element+'_upload')) {
 1923:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
 1924:             if (curr == 'none') {
 1925:                 form.elements['newsubdir_'+element][0].checked = true;
 1926:                 toggleNewsubdir(form,element);
 1927:                 document.getElementById('chooser_'+element+'_upload').style.display = 'block';
 1928:                 if (document.getElementById('uploadcrsres_'+element)) {
 1929:                     document.getElementById('uploadcrsres_'+element).value = '';
 1930:                 }
 1931:             }
 1932:         }
 1933:         return;
 1934:     }
 1935: 
 1936:     function toggleResImport(form,element) {
 1937:         var choices = new Array('crsres','upload');
 1938:         for (var i=0; i<choices.length; i++) {
 1939:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
 1940:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
 1941:             }
 1942:         }
 1943:     }
 1944: 
 1945:     function toggleNewsubdir(form,element) {
 1946:         var newsub = form.elements['newsubdir_'+element];
 1947:         if (newsub) {
 1948:             if (newsub.length) {
 1949:                 for (var j=0; j<newsub.length; j++) {
 1950:                     if (newsub[j].checked) {
 1951:                         if (document.getElementById('newsubdirname_'+element)) {
 1952:                             if (newsub[j].value == '1') {
 1953:                                 document.getElementById('newsubdirname_'+element).type = "text";
 1954:                                 if (document.getElementById('newsubdir_'+element)) {
 1955:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
 1956:                                 }
 1957:                             } else {
 1958:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
 1959:                                 document.getElementById('newsubdirname_'+element).value = "";
 1960:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
 1961:                             }
 1962:                         }
 1963:                         break; 
 1964:                     }
 1965:                 }
 1966:             }
 1967:         }
 1968:     }
 1969: 
 1970:     function updateCrsFile(form,element) {
 1971:         var directory = form.elements['coursepath_'+element];
 1972:         var filename = form.elements['coursefile_'+element];
 1973:         var path = directory.options[directory.selectedIndex].value;
 1974:         var file = filename.options[filename.selectedIndex].value;
 1975:         if (file != '') {
 1976:             form.elements[element].value = '$respath';
 1977:             if (path == '/') {
 1978:                 form.elements[element].value += file;
 1979:             } else {
 1980:                 form.elements[element].value += path+'/'+file;
 1981:             }
 1982:             unClean();
 1983:             if (document.getElementById('previewimg_'+element)) {
 1984:                 document.getElementById('previewimg_'+element).src = form.elements[element].value;
 1985:                 var newsrc = document.getElementById('previewimg_'+element).src; 
 1986:             }
 1987:             if (document.getElementById('showimg_'+element)) {
 1988:                 document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
 1989:             }
 1990:         }
 1991:         toggleChooser(form,element);
 1992:         return;
 1993:     }
 1994: 
 1995:     function uploadDone(suffix,name) {
 1996:         if (name) {
 1997: 	    document.forms["lonhomework"].elements[suffix].value = name;
 1998:             unClean();
 1999:             toggleChooser(document.forms["lonhomework"],suffix);
 2000:         }
 2001:     }
 2002: 
 2003: \$(document).ready(function(){
 2004: 
 2005:     \$(document).delegate('form :submit', 'click', function( event ) {
 2006:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
 2007:             var buttonId = this.id;
 2008:             var suffix = buttonId.toString();
 2009:             suffix = suffix.replace(/^crsupload_/,'');
 2010:             event.preventDefault();
 2011:             document.lonhomework.target = 'crsupload_target_'+suffix;
 2012:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
 2013:             \$(this.form).submit();
 2014:             document.lonhomework.target = '';
 2015:             if (document.getElementById('crsuploadto_'+suffix)) {
 2016:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
 2017:             }
 2018:             return false;
 2019:         }
 2020:     });
 2021: });
 2022: END
 2023:     }
 2024:     return <<"COLORFULEDIT"
 2025: <script type="text/javascript">
 2026: // <![CDATA[>
 2027:     function fold_box(curDepth, lastresource){
 2028: 
 2029:     // we need a list because there can be several blocks you need to fold in one tag
 2030:         var block = document.getElementsByName('foldblock_'+curDepth);
 2031:     // but there is only one folding button per tag
 2032:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
 2033: 
 2034:         if(block.item(0).style.display == 'none'){
 2035: 
 2036:             foldbutton.value = '@{[&mt("Hide")]}';
 2037:             for (i = 0; i < block.length; i++){
 2038:                 block.item(i).style.display = '';
 2039:             }
 2040:         }else{
 2041: 
 2042:             foldbutton.value = '@{[&mt("Show")]}';
 2043:             for (i = 0; i < block.length; i++){
 2044:                 // block.item(i).style.visibility = 'collapse';
 2045:                 block.item(i).style.display = 'none';
 2046:             }
 2047:         };
 2048:         saveState(lastresource);
 2049:     }
 2050: 
 2051:     function saveState (lastresource) {
 2052: 
 2053:         var tag_list = getTagList();
 2054:         if(tag_list != null){
 2055:             var timestamp = new Date().getTime();
 2056:             var key = lastresource;
 2057: 
 2058:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
 2059:             // starting with timestamp
 2060:             var value = timestamp+';';
 2061: 
 2062:             // building the list of key-value pairs
 2063:             for(var i = 0; i < tag_list.length; i++){
 2064:                 value += tag_list[i]+',';
 2065:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
 2066:             }
 2067: 
 2068:             // only iterate whole storage if nothing to override
 2069:             if(localStorage.getItem(key) == null){        
 2070: 
 2071:                 // prevent storage from growing large
 2072:                 if(localStorage.length > 50){
 2073:                     var regex_getTimestamp = /^(?:\d)+;/;
 2074:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
 2075:                     var oldest_key;
 2076:                     
 2077:                     for(var i = 1; i < localStorage.length; i++){
 2078:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
 2079:                             oldest_key = localStorage.key(i);
 2080:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
 2081:                         }
 2082:                     }
 2083:                     localStorage.removeItem(oldest_key);
 2084:                 }
 2085:             }
 2086:             localStorage.setItem(key,value);
 2087:         }
 2088:     }
 2089: 
 2090:     // restore folding status of blocks (on page load)
 2091:     function restoreState (lastresource) {
 2092:         if(localStorage.getItem(lastresource) != null){
 2093:             var key = lastresource;
 2094:             var value = localStorage.getItem(key);
 2095:             var regex_delTimestamp = /^\d+;/;
 2096: 
 2097:             value.replace(regex_delTimestamp, '');
 2098: 
 2099:             var valueArr = value.split(';');
 2100:             var pairs;
 2101:             var elements;
 2102:             for (var i = 0; i < valueArr.length; i++){
 2103:                 pairs = valueArr[i].split(',');
 2104:                 elements = document.getElementsByName(pairs[0]);
 2105: 
 2106:                 for (var j = 0; j < elements.length; j++){  
 2107:                     elements[j].style.display = pairs[1];
 2108:                     if (pairs[1] == "none"){
 2109:                         var regex_id = /([_\\d]+)\$/;
 2110:                         regex_id.exec(pairs[0]);
 2111:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
 2112:                     }
 2113:                 }
 2114:             }
 2115:         }
 2116:     }
 2117: 
 2118:     function getTagList () {
 2119:         
 2120:         var stringToSearch = document.lonhomework.innerHTML;
 2121: 
 2122:         var ret = new Array();
 2123:         var regex_findBlock = /(foldblock_.*?)"/g;
 2124:         var tag_list = stringToSearch.match(regex_findBlock);
 2125: 
 2126:         if(tag_list != null){
 2127:             for(var i = 0; i < tag_list.length; i++){            
 2128:                 ret.push(tag_list[i].replace(/"/, ''));
 2129:             }
 2130:         }
 2131:         return ret;
 2132:     }
 2133: 
 2134:     function saveScrollPosition (resource) {
 2135:         var tag_list = getTagList();
 2136: 
 2137:         // we dont always want to jump to the first block
 2138:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
 2139:         if(\$(window).scrollTop() > 170){
 2140:             if(tag_list != null){
 2141:                 var result;
 2142:                 for(var i = 0; i < tag_list.length; i++){
 2143:                     if(isElementInViewport(tag_list[i])){
 2144:                         result += tag_list[i]+';';
 2145:                     }
 2146:                 }
 2147:                 sessionStorage.setItem('anchor_'+resource, result);
 2148:             }
 2149:         } else {
 2150:             // we dont need to save zero, just delete the item to leave everything tidy
 2151:             sessionStorage.removeItem('anchor_'+resource);
 2152:         }
 2153:     }
 2154: 
 2155:     function restoreScrollPosition(resource){
 2156: 
 2157:         var elem = sessionStorage.getItem('anchor_'+resource);
 2158:         if(elem != null){
 2159:             var tag_list = elem.split(';');
 2160:             var elem_list;
 2161: 
 2162:             for(var i = 0; i < tag_list.length; i++){
 2163:                 elem_list = document.getElementsByName(tag_list[i]);
 2164:                 
 2165:                 if(elem_list.length > 0){
 2166:                     elem = elem_list[0];
 2167:                     break;
 2168:                 }
 2169:             }
 2170:             elem.scrollIntoView();
 2171:         }
 2172:     }
 2173: 
 2174:     function isElementInViewport(el) {
 2175: 
 2176:         // change to last element instead of first
 2177:         var elem = document.getElementsByName(el);
 2178:         var rect = elem[0].getBoundingClientRect();
 2179: 
 2180:         return (
 2181:             rect.top >= 0 &&
 2182:             rect.left >= 0 &&
 2183:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
 2184:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
 2185:         );
 2186:     }
 2187:     
 2188:     function autosize(depth){
 2189:         var cmInst = window['cm'+depth];
 2190:         var fitsizeButton = document.getElementById('fitsize'+depth);
 2191: 
 2192:         // is fixed size, switching to dynamic
 2193:         if (sessionStorage.getItem("autosized_"+depth) == null) {
 2194:             cmInst.setSize("","auto");
 2195:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
 2196:             sessionStorage.setItem("autosized_"+depth, "yes");
 2197: 
 2198:         // is dynamic size, switching to fixed
 2199:         } else {
 2200:             cmInst.setSize("","300px");
 2201:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
 2202:             sessionStorage.removeItem("autosized_"+depth);
 2203:         }
 2204:     }
 2205: 
 2206: $browse_or_search
 2207: 
 2208: // ]]>
 2209: </script>
 2210: COLORFULEDIT
 2211: }
 2212: 
 2213: sub xmleditor_js {
 2214:     return <<XMLEDIT
 2215: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
 2216: <script type="text/javascript">
 2217: // <![CDATA[>
 2218: 
 2219:     function saveScrollPosition (resource) {
 2220: 
 2221:         var scrollPos = \$(window).scrollTop();
 2222:         sessionStorage.setItem(resource,scrollPos);
 2223:     }
 2224: 
 2225:     function restoreScrollPosition(resource){
 2226: 
 2227:         var scrollPos = sessionStorage.getItem(resource);
 2228:         \$(window).scrollTop(scrollPos);
 2229:     }
 2230: 
 2231:     // unless internet explorer
 2232:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
 2233: 
 2234:         \$(document).ready(function() {
 2235:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
 2236:         });
 2237:     }
 2238: 
 2239:     // inserts text at cursor position into codemirror (xml editor only)
 2240:     function insertText(text){
 2241:         cm.focus();
 2242:         var curPos = cm.getCursor();
 2243:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
 2244:     }
 2245: // ]]>
 2246: </script>
 2247: XMLEDIT
 2248: }
 2249: 
 2250: sub insert_folding_button {
 2251:     my $curDepth = $Apache::lonxml::curdepth;
 2252:     my $lastresource = $env{'request.ambiguous'};
 2253: 
 2254:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
 2255:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
 2256: }
 2257: 
 2258: sub crsauthor_url {
 2259:     my ($url) = @_;
 2260:     if ($url eq '') {
 2261:         $url = $ENV{'REQUEST_URI'};
 2262:     }
 2263:     my ($cnum,$cdom);
 2264:     if ($env{'request.course.id'}) {
 2265:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
 2266:         if ($audom ne '' && $auname ne '') {
 2267:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
 2268:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
 2269:                 $cnum = $auname;
 2270:                 $cdom = $audom;
 2271:             }
 2272:         }
 2273:     }
 2274:     return ($cnum,$cdom);
 2275: }
 2276: 
 2277: sub import_crsauthor_form {
 2278:     my ($firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
 2279:     return (0) unless ($env{'request.course.id'});
 2280:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2281:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2282:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
 2283:     return (0) unless (($cnum ne '') && ($cdom ne ''));
 2284:     my @ids=&Apache::lonnet::current_machine_ids();
 2285:     my ($output,$is_home,$toppath,%subdirs,%files,%selimport_menus,$include,$exclude);
 2286: 
 2287:     if (grep(/^\Q$crshome\E$/,@ids)) {
 2288:         $is_home = 1;
 2289:     }
 2290:     $toppath = "/priv/$cdom/$cnum";
 2291:     my $nonemptydir = 1;
 2292:     my $js_only;
 2293:     if ($only) {
 2294:         map { $include->{$_} = 1; } split(/\s*,\s*/,$only);
 2295:         $js_only = join(',',map { &js_escape($_); } sort(keys(%{$include})));
 2296:     }
 2297:     $exclude = &Apache::lonnet::priv_exclude();
 2298:     &Apache::lonnet::recursedirs($is_home,1,$include,$exclude,1,0,$toppath,'',\%subdirs,\%files);
 2299:     my $numdirs = scalar(keys(%files));
 2300:     my %lt = &Apache::lonlocal::texthash (
 2301:         fnam => 'Filename',
 2302:         dire => 'Directory',
 2303:         se   => 'Select',
 2304:     );
 2305:     $output = $lt{'dire'}.':&nbsp;'.
 2306:               '<select id="'.$firstselectname.'" name="'.$firstselectname.'" '.
 2307:               'onchange="populateCrsSelects(this.form,'."'$firstselectname','$secondselectname',1,'$js_only',0,1,0,0,0".');">'.
 2308:               '<option value="" selected="selected">'.$lt{'se'}.'</option>';
 2309:     if ($files{'/'}) {
 2310:         $output .= '<option value="/">/</option>'."\n";
 2311:     }
 2312:     foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
 2313:         next if ($key eq '/');
 2314:         $output .= '<option value="'.$key.'">'.$key.'</option>'."\n";
 2315:     }
 2316:     $output .= '</select><br />'."\n".
 2317:                $lt{'fnam'}.':&nbsp;<select id="'.$secondselectname.'" name="'.$secondselectname.'">'."\n".
 2318:                '<option value="" selected="selected"></option>'."\n".
 2319:                '</select>'."\n".
 2320:                '<input type="hidden" id="crsres_include_'.$suffix.'" value="'.$only.'" />';
 2321:     return ($numdirs,$output);
 2322: }
 2323: 
 2324: sub show_crsfiles_js {
 2325:     my $excluderef = &Apache::lonnet::priv_exclude();
 2326:     my $se = &js_escape(&mt('Select'));
 2327:     my $exclude;
 2328:     if (ref($excluderef) eq 'HASH') {
 2329:         $exclude = join(',', map { &js_escape($_); } sort(keys(%{$excluderef})));
 2330:     }
 2331:     my $js = <<"END";
 2332: 
 2333: 
 2334:     function populateCrsSelects (form,dirsel,filesel,exc,include,setdir,setfile,recurse,nonemptydir,addtopdir) {
 2335:         var relpath = '';
 2336:         if ((setfile) && (dirsel != null) && (dirsel != 'undefined') && (dirsel != '')) {
 2337:             var currdir = form.elements[dirsel].options[form.elements[dirsel].selectedIndex].value;
 2338:             if (currdir == '') {
 2339:                 if ((filesel != null) && (filesel != 'undefined') && (filesel != '')) {
 2340:                     selelem = form.elements[filesel];
 2341:                     var j, numfiles = selelem.options.length -1;
 2342:                     if (numfiles >=0) {
 2343:                         for (j = numfiles; j >= 0; j--) {
 2344:                             selelem.remove(j);
 2345:                         }
 2346:                     }
 2347:                     if (selelem.options.length == 0) {
 2348:                         selelem.options[selelem.options.length] = new Option('','');
 2349:                         selelem.selectedIndex = 0;
 2350:                     }
 2351:                 }
 2352:                 return;
 2353:             } else {
 2354:                 relpath = encodeURIComponent(form.elements[dirsel].options[form.elements[dirsel].selectedIndex].value);
 2355:             }
 2356:         }
 2357:         var http = new XMLHttpRequest();
 2358:         var url = "/adm/courseauthor";
 2359:         var crsrole = "$env{'request.role'}";
 2360:         var exclude = '';
 2361:         if (exc) {
 2362:             exclude = '$exclude';
 2363:         }
 2364:         var params = "role=course&files=1&rec="+recurse+"&nonempty="+nonemptydir+"&exc="+exclude+"&inc="+include+"&addtop="+addtopdir+"&path="+relpath;
 2365:         http.open("POST", url, true);
 2366:         http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 2367:         http.onreadystatechange = function() {
 2368:             if (http.readyState == 4 && http.status == 200) {
 2369:                 var data = JSON.parse(http.responseText);
 2370:                 var selelem;
 2371:                 if ((setdir) && (dirsel != null) && (dirsel != 'undefined') && (dirsel != '')) {
 2372:                     if (Array.isArray(data.dirs)) {
 2373:                         selelem = form.elements[dirsel];
 2374:                         var i, numdirs = selelem.options.length -1;
 2375:                         if (numdirs >=0) {
 2376:                             for (i = numdirs; i >= 0; i--) {
 2377:                                 selelem.remove(i);
 2378:                             }
 2379:                         }
 2380:                         var len = data.dirs.length;
 2381:                         if (len) {
 2382:                             selelem.options[selelem.options.length] = new Option('$se','');
 2383:                             var j;
 2384:                             for (j = 0; j < len; j++) {
 2385:                                 selelem.options[selelem.options.length] = new Option(data.dirs[j],data.dirs[j]);
 2386:                             }
 2387:                             selelem.selectedIndex = 0;
 2388:                         }
 2389:                         if (!setfile) {
 2390:                             if ((filesel != null) && (filesel != 'undefined') && (filesel != '')) {
 2391:                                 selelem = form.elements[filesel];
 2392:                                 var j, numfiles = selelem.options.length -1;
 2393:                                 if (numfiles >=0) {
 2394:                                     for (j = numfiles; j >= 0; j--) {
 2395:                                         selelem.remove(j);
 2396:                                     }
 2397:                                 }
 2398:                                 if (selelem.options.length == 0) {
 2399:                                     selelem.options[selelem.options.length] = new Option('','');
 2400:                                     selelem.selectedIndex = 0;
 2401:                                 }
 2402:                             }
 2403:                         }
 2404:                     }
 2405:                 }
 2406:                 if ((setfile) && (filesel != null) && (filesel != 'undefined') && (filesel != '')) {
 2407:                     selelem = form.elements[filesel];
 2408:                     var i, numfiles = selelem.options.length -1;
 2409:                     if (numfiles >=0) {
 2410:                         for (i = numfiles; i >= 0; i--) {
 2411:                             selelem.remove(i);
 2412:                         }
 2413:                     }
 2414:                     var x;
 2415:                     for (x in data.files) {
 2416:                         if (Array.isArray(data.files[x])) {
 2417:                             if (data.files[x].length > 1) {
 2418:                                 selelem.options[selelem.options.length] = new Option('$se','');
 2419:                             }
 2420:                             var len = data.files[x].length;
 2421:                             if (len) {
 2422:                                 var k;
 2423:                                 for (k = 0; k < len; k++) {
 2424:                                     selelem.options[selelem.options.length] = new Option(data.files[x][k],data.files[x][k]);
 2425:                                 }
 2426:                                 selelem.selectedIndex = 0;
 2427:                             }
 2428:                         }
 2429:                     }
 2430:                     if (selelem.options.length == 0) {
 2431:                         selelem.options[selelem.options.length] = new Option('','');
 2432:                         selelem.selectedIndex = 0;
 2433:                     }
 2434:                 }
 2435:             }
 2436:         }
 2437:         http.send(params);
 2438:     }
 2439: END
 2440: }
 2441: 
 2442: =pod
 2443: 
 2444: =item * &iframe_wrapper_headjs()
 2445: 
 2446: #
 2447: # Where iframe is in use, if window.onload() executes before the custom resize function
 2448: # has been defined (jQuery), two global javascript vars (LCnotready and LCresizedef)
 2449: # are used to ensure document.ready() triggers a call to resize, so the iframe contents
 2450: # do not obscure the Functions menu.
 2451: #
 2452: 
 2453: =back
 2454: 
 2455: =cut
 2456: 
 2457: 
 2458: sub iframe_wrapper_headjs {
 2459:     return <<"ENDJS";
 2460: <script type="text/javascript">
 2461: // <![CDATA[
 2462: var LCnotready = 0;
 2463: var LCresizedef = 0;
 2464: // ]]>
 2465: </script>
 2466: 
 2467: ENDJS
 2468: 
 2469: }
 2470: 
 2471: =pod
 2472: 
 2473: =item * &iframe_wrapper_resizejs()
 2474: 
 2475: #
 2476: # jQuery to use when iframe is in use and a page resize occurs.
 2477: # This script will ensure that the iframe does not obscure any
 2478: # standard LON-CAPA inline menus (primary, secondary, and/or
 2479: # breadcrumbs and Functions menus. Expects javascript from
 2480: # &iframe_wrapper_headjs() to be in head portion of the web page,
 2481: # e.g., by inclusion in second arg passed to &start_page().
 2482: #
 2483: 
 2484: =back
 2485: 
 2486: =cut
 2487: 
 2488: sub iframe_wrapper_resizejs {
 2489:     my $offset = 5;
 2490:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['inhibitmenu']);
 2491:     if (($env{'form.inhibitmenu'} eq 'yes') || ($env{'form.only_body'})) {
 2492:         $offset = 0;
 2493:     }
 2494:     return &Apache::lonhtmlcommon::scripttag(<<SCRIPT);
 2495:     \$(document).ready( function() {
 2496:         \$(window).unbind('resize').resize(function(){
 2497:             var header = null;
 2498:             var offset = $offset;
 2499:             var height = 0;
 2500:             var hdrtop = 0;
 2501:             if (\$('div.LC_menus_content:first').length) {
 2502:                 if (\$('div.LC_menus_content:first').hasClass ("shown")) {
 2503:                     header = \$('div.LC_menus_content:first');
 2504:                     offset = 9;
 2505:                 }
 2506:             } else if (\$('div.LC_head_subbox:first').length) {
 2507:                 header = \$('div.LC_head_subbox:first');
 2508:                 offset = 9;
 2509:             } else {
 2510:                 if (\$('#LC_breadcrumbs').length) {
 2511:                     header = \$('#LC_breadcrumbs');
 2512:                 }
 2513:             }
 2514:             if (header != null && header.length) {
 2515:                 height = header.height();
 2516:                 hdrtop = header.position().top;
 2517:             }
 2518:             var pos = height + hdrtop + offset;
 2519:             \$('.LC_iframecontainer').css('top', pos);
 2520:         });
 2521:         LCresizedef = 1;
 2522:         if (LCnotready == 1) {
 2523:             LCnotready = 0;
 2524:             \$(window).trigger('resize');
 2525:         }
 2526:     });
 2527:     window.onload = function(){
 2528:          if (LCresizedef) {
 2529:              LCnotready = 0;
 2530:              \$(window).trigger('resize');
 2531:          } else {
 2532:              LCnotready = 1;
 2533:          }
 2534:     };
 2535: SCRIPT
 2536: 
 2537: }
 2538: 
 2539: =pod
 2540: 
 2541: =head1 Excel and CSV file utility routines
 2542: 
 2543: =cut
 2544: 
 2545: ###############################################################
 2546: ###############################################################
 2547: 
 2548: =pod
 2549: 
 2550: =over 4
 2551: 
 2552: =item * &csv_translate($text) 
 2553: 
 2554: Translate $text to allow it to be output as a 'comma separated values' 
 2555: format.
 2556: 
 2557: =cut
 2558: 
 2559: ###############################################################
 2560: ###############################################################
 2561: sub csv_translate {
 2562:     my $text = shift;
 2563:     $text =~ s/\"/\"\"/g;
 2564:     $text =~ s/\n/ /g;
 2565:     return $text;
 2566: }
 2567: 
 2568: ###############################################################
 2569: ###############################################################
 2570: 
 2571: =pod
 2572: 
 2573: =item * &define_excel_formats()
 2574: 
 2575: Define some commonly used Excel cell formats.
 2576: 
 2577: Currently supported formats:
 2578: 
 2579: =over 4
 2580: 
 2581: =item header
 2582: 
 2583: =item bold
 2584: 
 2585: =item h1
 2586: 
 2587: =item h2
 2588: 
 2589: =item h3
 2590: 
 2591: =item h4
 2592: 
 2593: =item i
 2594: 
 2595: =item date
 2596: 
 2597: =back
 2598: 
 2599: Inputs: $workbook
 2600: 
 2601: Returns: $format, a hash reference.
 2602: 
 2603: 
 2604: =cut
 2605: 
 2606: ###############################################################
 2607: ###############################################################
 2608: sub define_excel_formats {
 2609:     my ($workbook) = @_;
 2610:     my $format;
 2611:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 2612:                                                 bottom    => 1,
 2613:                                                 align     => 'center');
 2614:     $format->{'bold'} = $workbook->add_format(bold=>1);
 2615:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 2616:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 2617:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 2618:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 2619:     $format->{'i'}    = $workbook->add_format(italic=>1);
 2620:     $format->{'date'} = $workbook->add_format(num_format=>
 2621:                                             'mm/dd/yyyy hh:mm:ss');
 2622:     return $format;
 2623: }
 2624: 
 2625: ###############################################################
 2626: ###############################################################
 2627: 
 2628: =pod
 2629: 
 2630: =item * &create_workbook()
 2631: 
 2632: Create an Excel worksheet.  If it fails, output message on the
 2633: request object and return undefs.
 2634: 
 2635: Inputs: Apache request object
 2636: 
 2637: Returns (undef) on failure, 
 2638:     Excel worksheet object, scalar with filename, and formats 
 2639:     from &Apache::loncommon::define_excel_formats on success
 2640: 
 2641: =cut
 2642: 
 2643: ###############################################################
 2644: ###############################################################
 2645: sub create_workbook {
 2646:     my ($r) = @_;
 2647:         #
 2648:     # Create the excel spreadsheet
 2649:     my $filename = '/prtspool/'.
 2650:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2651:         time.'_'.rand(1000000000).'.xls';
 2652:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 2653:     if (! defined($workbook)) {
 2654:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 2655:         $r->print(
 2656:             '<p class="LC_error">'
 2657:            .&mt('Problems occurred in creating the new Excel file.')
 2658:            .' '.&mt('This error has been logged.')
 2659:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2660:            .'</p>'
 2661:         );
 2662:         return (undef);
 2663:     }
 2664:     #
 2665:     $workbook->set_tempdir(LONCAPA::tempdir());
 2666:     #
 2667:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 2668:     return ($workbook,$filename,$format);
 2669: }
 2670: 
 2671: ###############################################################
 2672: ###############################################################
 2673: 
 2674: =pod
 2675: 
 2676: =item * &create_text_file()
 2677: 
 2678: Create a file to write to and eventually make available to the user.
 2679: If file creation fails, outputs an error message on the request object and 
 2680: return undefs.
 2681: 
 2682: Inputs: Apache request object, and file suffix
 2683: 
 2684: Returns (undef) on failure, 
 2685:     Filehandle and filename on success.
 2686: 
 2687: =cut
 2688: 
 2689: ###############################################################
 2690: ###############################################################
 2691: sub create_text_file {
 2692:     my ($r,$suffix) = @_;
 2693:     if (! defined($suffix)) { $suffix = 'txt'; };
 2694:     my $fh;
 2695:     my $filename = '/prtspool/'.
 2696:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2697:         time.'_'.rand(1000000000).'.'.$suffix;
 2698:     $fh = Apache::File->new('>/home/httpd'.$filename);
 2699:     if (! defined($fh)) {
 2700:         $r->log_error("Couldn't open $filename for output $!");
 2701:         $r->print(
 2702:             '<p class="LC_error">'
 2703:            .&mt('Problems occurred in creating the output file.')
 2704:            .' '.&mt('This error has been logged.')
 2705:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2706:            .'</p>'
 2707:         );
 2708:     }
 2709:     return ($fh,$filename)
 2710: }
 2711: 
 2712: 
 2713: =pod 
 2714: 
 2715: =back
 2716: 
 2717: =cut
 2718: 
 2719: ###############################################################
 2720: ##        Home server <option> list generating code          ##
 2721: ###############################################################
 2722: 
 2723: # ------------------------------------------
 2724: 
 2725: sub domain_select {
 2726:     my ($name,$value,$multiple,$incdoms,$excdoms)=@_;
 2727:     my @possdoms;
 2728:     if (ref($incdoms) eq 'ARRAY') {
 2729:         @possdoms = @{$incdoms};
 2730:     } else {
 2731:         @possdoms = &Apache::lonnet::all_domains();
 2732:     }
 2733: 
 2734:     my %domains=map { 
 2735: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 2736:     } @possdoms;
 2737: 
 2738:     if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
 2739:         foreach my $dom (@{$excdoms}) {
 2740:             delete($domains{$dom});
 2741:         }
 2742:     }
 2743: 
 2744:     if ($multiple) {
 2745: 	$domains{''}=&mt('Any domain');
 2746: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2747: 	return &multiple_select_form($name,$value,4,\%domains);
 2748:     } else {
 2749: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2750: 	return &select_form($name,$value,\%domains);
 2751:     }
 2752: }
 2753: 
 2754: #-------------------------------------------
 2755: 
 2756: =pod
 2757: 
 2758: =head1 Routines for form select boxes
 2759: 
 2760: =over 4
 2761: 
 2762: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 2763: 
 2764: Returns a string containing a <select> element int multiple mode
 2765: 
 2766: 
 2767: Args:
 2768:   $name - name of the <select> element
 2769:   $value - scalar or array ref of values that should already be selected
 2770:   $size - number of rows long the select element is
 2771:   $hash - the elements should be 'option' => 'shown text'
 2772:           (shown text should already have been &mt())
 2773:   $order - (optional) array ref of the order to show the elements in
 2774: 
 2775: =cut
 2776: 
 2777: #-------------------------------------------
 2778: sub multiple_select_form {
 2779:     my ($name,$value,$size,$hash,$order)=@_;
 2780:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 2781:     my $output='';
 2782:     if (! defined($size)) {
 2783:         $size = 4;
 2784:         if (scalar(keys(%$hash))<4) {
 2785:             $size = scalar(keys(%$hash));
 2786:         }
 2787:     }
 2788:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 2789:     my @order;
 2790:     if (ref($order) eq 'ARRAY')  {
 2791:         @order = @{$order};
 2792:     } else {
 2793:         @order = sort(keys(%$hash));
 2794:     }
 2795:     if (exists($$hash{'select_form_order'})) {
 2796:         @order = @{$$hash{'select_form_order'}};
 2797:     }
 2798:         
 2799:     foreach my $key (@order) {
 2800:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 2801:         $output.='selected="selected" ' if ($selected{$key});
 2802:         $output.='>'.$hash->{$key}."</option>\n";
 2803:     }
 2804:     $output.="</select>\n";
 2805:     return $output;
 2806: }
 2807: 
 2808: #-------------------------------------------
 2809: 
 2810: =pod
 2811: 
 2812: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
 2813: 
 2814: Returns a string containing a <select name='$name' size='1'> form to 
 2815: allow a user to select options from a ref to a hash containing:
 2816: option_name => displayed text. An optional $onchange can include
 2817: a javascript onchange item, e.g., onchange="this.form.submit();".
 2818: An optional arg -- $readonly -- if true will cause the select form
 2819: to be disabled, e.g., for the case where an instructor has a section-
 2820: specific role, and is viewing/modifying parameters. 
 2821: 
 2822: See lonrights.pm for an example invocation and use.
 2823: 
 2824: =cut
 2825: 
 2826: #-------------------------------------------
 2827: sub select_form {
 2828:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
 2829:     return unless (ref($hashref) eq 'HASH');
 2830:     if ($onchange) {
 2831:         $onchange = ' onchange="'.$onchange.'"';
 2832:     }
 2833:     my $disabled;
 2834:     if ($readonly) {
 2835:         $disabled = ' disabled="disabled"';
 2836:     }
 2837:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2838:     my @keys;
 2839:     if (exists($hashref->{'select_form_order'})) {
 2840: 	@keys=@{$hashref->{'select_form_order'}};
 2841:     } else {
 2842: 	@keys=sort(keys(%{$hashref}));
 2843:     }
 2844:     foreach my $key (@keys) {
 2845:         $selectform.=
 2846: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2847:             ($key eq $def ? 'selected="selected" ' : '').
 2848:                 ">".$hashref->{$key}."</option>\n";
 2849:     }
 2850:     $selectform.="</select>";
 2851:     return $selectform;
 2852: }
 2853: 
 2854: # For display filters
 2855: 
 2856: sub display_filter {
 2857:     my ($context) = @_;
 2858:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2859:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2860:     my $phraseinput = 'hidden';
 2861:     my $includeinput = 'hidden';
 2862:     my ($checked,$includetypestext);
 2863:     if ($env{'form.displayfilter'} eq 'containing') {
 2864:         $phraseinput = 'text'; 
 2865:         if ($context eq 'parmslog') {
 2866:             $includeinput = 'checkbox';
 2867:             if ($env{'form.includetypes'}) {
 2868:                 $checked = ' checked="checked"';
 2869:             }
 2870:             $includetypestext = &mt('Include parameter types');
 2871:         }
 2872:     } else {
 2873:         $includetypestext = '&nbsp;';
 2874:     }
 2875:     my ($additional,$secondid,$thirdid);
 2876:     if ($context eq 'parmslog') {
 2877:         $additional = 
 2878:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2879:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2880:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2881:             '</label>';
 2882:         $secondid = 'includetypes';
 2883:         $thirdid = 'includetypestext';
 2884:     }
 2885:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2886:                                                     '$secondid','$thirdid')";
 2887:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2888: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},'',undef,
 2889: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2890: 	   '</label></span> <span class="LC_nobreak">'.
 2891:            &mt('Filter: [_1]',
 2892: 	   &select_form($env{'form.displayfilter'},
 2893: 			'displayfilter',
 2894: 			{'currentfolder' => 'Current folder/page',
 2895: 			 'containing' => 'Containing phrase',
 2896: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2897: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2898:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2899:                          '" />'.$additional;
 2900: }
 2901: 
 2902: sub display_filter_js {
 2903:     my $includetext = &mt('Include parameter types');
 2904:     return <<"ENDJS";
 2905:   
 2906: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2907:     var firstType = 'hidden';
 2908:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2909:         firstType = 'text';
 2910:     }
 2911:     firstObject = document.getElementById(firstid);
 2912:     if (typeof(firstObject) == 'object') {
 2913:         if (firstObject.type != firstType) {
 2914:             changeInputType(firstObject,firstType);
 2915:         }
 2916:     }
 2917:     if (context == 'parmslog') {
 2918:         var secondType = 'hidden';
 2919:         if (firstType == 'text') {
 2920:             secondType = 'checkbox';
 2921:         }
 2922:         secondObject = document.getElementById(secondid);  
 2923:         if (typeof(secondObject) == 'object') {
 2924:             if (secondObject.type != secondType) {
 2925:                 changeInputType(secondObject,secondType);
 2926:             }
 2927:         }
 2928:         var textItem = document.getElementById(thirdid);
 2929:         var currtext = textItem.innerHTML;
 2930:         var newtext;
 2931:         if (firstType == 'text') {
 2932:             newtext = '$includetext';
 2933:         } else {
 2934:             newtext = '&nbsp;';
 2935:         }
 2936:         if (currtext != newtext) {
 2937:             textItem.innerHTML = newtext;
 2938:         }
 2939:     }
 2940:     return;
 2941: }
 2942: 
 2943: function changeInputType(oldObject,newType) {
 2944:     var newObject = document.createElement('input');
 2945:     newObject.type = newType;
 2946:     if (oldObject.size) {
 2947:         newObject.size = oldObject.size;
 2948:     }
 2949:     if (oldObject.value) {
 2950:         newObject.value = oldObject.value;
 2951:     }
 2952:     if (oldObject.name) {
 2953:         newObject.name = oldObject.name;
 2954:     }
 2955:     if (oldObject.id) {
 2956:         newObject.id = oldObject.id;
 2957:     }
 2958:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2959:     return;
 2960: }
 2961: 
 2962: ENDJS
 2963: }
 2964: 
 2965: sub gradeleveldescription {
 2966:     my $gradelevel=shift;
 2967:     my %gradelevels=(0 => 'Not specified',
 2968: 		     1 => 'Grade 1',
 2969: 		     2 => 'Grade 2',
 2970: 		     3 => 'Grade 3',
 2971: 		     4 => 'Grade 4',
 2972: 		     5 => 'Grade 5',
 2973: 		     6 => 'Grade 6',
 2974: 		     7 => 'Grade 7',
 2975: 		     8 => 'Grade 8',
 2976: 		     9 => 'Grade 9',
 2977: 		     10 => 'Grade 10',
 2978: 		     11 => 'Grade 11',
 2979: 		     12 => 'Grade 12',
 2980: 		     13 => 'Grade 13',
 2981: 		     14 => '100 Level',
 2982: 		     15 => '200 Level',
 2983: 		     16 => '300 Level',
 2984: 		     17 => '400 Level',
 2985: 		     18 => 'Graduate Level');
 2986:     return &mt($gradelevels{$gradelevel});
 2987: }
 2988: 
 2989: sub select_level_form {
 2990:     my ($deflevel,$name)=@_;
 2991:     unless ($deflevel) { $deflevel=0; }
 2992:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2993:     for (my $i=0; $i<=18; $i++) {
 2994:         $selectform.="<option value=\"$i\" ".
 2995:             ($i==$deflevel ? 'selected="selected" ' : '').
 2996:                 ">".&gradeleveldescription($i)."</option>\n";
 2997:     }
 2998:     $selectform.="</select>";
 2999:     return $selectform;
 3000: }
 3001: 
 3002: #-------------------------------------------
 3003: 
 3004: =pod
 3005: 
 3006: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
 3007: 
 3008: Returns a string containing a <select name='$name' size='1'> form to 
 3009: allow a user to select the domain to preform an operation in.  
 3010: See loncreateuser.pm for an example invocation and use.
 3011: 
 3012: If the $includeempty flag is set, it also includes an empty choice ("no domain
 3013: selected");
 3014: 
 3015: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 3016: 
 3017: 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.
 3018: 
 3019: The optional $incdoms is a reference to an array of domains which will be the only available options.
 3020: 
 3021: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
 3022: 
 3023: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
 3024: 
 3025: =cut
 3026: 
 3027: #-------------------------------------------
 3028: sub select_dom_form {
 3029:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
 3030:     if ($onchange) {
 3031:         $onchange = ' onchange="'.$onchange.'"';
 3032:     }
 3033:     if ($disabled) {
 3034:         $disabled = ' disabled="disabled"';
 3035:     }
 3036:     my (@domains,%exclude);
 3037:     if (ref($incdoms) eq 'ARRAY') {
 3038:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 3039:     } else {
 3040:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 3041:     }
 3042:     if ($includeempty) { @domains=('',@domains); }
 3043:     if (ref($excdoms) eq 'ARRAY') {
 3044:         map { $exclude{$_} = 1; } @{$excdoms}; 
 3045:     }
 3046:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 3047:     foreach my $dom (@domains) {
 3048:         next if ($exclude{$dom});
 3049:         $selectdomain.="<option value=\"$dom\" ".
 3050:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 3051:         if ($showdomdesc) {
 3052:             if ($dom ne '') {
 3053:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 3054:                 if ($domdesc ne '') {
 3055:                     $selectdomain .= ' ('.$domdesc.')';
 3056:                 }
 3057:             } 
 3058:         }
 3059:         $selectdomain .= "</option>\n";
 3060:     }
 3061:     $selectdomain.="</select>";
 3062:     return $selectdomain;
 3063: }
 3064: 
 3065: #-------------------------------------------
 3066: 
 3067: =pod
 3068: 
 3069: =item * &home_server_form_item($domain,$name,$defaultflag)
 3070: 
 3071: input: 4 arguments (two required, two optional) - 
 3072:     $domain - domain of new user
 3073:     $name - name of form element
 3074:     $default - Value of 'default' causes a default item to be first 
 3075:                             option, and selected by default. 
 3076:     $hide - Value of 'hide' causes hiding of the name of the server, 
 3077:                             if 1 server found, or default, if 0 found.
 3078: output: returns 2 items: 
 3079: (a) form element which contains either:
 3080:    (i) <select name="$name">
 3081:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 3082:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 3083:        </select>
 3084:        form item if there are multiple library servers in $domain, or
 3085:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 3086:        if there is only one library server in $domain.
 3087: 
 3088: (b) number of library servers found.
 3089: 
 3090: See loncreateuser.pm for example of use.
 3091: 
 3092: =cut
 3093: 
 3094: #-------------------------------------------
 3095: sub home_server_form_item {
 3096:     my ($domain,$name,$default,$hide) = @_;
 3097:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 3098:     my $result;
 3099:     my $numlib = keys(%servers);
 3100:     if ($numlib > 1) {
 3101:         $result .= '<select name="'.$name.'" />'."\n";
 3102:         if ($default) {
 3103:             $result .= '<option value="default" selected="selected">'.&mt('default').
 3104:                        '</option>'."\n";
 3105:         }
 3106:         foreach my $hostid (sort(keys(%servers))) {
 3107:             $result.= '<option value="'.$hostid.'">'.
 3108: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 3109:         }
 3110:         $result .= '</select>'."\n";
 3111:     } elsif ($numlib == 1) {
 3112:         my $hostid;
 3113:         foreach my $item (keys(%servers)) {
 3114:             $hostid = $item;
 3115:         }
 3116:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 3117:                    $hostid.'" />';
 3118:                    if (!$hide) {
 3119:                        $result .= $hostid.' '.$servers{$hostid};
 3120:                    }
 3121:                    $result .= "\n";
 3122:     } elsif ($default) {
 3123:         $result .= '<input type="hidden" name="'.$name.
 3124:                    '" value="default" />';
 3125:                    if (!$hide) {
 3126:                        $result .= &mt('default');
 3127:                    }
 3128:                    $result .= "\n";
 3129:     }
 3130:     return ($result,$numlib);
 3131: }
 3132: 
 3133: =pod
 3134: 
 3135: =back 
 3136: 
 3137: =cut
 3138: 
 3139: ###############################################################
 3140: ##                  Decoding User Agent                      ##
 3141: ###############################################################
 3142: 
 3143: =pod
 3144: 
 3145: =head1 Decoding the User Agent
 3146: 
 3147: =over 4
 3148: 
 3149: =item * &decode_user_agent()
 3150: 
 3151: Inputs: $r
 3152: 
 3153: Outputs:
 3154: 
 3155: =over 4
 3156: 
 3157: =item * $httpbrowser
 3158: 
 3159: =item * $clientbrowser
 3160: 
 3161: =item * $clientversion
 3162: 
 3163: =item * $clientmathml
 3164: 
 3165: =item * $clientunicode
 3166: 
 3167: =item * $clientos
 3168: 
 3169: =item * $clientmobile
 3170: 
 3171: =item * $clientinfo
 3172: 
 3173: =item * $clientosversion
 3174: 
 3175: =back
 3176: 
 3177: =back 
 3178: 
 3179: =cut
 3180: 
 3181: ###############################################################
 3182: ###############################################################
 3183: sub decode_user_agent {
 3184:     my ($r)=@_;
 3185:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 3186:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 3187:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 3188:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 3189:     my $clientbrowser='unknown';
 3190:     my $clientversion='0';
 3191:     my $clientmathml='';
 3192:     my $clientunicode='0';
 3193:     my $clientmobile=0;
 3194:     my $clientosversion='';
 3195:     for (my $i=0;$i<=$#browsertype;$i++) {
 3196:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
 3197: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 3198: 	    $clientbrowser=$bname;
 3199:             $httpbrowser=~/$vreg/i;
 3200: 	    $clientversion=$1;
 3201:             $clientmathml=($clientversion>=$minv);
 3202:             $clientunicode=($clientversion>=$univ);
 3203: 	}
 3204:     }
 3205:     my $clientos='unknown';
 3206:     my $clientinfo;
 3207:     if (($httpbrowser=~/linux/i) ||
 3208:         ($httpbrowser=~/unix/i) ||
 3209:         ($httpbrowser=~/ux/i) ||
 3210:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 3211:     if (($httpbrowser=~/vax/i) ||
 3212:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 3213:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 3214:     if (($httpbrowser=~/mac/i) ||
 3215:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 3216:     if ($httpbrowser=~/win/i) {
 3217:         $clientos='win';
 3218:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
 3219:             $clientosversion = $1;
 3220:         }
 3221:     }
 3222:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 3223:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 3224:         $clientmobile=lc($1);
 3225:     }
 3226:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 3227:         $clientinfo = 'firefox-'.$1;
 3228:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 3229:         $clientinfo = 'chromeframe-'.$1;
 3230:     }
 3231:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 3232:             $clientunicode,$clientos,$clientmobile,$clientinfo,
 3233:             $clientosversion);
 3234: }
 3235: 
 3236: ###############################################################
 3237: ##    Authentication changing form generation subroutines    ##
 3238: ###############################################################
 3239: ##
 3240: ## All of the authform_xxxxxxx subroutines take their inputs in a
 3241: ## hash, and have reasonable default values.
 3242: ##
 3243: ##    formname = the name given in the <form> tag.
 3244: #-------------------------------------------
 3245: 
 3246: =pod
 3247: 
 3248: =head1 Authentication Routines
 3249: 
 3250: =over 4
 3251: 
 3252: =item * &authform_xxxxxx()
 3253: 
 3254: The authform_xxxxxx subroutines provide javascript and html forms which 
 3255: handle some of the conveniences required for authentication forms.  
 3256: This is not an optimal method, but it works.  
 3257: 
 3258: =over 4
 3259: 
 3260: =item * authform_header
 3261: 
 3262: =item * authform_authorwarning
 3263: 
 3264: =item * authform_nochange
 3265: 
 3266: =item * authform_kerberos
 3267: 
 3268: =item * authform_internal
 3269: 
 3270: =item * authform_filesystem
 3271: 
 3272: =item * authform_lti
 3273: 
 3274: =back
 3275: 
 3276: See loncreateuser.pm for invocation and use examples.
 3277: 
 3278: =cut
 3279: 
 3280: #-------------------------------------------
 3281: sub authform_header{  
 3282:     my %in = (
 3283:         formname => 'cu',
 3284:         kerb_def_dom => '',
 3285:         @_,
 3286:     );
 3287:     $in{'formname'} = 'document.' . $in{'formname'};
 3288:     my $result='';
 3289: 
 3290: #---------------------------------------------- Code for upper case translation
 3291:     my $Javascript_toUpperCase;
 3292:     unless ($in{kerb_def_dom}) {
 3293:         $Javascript_toUpperCase =<<"END";
 3294:         switch (choice) {
 3295:            case 'krb': currentform.elements[choicearg].value =
 3296:                currentform.elements[choicearg].value.toUpperCase();
 3297:                break;
 3298:            default:
 3299:         }
 3300: END
 3301:     } else {
 3302:         $Javascript_toUpperCase = "";
 3303:     }
 3304: 
 3305:     my $radioval = "'nochange'";
 3306:     if (defined($in{'curr_authtype'})) {
 3307:         if ($in{'curr_authtype'} ne '') {
 3308:             $radioval = "'".$in{'curr_authtype'}."arg'";
 3309:         }
 3310:     }
 3311:     my $argfield = 'null';
 3312:     if (defined($in{'mode'})) {
 3313:         if ($in{'mode'} eq 'modifycourse')  {
 3314:             if (defined($in{'curr_autharg'})) {
 3315:                 if ($in{'curr_autharg'} ne '') {
 3316:                     $argfield = "'$in{'curr_autharg'}'";
 3317:                 }
 3318:             }
 3319:         }
 3320:     }
 3321: 
 3322:     $result.=<<"END";
 3323: var current = new Object();
 3324: current.radiovalue = $radioval;
 3325: current.argfield = $argfield;
 3326: 
 3327: function changed_radio(choice,currentform) {
 3328:     var choicearg = choice + 'arg';
 3329:     // If a radio button in changed, we need to change the argfield
 3330:     if (current.radiovalue != choice) {
 3331:         current.radiovalue = choice;
 3332:         if (current.argfield != null) {
 3333:             currentform.elements[current.argfield].value = '';
 3334:         }
 3335:         if (choice == 'nochange') {
 3336:             current.argfield = null;
 3337:         } else {
 3338:             current.argfield = choicearg;
 3339:             switch(choice) {
 3340:                 case 'krb': 
 3341:                     currentform.elements[current.argfield].value = 
 3342:                         "$in{'kerb_def_dom'}";
 3343:                 break;
 3344:               default:
 3345:                 break;
 3346:             }
 3347:         }
 3348:     }
 3349:     return;
 3350: }
 3351: 
 3352: function changed_text(choice,currentform) {
 3353:     var choicearg = choice + 'arg';
 3354:     if (currentform.elements[choicearg].value !='') {
 3355:         $Javascript_toUpperCase
 3356:         // clear old field
 3357:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 3358:             currentform.elements[current.argfield].value = '';
 3359:         }
 3360:         current.argfield = choicearg;
 3361:     }
 3362:     set_auth_radio_buttons(choice,currentform);
 3363:     return;
 3364: }
 3365: 
 3366: function set_auth_radio_buttons(newvalue,currentform) {
 3367:     var numauthchoices = currentform.login.length;
 3368:     if (typeof numauthchoices  == "undefined") {
 3369:         return;
 3370:     } 
 3371:     var i=0;
 3372:     while (i < numauthchoices) {
 3373:         if (currentform.login[i].value == newvalue) { break; }
 3374:         i++;
 3375:     }
 3376:     if (i == numauthchoices) {
 3377:         return;
 3378:     }
 3379:     current.radiovalue = newvalue;
 3380:     currentform.login[i].checked = true;
 3381:     return;
 3382: }
 3383: END
 3384:     return $result;
 3385: }
 3386: 
 3387: sub authform_authorwarning {
 3388:     my $result='';
 3389:     $result='<i>'.
 3390:         &mt('As a general rule, only authors or co-authors should be '.
 3391:             'filesystem authenticated '.
 3392:             '(which allows access to the server filesystem).')."</i>\n";
 3393:     return $result;
 3394: }
 3395: 
 3396: sub authform_nochange {
 3397:     my %in = (
 3398:               formname => 'document.cu',
 3399:               kerb_def_dom => 'MSU.EDU',
 3400:               @_,
 3401:           );
 3402:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3403:     my $result;
 3404:     if (!$authnum) {
 3405:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 3406:     } else {
 3407:         $result = '<label>'.&mt('[_1] Do not change login data',
 3408:                   '<input type="radio" name="login" value="nochange" '.
 3409:                   'checked="checked" onclick="'.
 3410:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 3411: 	    '</label>';
 3412:     }
 3413:     return $result;
 3414: }
 3415: 
 3416: sub authform_kerberos {
 3417:     my %in = (
 3418:               formname => 'document.cu',
 3419:               kerb_def_dom => 'MSU.EDU',
 3420:               kerb_def_auth => 'krb4',
 3421:               @_,
 3422:               );
 3423:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 3424:         $autharg,$jscall,$disabled);
 3425:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3426:     if ($in{'kerb_def_auth'} eq 'krb5') {
 3427:        $check5 = ' checked="checked"';
 3428:     } else {
 3429:        $check4 = ' checked="checked"';
 3430:     }
 3431:     if ($in{'readonly'}) {
 3432:         $disabled = ' disabled="disabled"';
 3433:     }
 3434:     $krbarg = $in{'kerb_def_dom'};
 3435:     if (defined($in{'curr_authtype'})) {
 3436:         if ($in{'curr_authtype'} eq 'krb') {
 3437:             $krbcheck = ' checked="checked"';
 3438:             if (defined($in{'mode'})) {
 3439:                 if ($in{'mode'} eq 'modifyuser') {
 3440:                     $krbcheck = '';
 3441:                 }
 3442:             }
 3443:             if (defined($in{'curr_kerb_ver'})) {
 3444:                 if ($in{'curr_krb_ver'} eq '5') {
 3445:                     $check5 = ' checked="checked"';
 3446:                     $check4 = '';
 3447:                 } else {
 3448:                     $check4 = ' checked="checked"';
 3449:                     $check5 = '';
 3450:                 }
 3451:             }
 3452:             if (defined($in{'curr_autharg'})) {
 3453:                 $krbarg = $in{'curr_autharg'};
 3454:             }
 3455:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 3456:                 if (defined($in{'curr_autharg'})) {
 3457:                     $result = 
 3458:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 3459:         $in{'curr_autharg'},$krbver);
 3460:                 } else {
 3461:                     $result =
 3462:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 3463:                 }
 3464:                 return $result; 
 3465:             }
 3466:         }
 3467:     } else {
 3468:         if ($authnum == 1) {
 3469:             $authtype = '<input type="hidden" name="login" value="krb" />';
 3470:         }
 3471:     }
 3472:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 3473:         return;
 3474:     } elsif ($authtype eq '') {
 3475:         if (defined($in{'mode'})) {
 3476:             if ($in{'mode'} eq 'modifycourse') {
 3477:                 if ($authnum == 1) {
 3478:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
 3479:                 }
 3480:             }
 3481:         }
 3482:     }
 3483:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 3484:     if ($authtype eq '') {
 3485:         $authtype = '<input type="radio" name="login" value="krb" '.
 3486:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 3487:                     $krbcheck.$disabled.' />';
 3488:     }
 3489:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 3490:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 3491:          $in{'curr_authtype'} eq 'krb5') ||
 3492:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 3493:          $in{'curr_authtype'} eq 'krb4')) {
 3494:         $result .= &mt
 3495:         ('[_1] Kerberos authenticated with domain [_2] '.
 3496:          '[_3] Version 4 [_4] Version 5 [_5]',
 3497:          '<label>'.$authtype,
 3498:          '</label><input type="text" size="10" name="krbarg" '.
 3499:              'value="'.$krbarg.'" '.
 3500:              'onchange="'.$jscall.'"'.$disabled.' />',
 3501:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
 3502:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
 3503: 	 '</label>');
 3504:     } elsif ($can_assign{'krb4'}) {
 3505:         $result .= &mt
 3506:         ('[_1] Kerberos authenticated with domain [_2] '.
 3507:          '[_3] Version 4 [_4]',
 3508:          '<label>'.$authtype,
 3509:          '</label><input type="text" size="10" name="krbarg" '.
 3510:              'value="'.$krbarg.'" '.
 3511:              'onchange="'.$jscall.'"'.$disabled.' />',
 3512:          '<label><input type="hidden" name="krbver" value="4" />',
 3513:          '</label>');
 3514:     } elsif ($can_assign{'krb5'}) {
 3515:         $result .= &mt
 3516:         ('[_1] Kerberos authenticated with domain [_2] '.
 3517:          '[_3] Version 5 [_4]',
 3518:          '<label>'.$authtype,
 3519:          '</label><input type="text" size="10" name="krbarg" '.
 3520:              'value="'.$krbarg.'" '.
 3521:              'onchange="'.$jscall.'"'.$disabled.' />',
 3522:          '<label><input type="hidden" name="krbver" value="5" />',
 3523:          '</label>');
 3524:     }
 3525:     return $result;
 3526: }
 3527: 
 3528: sub authform_internal {
 3529:     my %in = (
 3530:                 formname => 'document.cu',
 3531:                 kerb_def_dom => 'MSU.EDU',
 3532:                 @_,
 3533:                 );
 3534:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
 3535:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3536:     if ($in{'readonly'}) {
 3537:         $disabled = ' disabled="disabled"';
 3538:     }
 3539:     if (defined($in{'curr_authtype'})) {
 3540:         if ($in{'curr_authtype'} eq 'int') {
 3541:             if ($can_assign{'int'}) {
 3542:                 $intcheck = 'checked="checked" ';
 3543:                 if (defined($in{'mode'})) {
 3544:                     if ($in{'mode'} eq 'modifyuser') {
 3545:                         $intcheck = '';
 3546:                     }
 3547:                 }
 3548:                 if (defined($in{'curr_autharg'})) {
 3549:                     $intarg = $in{'curr_autharg'};
 3550:                 }
 3551:             } else {
 3552:                 $result = &mt('Currently internally authenticated.');
 3553:                 return $result;
 3554:             }
 3555:         }
 3556:     } else {
 3557:         if ($authnum == 1) {
 3558:             $authtype = '<input type="hidden" name="login" value="int" />';
 3559:         }
 3560:     }
 3561:     if (!$can_assign{'int'}) {
 3562:         return;
 3563:     } elsif ($authtype eq '') {
 3564:         if (defined($in{'mode'})) {
 3565:             if ($in{'mode'} eq 'modifycourse') {
 3566:                 if ($authnum == 1) {
 3567:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
 3568:                 }
 3569:             }
 3570:         }
 3571:     }
 3572:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 3573:     if ($authtype eq '') {
 3574:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 3575:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
 3576:     }
 3577:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 3578:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3579:     $result = &mt
 3580:         ('[_1] Internally authenticated (with initial password [_2])',
 3581:          '<label>'.$authtype,'</label>'.$autharg);
 3582:     $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>';
 3583:     return $result;
 3584: }
 3585: 
 3586: sub authform_local {
 3587:     my %in = (
 3588:               formname => 'document.cu',
 3589:               kerb_def_dom => 'MSU.EDU',
 3590:               @_,
 3591:               );
 3592:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
 3593:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3594:     if ($in{'readonly'}) {
 3595:         $disabled = ' disabled="disabled"';
 3596:     } 
 3597:     if (defined($in{'curr_authtype'})) {
 3598:         if ($in{'curr_authtype'} eq 'loc') {
 3599:             if ($can_assign{'loc'}) {
 3600:                 $loccheck = 'checked="checked" ';
 3601:                 if (defined($in{'mode'})) {
 3602:                     if ($in{'mode'} eq 'modifyuser') {
 3603:                         $loccheck = '';
 3604:                     }
 3605:                 }
 3606:                 if (defined($in{'curr_autharg'})) {
 3607:                     $locarg = $in{'curr_autharg'};
 3608:                 }
 3609:             } else {
 3610:                 $result = &mt('Currently using local (institutional) authentication.');
 3611:                 return $result;
 3612:             }
 3613:         }
 3614:     } else {
 3615:         if ($authnum == 1) {
 3616:             $authtype = '<input type="hidden" name="login" value="loc" />';
 3617:         }
 3618:     }
 3619:     if (!$can_assign{'loc'}) {
 3620:         return;
 3621:     } elsif ($authtype eq '') {
 3622:         if (defined($in{'mode'})) {
 3623:             if ($in{'mode'} eq 'modifycourse') {
 3624:                 if ($authnum == 1) {
 3625:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
 3626:                 }
 3627:             }
 3628:         }
 3629:     }
 3630:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 3631:     if ($authtype eq '') {
 3632:         $authtype = '<input type="radio" name="login" value="loc" '.
 3633:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 3634:                     $jscall.'"'.$disabled.' />';
 3635:     }
 3636:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 3637:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3638:     $result = &mt('[_1] Local Authentication with argument [_2]',
 3639:                   '<label>'.$authtype,'</label>'.$autharg);
 3640:     return $result;
 3641: }
 3642: 
 3643: sub authform_filesystem {
 3644:     my %in = (
 3645:               formname => 'document.cu',
 3646:               kerb_def_dom => 'MSU.EDU',
 3647:               @_,
 3648:               );
 3649:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
 3650:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3651:     if ($in{'readonly'}) {
 3652:         $disabled = ' disabled="disabled"';
 3653:     }
 3654:     if (defined($in{'curr_authtype'})) {
 3655:         if ($in{'curr_authtype'} eq 'fsys') {
 3656:             if ($can_assign{'fsys'}) {
 3657:                 $fsyscheck = 'checked="checked" ';
 3658:                 if (defined($in{'mode'})) {
 3659:                     if ($in{'mode'} eq 'modifyuser') {
 3660:                         $fsyscheck = '';
 3661:                     }
 3662:                 }
 3663:             } else {
 3664:                 $result = &mt('Currently Filesystem Authenticated.');
 3665:                 return $result;
 3666:             }
 3667:         }
 3668:     } else {
 3669:         if ($authnum == 1) {
 3670:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 3671:         }
 3672:     }
 3673:     if (!$can_assign{'fsys'}) {
 3674:         return;
 3675:     } elsif ($authtype eq '') {
 3676:         if (defined($in{'mode'})) {
 3677:             if ($in{'mode'} eq 'modifycourse') {
 3678:                 if ($authnum == 1) {
 3679:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
 3680:                 }
 3681:             }
 3682:         }
 3683:     }
 3684:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 3685:     if ($authtype eq '') {
 3686:         $authtype = '<input type="radio" name="login" value="fsys" '.
 3687:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 3688:                     $jscall.'"'.$disabled.' />';
 3689:     }
 3690:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
 3691:                ' onchange="'.$jscall.'"'.$disabled.' />';
 3692:     $result = &mt
 3693:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 3694:          '<label>'.$authtype,'</label>'.$autharg);
 3695:     return $result;
 3696: }
 3697: 
 3698: sub authform_lti {
 3699:     my %in = (
 3700:               formname => 'document.cu',
 3701:               kerb_def_dom => 'MSU.EDU',
 3702:               @_,
 3703:               );
 3704:     my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
 3705:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3706:     if ($in{'readonly'}) {
 3707:         $disabled = ' disabled="disabled"';
 3708:     }
 3709:     if (defined($in{'curr_authtype'})) {
 3710:         if ($in{'curr_authtype'} eq 'lti') {
 3711:             if ($can_assign{'lti'}) {
 3712:                 $lticheck = 'checked="checked" ';
 3713:                 if (defined($in{'mode'})) {
 3714:                     if ($in{'mode'} eq 'modifyuser') {
 3715:                         $lticheck = '';
 3716:                     }
 3717:                 }
 3718:             } else {
 3719:                 $result = &mt('Currently LTI Authenticated.');
 3720:                 return $result;
 3721:             }
 3722:         }
 3723:     } else {
 3724:         if ($authnum == 1) {
 3725:             $authtype = '<input type="hidden" name="login" value="lti" />';
 3726:         }
 3727:     }
 3728:     if (!$can_assign{'lti'}) {
 3729:         return;
 3730:     } elsif ($authtype eq '') {
 3731:         if (defined($in{'mode'})) {
 3732:             if ($in{'mode'} eq 'modifycourse') {
 3733:                 if ($authnum == 1) {
 3734:                     $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
 3735:                 }
 3736:             }
 3737:         }
 3738:     }
 3739:     $jscall = "javascript:changed_radio('lti',$in{'formname'});";
 3740:     if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
 3741:         $authtype = '<input type="radio" name="login" value="lti" '.
 3742:                     $lticheck.' onchange="'.$jscall.'" onclick="'.
 3743:                     $jscall.'"'.$disabled.' />';
 3744:     }
 3745:     $autharg = '<input type="hidden" name="ltiarg" value="" />';
 3746:     if ($authtype) {
 3747:         $result = &mt('[_1] LTI Authenticated',
 3748:                       '<label>'.$authtype.'</label>'.$autharg);
 3749:     } else {
 3750:         $result = '<b>'.&mt('LTI Authenticated').'</b>'.
 3751:                   $autharg;
 3752:     }
 3753:     return $result;
 3754: }
 3755: 
 3756: sub get_assignable_auth {
 3757:     my ($dom) = @_;
 3758:     if ($dom eq '') {
 3759:         $dom = $env{'request.role.domain'};
 3760:     }
 3761:     my %can_assign = (
 3762:                           krb4 => 1,
 3763:                           krb5 => 1,
 3764:                           int  => 1,
 3765:                           loc  => 1,
 3766:                           lti  => 1,
 3767:                      );
 3768:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 3769:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 3770:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 3771:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 3772:             my $context;
 3773:             if ($env{'request.role'} =~ /^au/) {
 3774:                 $context = 'author';
 3775:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
 3776:                 $context = 'domain';
 3777:             } elsif ($env{'request.course.id'}) {
 3778:                 $context = 'course';
 3779:             }
 3780:             if ($context) {
 3781:                 if (ref($authhash->{$context}) eq 'HASH') {
 3782:                    %can_assign = %{$authhash->{$context}}; 
 3783:                 }
 3784:             }
 3785:         }
 3786:     }
 3787:     my $authnum = 0;
 3788:     foreach my $key (keys(%can_assign)) {
 3789:         if ($can_assign{$key}) {
 3790:             $authnum ++;
 3791:         }
 3792:     }
 3793:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 3794:         $authnum --;
 3795:     }
 3796:     return ($authnum,%can_assign);
 3797: }
 3798: 
 3799: sub check_passwd_rules {
 3800:     my ($domain,$plainpass) = @_;
 3801:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
 3802:     my ($min,$max,@chars,@brokerule,$warning);
 3803:     $min = $Apache::lonnet::passwdmin;
 3804:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
 3805:         if ($passwdconf{'min'} =~ /^\d+$/) {
 3806:             if ($passwdconf{'min'} > $min) {
 3807:                 $min = $passwdconf{'min'};
 3808:             }
 3809:         }
 3810:         if ($passwdconf{'max'} =~ /^\d+$/) {
 3811:             $max = $passwdconf{'max'};
 3812:         }
 3813:         @chars = @{$passwdconf{'chars'}};
 3814:     }
 3815:     if (($min) && (length($plainpass) < $min)) {
 3816:         push(@brokerule,'min');
 3817:     }
 3818:     if (($max) && (length($plainpass) > $max)) {
 3819:         push(@brokerule,'max');
 3820:     }
 3821:     if (@chars) {
 3822:         my %rules;
 3823:         map { $rules{$_} = 1; } @chars;
 3824:         if ($rules{'uc'}) {
 3825:             unless ($plainpass =~ /[A-Z]/) {
 3826:                 push(@brokerule,'uc');
 3827:             }
 3828:         }
 3829:         if ($rules{'lc'}) {
 3830:             unless ($plainpass =~ /[a-z]/) {
 3831:                 push(@brokerule,'lc');
 3832:             }
 3833:         }
 3834:         if ($rules{'num'}) {
 3835:             unless ($plainpass =~ /\d/) {
 3836:                 push(@brokerule,'num');
 3837:             }
 3838:         }
 3839:         if ($rules{'spec'}) {
 3840:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
 3841:                 push(@brokerule,'spec');
 3842:             }
 3843:         }
 3844:     }
 3845:     if (@brokerule) {
 3846:         my %rulenames = &Apache::lonlocal::texthash(
 3847:             uc   => 'At least one upper case letter',
 3848:             lc   => 'At least one lower case letter',
 3849:             num  => 'At least one number',
 3850:             spec => 'At least one non-alphanumeric',
 3851:         );
 3852:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
 3853:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
 3854:         $rulenames{'num'} .= ': 0123456789';
 3855:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
 3856:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
 3857:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
 3858:         $warning = &mt('Password did not satisfy the following:').'<ul>';
 3859:         foreach my $rule ('min','max','uc','lc','num','spec') {
 3860:             if (grep(/^$rule$/,@brokerule)) {
 3861:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
 3862:             }
 3863:         }
 3864:         $warning .= '</ul>';
 3865:     }
 3866:     if (wantarray) {
 3867:         return @brokerule;
 3868:     }
 3869:     return $warning;
 3870: }
 3871: 
 3872: sub passwd_validation_js {
 3873:     my ($currpasswdval,$domain,$context,$id) = @_;
 3874:     my (%passwdconf,$alertmsg);
 3875:     if ($context eq 'linkprot') {
 3876:         my %domconfig = &Apache::lonnet::get_dom('configuration',['ltisec'],$domain);
 3877:         if (ref($domconfig{'ltisec'}) eq 'HASH') {
 3878:             if (ref($domconfig{'ltisec'}{'rules'}) eq 'HASH') {
 3879:                 %passwdconf = %{$domconfig{'ltisec'}{'rules'}};
 3880:             }
 3881:         }
 3882:         if ($id eq 'add') {
 3883:             $alertmsg = &mt('Secret for added launcher did not satisfy requirement(s):').'\n\n';
 3884:         } elsif ($id =~ /^\d+$/) {
 3885:             my $pos = $id+1;
 3886:             $alertmsg = &mt('Secret for launcher [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
 3887:         } else {
 3888:             $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
 3889:         }
 3890:     } else {
 3891:         %passwdconf = &Apache::lonnet::get_passwdconf($domain);
 3892:         $alertmsg = &mt('Initial password did not satisfy requirement(s):').'\n\n';
 3893:     }
 3894:     my ($min,$max,@chars,$numrules,$intargjs,%alert);
 3895:     $numrules = 0;
 3896:     $min = $Apache::lonnet::passwdmin;
 3897:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
 3898:         if ($passwdconf{'min'} =~ /^\d+$/) {
 3899:             if ($passwdconf{'min'} > $min) {
 3900:                 $min = $passwdconf{'min'};
 3901:             }
 3902:         }
 3903:         if ($passwdconf{'max'} =~ /^\d+$/) {
 3904:             $max = $passwdconf{'max'};
 3905:             $numrules ++;
 3906:         }
 3907:         @chars = @{$passwdconf{'chars'}};
 3908:         if (@chars) {
 3909:             $numrules ++;
 3910:         }
 3911:     }
 3912:     if ($min > 0) {
 3913:         $numrules ++;
 3914:     }
 3915:     if (($min > 0) || ($max ne '') || (@chars > 0)) {
 3916:         if ($min) {
 3917:             $alert{'min'} = &mt('minimum [quant,_1,character]',$min).'\n';
 3918:         }
 3919:         if ($max) {
 3920:             $alert{'max'} = &mt('maximum [quant,_1,character]',$max).'\n';
 3921:         }
 3922:         my (@charalerts,@charrules);
 3923:         if (@chars) {
 3924:             if (grep(/^uc$/,@chars)) {
 3925:                 push(@charalerts,&mt('contain at least one upper case letter'));
 3926:                 push(@charrules,'uc');
 3927:             }
 3928:             if (grep(/^lc$/,@chars)) {
 3929:                 push(@charalerts,&mt('contain at least one lower case letter'));
 3930:                 push(@charrules,'lc');
 3931:             }
 3932:             if (grep(/^num$/,@chars)) {
 3933:                 push(@charalerts,&mt('contain at least one number'));
 3934:                 push(@charrules,'num');
 3935:             }
 3936:             if (grep(/^spec$/,@chars)) {
 3937:                 push(@charalerts,&mt('contain at least one non-alphanumeric'));
 3938:                 push(@charrules,'spec');
 3939:             }
 3940:         }
 3941:         $intargjs = qq|            var rulesmsg = '';\n|.
 3942:                     qq|            var currpwval = $currpasswdval;\n|;
 3943:             if ($min) {
 3944:                 $intargjs .= qq|
 3945:             if (currpwval.length < $min) {
 3946:                 rulesmsg += ' - $alert{min}';
 3947:             }
 3948: |;
 3949:             }
 3950:             if ($max) {
 3951:                 $intargjs .= qq|
 3952:             if (currpwval.length > $max) {
 3953:                 rulesmsg += ' - $alert{max}';
 3954:             }
 3955: |;
 3956:             }
 3957:             if (@chars > 0) {
 3958:                 my $charrulestr = '"'.join('","',@charrules).'"';
 3959:                 my $charalertstr = '"'.join('","',@charalerts).'"';
 3960:                 $intargjs .= qq|            var brokerules = new Array();\n|.
 3961:                              qq|            var charrules = new Array($charrulestr);\n|.
 3962:                              qq|            var charalerts = new Array($charalertstr);\n|;
 3963:                 my %rules;
 3964:                 map { $rules{$_} = 1; } @chars;
 3965:                 if ($rules{'uc'}) {
 3966:                     $intargjs .= qq|
 3967:             var ucRegExp = /[A-Z]/;
 3968:             if (!ucRegExp.test(currpwval)) {
 3969:                 brokerules.push('uc');
 3970:             }
 3971: |;
 3972:                 }
 3973:                 if ($rules{'lc'}) {
 3974:                     $intargjs .= qq|
 3975:             var lcRegExp = /[a-z]/;
 3976:             if (!lcRegExp.test(currpwval)) {
 3977:                 brokerules.push('lc');
 3978:             }
 3979: |;
 3980:                 }
 3981:                 if ($rules{'num'}) {
 3982:                      $intargjs .= qq|
 3983:             var numRegExp = /[0-9]/;
 3984:             if (!numRegExp.test(currpwval)) {
 3985:                 brokerules.push('num');
 3986:             }
 3987: |;
 3988:                 }
 3989:                 if ($rules{'spec'}) {
 3990:                      $intargjs .= q|
 3991:             var specRegExp = /[!"#$%&'()*+,\-.\/:;<=>?@[\\^\]_`{\|}~]/;
 3992:             if (!specRegExp.test(currpwval)) {
 3993:                 brokerules.push('spec');
 3994:             }
 3995: |;
 3996:                 }
 3997:                 $intargjs .= qq|
 3998:             if (brokerules.length > 0) {
 3999:                 for (var i=0; i<brokerules.length; i++) {
 4000:                     for (var j=0; j<charrules.length; j++) {
 4001:                         if (brokerules[i] == charrules[j]) {
 4002:                             rulesmsg += ' - '+charalerts[j]+'\\n';
 4003:                             break;
 4004:                         }
 4005:                     }
 4006:                 }
 4007:             }
 4008: |;
 4009:             }
 4010:             $intargjs .= qq|
 4011:             if (rulesmsg != '') {
 4012:                 rulesmsg = '$alertmsg'+rulesmsg;
 4013:                 alert(rulesmsg);
 4014:                 return false;
 4015:             }
 4016: |;
 4017:     }
 4018:     return ($numrules,$intargjs);
 4019: }
 4020: 
 4021: ###############################################################
 4022: ##    Get Kerberos Defaults for Domain                 ##
 4023: ###############################################################
 4024: ##
 4025: ## Returns default kerberos version and an associated argument
 4026: ## as listed in file domain.tab. If not listed, provides
 4027: ## appropriate default domain and kerberos version.
 4028: ##
 4029: #-------------------------------------------
 4030: 
 4031: =pod
 4032: 
 4033: =item * &get_kerberos_defaults()
 4034: 
 4035: get_kerberos_defaults($target_domain) returns the default kerberos
 4036: version and domain. If not found, it defaults to version 4 and the 
 4037: domain of the server.
 4038: 
 4039: =over 4
 4040: 
 4041: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 4042: 
 4043: =back
 4044: 
 4045: =back
 4046: 
 4047: =cut
 4048: 
 4049: #-------------------------------------------
 4050: sub get_kerberos_defaults {
 4051:     my $domain=shift;
 4052:     my ($krbdef,$krbdefdom);
 4053:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 4054:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 4055:         $krbdef = $domdefaults{'auth_def'};
 4056:         $krbdefdom = $domdefaults{'auth_arg_def'};
 4057:     } else {
 4058:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 4059:         my $krbdefdom=$1;
 4060:         $krbdefdom=~tr/a-z/A-Z/;
 4061:         $krbdef = "krb4";
 4062:     }
 4063:     return ($krbdef,$krbdefdom);
 4064: }
 4065: 
 4066: 
 4067: ###############################################################
 4068: ##                Thesaurus Functions                        ##
 4069: ###############################################################
 4070: 
 4071: =pod
 4072: 
 4073: =head1 Thesaurus Functions
 4074: 
 4075: =over 4
 4076: 
 4077: =item * &initialize_keywords()
 4078: 
 4079: Initializes the package variable %Keywords if it is empty.  Uses the
 4080: package variable $thesaurus_db_file.
 4081: 
 4082: =cut
 4083: 
 4084: ###################################################
 4085: 
 4086: sub initialize_keywords {
 4087:     return 1 if (scalar keys(%Keywords));
 4088:     # If we are here, %Keywords is empty, so fill it up
 4089:     #   Make sure the file we need exists...
 4090:     if (! -e $thesaurus_db_file) {
 4091:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 4092:                                  " failed because it does not exist");
 4093:         return 0;
 4094:     }
 4095:     #   Set up the hash as a database
 4096:     my %thesaurus_db;
 4097:     if (! tie(%thesaurus_db,'GDBM_File',
 4098:               $thesaurus_db_file,&GDBM_READER(),0640)){
 4099:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 4100:                                  $thesaurus_db_file);
 4101:         return 0;
 4102:     } 
 4103:     #  Get the average number of appearances of a word.
 4104:     my $avecount = $thesaurus_db{'average.count'};
 4105:     #  Put keywords (those that appear > average) into %Keywords
 4106:     while (my ($word,$data)=each (%thesaurus_db)) {
 4107:         my ($count,undef) = split /:/,$data;
 4108:         $Keywords{$word}++ if ($count > $avecount);
 4109:     }
 4110:     untie %thesaurus_db;
 4111:     # Remove special values from %Keywords.
 4112:     foreach my $value ('total.count','average.count') {
 4113:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 4114:   }
 4115:     return 1;
 4116: }
 4117: 
 4118: ###################################################
 4119: 
 4120: =pod
 4121: 
 4122: =item * &keyword($word)
 4123: 
 4124: Returns true if $word is a keyword.  A keyword is a word that appears more 
 4125: than the average number of times in the thesaurus database.  Calls 
 4126: &initialize_keywords
 4127: 
 4128: =cut
 4129: 
 4130: ###################################################
 4131: 
 4132: sub keyword {
 4133:     return if (!&initialize_keywords());
 4134:     my $word=lc(shift());
 4135:     $word=~s/\W//g;
 4136:     return exists($Keywords{$word});
 4137: }
 4138: 
 4139: ###############################################################
 4140: 
 4141: =pod 
 4142: 
 4143: =item * &get_related_words()
 4144: 
 4145: Look up a word in the thesaurus.  Takes a scalar argument and returns
 4146: an array of words.  If the keyword is not in the thesaurus, an empty array
 4147: will be returned.  The order of the words returned is determined by the
 4148: database which holds them.
 4149: 
 4150: Uses global $thesaurus_db_file.
 4151: 
 4152: 
 4153: =cut
 4154: 
 4155: ###############################################################
 4156: sub get_related_words {
 4157:     my $keyword = shift;
 4158:     my %thesaurus_db;
 4159:     if (! -e $thesaurus_db_file) {
 4160:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 4161:                                  "failed because the file does not exist");
 4162:         return ();
 4163:     }
 4164:     if (! tie(%thesaurus_db,'GDBM_File',
 4165:               $thesaurus_db_file,&GDBM_READER(),0640)){
 4166:         return ();
 4167:     } 
 4168:     my @Words=();
 4169:     my $count=0;
 4170:     if (exists($thesaurus_db{$keyword})) {
 4171: 	# The first element is the number of times
 4172: 	# the word appears.  We do not need it now.
 4173: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 4174: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 4175: 	my $threshold=$mostfrequentcount/10;
 4176:         foreach my $possibleword (@RelatedWords) {
 4177:             my ($word,$wordcount)=split(/\,/,$possibleword);
 4178:             if ($wordcount>$threshold) {
 4179: 		push(@Words,$word);
 4180:                 $count++;
 4181:                 if ($count>10) { last; }
 4182: 	    }
 4183:         }
 4184:     }
 4185:     untie %thesaurus_db;
 4186:     return @Words;
 4187: }
 4188: ###############################################################
 4189: #
 4190: #  Spell checking
 4191: #
 4192: 
 4193: =pod
 4194: 
 4195: =back
 4196: 
 4197: =head1 Spell checking
 4198: 
 4199: =over 4
 4200: 
 4201: =item * &check_spelling($wordlist $language)
 4202: 
 4203: Takes a string containing words and feeds it to an external
 4204: spellcheck program via a pipeline. Returns a string containing
 4205: them mis-spelled words.
 4206: 
 4207: Parameters:
 4208: 
 4209: =over 4
 4210: 
 4211: =item - $wordlist
 4212: 
 4213: String that will be fed into the spellcheck program.
 4214: 
 4215: =item - $language
 4216: 
 4217: Language string that specifies the language for which the spell
 4218: check will be performed.
 4219: 
 4220: =back
 4221: 
 4222: =back
 4223: 
 4224: Note: This sub assumes that aspell is installed.
 4225: 
 4226: 
 4227: =cut
 4228: 
 4229: 
 4230: sub check_spelling {
 4231:     my ($wordlist, $language) = @_;
 4232:     my @misspellings;
 4233:     
 4234:     # Generate the speller and set the langauge.
 4235:     # if explicitly selected:
 4236: 
 4237:     my $speller = Text::Aspell->new;
 4238:     if ($language) {
 4239: 	$speller->set_option('lang', $language);
 4240:     }
 4241: 
 4242:     # Turn the word list into an array of words by splittingon whitespace
 4243: 
 4244:     my @words = split(/\s+/, $wordlist);
 4245: 
 4246:     foreach my $word (@words) {
 4247: 	if(! $speller->check($word)) {
 4248: 	    push(@misspellings, $word);
 4249: 	}
 4250:     }
 4251:     return join(' ', @misspellings);
 4252:     
 4253: }
 4254: 
 4255: # -------------------------------------------------------------- Plaintext name
 4256: =pod
 4257: 
 4258: =head1 User Name Functions
 4259: 
 4260: =over 4
 4261: 
 4262: =item * &plainname($uname,$udom,$first)
 4263: 
 4264: Takes a users logon name and returns it as a string in
 4265: "first middle last generation" form 
 4266: if $first is set to 'lastname' then it returns it as
 4267: 'lastname generation, firstname middlename' if their is a lastname
 4268: 
 4269: =cut
 4270: 
 4271: 
 4272: ###############################################################
 4273: sub plainname {
 4274:     my ($uname,$udom,$first)=@_;
 4275:     return if (!defined($uname) || !defined($udom));
 4276:     my %names=&getnames($uname,$udom);
 4277:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 4278: 					  $names{'middlename'},
 4279: 					  $names{'lastname'},
 4280: 					  $names{'generation'},$first);
 4281:     $name=~s/^\s+//;
 4282:     $name=~s/\s+$//;
 4283:     $name=~s/\s+/ /g;
 4284:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 4285:     return $name;
 4286: }
 4287: 
 4288: # -------------------------------------------------------------------- Nickname
 4289: =pod
 4290: 
 4291: =item * &nickname($uname,$udom)
 4292: 
 4293: Gets a users name and returns it as a string as
 4294: 
 4295: "&quot;nickname&quot;"
 4296: 
 4297: if the user has a nickname or
 4298: 
 4299: "first middle last generation"
 4300: 
 4301: if the user does not
 4302: 
 4303: =cut
 4304: 
 4305: sub nickname {
 4306:     my ($uname,$udom)=@_;
 4307:     return if (!defined($uname) || !defined($udom));
 4308:     my %names=&getnames($uname,$udom);
 4309:     my $name=$names{'nickname'};
 4310:     if ($name) {
 4311:        $name='&quot;'.$name.'&quot;'; 
 4312:     } else {
 4313:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 4314: 	     $names{'lastname'}.' '.$names{'generation'};
 4315:        $name=~s/\s+$//;
 4316:        $name=~s/\s+/ /g;
 4317:     }
 4318:     return $name;
 4319: }
 4320: 
 4321: sub getnames {
 4322:     my ($uname,$udom)=@_;
 4323:     return if (!defined($uname) || !defined($udom));
 4324:     if ($udom eq 'public' && $uname eq 'public') {
 4325: 	return ('lastname' => &mt('Public'));
 4326:     }
 4327:     my $id=$uname.':'.$udom;
 4328:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 4329:     if ($cached) {
 4330: 	return %{$names};
 4331:     } else {
 4332: 	my %loadnames=&Apache::lonnet::get('environment',
 4333:                     ['firstname','middlename','lastname','generation','nickname'],
 4334: 					 $udom,$uname);
 4335: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 4336: 	return %loadnames;
 4337:     }
 4338: }
 4339: 
 4340: # -------------------------------------------------------------------- getemails
 4341: 
 4342: =pod
 4343: 
 4344: =item * &getemails($uname,$udom)
 4345: 
 4346: Gets a user's email information and returns it as a hash with keys:
 4347: notification, critnotification, permanentemail
 4348: 
 4349: For notification and critnotification, values are comma-separated lists 
 4350: of e-mail addresses; for permanentemail, value is a single e-mail address.
 4351:  
 4352: 
 4353: =cut
 4354: 
 4355: 
 4356: sub getemails {
 4357:     my ($uname,$udom)=@_;
 4358:     if ($udom eq 'public' && $uname eq 'public') {
 4359: 	return;
 4360:     }
 4361:     if (!$udom) { $udom=$env{'user.domain'}; }
 4362:     if (!$uname) { $uname=$env{'user.name'}; }
 4363:     my $id=$uname.':'.$udom;
 4364:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 4365:     if ($cached) {
 4366: 	return %{$names};
 4367:     } else {
 4368: 	my %loadnames=&Apache::lonnet::get('environment',
 4369:                     			   ['notification','critnotification',
 4370: 					    'permanentemail'],
 4371: 					   $udom,$uname);
 4372: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 4373: 	return %loadnames;
 4374:     }
 4375: }
 4376: 
 4377: sub flush_email_cache {
 4378:     my ($uname,$udom)=@_;
 4379:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4380:     if (!$uname) { $uname=$env{'user.name'};   }
 4381:     return if ($udom eq 'public' && $uname eq 'public');
 4382:     my $id=$uname.':'.$udom;
 4383:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 4384: }
 4385: 
 4386: # -------------------------------------------------------------------- getlangs
 4387: 
 4388: =pod
 4389: 
 4390: =item * &getlangs($uname,$udom)
 4391: 
 4392: Gets a user's language preference and returns it as a hash with key:
 4393: language.
 4394: 
 4395: =cut
 4396: 
 4397: 
 4398: sub getlangs {
 4399:     my ($uname,$udom) = @_;
 4400:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4401:     if (!$uname) { $uname=$env{'user.name'};   }
 4402:     my $id=$uname.':'.$udom;
 4403:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 4404:     if ($cached) {
 4405:         return %{$langs};
 4406:     } else {
 4407:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 4408:                                            $udom,$uname);
 4409:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 4410:         return %loadlangs;
 4411:     }
 4412: }
 4413: 
 4414: sub flush_langs_cache {
 4415:     my ($uname,$udom)=@_;
 4416:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4417:     if (!$uname) { $uname=$env{'user.name'};   }
 4418:     return if ($udom eq 'public' && $uname eq 'public');
 4419:     my $id=$uname.':'.$udom;
 4420:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 4421: }
 4422: 
 4423: # ------------------------------------------------------------------ Screenname
 4424: 
 4425: =pod
 4426: 
 4427: =item * &screenname($uname,$udom)
 4428: 
 4429: Gets a users screenname and returns it as a string
 4430: 
 4431: =cut
 4432: 
 4433: sub screenname {
 4434:     my ($uname,$udom)=@_;
 4435:     if ($uname eq $env{'user.name'} &&
 4436: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 4437:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 4438:     return $names{'screenname'};
 4439: }
 4440: 
 4441: 
 4442: # ------------------------------------------------------------- Confirm Wrapper
 4443: =pod
 4444: 
 4445: =item * &confirmwrapper($message)
 4446: 
 4447: Wrap messages about completion of operation in box
 4448: 
 4449: =cut
 4450: 
 4451: sub confirmwrapper {
 4452:     my ($message)=@_;
 4453:     if ($message) {
 4454:         return "\n".'<div class="LC_confirm_box">'."\n"
 4455:                .$message."\n"
 4456:                .'</div>'."\n";
 4457:     } else {
 4458:         return $message;
 4459:     }
 4460: }
 4461: 
 4462: # ------------------------------------------------------------- Message Wrapper
 4463: 
 4464: sub messagewrapper {
 4465:     my ($link,$username,$domain,$subject,$text)=@_;
 4466:     return 
 4467:         '<a href="/adm/email?compose=individual&amp;'.
 4468:         'recname='.$username.'&amp;recdom='.$domain.
 4469: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 4470:         'title="'.&mt('Send message').'">'.$link.'</a>';
 4471: }
 4472: 
 4473: # --------------------------------------------------------------- Notes Wrapper
 4474: 
 4475: sub noteswrapper {
 4476:     my ($link,$un,$do)=@_;
 4477:     return 
 4478: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 4479: }
 4480: 
 4481: # ------------------------------------------------------------- Aboutme Wrapper
 4482: 
 4483: sub aboutmewrapper {
 4484:     my ($link,$username,$domain,$target,$class)=@_;
 4485:     if (!defined($username)  && !defined($domain)) {
 4486:         return;
 4487:     }
 4488:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 4489: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 4490: }
 4491: 
 4492: # ------------------------------------------------------------ Syllabus Wrapper
 4493: 
 4494: sub syllabuswrapper {
 4495:     my ($linktext,$coursedir,$domain)=@_;
 4496:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 4497: }
 4498: 
 4499: # -----------------------------------------------------------------------------
 4500: 
 4501: sub aboutme_on {
 4502:     my ($uname,$udom)=@_;
 4503:     unless ($uname) { $uname=$env{'user.name'}; }
 4504:     unless ($udom)  { $udom=$env{'user.domain'}; }
 4505:     return if ($udom eq 'public' && $uname eq 'public');
 4506:     my $hashkey=$uname.':'.$udom;
 4507:     my ($aboutme,$cached)=&Apache::lonnet::is_cached_new('aboutme',$hashkey);
 4508:     if ($cached) {
 4509:         return $aboutme;
 4510:     }
 4511:     $aboutme = &Apache::lonnet::usertools_access($uname,$udom,'aboutme');
 4512:     &Apache::lonnet::do_cache_new('aboutme',$hashkey,$aboutme,3600);
 4513:     return $aboutme;
 4514: }
 4515: 
 4516: sub devalidate_aboutme_cache {
 4517:     my ($uname,$udom)=@_;
 4518:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4519:     if (!$uname) { $uname=$env{'user.name'};   }
 4520:     return if ($udom eq 'public' && $uname eq 'public');
 4521:     my $id=$uname.':'.$udom;
 4522:     &Apache::lonnet::devalidate_cache_new('aboutme',$id);
 4523: }
 4524: 
 4525: sub track_student_link {
 4526:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 4527:     my $link ="/adm/trackstudent?";
 4528:     my $title = 'View recent activity';
 4529:     if (defined($sname) && $sname !~ /^\s*$/ &&
 4530:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 4531:         $link .= "selected_student=$sname:$sdom";
 4532:         $title .= ' of this student';
 4533:     } 
 4534:     if (defined($target) && $target !~ /^\s*$/) {
 4535:         $target = qq{target="$target"};
 4536:     } else {
 4537:         $target = '';
 4538:     }
 4539:     if ($start) { $link.='&amp;start='.$start; }
 4540:     if ($only_body) { $link .= '&amp;only_body=1'; }
 4541:     $title = &mt($title);
 4542:     $linktext = &mt($linktext);
 4543:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 4544: 	&help_open_topic('View_recent_activity');
 4545: }
 4546: 
 4547: sub slot_reservations_link {
 4548:     my ($linktext,$sname,$sdom,$target) = @_;
 4549:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 4550:     my $title = 'View slot reservation history';
 4551:     if (defined($sname) && $sname !~ /^\s*$/ &&
 4552:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 4553:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 4554:         $title .= ' of this student';
 4555:     }
 4556:     if (defined($target) && $target !~ /^\s*$/) {
 4557:         $target = qq{target="$target"};
 4558:     } else {
 4559:         $target = '';
 4560:     }
 4561:     $title = &mt($title);
 4562:     $linktext = &mt($linktext);
 4563:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 4564: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 4565: 
 4566: }
 4567: 
 4568: # ===================================================== Display a student photo
 4569: 
 4570: 
 4571: sub student_image_tag {
 4572:     my ($domain,$user)=@_;
 4573:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 4574:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 4575: 	return '<img src="'.$imgsrc.'" align="right" />';
 4576:     } else {
 4577: 	return '';
 4578:     }
 4579: }
 4580: 
 4581: =pod
 4582: 
 4583: =back
 4584: 
 4585: =head1 Access .tab File Data
 4586: 
 4587: =over 4
 4588: 
 4589: =item * &languageids() 
 4590: 
 4591: returns list of all language ids
 4592: 
 4593: =cut
 4594: 
 4595: sub languageids {
 4596:     return sort(keys(%language));
 4597: }
 4598: 
 4599: =pod
 4600: 
 4601: =item * &languagedescription() 
 4602: 
 4603: returns description of a specified language id
 4604: 
 4605: =cut
 4606: 
 4607: sub languagedescription {
 4608:     my $code=shift;
 4609:     return  ($supported_language{$code}?'* ':'').
 4610:             $language{$code}.
 4611: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 4612: }
 4613: 
 4614: =pod
 4615: 
 4616: =item * &plainlanguagedescription
 4617: 
 4618: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 4619: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 4620: 
 4621: =cut
 4622: 
 4623: sub plainlanguagedescription {
 4624:     my $code=shift;
 4625:     return $language{$code};
 4626: }
 4627: 
 4628: =pod
 4629: 
 4630: =item * &supportedlanguagecode
 4631: 
 4632: Returns the supported language code (e.g. sptutf maps to pt) given a language
 4633: code.
 4634: 
 4635: =cut
 4636: 
 4637: sub supportedlanguagecode {
 4638:     my $code=shift;
 4639:     return $supported_language{$code};
 4640: }
 4641: 
 4642: =pod
 4643: 
 4644: =item * &latexlanguage()
 4645: 
 4646: Given a language key code returns the correspondnig language to use
 4647: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 4648: is no supported hyphenation for the language code.
 4649: 
 4650: =cut
 4651: 
 4652: sub latexlanguage {
 4653:     my $code = shift;
 4654:     return $latex_language{$code};
 4655: }
 4656: 
 4657: =pod
 4658: 
 4659: =item * &latexhyphenation()
 4660: 
 4661: Same as above but what's supplied is the language as it might be stored
 4662: in the metadata.
 4663: 
 4664: =cut
 4665: 
 4666: sub latexhyphenation {
 4667:     my $key = shift;
 4668:     return $latex_language_bykey{$key};
 4669: }
 4670: 
 4671: =pod
 4672: 
 4673: =item * &copyrightids() 
 4674: 
 4675: returns list of all copyrights
 4676: 
 4677: =cut
 4678: 
 4679: sub copyrightids {
 4680:     return sort(keys(%cprtag));
 4681: }
 4682: 
 4683: =pod
 4684: 
 4685: =item * &copyrightdescription() 
 4686: 
 4687: returns description of a specified copyright id
 4688: 
 4689: =cut
 4690: 
 4691: sub copyrightdescription {
 4692:     return &mt($cprtag{shift(@_)});
 4693: }
 4694: 
 4695: =pod
 4696: 
 4697: =item * &source_copyrightids() 
 4698: 
 4699: returns list of all source copyrights
 4700: 
 4701: =cut
 4702: 
 4703: sub source_copyrightids {
 4704:     return sort(keys(%scprtag));
 4705: }
 4706: 
 4707: =pod
 4708: 
 4709: =item * &source_copyrightdescription() 
 4710: 
 4711: returns description of a specified source copyright id
 4712: 
 4713: =cut
 4714: 
 4715: sub source_copyrightdescription {
 4716:     return &mt($scprtag{shift(@_)});
 4717: }
 4718: 
 4719: =pod
 4720: 
 4721: =item * &filecategories() 
 4722: 
 4723: returns list of all file categories
 4724: 
 4725: =cut
 4726: 
 4727: sub filecategories {
 4728:     return sort(keys(%category_extensions));
 4729: }
 4730: 
 4731: =pod
 4732: 
 4733: =item * &filecategorytypes() 
 4734: 
 4735: returns list of file types belonging to a given file
 4736: category
 4737: 
 4738: =cut
 4739: 
 4740: sub filecategorytypes {
 4741:     my ($cat) = @_;
 4742:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
 4743:         return @{$category_extensions{lc($cat)}};
 4744:     } else {
 4745:         return ();
 4746:     }
 4747: }
 4748: 
 4749: =pod
 4750: 
 4751: =item * &fileembstyle() 
 4752: 
 4753: returns embedding style for a specified file type
 4754: 
 4755: =cut
 4756: 
 4757: sub fileembstyle {
 4758:     return $fe{lc(shift(@_))};
 4759: }
 4760: 
 4761: sub filemimetype {
 4762:     return $fm{lc(shift(@_))};
 4763: }
 4764: 
 4765: 
 4766: sub filecategoryselect {
 4767:     my ($name,$value)=@_;
 4768:     return &select_form($value,$name,
 4769:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 4770: }
 4771: 
 4772: =pod
 4773: 
 4774: =item * &filedescription() 
 4775: 
 4776: returns description for a specified file type
 4777: 
 4778: =cut
 4779: 
 4780: sub filedescription {
 4781:     my $file_description = $fd{lc(shift())};
 4782:     $file_description =~ s:([\[\]]):~$1:g;
 4783:     return &mt($file_description);
 4784: }
 4785: 
 4786: =pod
 4787: 
 4788: =item * &filedescriptionex() 
 4789: 
 4790: returns description for a specified file type with
 4791: extra formatting
 4792: 
 4793: =cut
 4794: 
 4795: sub filedescriptionex {
 4796:     my $ex=shift;
 4797:     my $file_description = $fd{lc($ex)};
 4798:     $file_description =~ s:([\[\]]):~$1:g;
 4799:     return '.'.$ex.' '.&mt($file_description);
 4800: }
 4801: 
 4802: # End of .tab access
 4803: =pod
 4804: 
 4805: =back
 4806: 
 4807: =cut
 4808: 
 4809: # ------------------------------------------------------------------ File Types
 4810: sub fileextensions {
 4811:     return sort(keys(%fe));
 4812: }
 4813: 
 4814: # ----------------------------------------------------------- Display Languages
 4815: # returns a hash with all desired display languages
 4816: #
 4817: 
 4818: sub display_languages {
 4819:     my %languages=();
 4820:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 4821: 	$languages{$lang}=1;
 4822:     }
 4823:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 4824:     if ($env{'form.displaylanguage'}) {
 4825: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 4826: 	    $languages{$lang}=1;
 4827:         }
 4828:     }
 4829:     return %languages;
 4830: }
 4831: 
 4832: sub languages {
 4833:     my ($possible_langs) = @_;
 4834:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 4835:     if (!ref($possible_langs)) {
 4836: 	if( wantarray ) {
 4837: 	    return @preferred_langs;
 4838: 	} else {
 4839: 	    return $preferred_langs[0];
 4840: 	}
 4841:     }
 4842:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 4843:     my @preferred_possibilities;
 4844:     foreach my $preferred_lang (@preferred_langs) {
 4845: 	if (exists($possibilities{$preferred_lang})) {
 4846: 	    push(@preferred_possibilities, $preferred_lang);
 4847: 	}
 4848:     }
 4849:     if( wantarray ) {
 4850: 	return @preferred_possibilities;
 4851:     }
 4852:     return $preferred_possibilities[0];
 4853: }
 4854: 
 4855: sub user_lang {
 4856:     my ($touname,$toudom,$fromcid) = @_;
 4857:     my @userlangs;
 4858:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 4859:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 4860:                     $env{'course.'.$fromcid.'.languages'}));
 4861:     } else {
 4862:         my %langhash = &getlangs($touname,$toudom);
 4863:         if ($langhash{'languages'} ne '') {
 4864:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 4865:         } else {
 4866:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 4867:             if ($domdefs{'lang_def'} ne '') {
 4868:                 @userlangs = ($domdefs{'lang_def'});
 4869:             }
 4870:         }
 4871:     }
 4872:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 4873:     my $user_lh = Apache::localize->get_handle(@languages);
 4874:     return $user_lh;
 4875: }
 4876: 
 4877: 
 4878: ###############################################################
 4879: ##               Student Answer Attempts                     ##
 4880: ###############################################################
 4881: 
 4882: =pod
 4883: 
 4884: =head1 Alternate Problem Views
 4885: 
 4886: =over 4
 4887: 
 4888: =item * &get_previous_attempt($symb, $username, $domain, $course,
 4889:     $getattempt, $regexp, $gradesub, $usec, $identifier)
 4890: 
 4891: Return string with previous attempt on problem. Arguments:
 4892: 
 4893: =over 4
 4894: 
 4895: =item * $symb: Problem, including path
 4896: 
 4897: =item * $username: username of the desired student
 4898: 
 4899: =item * $domain: domain of the desired student
 4900: 
 4901: =item * $course: Course ID
 4902: 
 4903: =item * $getattempt: Leave blank for all attempts, otherwise put
 4904:     something
 4905: 
 4906: =item * $regexp: if string matches this regexp, the string will be
 4907:     sent to $gradesub
 4908: 
 4909: =item * $gradesub: routine that processes the string if it matches $regexp
 4910: 
 4911: =item * $usec: section of the desired student
 4912: 
 4913: =item * $identifier: counter for student (multiple students one problem) or 
 4914:     problem (one student; whole sequence).
 4915: 
 4916: =back
 4917: 
 4918: The output string is a table containing all desired attempts, if any.
 4919: 
 4920: =cut
 4921: 
 4922: sub get_previous_attempt {
 4923:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
 4924:   my $prevattempts='';
 4925:   no strict 'refs';
 4926:   if ($symb) {
 4927:     my (%returnhash)=
 4928:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 4929:     if ($returnhash{'version'}) {
 4930:       my %lasthash=();
 4931:       my $version;
 4932:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 4933:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
 4934:             if ($key =~ /\.rawrndseed$/) {
 4935:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
 4936:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
 4937:             } else {
 4938:                 $lasthash{$key}=$returnhash{$version.':'.$key};
 4939:             }
 4940:         }
 4941:       }
 4942:       $prevattempts=&start_data_table().&start_data_table_header_row();
 4943:       $prevattempts.='<th>'.&mt('History').'</th>';
 4944:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
 4945:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 4946:       foreach my $key (sort(keys(%lasthash))) {
 4947: 	my ($ign,@parts) = split(/\./,$key);
 4948: 	if ($#parts > 0) {
 4949: 	  my $data=$parts[-1];
 4950:           next if ($data eq 'foilorder');
 4951: 	  pop(@parts);
 4952:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 4953:           if ($data eq 'type') {
 4954:               unless ($showsurv) {
 4955:                   my $id = join(',',@parts);
 4956:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 4957:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 4958:                       $lasthidden{$ign.'.'.$id} = 1;
 4959:                   }
 4960:               }
 4961:               if ($identifier ne '') {
 4962:                   my $id = join(',',@parts);
 4963:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
 4964:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
 4965:                       $hidestatus{$ign.'.'.$id} = 1;
 4966:                   }
 4967:               }
 4968:           } elsif ($data eq 'regrader') {
 4969:               if (($identifier ne '') && (@parts)) {
 4970:                   my $id = join(',',@parts);
 4971:                   $regraded{$ign.'.'.$id} = 1;
 4972:               }
 4973:           } 
 4974: 	} else {
 4975: 	  if ($#parts == 0) {
 4976: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 4977: 	  } else {
 4978: 	    $prevattempts.='<th>'.$ign.'</th>';
 4979: 	  }
 4980: 	}
 4981:       }
 4982:       $prevattempts.=&end_data_table_header_row();
 4983:       if ($getattempt eq '') {
 4984:         my (%solved,%resets,%probstatus);
 4985:         if (($identifier ne '') && (keys(%regraded) > 0)) {
 4986:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 4987:                 foreach my $id (keys(%regraded)) {
 4988:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
 4989:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
 4990:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
 4991:                         push(@{$resets{$id}},$version);
 4992:                     }
 4993:                 }
 4994:             }
 4995:         }
 4996: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 4997:             my (@hidden,@unsolved);
 4998:             if (%typeparts) {
 4999:                 foreach my $id (keys(%typeparts)) {
 5000:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
 5001:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 5002:                         push(@hidden,$id);
 5003:                     } elsif ($identifier ne '') {
 5004:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
 5005:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
 5006:                                 ($hidestatus{$id})) {
 5007:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
 5008:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
 5009:                                 push(@{$solved{$id}},$version);
 5010:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
 5011:                                      (ref($solved{$id}) eq 'ARRAY')) {
 5012:                                 my $skip;
 5013:                                 if (ref($resets{$id}) eq 'ARRAY') {
 5014:                                     foreach my $reset (@{$resets{$id}}) {
 5015:                                         if ($reset > $solved{$id}[-1]) {
 5016:                                             $skip=1;
 5017:                                             last;
 5018:                                         }
 5019:                                     }
 5020:                                 }
 5021:                                 unless ($skip) {
 5022:                                     my ($ign,$partslist) = split(/\./,$id,2);
 5023:                                     push(@unsolved,$partslist);
 5024:                                 }
 5025:                             }
 5026:                         }
 5027:                     }
 5028:                 }
 5029:             }
 5030:             $prevattempts.=&start_data_table_row().
 5031:                            '<td>'.&mt('Transaction [_1]',$version);
 5032:             if (@unsolved) {
 5033:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
 5034:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
 5035:                                  &mt('Hide').'</label></span>';
 5036:             }
 5037:             $prevattempts .= '</td>';
 5038:             if (@hidden) {
 5039:                 foreach my $key (sort(keys(%lasthash))) {
 5040:                     next if ($key =~ /\.foilorder$/);
 5041:                     my $hide;
 5042:                     foreach my $id (@hidden) {
 5043:                         if ($key =~ /^\Q$id\E/) {
 5044:                             $hide = 1;
 5045:                             last;
 5046:                         }
 5047:                     }
 5048:                     if ($hide) {
 5049:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 5050:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 5051:                             my $value = &format_previous_attempt_value($key,
 5052:                                              $returnhash{$version.':'.$key});
 5053:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 5054:                         } else {
 5055:                             $prevattempts.='<td>&nbsp;</td>';
 5056:                         }
 5057:                     } else {
 5058:                         if ($key =~ /\./) {
 5059:                             my $value = $returnhash{$version.':'.$key};
 5060:                             if ($key =~ /\.rndseed$/) {
 5061:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 5062:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 5063:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 5064:                                 }
 5065:                             }
 5066:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 5067:                                            '&nbsp;</td>';
 5068:                         } else {
 5069:                             $prevattempts.='<td>&nbsp;</td>';
 5070:                         }
 5071:                     }
 5072:                 }
 5073:             } else {
 5074: 	        foreach my $key (sort(keys(%lasthash))) {
 5075:                     next if ($key =~ /\.foilorder$/);
 5076:                     my $value = $returnhash{$version.':'.$key};
 5077:                     if ($key =~ /\.rndseed$/) {
 5078:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 5079:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 5080:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 5081:                         }
 5082:                     }
 5083:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 5084:                                    '&nbsp;</td>';
 5085: 	        }
 5086:             }
 5087: 	    $prevattempts.=&end_data_table_row();
 5088: 	 }
 5089:       }
 5090:       my @currhidden = keys(%lasthidden);
 5091:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 5092:       foreach my $key (sort(keys(%lasthash))) {
 5093:           next if ($key =~ /\.foilorder$/);
 5094:           if (%typeparts) {
 5095:               my $hidden;
 5096:               foreach my $id (@currhidden) {
 5097:                   if ($key =~ /^\Q$id\E/) {
 5098:                       $hidden = 1;
 5099:                       last;
 5100:                   }
 5101:               }
 5102:               if ($hidden) {
 5103:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 5104:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 5105:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 5106:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 5107:                           $value = &$gradesub($value);
 5108:                       }
 5109:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
 5110:                   } else {
 5111:                       $prevattempts.='<td>&nbsp;</td>';
 5112:                   }
 5113:               } else {
 5114:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 5115:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 5116:                       $value = &$gradesub($value);
 5117:                   }
 5118:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 5119:               }
 5120:           } else {
 5121: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 5122: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 5123:                   $value = &$gradesub($value);
 5124:               }
 5125: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
 5126:           }
 5127:       }
 5128:       $prevattempts.= &end_data_table_row().&end_data_table();
 5129:     } else {
 5130:       my $msg;
 5131:       if ($symb =~ /ext\.tool$/) {
 5132:           $msg = &mt('No grade passed back.');
 5133:       } else {
 5134:           $msg = &mt('Nothing submitted - no attempts.');
 5135:       }
 5136:       $prevattempts=
 5137: 	  &start_data_table().&start_data_table_row().
 5138: 	  '<td>'.$msg.'</td>'.
 5139: 	  &end_data_table_row().&end_data_table();
 5140:     }
 5141:   } else {
 5142:     $prevattempts=
 5143: 	  &start_data_table().&start_data_table_row().
 5144: 	  '<td>'.&mt('No data.').'</td>'.
 5145: 	  &end_data_table_row().&end_data_table();
 5146:   }
 5147: }
 5148: 
 5149: sub format_previous_attempt_value {
 5150:     my ($key,$value) = @_;
 5151:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 5152:         $value = &Apache::lonlocal::locallocaltime($value);
 5153:     } elsif (ref($value) eq 'ARRAY') {
 5154:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
 5155:     } elsif ($key =~ /answerstring$/) {
 5156:         my %answers = &Apache::lonnet::str2hash($value);
 5157:         my @answer = %answers;
 5158:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
 5159:         my @anskeys = sort(keys(%answers));
 5160:         if (@anskeys == 1) {
 5161:             my $answer = $answers{$anskeys[0]};
 5162:             if ($answer =~ m{\0}) {
 5163:                 $answer =~ s{\0}{,}g;
 5164:             }
 5165:             my $tag_internal_answer_name = 'INTERNAL';
 5166:             if ($anskeys[0] eq $tag_internal_answer_name) {
 5167:                 $value = $answer; 
 5168:             } else {
 5169:                 $value = $anskeys[0].'='.$answer;
 5170:             }
 5171:         } else {
 5172:             foreach my $ans (@anskeys) {
 5173:                 my $answer = $answers{$ans};
 5174:                 if ($answer =~ m{\0}) {
 5175:                     $answer =~ s{\0}{,}g;
 5176:                 }
 5177:                 $value .=  $ans.'='.$answer.'<br />';;
 5178:             } 
 5179:         }
 5180:     } else {
 5181:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
 5182:     }
 5183:     return $value;
 5184: }
 5185: 
 5186: 
 5187: sub relative_to_absolute {
 5188:     my ($url,$output)=@_;
 5189:     my $parser=HTML::TokeParser->new(\$output);
 5190:     my $token;
 5191:     my $thisdir=$url;
 5192:     my @rlinks=();
 5193:     while ($token=$parser->get_token) {
 5194: 	if ($token->[0] eq 'S') {
 5195: 	    if ($token->[1] eq 'a') {
 5196: 		if ($token->[2]->{'href'}) {
 5197: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 5198: 		}
 5199: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 5200: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 5201: 	    } elsif ($token->[1] eq 'base') {
 5202: 		$thisdir=$token->[2]->{'href'};
 5203: 	    }
 5204: 	}
 5205:     }
 5206:     $thisdir=~s-/[^/]*$--;
 5207:     foreach my $link (@rlinks) {
 5208: 	unless (($link=~/^https?\:\/\//i) ||
 5209: 		($link=~/^\//) ||
 5210: 		($link=~/^javascript:/i) ||
 5211: 		($link=~/^mailto:/i) ||
 5212: 		($link=~/^\#/)) {
 5213: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 5214: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 5215: 	}
 5216:     }
 5217: # -------------------------------------------------- Deal with Applet codebases
 5218:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 5219:     return $output;
 5220: }
 5221: 
 5222: =pod
 5223: 
 5224: =item * &get_student_view()
 5225: 
 5226: show a snapshot of what student was looking at
 5227: 
 5228: =cut
 5229: 
 5230: sub get_student_view {
 5231:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 5232:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 5233:   my (%form);
 5234:   my @elements=('symb','courseid','domain','username');
 5235:   foreach my $element (@elements) {
 5236:       $form{'grade_'.$element}=eval '$'.$element #'
 5237:   }
 5238:   if (defined($moreenv)) {
 5239:       %form=(%form,%{$moreenv});
 5240:   }
 5241:   if (defined($target)) { $form{'grade_target'} = $target; }
 5242:   $feedurl=&Apache::lonnet::clutter($feedurl);
 5243:   if (($feedurl =~ /ext\.tool$/) && ($target eq 'tex')) {
 5244:       $feedurl =~ s{^/adm/wrapper}{};
 5245:   }
 5246:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 5247:   $userview=~s/\<body[^\>]*\>//gi;
 5248:   $userview=~s/\<\/body\>//gi;
 5249:   $userview=~s/\<html\>//gi;
 5250:   $userview=~s/\<\/html\>//gi;
 5251:   $userview=~s/\<head\>//gi;
 5252:   $userview=~s/\<\/head\>//gi;
 5253:   $userview=~s/action\s*\=/would_be_action\=/gi;
 5254:   $userview=&relative_to_absolute($feedurl,$userview);
 5255:   if (wantarray) {
 5256:      return ($userview,$response);
 5257:   } else {
 5258:      return $userview;
 5259:   }
 5260: }
 5261: 
 5262: sub get_student_view_with_retries {
 5263:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 5264: 
 5265:     my $ok = 0;                 # True if we got a good response.
 5266:     my $content;
 5267:     my $response;
 5268: 
 5269:     # Try to get the student_view done. within the retries count:
 5270:     
 5271:     do {
 5272:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 5273:          $ok      = $response->is_success;
 5274:          if (!$ok) {
 5275:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 5276:          }
 5277:          $retries--;
 5278:     } while (!$ok && ($retries > 0));
 5279:     
 5280:     if (!$ok) {
 5281:        $content = '';          # On error return an empty content.
 5282:     }
 5283:     if (wantarray) {
 5284:        return ($content, $response);
 5285:     } else {
 5286:        return $content;
 5287:     }
 5288: }
 5289: 
 5290: sub css_links {
 5291:     my ($currsymb,$level) = @_;
 5292:     my ($links,@symbs,%cssrefs,%httpref);
 5293:     if ($level eq 'map') {
 5294:         my $navmap = Apache::lonnavmaps::navmap->new();
 5295:         if (ref($navmap)) {
 5296:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
 5297:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
 5298:             foreach my $res (@resources) {
 5299:                 if (ref($res) && $res->symb()) {
 5300:                     push(@symbs,$res->symb());
 5301:                 }
 5302:             }
 5303:         }
 5304:     } else {
 5305:         @symbs = ($currsymb);
 5306:     }
 5307:     foreach my $symb (@symbs) {
 5308:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
 5309:         if ($css_href =~ /\S/) {
 5310:             unless ($css_href =~ m{https?://}) {
 5311:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
 5312:                 my $proburl =  &Apache::lonnet::clutter($url);
 5313:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
 5314:                 unless ($css_href =~ m{^/}) {
 5315:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
 5316:                 }
 5317:                 if ($css_href =~ m{^/(res|uploaded)/}) {
 5318:                     unless (($httpref{'httpref.'.$css_href}) ||
 5319:                             (&Apache::lonnet::is_on_map($css_href))) {
 5320:                         my $thisurl = $proburl;
 5321:                         if ($env{'httpref.'.$proburl}) {
 5322:                             $thisurl = $env{'httpref.'.$proburl};
 5323:                         }
 5324:                         $httpref{'httpref.'.$css_href} = $thisurl;
 5325:                     }
 5326:                 }
 5327:             }
 5328:             $cssrefs{$css_href} = 1;
 5329:         }
 5330:     }
 5331:     if (keys(%httpref)) {
 5332:         &Apache::lonnet::appenv(\%httpref);
 5333:     }
 5334:     if (keys(%cssrefs)) {
 5335:         foreach my $css_href (keys(%cssrefs)) {
 5336:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
 5337:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
 5338:         }
 5339:     }
 5340:     return $links;
 5341: }
 5342: 
 5343: =pod
 5344: 
 5345: =item * &get_student_answers() 
 5346: 
 5347: show a snapshot of how student was answering problem
 5348: 
 5349: =cut
 5350: 
 5351: sub get_student_answers {
 5352:   my ($symb,$username,$domain,$courseid,%form) = @_;
 5353:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 5354:   my (%moreenv);
 5355:   my @elements=('symb','courseid','domain','username');
 5356:   foreach my $element (@elements) {
 5357:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 5358:   }
 5359:   $moreenv{'grade_target'}='answer';
 5360:   %moreenv=(%form,%moreenv);
 5361:   $feedurl = &Apache::lonnet::clutter($feedurl);
 5362:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 5363:   return $userview;
 5364: }
 5365: 
 5366: =pod
 5367: 
 5368: =item * &submlink()
 5369: 
 5370: Inputs: $text $uname $udom $symb $target
 5371: 
 5372: Returns: A link to grades.pm such as to see the SUBM view of a student
 5373: 
 5374: =cut
 5375: 
 5376: ###############################################
 5377: sub submlink {
 5378:     my ($text,$uname,$udom,$symb,$target)=@_;
 5379:     if (!($uname && $udom)) {
 5380: 	(my $cursymb, my $courseid,$udom,$uname)=
 5381: 	    &Apache::lonnet::whichuser($symb);
 5382: 	if (!$symb) { $symb=$cursymb; }
 5383:     }
 5384:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 5385:     $symb=&escape($symb);
 5386:     if ($target) { $target=" target=\"$target\""; }
 5387:     return
 5388:         '<a href="/adm/grades?command=submission'.
 5389:         '&amp;symb='.$symb.
 5390:         '&amp;student='.$uname.
 5391:         '&amp;userdom='.$udom.'"'.
 5392:         $target.'>'.$text.'</a>';
 5393: }
 5394: ##############################################
 5395: 
 5396: =pod
 5397: 
 5398: =item * &pgrdlink()
 5399: 
 5400: Inputs: $text $uname $udom $symb $target
 5401: 
 5402: Returns: A link to grades.pm such as to see the PGRD view of a student
 5403: 
 5404: =cut
 5405: 
 5406: ###############################################
 5407: sub pgrdlink {
 5408:     my $link=&submlink(@_);
 5409:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 5410:     return $link;
 5411: }
 5412: ##############################################
 5413: 
 5414: =pod
 5415: 
 5416: =item * &pprmlink()
 5417: 
 5418: Inputs: $text $uname $udom $symb $target
 5419: 
 5420: Returns: A link to parmset.pm such as to see the PPRM view of a
 5421: student and a specific resource
 5422: 
 5423: =cut
 5424: 
 5425: ###############################################
 5426: sub pprmlink {
 5427:     my ($text,$uname,$udom,$symb,$target)=@_;
 5428:     if (!($uname && $udom)) {
 5429: 	(my $cursymb, my $courseid,$udom,$uname)=
 5430: 	    &Apache::lonnet::whichuser($symb);
 5431: 	if (!$symb) { $symb=$cursymb; }
 5432:     }
 5433:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 5434:     $symb=&escape($symb);
 5435:     if ($target) { $target="target=\"$target\""; }
 5436:     return '<a href="/adm/parmset?command=set&amp;'.
 5437: 	'symb='.$symb.'&amp;uname='.$uname.
 5438: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 5439: }
 5440: ##############################################
 5441: 
 5442: =pod
 5443: 
 5444: =back
 5445: 
 5446: =cut
 5447: 
 5448: ###############################################
 5449: 
 5450: 
 5451: sub timehash {
 5452:     my ($thistime) = @_;
 5453:     my $timezone = &Apache::lonlocal::gettimezone();
 5454:     my $dt = DateTime->from_epoch(epoch => $thistime)
 5455:                      ->set_time_zone($timezone);
 5456:     my $wday = $dt->day_of_week();
 5457:     if ($wday == 7) { $wday = 0; }
 5458:     return ( 'second' => $dt->second(),
 5459:              'minute' => $dt->minute(),
 5460:              'hour'   => $dt->hour(),
 5461:              'day'     => $dt->day_of_month(),
 5462:              'month'   => $dt->month(),
 5463:              'year'    => $dt->year(),
 5464:              'weekday' => $wday,
 5465:              'dayyear' => $dt->day_of_year(),
 5466:              'dlsav'   => $dt->is_dst() );
 5467: }
 5468: 
 5469: sub utc_string {
 5470:     my ($date)=@_;
 5471:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 5472: }
 5473: 
 5474: sub maketime {
 5475:     my %th=@_;
 5476:     my ($epoch_time,$timezone,$dt);
 5477:     $timezone = &Apache::lonlocal::gettimezone();
 5478:     eval {
 5479:         $dt = DateTime->new( year   => $th{'year'},
 5480:                              month  => $th{'month'},
 5481:                              day    => $th{'day'},
 5482:                              hour   => $th{'hour'},
 5483:                              minute => $th{'minute'},
 5484:                              second => $th{'second'},
 5485:                              time_zone => $timezone,
 5486:                          );
 5487:     };
 5488:     if (!$@) {
 5489:         $epoch_time = $dt->epoch;
 5490:         if ($epoch_time) {
 5491:             return $epoch_time;
 5492:         }
 5493:     }
 5494:     return POSIX::mktime(
 5495:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 5496:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 5497: }
 5498: 
 5499: #########################################
 5500: 
 5501: sub findallcourses {
 5502:     my ($roles,$uname,$udom) = @_;
 5503:     my %roles;
 5504:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 5505:     my %courses;
 5506:     my $now=time;
 5507:     if (!defined($uname)) {
 5508:         $uname = $env{'user.name'};
 5509:     }
 5510:     if (!defined($udom)) {
 5511:         $udom = $env{'user.domain'};
 5512:     }
 5513:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 5514:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 5515:         if (!%roles) {
 5516:             %roles = (
 5517:                        cc => 1,
 5518:                        co => 1,
 5519:                        in => 1,
 5520:                        ep => 1,
 5521:                        ta => 1,
 5522:                        cr => 1,
 5523:                        st => 1,
 5524:              );
 5525:         }
 5526:         foreach my $entry (keys(%roleshash)) {
 5527:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 5528:             if ($trole =~ /^cr/) { 
 5529:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 5530:             } else {
 5531:                 next if (!exists($roles{$trole}));
 5532:             }
 5533:             if ($tend) {
 5534:                 next if ($tend < $now);
 5535:             }
 5536:             if ($tstart) {
 5537:                 next if ($tstart > $now);
 5538:             }
 5539:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 5540:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 5541:             my $value = $trole.'/'.$cdom.'/';
 5542:             if ($secpart eq '') {
 5543:                 ($cnum,$role) = split(/_/,$cnumpart); 
 5544:                 $sec = 'none';
 5545:                 $value .= $cnum.'/';
 5546:             } else {
 5547:                 $cnum = $cnumpart;
 5548:                 ($sec,$role) = split(/_/,$secpart);
 5549:                 $value .= $cnum.'/'.$sec;
 5550:             }
 5551:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 5552:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 5553:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 5554:                 }
 5555:             } else {
 5556:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 5557:             }
 5558:         }
 5559:     } else {
 5560:         foreach my $key (keys(%env)) {
 5561: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 5562:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 5563: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 5564: 	        next if ($role eq 'ca' || $role eq 'aa');
 5565: 	        next if (%roles && !exists($roles{$role}));
 5566: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 5567:                 my $active=1;
 5568:                 if ($starttime) {
 5569: 		    if ($now<$starttime) { $active=0; }
 5570:                 }
 5571:                 if ($endtime) {
 5572:                     if ($now>$endtime) { $active=0; }
 5573:                 }
 5574:                 if ($active) {
 5575:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 5576:                     if ($sec eq '') {
 5577:                         $sec = 'none';
 5578:                     } else {
 5579:                         $value .= $sec;
 5580:                     }
 5581:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 5582:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 5583:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 5584:                         }
 5585:                     } else {
 5586:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 5587:                     }
 5588:                 }
 5589:             }
 5590:         }
 5591:     }
 5592:     return %courses;
 5593: }
 5594: 
 5595: ###############################################
 5596: 
 5597: sub blockcheck {
 5598:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
 5599:     unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
 5600:         my ($has_evb,$check_ipaccess);
 5601:         my $dom = $env{'user.domain'};
 5602:         if ($env{'request.course.id'}) {
 5603:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5604:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5605:             my $checkrole = "cm./$cdom/$cnum";
 5606:             my $sec = $env{'request.course.sec'};
 5607:             if ($sec ne '') {
 5608:                 $checkrole .= "/$sec";
 5609:             }
 5610:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 5611:                 ($env{'request.role'} !~ /^st/)) {
 5612:                 $has_evb = 1;
 5613:             }
 5614:             unless ($has_evb) {
 5615:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
 5616:                     ($activity eq 'boards') || ($activity eq 'groups') || ($activity eq 'chat')) {
 5617:                     if ($udom eq $cdom) {
 5618:                         $check_ipaccess = 1;
 5619:                     }
 5620:                 }
 5621:             }
 5622:         } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
 5623:                 ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
 5624:             my $checkrole;
 5625:             if ($env{'request.role.domain'} eq '') {
 5626:                 $checkrole = "cm./$env{'user.domain'}/";
 5627:             } else {
 5628:                 $checkrole = "cm./$env{'request.role.domain'}/";
 5629:             }
 5630:             if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
 5631:                 $has_evb = 1;
 5632:             }
 5633:         }
 5634:         unless ($has_evb || $check_ipaccess) {
 5635:             my @machinedoms = &Apache::lonnet::current_machine_domains();
 5636:             if (($dom eq 'public') && ($activity eq 'port')) {
 5637:                 $dom = $udom;
 5638:             }
 5639:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
 5640:                 $check_ipaccess = 1;
 5641:             } else {
 5642:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 5643:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
 5644:                 my $prim = &Apache::lonnet::domain($dom,'primary');
 5645:                 my $intdom = &Apache::lonnet::internet_dom($prim);
 5646:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
 5647:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
 5648:                         $check_ipaccess = 1;
 5649:                     }
 5650:                 }
 5651:             }
 5652:         }
 5653:         if ($check_ipaccess) {
 5654:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
 5655:             unless (defined($cached)) {
 5656:                 my %domconfig =
 5657:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
 5658:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
 5659:             }
 5660:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
 5661:                 foreach my $id (keys(%{$ipaccessref})) {
 5662:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
 5663:                         my $range = $ipaccessref->{$id}->{'ip'};
 5664:                         if ($range) {
 5665:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
 5666:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
 5667:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
 5668:                                         return ('','','',$id,$dom);
 5669:                                         last;
 5670:                                     }
 5671:                                 }
 5672:                             }
 5673:                         }
 5674:                     }
 5675:                 }
 5676:             }
 5677:         }
 5678:         if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
 5679:             return ();
 5680:         }
 5681:     }
 5682:     if (defined($udom) && defined($uname)) {
 5683:         # If uname and udom are for a course, check for blocks in the course.
 5684:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
 5685:             my ($startblock,$endblock,$triggerblock) =
 5686:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
 5687:             return ($startblock,$endblock,$triggerblock);
 5688:         }
 5689:     } else {
 5690:         $udom = $env{'user.domain'};
 5691:         $uname = $env{'user.name'};
 5692:     }
 5693: 
 5694:     my $startblock = 0;
 5695:     my $endblock = 0;
 5696:     my $triggerblock = '';
 5697:     my %live_courses;
 5698:     unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
 5699:         %live_courses = &findallcourses(undef,$uname,$udom);
 5700:     }
 5701: 
 5702:     # If uname is for a user, and activity is course-specific, i.e.,
 5703:     # boards, chat or groups, check for blocking in current course only.
 5704: 
 5705:     if (($activity eq 'boards' || $activity eq 'chat' ||
 5706:          $activity eq 'groups' || $activity eq 'printout' ||
 5707:          $activity eq 'search' || $activity eq 'reinit' ||
 5708:          $activity eq 'alert') &&
 5709:         ($env{'request.course.id'})) {
 5710:         foreach my $key (keys(%live_courses)) {
 5711:             if ($key ne $env{'request.course.id'}) {
 5712:                 delete($live_courses{$key});
 5713:             }
 5714:         }
 5715:     }
 5716: 
 5717:     my $otheruser = 0;
 5718:     my %own_courses;
 5719:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 5720:         # Resource belongs to user other than current user.
 5721:         $otheruser = 1;
 5722:         # Gather courses for current user
 5723:         %own_courses = 
 5724:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 5725:     }
 5726: 
 5727:     # Gather active course roles - course coordinator, instructor, 
 5728:     # exam proctor, ta, student, or custom role.
 5729: 
 5730:     foreach my $course (keys(%live_courses)) {
 5731:         my ($cdom,$cnum);
 5732:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 5733:             $cdom = $env{'course.'.$course.'.domain'};
 5734:             $cnum = $env{'course.'.$course.'.num'};
 5735:         } else {
 5736:             ($cdom,$cnum) = split(/_/,$course); 
 5737:         }
 5738:         my $no_ownblock = 0;
 5739:         my $no_userblock = 0;
 5740:         if ($otheruser && $activity ne 'com') {
 5741:             # Check if current user has 'evb' priv for this
 5742:             if (defined($own_courses{$course})) {
 5743:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 5744:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5745:                     if ($sec ne 'none') {
 5746:                         $checkrole .= '/'.$sec;
 5747:                     }
 5748:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5749:                         $no_ownblock = 1;
 5750:                         last;
 5751:                     }
 5752:                 }
 5753:             }
 5754:             # if they have 'evb' priv and are currently not playing student
 5755:             next if (($no_ownblock) &&
 5756:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 5757:         }
 5758:         foreach my $sec (keys(%{$live_courses{$course}})) {
 5759:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5760:             if ($sec ne 'none') {
 5761:                 $checkrole .= '/'.$sec;
 5762:             }
 5763:             if ($otheruser) {
 5764:                 # Resource belongs to user other than current user.
 5765:                 # Assemble privs for that user, and check for 'evb' priv.
 5766:                 my (%allroles,%userroles);
 5767:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 5768:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 5769:                         my ($trole,$tdom,$tnum,$tsec);
 5770:                         if ($entry =~ /^cr/) {
 5771:                             ($trole,$tdom,$tnum,$tsec) = 
 5772:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 5773:                         } else {
 5774:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 5775:                         }
 5776:                         my ($spec,$area,$trest);
 5777:                         $area = '/'.$tdom.'/'.$tnum;
 5778:                         $trest = $tnum;
 5779:                         if ($tsec ne '') {
 5780:                             $area .= '/'.$tsec;
 5781:                             $trest .= '/'.$tsec;
 5782:                         }
 5783:                         $spec = $trole.'.'.$area;
 5784:                         if ($trole =~ /^cr/) {
 5785:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 5786:                                                               $tdom,$spec,$trest,$area);
 5787:                         } else {
 5788:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 5789:                                                                 $tdom,$spec,$trest,$area);
 5790:                         }
 5791:                     }
 5792:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 5793:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 5794:                         if ($1) {
 5795:                             $no_userblock = 1;
 5796:                             last;
 5797:                         }
 5798:                     }
 5799:                 }
 5800:             } else {
 5801:                 # Resource belongs to current user
 5802:                 # Check for 'evb' priv via lonnet::allowed().
 5803:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5804:                     $no_ownblock = 1;
 5805:                     last;
 5806:                 }
 5807:             }
 5808:         }
 5809:         # if they have the evb priv and are currently not playing student
 5810:         next if (($no_ownblock) &&
 5811:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 5812:         next if ($no_userblock);
 5813: 
 5814:         # Retrieve blocking times and identity of blocker for course
 5815:         # of specified user, unless user has 'evb' privilege.
 5816: 
 5817:         my ($start,$end,$trigger) = 
 5818:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
 5819:         if (($start != 0) && 
 5820:             (($startblock == 0) || ($startblock > $start))) {
 5821:             $startblock = $start;
 5822:             if ($trigger ne '') {
 5823:                 $triggerblock = $trigger;
 5824:             }
 5825:         }
 5826:         if (($end != 0)  &&
 5827:             (($endblock == 0) || ($endblock < $end))) {
 5828:             $endblock = $end;
 5829:             if ($trigger ne '') {
 5830:                 $triggerblock = $trigger;
 5831:             }
 5832:         }
 5833:     }
 5834:     return ($startblock,$endblock,$triggerblock);
 5835: }
 5836: 
 5837: sub get_blocks {
 5838:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
 5839:     my $startblock = 0;
 5840:     my $endblock = 0;
 5841:     my $triggerblock = '';
 5842:     my $course = $cdom.'_'.$cnum;
 5843:     $setters->{$course} = {};
 5844:     $setters->{$course}{'staff'} = [];
 5845:     $setters->{$course}{'times'} = [];
 5846:     $setters->{$course}{'triggers'} = [];
 5847:     my (@blockers,%triggered);
 5848:     my $now = time;
 5849:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 5850:     if ($activity eq 'docs') {
 5851:         my ($blocked,$nosymbcache,$noenccheck);
 5852:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
 5853:             $blocked = 1;
 5854:             $nosymbcache = 1;
 5855:             $noenccheck = 1;
 5856:         }
 5857:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
 5858:         foreach my $block (@blockers) {
 5859:             if ($block =~ /^firstaccess____(.+)$/) {
 5860:                 my $item = $1;
 5861:                 my $type = 'map';
 5862:                 my $timersymb = $item;
 5863:                 if ($item eq 'course') {
 5864:                     $type = 'course';
 5865:                 } elsif ($item =~ /___\d+___/) {
 5866:                     $type = 'resource';
 5867:                 } else {
 5868:                     $timersymb = &Apache::lonnet::symbread($item);
 5869:                 }
 5870:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5871:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 5872:                 $triggered{$block} = {
 5873:                                        start => $start,
 5874:                                        end   => $end,
 5875:                                        type  => $type,
 5876:                                      };
 5877:             }
 5878:         }
 5879:     } else {
 5880:         foreach my $block (keys(%commblocks)) {
 5881:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 5882:                 my ($start,$end) = ($1,$2);
 5883:                 if ($start <= time && $end >= time) {
 5884:                     if (ref($commblocks{$block}) eq 'HASH') {
 5885:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5886:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5887:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 5888:                                     push(@blockers,$block);
 5889:                                 }
 5890:                             }
 5891:                         }
 5892:                     }
 5893:                 }
 5894:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 5895:                 my $item = $1;
 5896:                 my $timersymb = $item; 
 5897:                 my $type = 'map';
 5898:                 if ($item eq 'course') {
 5899:                     $type = 'course';
 5900:                 } elsif ($item =~ /___\d+___/) {
 5901:                     $type = 'resource';
 5902:                 } else {
 5903:                     $timersymb = &Apache::lonnet::symbread($item);
 5904:                 }
 5905:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5906:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 5907:                 if ($start && $end) {
 5908:                     if (($start <= time) && ($end >= time)) {
 5909:                         if (ref($commblocks{$block}) eq 'HASH') {
 5910:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5911:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5912:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
 5913:                                         push(@blockers,$block);
 5914:                                         $triggered{$block} = {
 5915:                                                                start => $start,
 5916:                                                                end   => $end,
 5917:                                                                type  => $type,
 5918:                                                              };
 5919:                                     }
 5920:                                 }
 5921:                             }
 5922:                         }
 5923:                     }
 5924:                 }
 5925:             }
 5926:         }
 5927:     }
 5928:     foreach my $blocker (@blockers) {
 5929:         my ($staff_name,$staff_dom,$title,$blocks) =
 5930:             &parse_block_record($commblocks{$blocker});
 5931:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 5932:         my ($start,$end,$triggertype);
 5933:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 5934:             ($start,$end) = ($1,$2);
 5935:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 5936:             $start = $triggered{$blocker}{'start'};
 5937:             $end = $triggered{$blocker}{'end'};
 5938:             $triggertype = $triggered{$blocker}{'type'};
 5939:         }
 5940:         if ($start) {
 5941:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 5942:             if ($triggertype) {
 5943:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 5944:             } else {
 5945:                 push(@{$$setters{$course}{'triggers'}},0);
 5946:             }
 5947:             if ( ($startblock == 0) || ($startblock > $start) ) {
 5948:                 $startblock = $start;
 5949:                 if ($triggertype) {
 5950:                     $triggerblock = $blocker;
 5951:                 }
 5952:             }
 5953:             if ( ($endblock == 0) || ($endblock < $end) ) {
 5954:                $endblock = $end;
 5955:                if ($triggertype) {
 5956:                    $triggerblock = $blocker;
 5957:                }
 5958:             }
 5959:         }
 5960:     }
 5961:     return ($startblock,$endblock,$triggerblock);
 5962: }
 5963: 
 5964: sub parse_block_record {
 5965:     my ($record) = @_;
 5966:     my ($setuname,$setudom,$title,$blocks);
 5967:     if (ref($record) eq 'HASH') {
 5968:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 5969:         $title = &unescape($record->{'event'});
 5970:         $blocks = $record->{'blocks'};
 5971:     } else {
 5972:         my @data = split(/:/,$record,3);
 5973:         if (scalar(@data) eq 2) {
 5974:             $title = $data[1];
 5975:             ($setuname,$setudom) = split(/@/,$data[0]);
 5976:         } else {
 5977:             ($setuname,$setudom,$title) = @data;
 5978:         }
 5979:         $blocks = { 'com' => 'on' };
 5980:     }
 5981:     return ($setuname,$setudom,$title,$blocks);
 5982: }
 5983: 
 5984: sub blocking_status {
 5985:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
 5986:     my %setters;
 5987: 
 5988: # check for active blocking
 5989:     if ($clientip eq '') {
 5990:         $clientip = &Apache::lonnet::get_requestor_ip();
 5991:     }
 5992:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
 5993:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
 5994:     my $blocked = 0;
 5995:     if (($startblock && $endblock) || ($by_ip)) {
 5996:         $blocked = 1;
 5997:     }
 5998: 
 5999: # caller just wants to know whether a block is active
 6000:     if (!wantarray) { return $blocked; }
 6001: 
 6002: # build a link to a popup window containing the details
 6003:     my $querystring  = "?activity=$activity";
 6004: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
 6005:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
 6006:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
 6007:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
 6008:     } elsif ($activity eq 'docs') {
 6009:         my $showurl = &Apache::lonenc::check_encrypt($url);
 6010:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
 6011:         if ($symb) {
 6012:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
 6013:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
 6014:         }
 6015:     }
 6016: 
 6017:     my $output .= <<'END_MYBLOCK';
 6018: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 6019:     var options = "width=" + w + ",height=" + h + ",";
 6020:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 6021:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 6022:     var newWin = window.open(url, wdwName, options);
 6023:     newWin.focus();
 6024: }
 6025: END_MYBLOCK
 6026: 
 6027:     $output = Apache::lonhtmlcommon::scripttag($output);
 6028:   
 6029:     my $popupUrl = "/adm/blockingstatus/$querystring";
 6030:     my $text = &mt('Communication Blocked');
 6031:     my $class = 'LC_comblock';
 6032:     if ($activity eq 'docs') {
 6033:         $text = &mt('Content Access Blocked');
 6034:         $class = '';
 6035:     } elsif ($activity eq 'printout') {
 6036:         $text = &mt('Printing Blocked');
 6037:     } elsif ($activity eq 'passwd') {
 6038:         $text = &mt('Password Changing Blocked');
 6039:     } elsif ($activity eq 'grades') {
 6040:         $text = &mt('Gradebook Blocked');
 6041:     } elsif ($activity eq 'search') {
 6042:         $text = &mt('Search Blocked');
 6043:     } elsif ($activity eq 'alert') {
 6044:         $text = &mt('Checking Critical Messages Blocked');
 6045:     } elsif ($activity eq 'reinit') {
 6046:         $text = &mt('Checking Course Update Blocked');
 6047:     } elsif ($activity eq 'about') {
 6048:         $text = &mt('Access to User Information Pages Blocked');
 6049:     } elsif ($activity eq 'wishlist') {
 6050:         $text = &mt('Access to Stored Links Blocked');
 6051:     } elsif ($activity eq 'annotate') {
 6052:         $text = &mt('Access to Annotations Blocked');
 6053:     }
 6054:     $output .= <<"END_BLOCK";
 6055: <div class='$class'>
 6056:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 6057:   title='$text'>
 6058:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 6059:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 6060:   title='$text'>$text</a>
 6061: </div>
 6062: 
 6063: END_BLOCK
 6064: 
 6065:     return ($blocked, $output);
 6066: }
 6067: 
 6068: ###############################################
 6069: 
 6070: sub check_ip_acc {
 6071:     my ($acc,$clientip)=@_;
 6072:     &Apache::lonxml::debug("acc is $acc");
 6073:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 6074:         return 1;
 6075:     }
 6076:     my ($ip,$allowed);
 6077:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
 6078:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
 6079:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
 6080:     } else {
 6081:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
 6082:         $ip = $remote_ip || $env{'request.host'} || $clientip;
 6083:     }
 6084: 
 6085:     my $name;
 6086:     my %access = (
 6087:                      allowfrom => 1,
 6088:                      denyfrom  => 0,
 6089:                  );
 6090:     my @allows;
 6091:     my @denies;
 6092:     foreach my $item (split(',',$acc)) {
 6093:         $item =~ s/^\s*//;
 6094:         $item =~ s/\s*$//;
 6095:         my $pattern;
 6096:         if ($item =~ /^\!(.+)$/) {
 6097:             push(@denies,$1);
 6098:         } else {
 6099:             push(@allows,$item);
 6100:         }
 6101:    }
 6102:    my $numdenies = scalar(@denies);
 6103:    my $numallows = scalar(@allows);
 6104:    my $count = 0;
 6105:    foreach my $pattern (@denies,@allows) {
 6106:         $count ++; 
 6107:         my $acctype = 'allowfrom';
 6108:         if ($count <= $numdenies) {
 6109:             $acctype = 'denyfrom';
 6110:         }
 6111:         if ($pattern =~ /\*$/) {
 6112:             #35.8.*
 6113:             $pattern=~s/\*//;
 6114:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 6115:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 6116:             #35.8.3.[34-56]
 6117:             my $low=$2;
 6118:             my $high=$3;
 6119:             $pattern=$1;
 6120:             if ($ip =~ /^\Q$pattern\E/) {
 6121:                 my $last=(split(/\./,$ip))[3];
 6122:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
 6123:             }
 6124:         } elsif ($pattern =~ /^\*/) {
 6125:             #*.msu.edu
 6126:             $pattern=~s/\*//;
 6127:             if (!defined($name)) {
 6128:                 use Socket;
 6129:                 my $netaddr=inet_aton($ip);
 6130:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 6131:             }
 6132:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 6133:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 6134:             #127.0.0.1
 6135:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 6136:         } else {
 6137:             #some.name.com
 6138:             if (!defined($name)) {
 6139:                 use Socket;
 6140:                 my $netaddr=inet_aton($ip);
 6141:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 6142:             }
 6143:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 6144:         }
 6145:         if ($allowed =~ /^(0|1)$/) { last; }
 6146:     }
 6147:     if ($allowed eq '') {
 6148:         if ($numdenies && !$numallows) {
 6149:             $allowed = 1;
 6150:         } else {
 6151:             $allowed = 0;
 6152:         }
 6153:     }
 6154:     return $allowed;
 6155: }
 6156: 
 6157: ###############################################
 6158: 
 6159: =pod
 6160: 
 6161: =head1 Domain Template Functions
 6162: 
 6163: =over 4
 6164: 
 6165: =item * &determinedomain()
 6166: 
 6167: Inputs: $domain (usually will be undef)
 6168: 
 6169: Returns: Determines which domain should be used for designs
 6170: 
 6171: =cut
 6172: 
 6173: ###############################################
 6174: sub determinedomain {
 6175:     my $domain=shift;
 6176:     if (! $domain) {
 6177:         # Determine domain if we have not been given one
 6178:         $domain = &Apache::lonnet::default_login_domain();
 6179:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 6180:         if ($env{'request.role.domain'}) { 
 6181:             $domain=$env{'request.role.domain'}; 
 6182:         }
 6183:     }
 6184:     return $domain;
 6185: }
 6186: ###############################################
 6187: 
 6188: sub devalidate_domconfig_cache {
 6189:     my ($udom)=@_;
 6190:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 6191: }
 6192: 
 6193: # ---------------------- Get domain configuration for a domain
 6194: sub get_domainconf {
 6195:     my ($udom) = @_;
 6196:     my $cachetime=1800;
 6197:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 6198:     if (defined($cached)) { return %{$result}; }
 6199: 
 6200:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 6201: 					     ['login','rolecolors','autoenroll'],$udom);
 6202:     my (%designhash,%legacy);
 6203:     if (keys(%domconfig) > 0) {
 6204:         if (ref($domconfig{'login'}) eq 'HASH') {
 6205:             if (keys(%{$domconfig{'login'}})) {
 6206:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 6207:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 6208:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
 6209:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 6210:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
 6211:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
 6212:                                         if ($key eq 'loginvia') {
 6213:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 6214:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 6215:                                                 $designhash{$udom.'.login.loginvia'} = $server;
 6216:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 6217: 
 6218:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 6219:                                                 } else {
 6220:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 6221:                                                 }
 6222:                                             }
 6223:                                         } elsif ($key eq 'headtag') {
 6224:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
 6225:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
 6226:                                             }
 6227:                                         }
 6228:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
 6229:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
 6230:                                         }
 6231:                                     }
 6232:                                 }
 6233:                             }
 6234:                         } elsif ($key eq 'saml') {
 6235:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 6236:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
 6237:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
 6238:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
 6239:                                         foreach my $item ('text','img','alt','url','title','window','notsso') {
 6240:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
 6241:                                         }
 6242:                                     }
 6243:                                 }
 6244:                             }
 6245:                         } else {
 6246:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 6247:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 6248:                                     $domconfig{'login'}{$key}{$img};
 6249:                             }
 6250:                         }
 6251:                     } else {
 6252:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 6253:                     }
 6254:                 }
 6255:             } else {
 6256:                 $legacy{'login'} = 1;
 6257:             }
 6258:         } else {
 6259:             $legacy{'login'} = 1;
 6260:         }
 6261:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 6262:             if (keys(%{$domconfig{'rolecolors'}})) {
 6263:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 6264:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 6265:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 6266:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 6267:                         }
 6268:                     }
 6269:                 }
 6270:             } else {
 6271:                 $legacy{'rolecolors'} = 1;
 6272:             }
 6273:         } else {
 6274:             $legacy{'rolecolors'} = 1;
 6275:         }
 6276:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 6277:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 6278:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 6279:             }
 6280:         }
 6281:         if (keys(%legacy) > 0) {
 6282:             my %legacyhash = &get_legacy_domconf($udom);
 6283:             foreach my $item (keys(%legacyhash)) {
 6284:                 if ($item =~ /^\Q$udom\E\.login/) {
 6285:                     if ($legacy{'login'}) { 
 6286:                         $designhash{$item} = $legacyhash{$item};
 6287:                     }
 6288:                 } else {
 6289:                     if ($legacy{'rolecolors'}) {
 6290:                         $designhash{$item} = $legacyhash{$item};
 6291:                     }
 6292:                 }
 6293:             }
 6294:         }
 6295:     } else {
 6296:         %designhash = &get_legacy_domconf($udom); 
 6297:     }
 6298:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 6299: 				  $cachetime);
 6300:     return %designhash;
 6301: }
 6302: 
 6303: sub get_legacy_domconf {
 6304:     my ($udom) = @_;
 6305:     my %legacyhash;
 6306:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 6307:     my $designfile =  $designdir.'/'.$udom.'.tab';
 6308:     if (-e $designfile) {
 6309:         if ( open (my $fh,'<',$designfile) ) {
 6310:             while (my $line = <$fh>) {
 6311:                 next if ($line =~ /^\#/);
 6312:                 chomp($line);
 6313:                 my ($key,$val)=(split(/\=/,$line));
 6314:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 6315:             }
 6316:             close($fh);
 6317:         }
 6318:     }
 6319:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 6320:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 6321:     }
 6322:     return %legacyhash;
 6323: }
 6324: 
 6325: =pod
 6326: 
 6327: =item * &domainlogo()
 6328: 
 6329: Inputs: $domain (usually will be undef)
 6330: 
 6331: Returns: A link to a domain logo, if the domain logo exists.
 6332: If the domain logo does not exist, a description of the domain.
 6333: 
 6334: =cut
 6335: 
 6336: ###############################################
 6337: sub domainlogo {
 6338:     my $domain = &determinedomain(shift);
 6339:     my %designhash = &get_domainconf($domain);    
 6340:     # See if there is a logo
 6341:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 6342:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 6343:         if ($imgsrc =~ m{^/(adm|res)/}) {
 6344: 	    if ($imgsrc =~ m{^/res/}) {
 6345: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 6346: 		&Apache::lonnet::repcopy($local_name);
 6347: 	    }
 6348: 	   $imgsrc = &lonhttpdurl($imgsrc);
 6349:         }
 6350:         my $alttext = $domain;
 6351:         if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
 6352:             $alttext = $designhash{$domain.'.login.alttext_domlogo'};
 6353:         }
 6354:         return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
 6355:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 6356:         return &Apache::lonnet::domain($domain,'description');
 6357:     } else {
 6358:         return '';
 6359:     }
 6360: }
 6361: ##############################################
 6362: 
 6363: =pod
 6364: 
 6365: =item * &designparm()
 6366: 
 6367: Inputs: $which parameter; $domain (usually will be undef)
 6368: 
 6369: Returns: value of designparamter $which
 6370: 
 6371: =cut
 6372: 
 6373: 
 6374: ##############################################
 6375: sub designparm {
 6376:     my ($which,$domain)=@_;
 6377:     if (exists($env{'environment.color.'.$which})) {
 6378:         return $env{'environment.color.'.$which};
 6379:     }
 6380:     $domain=&determinedomain($domain);
 6381:     my %domdesign;
 6382:     unless ($domain eq 'public') {
 6383:         %domdesign = &get_domainconf($domain);
 6384:     }
 6385:     my $output;
 6386:     if ($domdesign{$domain.'.'.$which} ne '') {
 6387:         $output = $domdesign{$domain.'.'.$which};
 6388:     } else {
 6389:         $output = $defaultdesign{$which};
 6390:     }
 6391:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 6392:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 6393:         if ($output =~ m{^/(adm|res)/}) {
 6394:             if ($output =~ m{^/res/}) {
 6395:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 6396:                 &Apache::lonnet::repcopy($local_name);
 6397:             }
 6398:             $output = &lonhttpdurl($output);
 6399:         }
 6400:     }
 6401:     return $output;
 6402: }
 6403: 
 6404: ##############################################
 6405: =pod
 6406: 
 6407: =item * &authorspace()
 6408: 
 6409: Inputs: $url (usually will be undef).
 6410: 
 6411: Returns: Path to Authoring Space containing the resource or 
 6412:          directory being viewed (or for which action is being taken). 
 6413:          If $url is provided, and begins /priv/<domain>/<uname>
 6414:          the path will be that portion of the $context argument.
 6415:          Otherwise the path will be for the author space of the current
 6416:          user when the current role is author, or for that of the 
 6417:          co-author/assistant co-author space when the current role 
 6418:          is co-author or assistant co-author.
 6419: 
 6420: =cut
 6421: 
 6422: sub authorspace {
 6423:     my ($url) = @_;
 6424:     if ($url ne '') {
 6425:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 6426:            return $1;
 6427:         }
 6428:     }
 6429:     my $caname = '';
 6430:     my $cadom = '';
 6431:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 6432:         ($cadom,$caname) =
 6433:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 6434:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 6435:         $caname = $env{'user.name'};
 6436:         $cadom = $env{'user.domain'};
 6437:     }
 6438:     if (($caname ne '') && ($cadom ne '')) {
 6439:         return "/priv/$cadom/$caname/";
 6440:     }
 6441:     return;
 6442: }
 6443: 
 6444: ##############################################
 6445: =pod
 6446: 
 6447: =item * &head_subbox()
 6448: 
 6449: Inputs: $content (contains HTML code with page functions, etc.)
 6450: 
 6451: Returns: HTML div with $content
 6452:          To be included in page header
 6453: 
 6454: =cut
 6455: 
 6456: sub head_subbox {
 6457:     my ($content)=@_;
 6458:     my $output =
 6459:         '<div class="LC_head_subbox">'
 6460:        .$content
 6461:        .'</div>'
 6462: }
 6463: 
 6464: ##############################################
 6465: =pod
 6466: 
 6467: =item * &CSTR_pageheader()
 6468: 
 6469: Input: (optional) filename from which breadcrumb trail is built.
 6470:        In most cases no input as needed, as $env{'request.filename'}
 6471:        is appropriate for use in building the breadcrumb trail.
 6472:        frameset flag
 6473:        If page header is being requested for use in a frameset, then
 6474:        the second (option) argument -- frameset will be true, and
 6475:        the target attribute set for links should be target="_parent".
 6476:        If $title is supplied as the thitd arg, that will be used to 
 6477:        the left of the breadcrumbs tail for the current path.
 6478: 
 6479: Returns: HTML div with CSTR path and recent box
 6480:          To be included on Authoring Space pages
 6481: 
 6482: =cut
 6483: 
 6484: sub CSTR_pageheader {
 6485:     my ($trailfile,$frameset,$title) = @_;
 6486:     if ($trailfile eq '') {
 6487:         $trailfile = $env{'request.filename'};
 6488:     }
 6489: 
 6490: # this is for resources; directories have customtitle, and crumbs
 6491: # and select recent are created in lonpubdir.pm
 6492: 
 6493:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 6494:     my ($udom,$uname,$thisdisfn)=
 6495:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 6496:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 6497:     $formaction =~ s{/+}{/}g;
 6498: 
 6499:     my $parentpath = '';
 6500:     my $lastitem = '';
 6501:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 6502:         $parentpath = $1;
 6503:         $lastitem = $2;
 6504:     } else {
 6505:         $lastitem = $thisdisfn;
 6506:     }
 6507: 
 6508:     my $crsauthor;
 6509:     if (($env{'request.course.id'}) &&
 6510:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
 6511:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
 6512:         $crsauthor = 1;
 6513:         if ($title eq '') {
 6514:             $title = &mt('Course Authoring Space');
 6515:         }
 6516:     } elsif ($title eq '') {
 6517:         $title = &mt('Authoring Space');
 6518:     }
 6519: 
 6520:     my ($target,$crumbtarget) = (' target="_top"','_top');
 6521:     if ($frameset) {
 6522:         $target = ' target="_parent"';
 6523:         $crumbtarget = '_parent';
 6524:     } elsif (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
 6525:         $target = '';
 6526:         $crumbtarget = '';
 6527:     } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
 6528:         $target = ' target="'.$env{'request.deeplink.target'}.'"';
 6529:         $crumbtarget = $env{'request.deeplink.target'};
 6530:     }
 6531: 
 6532:     my $output =
 6533:          '<div>'
 6534:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 6535:         .'<b>'.$title.'</b> '
 6536:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
 6537:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
 6538: 
 6539:     if ($lastitem) {
 6540:         $output .=
 6541:              '<span class="LC_filename">'
 6542:             .$lastitem
 6543:             .'</span>';
 6544:     }
 6545: 
 6546:     if ($crsauthor) {
 6547:         $output .= '</form>'.&Apache::lonmenu::constspaceform($frameset);
 6548:     } else {
 6549:         $output .=
 6550:              '<br />'
 6551:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
 6552:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 6553:             .'</form>'
 6554:             .&Apache::lonmenu::constspaceform($frameset);
 6555:     }
 6556:     $output .= '</div>';
 6557: 
 6558:     return $output;
 6559: }
 6560: 
 6561: ##############################################
 6562: =pod
 6563: 
 6564: =item * &nocodemirror()
 6565: 
 6566: Input: None
 6567: 
 6568: Returns: 1 if CodeMirror is deactivated based on
 6569:          user's preference, or domain default,
 6570:          if user indicated use of default.
 6571: 
 6572: =cut
 6573: 
 6574: sub nocodemirror {
 6575:     my $nocodem = $env{'environment.nocodemirror'};
 6576:     unless ($nocodem) {
 6577:         my %domdefs = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
 6578:         if ($domdefs{'nocodemirror'}) {
 6579:             $nocodem = 'yes';
 6580:         }
 6581:     }
 6582:     if ($nocodem eq 'yes') {
 6583:         return 1;
 6584:     }
 6585:     return;
 6586: }
 6587: 
 6588: ##############################################
 6589: =pod
 6590: 
 6591: =item * &permitted_editors()
 6592: 
 6593: Input: $uri (optional)
 6594: 
 6595: Returns: %editors hash in which keys are editors
 6596:          permitted in current Authoring Space.
 6597:          Value for each key is 1. Possible keys
 6598:          are: edit, xml, and daxe. If no specific
 6599:          set of editors has been set for the Author
 6600:          who owns the Authoring Space, then the
 6601:          domain default will be used.  If no domain
 6602:          default has been set, then the keys will be
 6603:          edit and xml.
 6604: 
 6605: =cut
 6606: 
 6607: sub permitted_editors {
 6608:     my ($uri) = @_;
 6609:     my ($is_author,$is_coauthor,$auname,$audom,%editors);
 6610:     if ($env{'request.role'} =~ m{^au\./}) {
 6611:         $is_author = 1;
 6612:     } elsif ($env{'request.role'} =~ m{^(?:ca|aa)\./($match_domain)/($match_username)}) {
 6613:         ($audom,$auname) = ($1,$2);
 6614:         if (($audom ne '') && ($auname ne '')) {
 6615:             if (($env{'user.domain'} eq $audom) &&
 6616:                 ($env{'user.name'} eq $auname)) {
 6617:                 $is_author = 1;
 6618:             } else {
 6619:                 $is_coauthor = 1;
 6620:             }
 6621:         }
 6622:     } elsif ($env{'request.course.id'}) {
 6623:         if ($env{'request.editurl'} =~ m{^/priv/($match_domain)/($match_username)/}) {
 6624:             ($audom,$auname) = ($1,$2);
 6625:         } elsif ($env{'request.uri'} =~ m{^/priv/($match_domain)/($match_username)/}) {
 6626:             ($audom,$auname) = ($1,$2);
 6627:         } elsif (($uri eq '/daxesave') &&
 6628:                  ($env{'form.path'} =~ m{^/daxeopen/priv/($match_domain)/($match_username)/})) {
 6629:             ($audom,$auname) = ($1,$2);
 6630:         }
 6631:         if (($audom ne '') && ($auname ne '')) {
 6632:             if (($env{'user.domain'} eq $audom) &&
 6633:                 ($env{'user.name'} eq $auname)) {
 6634:                 $is_author = 1;
 6635:             } else {
 6636:                 $is_coauthor = 1;
 6637:             }
 6638:         }
 6639:     }
 6640:     if ($is_author) {
 6641:         if (exists($env{'environment.editors'})) {
 6642:             map { $editors{$_} = 1; } split(/,/,$env{'environment.editors'});
 6643:         } else {
 6644:             %editors = ( edit => 1,
 6645:                          xml => 1,
 6646:                        );
 6647:         }
 6648:     } elsif ($is_coauthor) {
 6649:         if (exists($env{"environment.internal.editors./$audom/$auname"})) {
 6650:             map { $editors{$_} = 1; } split(/,/,$env{"environment.internal.editors./$audom/$auname"});
 6651:         } else {
 6652:             %editors = ( edit => 1,
 6653:                          xml => 1,
 6654:                        );
 6655:         }
 6656:     } else {
 6657:         %editors = ( edit => 1,
 6658:                      xml => 1,
 6659:                    );
 6660:     }
 6661:     return %editors;
 6662: }
 6663: 
 6664: ###############################################
 6665: ###############################################
 6666: 
 6667: =pod
 6668: 
 6669: =back
 6670: 
 6671: =head1 HTML Helpers
 6672: 
 6673: =over 4
 6674: 
 6675: =item * &bodytag()
 6676: 
 6677: Returns a uniform header for LON-CAPA web pages.
 6678: 
 6679: Inputs: 
 6680: 
 6681: =over 4
 6682: 
 6683: =item * $title, A title to be displayed on the page.
 6684: 
 6685: =item * $function, the current role (can be undef).
 6686: 
 6687: =item * $addentries, extra parameters for the <body> tag.
 6688: 
 6689: =item * $bodyonly, if defined, only return the <body> tag.
 6690: 
 6691: =item * $domain, if defined, force a given domain.
 6692: 
 6693: =item * $forcereg, if page should register as content page (relevant for 
 6694:             text interface only)
 6695: 
 6696: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 6697:                      navigational links
 6698: 
 6699: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 6700: 
 6701: =item * $args, optional argument valid values are
 6702:             no_auto_mt_title -> prevents &mt()ing the title arg
 6703:             use_absolute     -> for external resource or syllabus, this will
 6704:                                 contain https://<hostname> if server uses
 6705:                                 https (as per hosts.tab), but request is for http
 6706:             hostname         -> hostname, from $r->hostname().
 6707: 
 6708: =item * $advtoolsref, optional argument, ref to an array containing
 6709:             inlineremote items to be added in "Functions" menu below
 6710:             breadcrumbs.
 6711: 
 6712: =item * $ltiscope, optional argument, will be one of: resource, map or
 6713:             course, if LON-CAPA is in LTI Provider context. Value is
 6714:             the scope of use, i.e., launch was for access to a single, a map
 6715:             or the entire course.
 6716: 
 6717: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
 6718:             context, this will contain the URL for the landing item in
 6719:             the course, after launch from an LTI Consumer
 6720: 
 6721: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
 6722:             context, this will contain a reference to hash of items
 6723:             to be included in the page header and/or inline menu.
 6724: 
 6725: =item * $menucoll, optional argument, if specific menu collection is in
 6726:             effect, either set as the default for the course, or set for
 6727:             the deeplink paramater for $env{'request.deeplink.login'}
 6728:             then $menucoll will be the number of that collection. 
 6729: 
 6730: =item * $menuref, optional argument, reference to a hash, containing the
 6731:             menu options included for the menu in effect, based on the
 6732:             configuration for the numbered menu collection in use.  
 6733: 
 6734: =item * $showncrumbsref, reference to a scalar. Calls to lonmenu::innerregister
 6735:             within &bodytag() can result in calls to lonhtmlcommon::breadcrumbs(),
 6736:             if so, $showncrumbsref is set there to 1, and will propagate back
 6737:             via &bodytag() to &start_page(), to prevent lonhtmlcommon::breadcrumbs()
 6738:             being called a second time.
 6739: 
 6740: =back
 6741: 
 6742: Returns: A uniform header for LON-CAPA web pages.  
 6743: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 6744: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 6745: other decorations will be returned.
 6746: 
 6747: =cut
 6748: 
 6749: sub bodytag {
 6750:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 6751:         $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri,
 6752:         $ltimenu,$menucoll,$menuref,$showncrumbsref)=@_;
 6753: 
 6754:     my $public;
 6755:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 6756:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 6757:         $public = 1;
 6758:     }
 6759:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 6760:     my $httphost = $args->{'use_absolute'};
 6761:     my $hostname = $args->{'hostname'};
 6762: 
 6763:     $function = &get_users_function() if (!$function);
 6764:     my $img =    &designparm($function.'.img',$domain);
 6765:     my $font =   &designparm($function.'.font',$domain);
 6766:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 6767: 
 6768:     my %design = ( 'style'   => 'margin-top: 0',
 6769: 		   'bgcolor' => $pgbg,
 6770: 		   'text'    => $font,
 6771:                    'alink'   => &designparm($function.'.alink',$domain),
 6772: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 6773: 		   'link'    => &designparm($function.'.link',$domain),);
 6774:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 6775: 
 6776:  # role and realm
 6777:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
 6778:     if ($realm) {
 6779:         $realm = '/'.$realm;
 6780:     }
 6781:     if ($role eq 'ca') {
 6782:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 6783:         $realm = &plainname($rname,$rdom);
 6784:     } 
 6785: # realm
 6786:     my ($cid,$sec);
 6787:     if ($env{'request.course.id'}) {
 6788:         $cid = $env{'request.course.id'};
 6789:         if ($env{'request.course.sec'}) {
 6790:             $sec = $env{'request.course.sec'};
 6791:         }
 6792:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
 6793:         if (&Apache::lonnet::is_course($1,$2)) {
 6794:             $cid = $1.'_'.$2;
 6795:             $sec = $3;
 6796:         }
 6797:     }
 6798:     if ($cid) {
 6799:         if ($env{'request.role'} !~ /^cr/) {
 6800:             $role = &Apache::lonnet::plaintext($role,&course_type());
 6801:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
 6802:             if ($env{'request.role.desc'}) {
 6803:                 $role = $env{'request.role.desc'};
 6804:             } else {
 6805:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
 6806:             }
 6807:         } else {
 6808:             $role = (split(/\//,$role,4))[-1]; 
 6809:         }
 6810:         if ($sec) {
 6811:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
 6812:         }   
 6813: 	$realm = $env{'course.'.$cid.'.description'};
 6814:     } else {
 6815:         $role = &Apache::lonnet::plaintext($role);
 6816:     }
 6817: 
 6818:     if (!$realm) { $realm='&nbsp;'; }
 6819: 
 6820:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 6821: 
 6822: # construct main body tag
 6823:     my $bodytag = "<body $extra_body_attr>".
 6824: 	&Apache::lontexconvert::init_math_support();
 6825: 
 6826:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 6827: 
 6828:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 6829:         return $bodytag;
 6830:     }
 6831: 
 6832:     if ($public) {
 6833: 	undef($role);
 6834:     }
 6835: 
 6836:     my $showcrstitle = 1;
 6837:     if (($cid) && ($env{'request.lti.login'})) {
 6838:         if (ref($ltimenu) eq 'HASH') {
 6839:             unless ($ltimenu->{'role'}) {
 6840:                 undef($role);
 6841:             }
 6842:             unless ($ltimenu->{'coursetitle'}) {
 6843:                 $realm='&nbsp;';
 6844:                 $showcrstitle = 0;
 6845:             }
 6846:         }
 6847:     } elsif (($cid) && ($menucoll)) {
 6848:         if (ref($menuref) eq 'HASH') {
 6849:             unless ($menuref->{'role'}) {
 6850:                 undef($role);
 6851:             }
 6852:             unless ($menuref->{'crs'}) {
 6853:                 $realm='&nbsp;';
 6854:                 $showcrstitle = 0;
 6855:             }
 6856:         }
 6857:     }
 6858: 
 6859:     my $titleinfo = '<h1>'.$title.'</h1>';
 6860:     #
 6861:     # Extra info if you are the DC
 6862:     my $dc_info = '';
 6863:     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
 6864:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
 6865:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 6866:         $dc_info =~ s/\s+$//;
 6867:     }
 6868: 
 6869:     my $crstype;
 6870:     if ($cid) {
 6871:         $crstype = $env{'course.'.$cid.'.type'};
 6872:     } elsif ($args->{'crstype'}) {
 6873:         $crstype = $args->{'crstype'};
 6874:     }
 6875:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
 6876:         undef($role);
 6877:     } else {
 6878:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
 6879:     }
 6880: 
 6881:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 6882: 
 6883:         #    if ($env{'request.state'} eq 'construct') {
 6884:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 6885:         #    }
 6886: 
 6887:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 6888:             Apache::lonmenu::utilityfunctions($httphost), 'start');
 6889: 
 6890:         if ($args->{'collapsible_header'}) {
 6891:             my $alttext = &mt('menu state: collapsed');
 6892:             my $tooltip = &mt('display standard menus');
 6893:             $bodytag .= <<"END";
 6894: <div id="LC_expandingContainer" style="display:inline;">
 6895: <div id="LC_collapsible" class="LC_collapse_trigger" style="position: absolute;top: -5px;left: 0px; z-index:101; display:inline;">
 6896: <a href="#" style="text-decoration:none;"><img class="LC_collapsible_indicator" alt="$alttext" title="$tooltip" src="/res/adm/pages/collapsed.png" style="border:0;margin:0;padding:0;max-width:100%;height:auto" /></a></div>
 6897: <div class="LC_menus_content hidden">
 6898: END
 6899:         }
 6900:         unless ($args->{'no_primary_menu'}) {
 6901:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
 6902:                                                               $args->{'links_disabled'},
 6903:                                                               $args->{'links_target'},
 6904:                                                               $args->{'collapsible_header'});
 6905: 
 6906:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 6907:                 if ($dc_info) {
 6908:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 6909:                 }
 6910:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 6911:                                <em>$realm</em> $dc_info</div>|;
 6912:                 return $bodytag;
 6913:             }
 6914: 
 6915:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 6916:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 6917:             }
 6918: 
 6919:             $bodytag .= $right;
 6920: 
 6921:             if ($dc_info) {
 6922:                 $dc_info = &dc_courseid_toggle($dc_info);
 6923:             }
 6924:             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 6925:         }
 6926: 
 6927:         #if directed to not display the secondary menu, don't.  
 6928:         if ($args->{'no_secondary_menu'}) {
 6929:             return $bodytag;
 6930:         }
 6931:         #don't show menus for public users
 6932:         if (!$public){
 6933:             unless ($args->{'no_inline_menu'}) {
 6934:                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
 6935:                                                             $args->{'no_primary_menu'},
 6936:                                                             $menucoll,$menuref,
 6937:                                                             $args->{'links_disabled'},
 6938:                                                             $args->{'links_target'});
 6939:             }
 6940:             $bodytag .= Apache::lonmenu::serverform();
 6941:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 6942:             if ($env{'request.state'} eq 'construct') {
 6943:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 6944:                                 $args->{'bread_crumbs'},'','',$hostname,
 6945:                                 $ltiscope,$ltiuri,$showncrumbsref);
 6946:             } elsif ($forcereg) {
 6947:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 6948:                                 $args->{'group'},$args->{'hide_buttons'},
 6949:                                 $hostname,$ltiscope,$ltiuri,$showncrumbsref);
 6950:             } else {
 6951:                 $bodytag .= 
 6952:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 6953:                                                         $forcereg,$args->{'group'},
 6954:                                                         $args->{'bread_crumbs'},
 6955:                                                         $advtoolsref,'',$hostname);
 6956:             }
 6957:         }else{
 6958:             # this is to seperate menu from content when there's no secondary
 6959:             # menu. Especially needed for public accessible ressources.
 6960:             $bodytag .= '<hr style="clear:both" />';
 6961:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 6962:         }
 6963:         if ($args->{'collapsible_header'}) {
 6964:             $bodytag .= '<div id="LC_collapsible_separator"></div>'.
 6965:                         '</div></div>';
 6966:         }
 6967:         return $bodytag;
 6968: }
 6969: 
 6970: sub dc_courseid_toggle {
 6971:     my ($dc_info) = @_;
 6972:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 6973:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 6974:            &mt('(More ...)').'</a></span>'.
 6975:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 6976: }
 6977: 
 6978: sub make_attr_string {
 6979:     my ($register,$attr_ref) = @_;
 6980: 
 6981:     if ($attr_ref && !ref($attr_ref)) {
 6982: 	die("addentries Must be a hash ref ".
 6983: 	    join(':',caller(1))." ".
 6984: 	    join(':',caller(0))." ");
 6985:     }
 6986: 
 6987:     if ($register) {
 6988: 	my ($on_load,$on_unload);
 6989: 	foreach my $key (keys(%{$attr_ref})) {
 6990: 	    if      (lc($key) eq 'onload') {
 6991: 		$on_load.=$attr_ref->{$key}.';';
 6992: 		delete($attr_ref->{$key});
 6993: 
 6994: 	    } elsif (lc($key) eq 'onunload') {
 6995: 		$on_unload.=$attr_ref->{$key}.';';
 6996: 		delete($attr_ref->{$key});
 6997: 	    }
 6998: 	}
 6999: 	$attr_ref->{'onload'}  = $on_load;
 7000: 	$attr_ref->{'onunload'}= $on_unload;
 7001:     }
 7002: 
 7003:     my $attr_string;
 7004:     foreach my $attr (sort(keys(%$attr_ref))) {
 7005: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 7006:     }
 7007:     return $attr_string;
 7008: }
 7009: 
 7010: 
 7011: ###############################################
 7012: ###############################################
 7013: 
 7014: =pod
 7015: 
 7016: =item * &endbodytag()
 7017: 
 7018: Returns a uniform footer for LON-CAPA web pages.
 7019: 
 7020: Inputs: 1 - optional reference to an args hash
 7021: If in the hash, key for noredirectlink has a value which evaluates to true,
 7022: a 'Continue' link is not displayed if the page contains an
 7023: internal redirect in the <head></head> section,
 7024: i.e., $env{'internal.head.redirect'} exists   
 7025: 
 7026: =cut
 7027: 
 7028: sub endbodytag {
 7029:     my ($args) = @_;
 7030:     my $endbodytag;
 7031:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 7032:         $endbodytag='</body>';
 7033:     }
 7034:     if ( exists( $env{'internal.head.redirect'} ) ) {
 7035:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 7036:             my ($endbodyjs,$idattr);
 7037:             if ($env{'internal.head.to_opener'}) {
 7038:                 my $linkid = 'LC_continue_link';
 7039:                 $idattr = ' id="'.$linkid.'"';
 7040:                 my $redirect_for_js = &js_escape($env{'internal.head.redirect'});
 7041:                 $endbodyjs=<<ENDJS;
 7042: <script type="text/javascript">
 7043: // <![CDATA[
 7044: function ebFunction(evt) {
 7045:     evt.preventDefault();
 7046:     var dest = '$redirect_for_js';
 7047:     if (window.opener != null && !window.opener.closed) {
 7048:         window.opener.location.href=dest;
 7049:         window.close();
 7050:     } else {
 7051:         window.location.href=dest;
 7052:     }
 7053:     return false;
 7054: }
 7055: 
 7056: \$(document).ready(function () {
 7057:   if (document.getElementById('$linkid')) {
 7058:     var clickelem = document.getElementById('$linkid');
 7059:     clickelem.addEventListener('click',ebFunction,false);
 7060:   }
 7061: });
 7062: // ]]>
 7063: </script>
 7064: ENDJS
 7065:             }
 7066: 	    $endbodytag=
 7067: 	        "$endbodyjs<br /><a href=\"$env{'internal.head.redirect'}\"$idattr>".
 7068: 	        &mt('Continue').'</a>'.
 7069: 	        $endbodytag;
 7070:         }
 7071:     }
 7072:     if ((ref($args) eq 'HASH') && ($args->{'dashjs'})) {
 7073:         $endbodytag = &Apache::lonhtmlcommon::dash_to_minus_js().$endbodytag;
 7074:     }
 7075:     return $endbodytag;
 7076: }
 7077: 
 7078: =pod
 7079: 
 7080: =item * &standard_css()
 7081: 
 7082: Returns a style sheet
 7083: 
 7084: Inputs: (all optional)
 7085:             domain         -> force to color decorate a page for a specific
 7086:                                domain
 7087:             function       -> force usage of a specific rolish color scheme
 7088:             bgcolor        -> override the default page bgcolor
 7089: 
 7090: =cut
 7091: 
 7092: sub standard_css {
 7093:     my ($function,$domain,$bgcolor) = @_;
 7094:     $function  = &get_users_function() if (!$function);
 7095:     my $img    = &designparm($function.'.img',   $domain);
 7096:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 7097:     my $font   = &designparm($function.'.font',  $domain);
 7098:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 7099: #second colour for later usage
 7100:     my $sidebg = &designparm($function.'.sidebg',$domain);
 7101:     my $pgbg_or_bgcolor =
 7102: 	         $bgcolor ||
 7103: 	         &designparm($function.'.pgbg',  $domain);
 7104:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 7105:     my $alink  = &designparm($function.'.alink', $domain);
 7106:     my $vlink  = &designparm($function.'.vlink', $domain);
 7107:     my $link   = &designparm($function.'.link',  $domain);
 7108: 
 7109:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 7110:     my $mono                 = 'monospace';
 7111:     my $data_table_head      = $sidebg;
 7112:     my $data_table_light     = '#FAFAFA';
 7113:     my $data_table_dark      = '#E0E0E0';
 7114:     my $data_table_darker    = '#CCCCCC';
 7115:     my $data_table_highlight = '#FFFF00';
 7116:     my $mail_new             = '#FFBB77';
 7117:     my $mail_new_hover       = '#DD9955';
 7118:     my $mail_read            = '#BBBB77';
 7119:     my $mail_read_hover      = '#999944';
 7120:     my $mail_replied         = '#AAAA88';
 7121:     my $mail_replied_hover   = '#888855';
 7122:     my $mail_other           = '#99BBBB';
 7123:     my $mail_other_hover     = '#669999';
 7124:     my $table_header         = '#DDDDDD';
 7125:     my $feedback_link_bg     = '#BBBBBB';
 7126:     my $lg_border_color      = '#C8C8C8';
 7127:     my $button_hover         = '#BF2317';
 7128: 
 7129:     my $border = ($env{'browser.type'} eq 'explorer' ||
 7130:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 7131:                                              : '0 3px 0 4px';
 7132: 
 7133: 
 7134:     return <<END;
 7135: 
 7136: /* needed for iframe to allow 100% height in FF */
 7137: body, html { 
 7138:     margin: 0;
 7139:     padding: 0 0.5%;
 7140:     height: 99%; /* to avoid scrollbars */
 7141: }
 7142: 
 7143: body {
 7144:   font-family: $sans;
 7145:   line-height:130%;
 7146:   font-size:0.83em;
 7147:   color:$font;
 7148: }
 7149: 
 7150: a:focus,
 7151: a:focus img {
 7152:   color: red;
 7153: }
 7154: 
 7155: form, .inline {
 7156:   display: inline;
 7157: }
 7158: 
 7159: .LC_menus_content.shown{
 7160:   display: inline;
 7161: }
 7162: 
 7163: .LC_menus_content.hidden {
 7164:   display: none;
 7165: }
 7166: 
 7167: .LC_right {
 7168:   text-align:right;
 7169: }
 7170: 
 7171: .LC_middle {
 7172:   vertical-align:middle;
 7173: }
 7174: 
 7175: .LC_floatleft {
 7176:   float: left;
 7177: }
 7178: 
 7179: .LC_floatright {
 7180:   float: right;
 7181: }
 7182: 
 7183: .LC_400Box {
 7184:   width:400px;
 7185: }
 7186: 
 7187: #LC_collapsible_separator {
 7188:     border: 1px solid black;
 7189:     width: 99.9%;
 7190:     height: 0px;
 7191: }
 7192: 
 7193: .LC_iframecontainer {
 7194:     width: 98%;
 7195:     margin: 0;
 7196:     position: fixed;
 7197:     top: 8.5em;
 7198:     bottom: 0;
 7199: }
 7200: 
 7201: .LC_iframecontainer iframe{
 7202:     border: none;
 7203:     width: 100%;
 7204:     height: 100%;
 7205: }
 7206: 
 7207: .LC_filename {
 7208:   font-family: $mono;
 7209:   white-space:pre;
 7210:   font-size: 120%;
 7211: }
 7212: 
 7213: .LC_fileicon {
 7214:   border: none;
 7215:   height: 1.3em;
 7216:   vertical-align: text-bottom;
 7217:   margin-right: 0.3em;
 7218:   text-decoration:none;
 7219: }
 7220: 
 7221: .LC_setting {
 7222:   text-decoration:underline;
 7223: }
 7224: 
 7225: .LC_error {
 7226:   color: red;
 7227: }
 7228: 
 7229: .LC_warning {
 7230:   color: darkorange;
 7231: }
 7232: 
 7233: .LC_diff_removed {
 7234:   color: red;
 7235: }
 7236: 
 7237: .LC_info,
 7238: .LC_success,
 7239: .LC_diff_added {
 7240:   color: green;
 7241: }
 7242: 
 7243: div.LC_confirm_box {
 7244:   background-color: #FAFAFA;
 7245:   border: 1px solid $lg_border_color;
 7246:   margin-right: 0;
 7247:   padding: 5px;
 7248: }
 7249: 
 7250: div.LC_confirm_box .LC_error img,
 7251: div.LC_confirm_box .LC_success img {
 7252:   vertical-align: middle;
 7253: }
 7254: 
 7255: .LC_maxwidth {
 7256:   max-width: 100%;
 7257:   height: auto;
 7258: }
 7259: 
 7260: .LC_textsize_mobile {
 7261:   \@media only screen and (max-device-width: 480px) {
 7262:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
 7263:   }
 7264: }
 7265: 
 7266: .LC_icon {
 7267:   border: none;
 7268:   vertical-align: middle;
 7269: }
 7270: 
 7271: .LC_docs_spacer {
 7272:   width: 25px;
 7273:   height: 1px;
 7274:   border: none;
 7275: }
 7276: 
 7277: .LC_internal_info {
 7278:   color: #999999;
 7279: }
 7280: 
 7281: .LC_discussion {
 7282:   background: $data_table_dark;
 7283:   border: 1px solid black;
 7284:   margin: 2px;
 7285: }
 7286: 
 7287: .LC_disc_action_left {
 7288:   background: $sidebg;
 7289:   text-align: left;
 7290:   padding: 4px;
 7291:   margin: 2px;
 7292: }
 7293: 
 7294: .LC_disc_action_right {
 7295:   background: $sidebg;
 7296:   text-align: right;
 7297:   padding: 4px;
 7298:   margin: 2px;
 7299: }
 7300: 
 7301: .LC_disc_new_item {
 7302:   background: white;
 7303:   border: 2px solid red;
 7304:   margin: 4px;
 7305:   padding: 4px;
 7306: }
 7307: 
 7308: .LC_disc_old_item {
 7309:   background: white;
 7310:   margin: 4px;
 7311:   padding: 4px;
 7312: }
 7313: 
 7314: table.LC_pastsubmission {
 7315:   border: 1px solid black;
 7316:   margin: 2px;
 7317: }
 7318: 
 7319: table#LC_menubuttons {
 7320:   width: 100%;
 7321:   background: $pgbg;
 7322:   border: 2px;
 7323:   border-collapse: separate;
 7324:   padding: 0;
 7325: }
 7326: 
 7327: table#LC_title_bar a {
 7328:   color: $fontmenu;
 7329: }
 7330: 
 7331: table#LC_title_bar {
 7332:   clear: both;
 7333:   display: none;
 7334: }
 7335: 
 7336: table#LC_title_bar,
 7337: table.LC_breadcrumbs, /* obsolete? */
 7338: table#LC_title_bar.LC_with_remote {
 7339:   width: 100%;
 7340:   border-color: $pgbg;
 7341:   border-style: solid;
 7342:   border-width: $border;
 7343:   background: $pgbg;
 7344:   color: $fontmenu;
 7345:   border-collapse: collapse;
 7346:   padding: 0;
 7347:   margin: 0;
 7348: }
 7349: 
 7350: ul.LC_breadcrumb_tools_outerlist {
 7351:     margin: 0;
 7352:     padding: 0;
 7353:     position: relative;
 7354:     list-style: none;
 7355: }
 7356: ul.LC_breadcrumb_tools_outerlist li {
 7357:     display: inline;
 7358: }
 7359: 
 7360: .LC_breadcrumb_tools_navigation {
 7361:     padding: 0;
 7362:     margin: 0;
 7363:     float: left;
 7364: }
 7365: .LC_breadcrumb_tools_tools {
 7366:     padding: 0;
 7367:     margin: 0;
 7368:     float: right;
 7369: }
 7370: 
 7371: .LC_placement_prog {
 7372:     padding-right: 20px;
 7373:     font-weight: bold;
 7374:     font-size: 90%;
 7375: }
 7376: 
 7377: table#LC_title_bar td {
 7378:   background: $tabbg;
 7379: }
 7380: 
 7381: table#LC_menubuttons img {
 7382:   border: none;
 7383: }
 7384: 
 7385: .LC_breadcrumbs_component {
 7386:   float: right;
 7387:   margin: 0 1em;
 7388: }
 7389: .LC_breadcrumbs_component img {
 7390:   vertical-align: middle;
 7391: }
 7392: 
 7393: .LC_breadcrumbs_hoverable {
 7394:   background: $sidebg;
 7395: }
 7396: 
 7397: td.LC_table_cell_checkbox {
 7398:   text-align: center;
 7399: }
 7400: 
 7401: .LC_fontsize_small {
 7402:   font-size: 70%;
 7403: }
 7404: 
 7405: #LC_breadcrumbs {
 7406:   clear:both;
 7407:   background: $sidebg;
 7408:   border-bottom: 1px solid $lg_border_color;
 7409:   line-height: 2.5em;
 7410:   overflow: hidden;
 7411:   margin: 0;
 7412:   padding: 0;
 7413:   text-align: left;
 7414: }
 7415: 
 7416: .LC_head_subbox, .LC_actionbox {
 7417:   clear:both;
 7418:   background: #F8F8F8; /* $sidebg; */
 7419:   border: 1px solid $sidebg;
 7420:   margin: 0 0 10px 0;
 7421:   padding: 3px;
 7422:   text-align: left;
 7423: }
 7424: 
 7425: .LC_fontsize_medium {
 7426:   font-size: 85%;
 7427: }
 7428: 
 7429: .LC_fontsize_large {
 7430:   font-size: 120%;
 7431: }
 7432: 
 7433: .LC_menubuttons_inline_text {
 7434:   color: $font;
 7435:   font-size: 90%;
 7436:   padding-left:3px;
 7437: }
 7438: 
 7439: .LC_menubuttons_inline_text img{
 7440:   vertical-align: middle;
 7441: }
 7442: 
 7443: li.LC_menubuttons_inline_text img {
 7444:   cursor:pointer;
 7445:   text-decoration: none;
 7446: }
 7447: 
 7448: .LC_menubuttons_link {
 7449:   text-decoration: none;
 7450: }
 7451: 
 7452: .LC_menubuttons_category {
 7453:   color: $font;
 7454:   background: $pgbg;
 7455:   font-size: larger;
 7456:   font-weight: bold;
 7457: }
 7458: 
 7459: td.LC_menubuttons_text {
 7460:   color: $font;
 7461: }
 7462: 
 7463: .LC_current_location {
 7464:   background: $tabbg;
 7465: }
 7466: 
 7467: td.LC_zero_height {
 7468:   line-height: 0; 
 7469:   cellpadding: 0;
 7470: }
 7471: 
 7472: table.LC_data_table {
 7473:   border: 1px solid #000000;
 7474:   border-collapse: separate;
 7475:   border-spacing: 1px;
 7476:   background: $pgbg;
 7477: }
 7478: 
 7479: .LC_data_table_dense {
 7480:   font-size: small;
 7481: }
 7482: 
 7483: table.LC_nested_outer {
 7484:   border: 1px solid #000000;
 7485:   border-collapse: collapse;
 7486:   border-spacing: 0;
 7487:   width: 100%;
 7488: }
 7489: 
 7490: table.LC_innerpickbox,
 7491: table.LC_nested {
 7492:   border: none;
 7493:   border-collapse: collapse;
 7494:   border-spacing: 0;
 7495:   width: 100%;
 7496: }
 7497: 
 7498: table.LC_data_table tr th,
 7499: table.LC_calendar tr th,
 7500: table.LC_prior_tries tr th,
 7501: table.LC_innerpickbox tr th {
 7502:   font-weight: bold;
 7503:   background-color: $data_table_head;
 7504:   color:$fontmenu;
 7505:   font-size:90%;
 7506: }
 7507: 
 7508: table.LC_innerpickbox tr th,
 7509: table.LC_innerpickbox tr td {
 7510:   vertical-align: top;
 7511: }
 7512: 
 7513: table.LC_data_table tr.LC_info_row > td {
 7514:   background-color: #CCCCCC;
 7515:   font-weight: bold;
 7516:   text-align: left;
 7517: }
 7518: 
 7519: table.LC_data_table tr.LC_odd_row > td {
 7520:   background-color: $data_table_light;
 7521:   padding: 2px;
 7522:   vertical-align: top;
 7523: }
 7524: 
 7525: table.LC_pick_box tr > td.LC_odd_row {
 7526:   background-color: $data_table_light;
 7527:   vertical-align: top;
 7528: }
 7529: 
 7530: table.LC_data_table tr.LC_even_row > td {
 7531:   background-color: $data_table_dark;
 7532:   padding: 2px;
 7533:   vertical-align: top;
 7534: }
 7535: 
 7536: table.LC_pick_box tr > td.LC_even_row {
 7537:   background-color: $data_table_dark;
 7538:   vertical-align: top;
 7539: }
 7540: 
 7541: table.LC_data_table tr.LC_data_table_highlight td {
 7542:   background-color: $data_table_darker;
 7543: }
 7544: 
 7545: table.LC_data_table tr td.LC_leftcol_header {
 7546:   background-color: $data_table_head;
 7547:   font-weight: bold;
 7548: }
 7549: 
 7550: table.LC_data_table tr.LC_empty_row td,
 7551: table.LC_nested tr.LC_empty_row td {
 7552:   font-weight: bold;
 7553:   font-style: italic;
 7554:   text-align: center;
 7555:   padding: 8px;
 7556: }
 7557: 
 7558: table.LC_data_table tr.LC_empty_row td,
 7559: table.LC_data_table tr.LC_footer_row td {
 7560:   background-color: $sidebg;
 7561: }
 7562: 
 7563: table.LC_nested tr.LC_empty_row td {
 7564:   background-color: #FFFFFF;
 7565: }
 7566: 
 7567: table.LC_caption {
 7568: }
 7569: 
 7570: table.LC_nested tr.LC_empty_row td {
 7571:   padding: 4ex
 7572: }
 7573: 
 7574: table.LC_nested_outer tr th {
 7575:   font-weight: bold;
 7576:   color:$fontmenu;
 7577:   background-color: $data_table_head;
 7578:   font-size: small;
 7579:   border-bottom: 1px solid #000000;
 7580: }
 7581: 
 7582: table.LC_nested_outer tr td.LC_subheader {
 7583:   background-color: $data_table_head;
 7584:   font-weight: bold;
 7585:   font-size: small;
 7586:   border-bottom: 1px solid #000000;
 7587:   text-align: right;
 7588: }
 7589: 
 7590: table.LC_nested tr.LC_info_row td {
 7591:   background-color: #CCCCCC;
 7592:   font-weight: bold;
 7593:   font-size: small;
 7594:   text-align: center;
 7595: }
 7596: 
 7597: table.LC_nested tr.LC_info_row td.LC_left_item,
 7598: table.LC_nested_outer tr th.LC_left_item {
 7599:   text-align: left;
 7600: }
 7601: 
 7602: table.LC_nested td {
 7603:   background-color: #FFFFFF;
 7604:   font-size: small;
 7605: }
 7606: 
 7607: table.LC_nested_outer tr th.LC_right_item,
 7608: table.LC_nested tr.LC_info_row td.LC_right_item,
 7609: table.LC_nested tr.LC_odd_row td.LC_right_item,
 7610: table.LC_nested tr td.LC_right_item {
 7611:   text-align: right;
 7612: }
 7613: 
 7614: table.LC_nested tr.LC_odd_row td {
 7615:   background-color: #EEEEEE;
 7616: }
 7617: 
 7618: table.LC_createuser {
 7619: }
 7620: 
 7621: table.LC_createuser tr.LC_section_row td {
 7622:   font-size: small;
 7623: }
 7624: 
 7625: table.LC_createuser tr.LC_info_row td  {
 7626:   background-color: #CCCCCC;
 7627:   font-weight: bold;
 7628:   text-align: center;
 7629: }
 7630: 
 7631: table.LC_calendar {
 7632:   border: 1px solid #000000;
 7633:   border-collapse: collapse;
 7634:   width: 98%;
 7635: }
 7636: 
 7637: table.LC_calendar_pickdate {
 7638:   font-size: xx-small;
 7639: }
 7640: 
 7641: table.LC_calendar tr td {
 7642:   border: 1px solid #000000;
 7643:   vertical-align: top;
 7644:   width: 14%;
 7645: }
 7646: 
 7647: table.LC_calendar tr td.LC_calendar_day_empty {
 7648:   background-color: $data_table_dark;
 7649: }
 7650: 
 7651: table.LC_calendar tr td.LC_calendar_day_current {
 7652:   background-color: $data_table_highlight;
 7653: }
 7654: 
 7655: table.LC_data_table tr td.LC_mail_new {
 7656:   background-color: $mail_new;
 7657: }
 7658: 
 7659: table.LC_data_table tr.LC_mail_new:hover {
 7660:   background-color: $mail_new_hover;
 7661: }
 7662: 
 7663: table.LC_data_table tr td.LC_mail_read {
 7664:   background-color: $mail_read;
 7665: }
 7666: 
 7667: /*
 7668: table.LC_data_table tr.LC_mail_read:hover {
 7669:   background-color: $mail_read_hover;
 7670: }
 7671: */
 7672: 
 7673: table.LC_data_table tr td.LC_mail_replied {
 7674:   background-color: $mail_replied;
 7675: }
 7676: 
 7677: /*
 7678: table.LC_data_table tr.LC_mail_replied:hover {
 7679:   background-color: $mail_replied_hover;
 7680: }
 7681: */
 7682: 
 7683: table.LC_data_table tr td.LC_mail_other {
 7684:   background-color: $mail_other;
 7685: }
 7686: 
 7687: /*
 7688: table.LC_data_table tr.LC_mail_other:hover {
 7689:   background-color: $mail_other_hover;
 7690: }
 7691: */
 7692: 
 7693: table.LC_data_table tr > td.LC_browser_file,
 7694: table.LC_data_table tr > td.LC_browser_file_published {
 7695:   background: #AAEE77;
 7696: }
 7697: 
 7698: table.LC_data_table tr > td.LC_browser_file_locked,
 7699: table.LC_data_table tr > td.LC_browser_file_unpublished {
 7700:   background: #FFAA99;
 7701: }
 7702: 
 7703: table.LC_data_table tr > td.LC_browser_file_obsolete {
 7704:   background: #888888;
 7705: }
 7706: 
 7707: table.LC_data_table tr > td.LC_browser_file_modified,
 7708: table.LC_data_table tr > td.LC_browser_file_metamodified {
 7709:   background: #F8F866;
 7710: }
 7711: 
 7712: table.LC_data_table tr.LC_browser_folder > td {
 7713:   background: #E0E8FF;
 7714: }
 7715: 
 7716: table.LC_data_table tr > td.LC_roles_is {
 7717:   /* background: #77FF77; */
 7718: }
 7719: 
 7720: table.LC_data_table tr > td.LC_roles_future {
 7721:   border-right: 8px solid #FFFF77;
 7722: }
 7723: 
 7724: table.LC_data_table tr > td.LC_roles_will {
 7725:   border-right: 8px solid #FFAA77;
 7726: }
 7727: 
 7728: table.LC_data_table tr > td.LC_roles_expired {
 7729:   border-right: 8px solid #FF7777;
 7730: }
 7731: 
 7732: table.LC_data_table tr > td.LC_roles_will_not {
 7733:   border-right: 8px solid #AAFF77;
 7734: }
 7735: 
 7736: table.LC_data_table tr > td.LC_roles_selected {
 7737:   border-right: 8px solid #11CC55;
 7738: }
 7739: 
 7740: span.LC_current_location {
 7741:   font-size:larger;
 7742:   background: $pgbg;
 7743: }
 7744: 
 7745: span.LC_current_nav_location {
 7746:   font-weight:bold;
 7747:   background: $sidebg;
 7748: }
 7749: 
 7750: span.LC_parm_menu_item {
 7751:   font-size: larger;
 7752: }
 7753: 
 7754: span.LC_parm_scope_all {
 7755:   color: red;
 7756: }
 7757: 
 7758: span.LC_parm_scope_folder {
 7759:   color: green;
 7760: }
 7761: 
 7762: span.LC_parm_scope_resource {
 7763:   color: orange;
 7764: }
 7765: 
 7766: span.LC_parm_part {
 7767:   color: blue;
 7768: }
 7769: 
 7770: span.LC_parm_folder,
 7771: span.LC_parm_symb {
 7772:   font-size: x-small;
 7773:   font-family: $mono;
 7774:   color: #AAAAAA;
 7775: }
 7776: 
 7777: ul.LC_parm_parmlist li {
 7778:   display: inline-block;
 7779:   padding: 0.3em 0.8em;
 7780:   vertical-align: top;
 7781:   width: 150px;
 7782:   border-top:1px solid $lg_border_color;
 7783: }
 7784: 
 7785: td.LC_parm_overview_level_menu,
 7786: td.LC_parm_overview_map_menu,
 7787: td.LC_parm_overview_parm_selectors,
 7788: td.LC_parm_overview_restrictions  {
 7789:   border: 1px solid black;
 7790:   border-collapse: collapse;
 7791: }
 7792: 
 7793: span.LC_parm_recursive,
 7794: td.LC_parm_recursive {
 7795:   font-weight: bold;
 7796:   font-size: smaller;
 7797: }
 7798: 
 7799: table.LC_parm_overview_restrictions td {
 7800:   border-width: 1px 4px 1px 4px;
 7801:   border-style: solid;
 7802:   border-color: $pgbg;
 7803:   text-align: center;
 7804: }
 7805: 
 7806: table.LC_parm_overview_restrictions th {
 7807:   background: $tabbg;
 7808:   border-width: 1px 4px 1px 4px;
 7809:   border-style: solid;
 7810:   border-color: $pgbg;
 7811: }
 7812: 
 7813: table#LC_helpmenu {
 7814:   border: none;
 7815:   height: 55px;
 7816:   border-spacing: 0;
 7817: }
 7818: 
 7819: table#LC_helpmenu fieldset legend {
 7820:   font-size: larger;
 7821: }
 7822: 
 7823: table#LC_helpmenu_links {
 7824:   width: 100%;
 7825:   border: 1px solid black;
 7826:   background: $pgbg;
 7827:   padding: 0;
 7828:   border-spacing: 1px;
 7829: }
 7830: 
 7831: table#LC_helpmenu_links tr td {
 7832:   padding: 1px;
 7833:   background: $tabbg;
 7834:   text-align: center;
 7835:   font-weight: bold;
 7836: }
 7837: 
 7838: table#LC_helpmenu_links a:link,
 7839: table#LC_helpmenu_links a:visited,
 7840: table#LC_helpmenu_links a:active {
 7841:   text-decoration: none;
 7842:   color: $font;
 7843: }
 7844: 
 7845: table#LC_helpmenu_links a:hover {
 7846:   text-decoration: underline;
 7847:   color: $vlink;
 7848: }
 7849: 
 7850: .LC_chrt_popup_exists {
 7851:   border: 1px solid #339933;
 7852:   margin: -1px;
 7853: }
 7854: 
 7855: .LC_chrt_popup_up {
 7856:   border: 1px solid yellow;
 7857:   margin: -1px;
 7858: }
 7859: 
 7860: .LC_chrt_popup {
 7861:   border: 1px solid #8888FF;
 7862:   background: #CCCCFF;
 7863: }
 7864: 
 7865: table.LC_pick_box {
 7866:   border-collapse: separate;
 7867:   background: white;
 7868:   border: 1px solid black;
 7869:   border-spacing: 1px;
 7870: }
 7871: 
 7872: table.LC_pick_box td.LC_pick_box_title {
 7873:   background: $sidebg;
 7874:   font-weight: bold;
 7875:   text-align: left;
 7876:   vertical-align: top;
 7877:   width: 184px;
 7878:   padding: 8px;
 7879: }
 7880: 
 7881: table.LC_pick_box td.LC_pick_box_value {
 7882:   text-align: left;
 7883:   padding: 8px;
 7884: }
 7885: 
 7886: table.LC_pick_box td.LC_pick_box_select {
 7887:   text-align: left;
 7888:   padding: 8px;
 7889: }
 7890: 
 7891: table.LC_pick_box td.LC_pick_box_separator {
 7892:   padding: 0;
 7893:   height: 1px;
 7894:   background: black;
 7895: }
 7896: 
 7897: table.LC_pick_box td.LC_pick_box_submit {
 7898:   text-align: right;
 7899: }
 7900: 
 7901: table.LC_pick_box td.LC_evenrow_value {
 7902:   text-align: left;
 7903:   padding: 8px;
 7904:   background-color: $data_table_light;
 7905: }
 7906: 
 7907: table.LC_pick_box td.LC_oddrow_value {
 7908:   text-align: left;
 7909:   padding: 8px;
 7910:   background-color: $data_table_light;
 7911: }
 7912: 
 7913: span.LC_helpform_receipt_cat {
 7914:   font-weight: bold;
 7915: }
 7916: 
 7917: table.LC_group_priv_box {
 7918:   background: white;
 7919:   border: 1px solid black;
 7920:   border-spacing: 1px;
 7921: }
 7922: 
 7923: table.LC_group_priv_box td.LC_pick_box_title {
 7924:   background: $tabbg;
 7925:   font-weight: bold;
 7926:   text-align: right;
 7927:   width: 184px;
 7928: }
 7929: 
 7930: table.LC_group_priv_box td.LC_groups_fixed {
 7931:   background: $data_table_light;
 7932:   text-align: center;
 7933: }
 7934: 
 7935: table.LC_group_priv_box td.LC_groups_optional {
 7936:   background: $data_table_dark;
 7937:   text-align: center;
 7938: }
 7939: 
 7940: table.LC_group_priv_box td.LC_groups_functionality {
 7941:   background: $data_table_darker;
 7942:   text-align: center;
 7943:   font-weight: bold;
 7944: }
 7945: 
 7946: table.LC_group_priv td {
 7947:   text-align: left;
 7948:   padding: 0;
 7949: }
 7950: 
 7951: .LC_navbuttons {
 7952:   margin: 2ex 0ex 2ex 0ex;
 7953: }
 7954: 
 7955: .LC_topic_bar {
 7956:   font-weight: bold;
 7957:   background: $tabbg;
 7958:   margin: 1em 0em 1em 2em;
 7959:   padding: 3px;
 7960:   font-size: 1.2em;
 7961: }
 7962: 
 7963: .LC_topic_bar span {
 7964:   left: 0.5em;
 7965:   position: absolute;
 7966:   vertical-align: middle;
 7967:   font-size: 1.2em;
 7968: }
 7969: 
 7970: table.LC_course_group_status {
 7971:   margin: 20px;
 7972: }
 7973: 
 7974: table.LC_status_selector td {
 7975:   vertical-align: top;
 7976:   text-align: center;
 7977:   padding: 4px;
 7978: }
 7979: 
 7980: div.LC_feedback_link {
 7981:   clear: both;
 7982:   background: $sidebg;
 7983:   width: 100%;
 7984:   padding-bottom: 10px;
 7985:   border: 1px $tabbg solid;
 7986:   height: 22px;
 7987:   line-height: 22px;
 7988:   padding-top: 5px;
 7989: }
 7990: 
 7991: div.LC_feedback_link img {
 7992:   height: 22px;
 7993:   vertical-align:middle;
 7994: }
 7995: 
 7996: div.LC_feedback_link a {
 7997:   text-decoration: none;
 7998: }
 7999: 
 8000: div.LC_comblock {
 8001:   display:inline;
 8002:   color:$font;
 8003:   font-size:90%;
 8004: }
 8005: 
 8006: div.LC_feedback_link div.LC_comblock {
 8007:   padding-left:5px;
 8008: }
 8009: 
 8010: div.LC_feedback_link div.LC_comblock a {
 8011:   color:$font;
 8012: }
 8013: 
 8014: span.LC_feedback_link {
 8015:   /* background: $feedback_link_bg; */
 8016:   font-size: larger;
 8017: }
 8018: 
 8019: span.LC_message_link {
 8020:   /* background: $feedback_link_bg; */
 8021:   font-size: larger;
 8022:   position: absolute;
 8023:   right: 1em;
 8024: }
 8025: 
 8026: table.LC_prior_tries {
 8027:   border: 1px solid #000000;
 8028:   border-collapse: separate;
 8029:   border-spacing: 1px;
 8030: }
 8031: 
 8032: table.LC_prior_tries td {
 8033:   padding: 2px;
 8034: }
 8035: 
 8036: .LC_answer_correct {
 8037:   background: lightgreen;
 8038:   color: darkgreen;
 8039:   padding: 6px;
 8040: }
 8041: 
 8042: .LC_answer_charged_try {
 8043:   background: #FFAAAA;
 8044:   color: darkred;
 8045:   padding: 6px;
 8046: }
 8047: 
 8048: .LC_answer_not_charged_try,
 8049: .LC_answer_no_grade,
 8050: .LC_answer_late {
 8051:   background: lightyellow;
 8052:   color: black;
 8053:   padding: 6px;
 8054: }
 8055: 
 8056: .LC_answer_previous {
 8057:   background: lightblue;
 8058:   color: darkblue;
 8059:   padding: 6px;
 8060: }
 8061: 
 8062: .LC_answer_no_message {
 8063:   background: #FFFFFF;
 8064:   color: black;
 8065:   padding: 6px;
 8066: }
 8067: 
 8068: .LC_answer_unknown,
 8069: .LC_answer_warning {
 8070:   background: orange;
 8071:   color: black;
 8072:   padding: 6px;
 8073: }
 8074: 
 8075: span.LC_prior_numerical,
 8076: span.LC_prior_string,
 8077: span.LC_prior_custom,
 8078: span.LC_prior_reaction,
 8079: span.LC_prior_math {
 8080:   font-family: $mono;
 8081:   white-space: pre;
 8082: }
 8083: 
 8084: span.LC_prior_string {
 8085:   font-family: $mono;
 8086:   white-space: pre;
 8087: }
 8088: 
 8089: table.LC_prior_option {
 8090:   width: 100%;
 8091:   border-collapse: collapse;
 8092: }
 8093: 
 8094: table.LC_prior_rank,
 8095: table.LC_prior_match {
 8096:   border-collapse: collapse;
 8097: }
 8098: 
 8099: table.LC_prior_option tr td,
 8100: table.LC_prior_rank tr td,
 8101: table.LC_prior_match tr td {
 8102:   border: 1px solid #000000;
 8103: }
 8104: 
 8105: .LC_nobreak {
 8106:   white-space: nowrap;
 8107: }
 8108: 
 8109: span.LC_cusr_emph {
 8110:   font-style: italic;
 8111: }
 8112: 
 8113: span.LC_cusr_subheading {
 8114:   font-weight: normal;
 8115:   font-size: 85%;
 8116: }
 8117: 
 8118: div.LC_docs_entry_move {
 8119:   border: 1px solid #BBBBBB;
 8120:   background: #DDDDDD;
 8121:   width: 22px;
 8122:   padding: 1px;
 8123:   margin: 0;
 8124: }
 8125: 
 8126: table.LC_data_table tr > td.LC_docs_entry_commands,
 8127: table.LC_data_table tr > td.LC_docs_entry_parameter {
 8128:   font-size: x-small;
 8129: }
 8130: 
 8131: .LC_docs_entry_parameter {
 8132:   white-space: nowrap;
 8133: }
 8134: 
 8135: .LC_docs_copy {
 8136:   color: #000099;
 8137: }
 8138: 
 8139: .LC_docs_cut {
 8140:   color: #550044;
 8141: }
 8142: 
 8143: .LC_docs_rename {
 8144:   color: #009900;
 8145: }
 8146: 
 8147: .LC_docs_remove {
 8148:   color: #990000;
 8149: }
 8150: 
 8151: .LC_docs_alias {
 8152:   color: #440055;  
 8153: }
 8154: 
 8155: .LC_domprefs_email,
 8156: .LC_docs_alias_name,
 8157: .LC_docs_reinit_warn,
 8158: .LC_docs_ext_edit {
 8159:   font-size: x-small;
 8160: }
 8161: 
 8162: table.LC_docs_adddocs td,
 8163: table.LC_docs_adddocs th {
 8164:   border: 1px solid #BBBBBB;
 8165:   padding: 4px;
 8166:   background: #DDDDDD;
 8167: }
 8168: 
 8169: table.LC_sty_begin {
 8170:   background: #BBFFBB;
 8171: }
 8172: 
 8173: table.LC_sty_end {
 8174:   background: #FFBBBB;
 8175: }
 8176: 
 8177: table.LC_double_column {
 8178:   border-width: 0;
 8179:   border-collapse: collapse;
 8180:   width: 100%;
 8181:   padding: 2px;
 8182: }
 8183: 
 8184: table.LC_double_column tr td.LC_left_col {
 8185:   top: 2px;
 8186:   left: 2px;
 8187:   width: 47%;
 8188:   vertical-align: top;
 8189: }
 8190: 
 8191: table.LC_double_column tr td.LC_right_col {
 8192:   top: 2px;
 8193:   right: 2px;
 8194:   width: 47%;
 8195:   vertical-align: top;
 8196: }
 8197: 
 8198: div.LC_left_float {
 8199:   float: left;
 8200:   padding-right: 5%;
 8201:   padding-bottom: 4px;
 8202: }
 8203: 
 8204: div.LC_clear_float_header {
 8205:   padding-bottom: 2px;
 8206: }
 8207: 
 8208: div.LC_clear_float_footer {
 8209:   padding-top: 10px;
 8210:   clear: both;
 8211: }
 8212: 
 8213: div.LC_grade_show_user {
 8214: /*  border-left: 5px solid $sidebg; */
 8215:   border-top: 5px solid #000000;
 8216:   margin: 50px 0 0 0;
 8217:   padding: 15px 0 5px 10px;
 8218: }
 8219: 
 8220: div.LC_grade_show_user_odd_row {
 8221: /*  border-left: 5px solid #000000; */
 8222: }
 8223: 
 8224: div.LC_grade_show_user div.LC_Box {
 8225:   margin-right: 50px;
 8226: }
 8227: 
 8228: div.LC_grade_submissions,
 8229: div.LC_grade_message_center,
 8230: div.LC_grade_info_links {
 8231:   margin: 5px;
 8232:   width: 99%;
 8233:   background: #FFFFFF;
 8234: }
 8235: 
 8236: div.LC_grade_submissions_header,
 8237: div.LC_grade_message_center_header {
 8238:   font-weight: bold;
 8239:   font-size: large;
 8240: }
 8241: 
 8242: div.LC_grade_submissions_body,
 8243: div.LC_grade_message_center_body {
 8244:   border: 1px solid black;
 8245:   width: 99%;
 8246:   background: #FFFFFF;
 8247: }
 8248: 
 8249: table.LC_scantron_action {
 8250:   width: 100%;
 8251: }
 8252: 
 8253: table.LC_scantron_action tr th {
 8254:   font-weight:bold;
 8255:   font-style:normal;
 8256: }
 8257: 
 8258: .LC_edit_problem_header,
 8259: div.LC_edit_problem_footer {
 8260:   font-weight: normal;
 8261:   font-size:  medium;
 8262:   margin: 2px;
 8263:   background-color: $sidebg;
 8264: }
 8265: 
 8266: div.LC_edit_problem_header,
 8267: div.LC_edit_problem_header div,
 8268: div.LC_edit_problem_footer,
 8269: div.LC_edit_problem_footer div,
 8270: div.LC_edit_problem_editxml_header,
 8271: div.LC_edit_problem_editxml_header div {
 8272:   z-index: 100;
 8273: }
 8274: 
 8275: div.LC_edit_problem_header_title {
 8276:   font-weight: bold;
 8277:   font-size: larger;
 8278:   background: $tabbg;
 8279:   padding: 3px;
 8280:   margin: 0 0 5px 0;
 8281: }
 8282: 
 8283: table.LC_edit_problem_header_title {
 8284:   width: 100%;
 8285:   background: $tabbg;
 8286: }
 8287: 
 8288: div.LC_edit_actionbar {
 8289:     background-color: $sidebg;
 8290:     margin: 0;
 8291:     padding: 0;
 8292:     line-height: 200%;
 8293: }
 8294: 
 8295: div.LC_edit_actionbar div{
 8296:     padding: 0;
 8297:     margin: 0;
 8298:     display: inline-block;
 8299: }
 8300: 
 8301: .LC_edit_opt {
 8302:   padding-left: 1em;
 8303:   white-space: nowrap;
 8304: }
 8305: 
 8306: .LC_edit_problem_latexhelper{
 8307:     text-align: right;
 8308: }
 8309: 
 8310: #LC_edit_problem_colorful div{
 8311:     margin-left: 40px;
 8312: }
 8313: 
 8314: #LC_edit_problem_codemirror div{
 8315:     margin-left: 0px;
 8316: }
 8317: 
 8318: img.stift {
 8319:   border-width: 0;
 8320:   vertical-align: middle;
 8321: }
 8322: 
 8323: table td.LC_mainmenu_col_fieldset {
 8324:   vertical-align: top;
 8325: }
 8326: 
 8327: div.LC_createcourse {
 8328:   margin: 10px 10px 10px 10px;
 8329: }
 8330: 
 8331: .LC_dccid {
 8332:   float: right;
 8333:   margin: 0.2em 0 0 0;
 8334:   padding: 0;
 8335:   font-size: 90%;
 8336:   display:none;
 8337: }
 8338: 
 8339: ol.LC_primary_menu a:hover,
 8340: ol#LC_MenuBreadcrumbs a:hover,
 8341: ol#LC_PathBreadcrumbs a:hover,
 8342: ul#LC_secondary_menu a:hover,
 8343: .LC_FormSectionClearButton input:hover
 8344: ul.LC_TabContent   li:hover a {
 8345:   color:$button_hover;
 8346:   text-decoration:none;
 8347: }
 8348: 
 8349: h1 {
 8350:   padding: 0;
 8351:   line-height:130%;
 8352: }
 8353: 
 8354: h2,
 8355: h3,
 8356: h4,
 8357: h5,
 8358: h6 {
 8359:   margin: 5px 0 5px 0;
 8360:   padding: 0;
 8361:   line-height:130%;
 8362: }
 8363: 
 8364: .LC_hcell {
 8365:   padding:3px 15px 3px 15px;
 8366:   margin: 0;
 8367:   background-color:$tabbg;
 8368:   color:$fontmenu;
 8369:   border-bottom:solid 1px $lg_border_color;
 8370: }
 8371: 
 8372: .LC_Box > .LC_hcell {
 8373:   margin: 0 -10px 10px -10px;
 8374: }
 8375: 
 8376: .LC_noBorder {
 8377:   border: 0;
 8378: }
 8379: 
 8380: .LC_FormSectionClearButton input {
 8381:   background-color:transparent;
 8382:   border: none;
 8383:   cursor:pointer;
 8384:   text-decoration:underline;
 8385: }
 8386: 
 8387: .LC_help_open_topic {
 8388:   color: #FFFFFF;
 8389:   background-color: #EEEEFF;
 8390:   margin: 1px;
 8391:   padding: 4px;
 8392:   border: 1px solid #000033;
 8393:   white-space: nowrap;
 8394:   /* vertical-align: middle; */
 8395: }
 8396: 
 8397: dl,
 8398: ul,
 8399: div,
 8400: fieldset {
 8401:   margin: 10px 10px 10px 0;
 8402:   /* overflow: hidden; */
 8403: }
 8404: 
 8405: fieldset#LC_selectuser {
 8406:     margin: 0;
 8407:     padding: 0;
 8408: }
 8409: 
 8410: article.geogebraweb div {
 8411:     margin: 0;
 8412: }
 8413: 
 8414: fieldset > legend {
 8415:   font-weight: bold;
 8416:   padding: 0 5px 0 5px;
 8417: }
 8418: 
 8419: #LC_nav_bar {
 8420:   float: left;
 8421:   background-color: $pgbg_or_bgcolor;
 8422:   margin: 0 0 2px 0;
 8423: }
 8424: 
 8425: #LC_realm {
 8426:   margin: 0.2em 0 0 0;
 8427:   padding: 0;
 8428:   font-weight: bold;
 8429:   text-align: center;
 8430:   background-color: $pgbg_or_bgcolor;
 8431: }
 8432: 
 8433: #LC_nav_bar em {
 8434:   font-weight: bold;
 8435:   font-style: normal;
 8436: }
 8437: 
 8438: ol.LC_primary_menu {
 8439:   margin: 0;
 8440:   padding: 0;
 8441: }
 8442: 
 8443: ol#LC_PathBreadcrumbs {
 8444:   margin: 0;
 8445: }
 8446: 
 8447: ol.LC_primary_menu li {
 8448:   color: RGB(80, 80, 80);
 8449:   vertical-align: middle;
 8450:   text-align: left;
 8451:   list-style: none;
 8452:   position: relative;
 8453:   float: left;
 8454:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
 8455:   line-height: 1.5em;
 8456: }
 8457: 
 8458: ol.LC_primary_menu li a,
 8459: ol.LC_primary_menu li p {
 8460:   display: block;
 8461:   margin: 0;
 8462:   padding: 0 5px 0 10px;
 8463:   text-decoration: none;
 8464: }
 8465: 
 8466: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
 8467:   display: inline-block;
 8468:   width: 95%;
 8469:   text-align: left;
 8470: }
 8471: 
 8472: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
 8473:   display: inline-block;	
 8474:   width: 5%;
 8475:   float: right;
 8476:   text-align: right;
 8477:   font-size: 70%;
 8478: }
 8479: 
 8480: ol.LC_primary_menu ul {
 8481:   display: none;
 8482:   width: 15em;
 8483:   background-color: $data_table_light;
 8484:   position: absolute;
 8485:   top: 100%;
 8486: }
 8487: 
 8488: ol.LC_primary_menu ul ul {
 8489:   left: 100%;
 8490:   top: 0;
 8491: }
 8492: 
 8493: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
 8494:   display: block;
 8495:   position: absolute;
 8496:   margin: 0;
 8497:   padding: 0;
 8498:   z-index: 2;
 8499: }
 8500: 
 8501: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 8502: /* First Submenu -> size should be smaller than the menu title of the whole menu */
 8503:   font-size: 90%;
 8504:   vertical-align: top;
 8505:   float: none;
 8506:   border-left: 1px solid black;
 8507:   border-right: 1px solid black;
 8508: /* A dark bottom border to visualize different menu options; 
 8509: overwritten in the create_submenu routine for the last border-bottom of the menu */
 8510:   border-bottom: 1px solid $data_table_dark; 
 8511: }
 8512: 
 8513: ol.LC_primary_menu li li p:hover {
 8514:   color:$button_hover;
 8515:   text-decoration:none;
 8516:   background-color:$data_table_dark;
 8517: }
 8518: 
 8519: ol.LC_primary_menu li li a:hover {
 8520:    color:$button_hover;
 8521:    background-color:$data_table_dark;
 8522: }
 8523: 
 8524: /* Font-size equal to the size of the predecessors*/
 8525: ol.LC_primary_menu li:hover li li {
 8526:   font-size: 100%;
 8527: }
 8528: 
 8529: ol.LC_primary_menu li img {
 8530:   vertical-align: bottom;
 8531:   height: 1.1em;
 8532:   margin: 0.2em 0 0 0;
 8533: }
 8534: 
 8535: ol.LC_primary_menu a {
 8536:   color: RGB(80, 80, 80);
 8537:   text-decoration: none;
 8538: }
 8539: 
 8540: ol.LC_primary_menu a.LC_new_message {
 8541:   font-weight:bold;
 8542:   color: darkred;
 8543: }
 8544: 
 8545: ol.LC_docs_parameters {
 8546:   margin-left: 0;
 8547:   padding: 0;
 8548:   list-style: none;
 8549: }
 8550: 
 8551: ol.LC_docs_parameters li {
 8552:   margin: 0;
 8553:   padding-right: 20px;
 8554:   display: inline;
 8555: }
 8556: 
 8557: ol.LC_docs_parameters li:before {
 8558:   content: "\\002022 \\0020";
 8559: }
 8560: 
 8561: li.LC_docs_parameters_title {
 8562:   font-weight: bold;
 8563: }
 8564: 
 8565: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 8566:   content: "";
 8567: }
 8568: 
 8569: ul#LC_secondary_menu {
 8570:   clear: right;
 8571:   color: $fontmenu;
 8572:   background: $tabbg;
 8573:   list-style: none;
 8574:   padding: 0;
 8575:   margin: 0;
 8576:   width: 100%;
 8577:   text-align: left;
 8578:   float: left;
 8579: }
 8580: 
 8581: ul#LC_secondary_menu li {
 8582:   font-weight: bold;
 8583:   line-height: 1.8em;
 8584:   border-right: 1px solid black;
 8585:   float: left;
 8586: }
 8587: 
 8588: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 8589:   background-color: $data_table_light;
 8590: }
 8591: 
 8592: ul#LC_secondary_menu li a {
 8593:   padding: 0 0.8em;
 8594: }
 8595: 
 8596: ul#LC_secondary_menu li ul {
 8597:   display: none;
 8598: }
 8599: 
 8600: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 8601:   display: block;
 8602:   position: absolute;
 8603:   margin: 0;
 8604:   padding: 0;
 8605:   list-style:none;
 8606:   float: none;
 8607:   background-color: $data_table_light;
 8608:   z-index: 2;
 8609:   margin-left: -1px;
 8610: }
 8611: 
 8612: ul#LC_secondary_menu li ul li {
 8613:   font-size: 90%;
 8614:   vertical-align: top;
 8615:   border-left: 1px solid black;
 8616:   border-right: 1px solid black;
 8617:   background-color: $data_table_light;
 8618:   list-style:none;
 8619:   float: none;
 8620: }
 8621: 
 8622: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 8623:   background-color: $data_table_dark;
 8624: }
 8625: 
 8626: ul.LC_TabContent {
 8627:   display:block;
 8628:   background: $sidebg;
 8629:   border-bottom: solid 1px $lg_border_color;
 8630:   list-style:none;
 8631:   margin: -1px -10px 0 -10px;
 8632:   padding: 0;
 8633: }
 8634: 
 8635: ul.LC_TabContent li,
 8636: ul.LC_TabContentBigger li {
 8637:   float:left;
 8638: }
 8639: 
 8640: ul#LC_secondary_menu li a {
 8641:   color: $fontmenu;
 8642:   text-decoration: none;
 8643: }
 8644: 
 8645: ul.LC_TabContent {
 8646:   min-height:20px;
 8647: }
 8648: 
 8649: ul.LC_TabContent li {
 8650:   vertical-align:middle;
 8651:   padding: 0 16px 0 10px;
 8652:   background-color:$tabbg;
 8653:   border-bottom:solid 1px $lg_border_color;
 8654:   border-left: solid 1px $font;
 8655: }
 8656: 
 8657: ul.LC_TabContent .right {
 8658:   float:right;
 8659: }
 8660: 
 8661: ul.LC_TabContent li a,
 8662: ul.LC_TabContent li {
 8663:   color:rgb(47,47,47);
 8664:   text-decoration:none;
 8665:   font-size:95%;
 8666:   font-weight:bold;
 8667:   min-height:20px;
 8668: }
 8669: 
 8670: ul.LC_TabContent li a:hover,
 8671: ul.LC_TabContent li a:focus {
 8672:   color: $button_hover;
 8673:   background:none;
 8674:   outline:none;
 8675: }
 8676: 
 8677: ul.LC_TabContent li:hover {
 8678:   color: $button_hover;
 8679:   cursor:pointer;
 8680: }
 8681: 
 8682: ul.LC_TabContent li.active {
 8683:   color: $font;
 8684:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 8685:   border-bottom:solid 1px #FFFFFF;
 8686:   cursor: default;
 8687: }
 8688: 
 8689: ul.LC_TabContent li.active a {
 8690:   color:$font;
 8691:   background:#FFFFFF;
 8692:   outline: none;
 8693: }
 8694: 
 8695: ul.LC_TabContent li.goback {
 8696:   float: left;
 8697:   border-left: none;
 8698: }
 8699: 
 8700: #maincoursedoc {
 8701:   clear:both;
 8702: }
 8703: 
 8704: ul.LC_TabContentBigger {
 8705:   display:block;
 8706:   list-style:none;
 8707:   padding: 0;
 8708: }
 8709: 
 8710: ul.LC_TabContentBigger li {
 8711:   vertical-align:bottom;
 8712:   height: 30px;
 8713:   font-size:110%;
 8714:   font-weight:bold;
 8715:   color: #737373;
 8716: }
 8717: 
 8718: ul.LC_TabContentBigger li.active {
 8719:   position: relative;
 8720:   top: 1px;
 8721: }
 8722: 
 8723: ul.LC_TabContentBigger li a {
 8724:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 8725:   height: 30px;
 8726:   line-height: 30px;
 8727:   text-align: center;
 8728:   display: block;
 8729:   text-decoration: none;
 8730:   outline: none;  
 8731: }
 8732: 
 8733: ul.LC_TabContentBigger li.active a {
 8734:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 8735:   color:$font;
 8736: }
 8737: 
 8738: ul.LC_TabContentBigger li b {
 8739:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 8740:   display: block;
 8741:   float: left;
 8742:   padding: 0 30px;
 8743:   border-bottom: 1px solid $lg_border_color;
 8744: }
 8745: 
 8746: ul.LC_TabContentBigger li:hover b {
 8747:   color:$button_hover;
 8748: }
 8749: 
 8750: ul.LC_TabContentBigger li.active b {
 8751:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 8752:   color:$font;
 8753:   border: 0;
 8754: }
 8755: 
 8756: 
 8757: ul.LC_CourseBreadcrumbs {
 8758:   background: $sidebg;
 8759:   height: 2em;
 8760:   padding-left: 10px;
 8761:   margin: 0;
 8762:   list-style-position: inside;
 8763: }
 8764: 
 8765: ol#LC_MenuBreadcrumbs,
 8766: ol#LC_PathBreadcrumbs {
 8767:   padding-left: 10px;
 8768:   margin: 0;
 8769:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 8770: }
 8771: 
 8772: ol#LC_MenuBreadcrumbs li,
 8773: ol#LC_PathBreadcrumbs li,
 8774: ul.LC_CourseBreadcrumbs li {
 8775:   display: inline;
 8776:   white-space: normal;  
 8777: }
 8778: 
 8779: ol#LC_MenuBreadcrumbs li a,
 8780: ul.LC_CourseBreadcrumbs li a {
 8781:   text-decoration: none;
 8782:   font-size:90%;
 8783: }
 8784: 
 8785: ol#LC_MenuBreadcrumbs h1 {
 8786:   display: inline;
 8787:   font-size: 90%;
 8788:   line-height: 2.5em;
 8789:   margin: 0;
 8790:   padding: 0;
 8791: }
 8792: 
 8793: ol#LC_PathBreadcrumbs li a {
 8794:   text-decoration:none;
 8795:   font-size:100%;
 8796:   font-weight:bold;
 8797: }
 8798: 
 8799: .LC_Box {
 8800:   border: solid 1px $lg_border_color;
 8801:   padding: 0 10px 10px 10px;
 8802: }
 8803: 
 8804: .LC_DocsBox {
 8805:   border: solid 1px $lg_border_color;
 8806:   padding: 0 0 10px 10px;
 8807: }
 8808: 
 8809: .LC_AboutMe_Image {
 8810:   float:left;
 8811:   margin-right:10px;
 8812: }
 8813: 
 8814: .LC_Clear_AboutMe_Image {
 8815:   clear:left;
 8816: }
 8817: 
 8818: dl.LC_ListStyleClean dt {
 8819:   padding-right: 5px;
 8820:   display: table-header-group;
 8821: }
 8822: 
 8823: dl.LC_ListStyleClean dd {
 8824:   display: table-row;
 8825: }
 8826: 
 8827: .LC_ListStyleClean,
 8828: .LC_ListStyleSimple,
 8829: .LC_ListStyleNormal,
 8830: .LC_ListStyleSpecial {
 8831:   /* display:block; */
 8832:   list-style-position: inside;
 8833:   list-style-type: none;
 8834:   overflow: hidden;
 8835:   padding: 0;
 8836: }
 8837: 
 8838: .LC_ListStyleSimple li,
 8839: .LC_ListStyleSimple dd,
 8840: .LC_ListStyleNormal li,
 8841: .LC_ListStyleNormal dd,
 8842: .LC_ListStyleSpecial li,
 8843: .LC_ListStyleSpecial dd {
 8844:   margin: 0;
 8845:   padding: 5px 5px 5px 10px;
 8846:   clear: both;
 8847: }
 8848: 
 8849: .LC_ListStyleClean li,
 8850: .LC_ListStyleClean dd {
 8851:   padding-top: 0;
 8852:   padding-bottom: 0;
 8853: }
 8854: 
 8855: .LC_ListStyleSimple dd,
 8856: .LC_ListStyleSimple li {
 8857:   border-bottom: solid 1px $lg_border_color;
 8858: }
 8859: 
 8860: .LC_ListStyleSpecial li,
 8861: .LC_ListStyleSpecial dd {
 8862:   list-style-type: none;
 8863:   background-color: RGB(220, 220, 220);
 8864:   margin-bottom: 4px;
 8865: }
 8866: 
 8867: table.LC_SimpleTable {
 8868:   margin:5px;
 8869:   border:solid 1px $lg_border_color;
 8870: }
 8871: 
 8872: table.LC_SimpleTable tr {
 8873:   padding: 0;
 8874:   border:solid 1px $lg_border_color;
 8875: }
 8876: 
 8877: table.LC_SimpleTable thead {
 8878:   background:rgb(220,220,220);
 8879: }
 8880: 
 8881: div.LC_columnSection {
 8882:   display: block;
 8883:   clear: both;
 8884:   overflow: hidden;
 8885:   margin: 0;
 8886: }
 8887: 
 8888: div.LC_columnSection>* {
 8889:   float: left;
 8890:   margin: 10px 20px 10px 0;
 8891:   overflow:hidden;
 8892: }
 8893: 
 8894: table em {
 8895:   font-weight: bold;
 8896:   font-style: normal;
 8897: }
 8898: 
 8899: table.LC_tableBrowseRes,
 8900: table.LC_tableOfContent {
 8901:   border:none;
 8902:   border-spacing: 1px;
 8903:   padding: 3px;
 8904:   background-color: #FFFFFF;
 8905:   font-size: 90%;
 8906: }
 8907: 
 8908: table.LC_tableOfContent {
 8909:   border-collapse: collapse;
 8910: }
 8911: 
 8912: table.LC_tableBrowseRes a,
 8913: table.LC_tableOfContent a {
 8914:   background-color: transparent;
 8915:   text-decoration: none;
 8916: }
 8917: 
 8918: table.LC_tableOfContent img {
 8919:   border: none;
 8920:   height: 1.3em;
 8921:   vertical-align: text-bottom;
 8922:   margin-right: 0.3em;
 8923: }
 8924: 
 8925: a#LC_content_toolbar_firsthomework {
 8926:   background-image:url(/res/adm/pages/open-first-problem.gif);
 8927: }
 8928: 
 8929: a#LC_content_toolbar_everything {
 8930:   background-image:url(/res/adm/pages/show-all.gif);
 8931: }
 8932: 
 8933: a#LC_content_toolbar_uncompleted {
 8934:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 8935: }
 8936: 
 8937: #LC_content_toolbar_clearbubbles {
 8938:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 8939: }
 8940: 
 8941: a#LC_content_toolbar_changefolder {
 8942:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 8943: }
 8944: 
 8945: a#LC_content_toolbar_changefolder_toggled {
 8946:   background-image:url(/res/adm/pages/open-all-folders.gif);
 8947: }
 8948: 
 8949: a#LC_content_toolbar_edittoplevel {
 8950:   background-image:url(/res/adm/pages/edittoplevel.gif);
 8951: }
 8952: 
 8953: a#LC_content_toolbar_printout {
 8954:   background-image:url(/res/adm/pages/printout.gif);
 8955: }
 8956: 
 8957: ul#LC_toolbar li a:hover {
 8958:   background-position: bottom center;
 8959: }
 8960: 
 8961: ul#LC_toolbar {
 8962:   padding: 0;
 8963:   margin: 2px;
 8964:   list-style:none;
 8965:   position:relative;
 8966:   background-color:white;
 8967:   overflow: auto;
 8968: }
 8969: 
 8970: ul#LC_toolbar li {
 8971:   border:1px solid white;
 8972:   padding: 0;
 8973:   margin: 0;
 8974:   float: left;
 8975:   display:inline;
 8976:   vertical-align:middle;
 8977:   white-space: nowrap;
 8978: }
 8979: 
 8980: 
 8981: a.LC_toolbarItem {
 8982:   display:block;
 8983:   padding: 0;
 8984:   margin: 0;
 8985:   height: 32px;
 8986:   width: 32px;
 8987:   color:white;
 8988:   border: none;
 8989:   background-repeat:no-repeat;
 8990:   background-color:transparent;
 8991: }
 8992: 
 8993: ul.LC_funclist {
 8994:     margin: 0;
 8995:     padding: 0.5em 1em 0.5em 0;
 8996: }
 8997: 
 8998: ul.LC_funclist > li:first-child {
 8999:     font-weight:bold; 
 9000:     margin-left:0.8em;
 9001: }
 9002: 
 9003: ul.LC_funclist + ul.LC_funclist {
 9004:     /* 
 9005:        left border as a seperator if we have more than
 9006:        one list 
 9007:     */
 9008:     border-left: 1px solid $sidebg;
 9009:     /* 
 9010:        this hides the left border behind the border of the 
 9011:        outer box if element is wrapped to the next 'line' 
 9012:     */
 9013:     margin-left: -1px;
 9014: }
 9015: 
 9016: ul.LC_funclist li {
 9017:   display: inline;
 9018:   white-space: nowrap;
 9019:   margin: 0 0 0 25px;
 9020:   line-height: 150%;
 9021: }
 9022: 
 9023: .LC_hidden {
 9024:   display: none;
 9025: }
 9026: 
 9027: .LCmodal-overlay {
 9028: 		position:fixed;
 9029: 		top:0;
 9030: 		right:0;
 9031: 		bottom:0;
 9032: 		left:0;
 9033: 		height:100%;
 9034: 		width:100%;
 9035: 		margin:0;
 9036: 		padding:0;
 9037: 		background:#999;
 9038: 		opacity:.75;
 9039: 		filter: alpha(opacity=75);
 9040: 		-moz-opacity: 0.75;
 9041: 		z-index:101;
 9042: }
 9043: 
 9044: * html .LCmodal-overlay {   
 9045: 		position: absolute;
 9046: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 9047: }
 9048: 
 9049: .LCmodal-window {
 9050: 		position:fixed;
 9051: 		top:50%;
 9052: 		left:50%;
 9053: 		margin:0;
 9054: 		padding:0;
 9055: 		z-index:102;
 9056: 	}
 9057: 
 9058: * html .LCmodal-window {
 9059: 		position:absolute;
 9060: }
 9061: 
 9062: .LCclose-window {
 9063: 		position:absolute;
 9064: 		width:32px;
 9065: 		height:32px;
 9066: 		right:8px;
 9067: 		top:8px;
 9068: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 9069: 		text-indent:-99999px;
 9070: 		overflow:hidden;
 9071: 		cursor:pointer;
 9072: }
 9073: 
 9074: .LCisDisabled {
 9075:   cursor: not-allowed;
 9076:   opacity: 0.5;
 9077: }
 9078: 
 9079: a[aria-disabled="true"] {
 9080:   color: currentColor;
 9081:   display: inline-block;  /* For IE11/ MS Edge bug */
 9082:   pointer-events: none;
 9083:   text-decoration: none;
 9084: }
 9085: 
 9086: pre.LC_wordwrap {
 9087:   white-space: pre-wrap;
 9088:   white-space: -moz-pre-wrap;
 9089:   white-space: -pre-wrap;
 9090:   white-space: -o-pre-wrap;
 9091:   word-wrap: break-word;
 9092: }
 9093: 
 9094: /*
 9095:   styles used for response display
 9096: */
 9097: div.LC_radiofoil, div.LC_rankfoil {
 9098:   margin: .5em 0em .5em 0em;
 9099: }
 9100: table.LC_itemgroup {
 9101:   margin-top: 1em;
 9102: }
 9103: 
 9104: /*
 9105:   styles used by TTH when "Default set of options to pass to tth/m
 9106:   when converting TeX" in course settings has been set
 9107: 
 9108:   option passed: -t
 9109: 
 9110: */
 9111: 
 9112: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 9113: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 9114: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 9115: td div.norm {line-height:normal;}
 9116: 
 9117: /*
 9118:   option passed -y3
 9119: */
 9120: 
 9121: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 9122: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 9123: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 9124: 
 9125: /*
 9126:   sections with roles, for content only
 9127: */
 9128: section[class^="role-"] {
 9129:   padding-left: 10px;
 9130:   padding-right: 5px;
 9131:   margin-top: 8px;
 9132:   margin-bottom: 8px;
 9133:   border: 1px solid #2A4;
 9134:   border-radius: 5px;
 9135:   box-shadow: 0px 1px 1px #BBB;
 9136: }
 9137: section[class^="role-"]>h1 {
 9138:   position: relative;
 9139:   margin: 0px;
 9140:   padding-top: 10px;
 9141:   padding-left: 40px;
 9142: }
 9143: section[class^="role-"]>h1:before {
 9144:   position: absolute;
 9145:   left: -5px;
 9146:   top: 5px;
 9147: }
 9148: section.role-activity>h1:before {
 9149:   content:url('/adm/daxe/images/section_icons/activity.png');
 9150: }
 9151: section.role-advice>h1:before {
 9152:   content:url('/adm/daxe/images/section_icons/advice.png');
 9153: }
 9154: section.role-bibliography>h1:before {
 9155:   content:url('/adm/daxe/images/section_icons/bibliography.png');
 9156: }
 9157: section.role-citation>h1:before {
 9158:   content:url('/adm/daxe/images/section_icons/citation.png');
 9159: }
 9160: section.role-conclusion>h1:before {
 9161:   content:url('/adm/daxe/images/section_icons/conclusion.png');
 9162: }
 9163: section.role-definition>h1:before {
 9164:   content:url('/adm/daxe/images/section_icons/definition.png');
 9165: }
 9166: section.role-demonstration>h1:before {
 9167:   content:url('/adm/daxe/images/section_icons/demonstration.png');
 9168: }
 9169: section.role-example>h1:before {
 9170:   content:url('/adm/daxe/images/section_icons/example.png');
 9171: }
 9172: section.role-explanation>h1:before {
 9173:   content:url('/adm/daxe/images/section_icons/explanation.png');
 9174: }
 9175: section.role-introduction>h1:before {
 9176:   content:url('/adm/daxe/images/section_icons/introduction.png');
 9177: }
 9178: section.role-method>h1:before {
 9179:   content:url('/adm/daxe/images/section_icons/method.png');
 9180: }
 9181: section.role-more_information>h1:before {
 9182:   content:url('/adm/daxe/images/section_icons/more_information.png');
 9183: }
 9184: section.role-objectives>h1:before {
 9185:   content:url('/adm/daxe/images/section_icons/objectives.png');
 9186: }
 9187: section.role-prerequisites>h1:before {
 9188:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
 9189: }
 9190: section.role-remark>h1:before {
 9191:   content:url('/adm/daxe/images/section_icons/remark.png');
 9192: }
 9193: section.role-reminder>h1:before {
 9194:   content:url('/adm/daxe/images/section_icons/reminder.png');
 9195: }
 9196: section.role-summary>h1:before {
 9197:   content:url('/adm/daxe/images/section_icons/summary.png');
 9198: }
 9199: section.role-syntax>h1:before {
 9200:   content:url('/adm/daxe/images/section_icons/syntax.png');
 9201: }
 9202: section.role-warning>h1:before {
 9203:   content:url('/adm/daxe/images/section_icons/warning.png');
 9204: }
 9205: 
 9206: #LC_minitab_header {
 9207:   float:left;
 9208:   width:100%;
 9209:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
 9210:   font-size:93%;
 9211:   line-height:normal;
 9212:   margin: 0.5em 0 0.5em 0;
 9213: }
 9214: #LC_minitab_header ul {
 9215:   margin:0;
 9216:   padding:10px 10px 0;
 9217:   list-style:none;
 9218: }
 9219: #LC_minitab_header li {
 9220:   float:left;
 9221:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
 9222:   margin:0;
 9223:   padding:0 0 0 9px;
 9224: }
 9225: #LC_minitab_header a {
 9226:   display:block;
 9227:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
 9228:   padding:5px 15px 4px 6px;
 9229: }
 9230: #LC_minitab_header #LC_current_minitab {
 9231:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
 9232: }
 9233: #LC_minitab_header #LC_current_minitab a {
 9234:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
 9235:   padding-bottom:5px;
 9236: }
 9237: 
 9238: 
 9239: END
 9240: }
 9241: 
 9242: =pod
 9243: 
 9244: =item * &headtag()
 9245: 
 9246: Returns a uniform footer for LON-CAPA web pages.
 9247: 
 9248: Inputs: $title - optional title for the head
 9249:         $head_extra - optional extra HTML to put inside the <head>
 9250:         $args - optional arguments
 9251:             force_register - if is true call registerurl so the remote is 
 9252:                              informed
 9253:             redirect       -> array ref of
 9254:                                    1- seconds before redirect occurs
 9255:                                    2- url to redirect to
 9256:                                    3- whether the side effect should occur
 9257:                            (side effect of setting 
 9258:                                $env{'internal.head.redirect'} to the url 
 9259:                                redirected to)
 9260:                                    4- whether the redirect target should be
 9261:                                       the opener of the current (pop-up)
 9262:                                       window (side effect of setting
 9263:                                       $env{'internal.head.to_opener'} to
 9264:                                       1, if true.
 9265:                                    5- whether encrypt check should be skipped
 9266:             domain         -> force to color decorate a page for a specific
 9267:                                domain
 9268:             function       -> force usage of a specific rolish color scheme
 9269:             bgcolor        -> override the default page bgcolor
 9270:             no_auto_mt_title
 9271:                            -> prevent &mt()ing the title arg
 9272: 
 9273: =cut
 9274: 
 9275: sub headtag {
 9276:     my ($title,$head_extra,$args) = @_;
 9277:     
 9278:     my $function = $args->{'function'} || &get_users_function();
 9279:     my $domain   = $args->{'domain'}   || &determinedomain();
 9280:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 9281:     my $httphost = $args->{'use_absolute'};
 9282:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 9283: 		   $Apache::lonnet::perlvar{'lonVersion'},
 9284: 		   #time(),
 9285: 		   $env{'environment.color.timestamp'},
 9286: 		   $function,$domain,$bgcolor);
 9287: 
 9288:     $url = '/adm/css/'.&escape($url).'.css';
 9289: 
 9290:     my $result =
 9291: 	'<head>'.
 9292: 	&font_settings($args);
 9293: 
 9294:     my $inhibitprint;
 9295:     if ($args->{'print_suppress'}) {
 9296:         $inhibitprint = &print_suppression();
 9297:     }
 9298: 
 9299:     if (!$args->{'frameset'}) {
 9300: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 9301:     }
 9302:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
 9303:         $result .= Apache::lonxml::display_title();
 9304:     }
 9305:     if (!$args->{'no_nav_bar'} 
 9306: 	&& !$args->{'only_body'}
 9307: 	&& !$args->{'frameset'}) {
 9308: 	$result .= &help_menu_js($httphost);
 9309:         $result.=&modal_window();
 9310:         $result.=&togglebox_script();
 9311:         $result.=&wishlist_window();
 9312:         $result.=&LCprogressbarUpdate_script();
 9313:     } else {
 9314:         if ($args->{'add_modal'}) {
 9315:            $result.=&modal_window();
 9316:         }
 9317:         if ($args->{'add_wishlist'}) {
 9318:            $result.=&wishlist_window();
 9319:         }
 9320:         if ($args->{'add_togglebox'}) {
 9321:            $result.=&togglebox_script();
 9322:         }
 9323:         if ($args->{'add_progressbar'}) {
 9324:            $result.=&LCprogressbarUpdate_script();
 9325:         }
 9326:     }
 9327:     if (ref($args->{'redirect'})) {
 9328: 	my ($time,$url,$inhibit_continue,$to_opener,$skip_enc_check) = @{$args->{'redirect'}};
 9329:         if (!$skip_enc_check) {
 9330:             $url = &Apache::lonenc::check_encrypt($url);
 9331:         }
 9332: 	if (!$inhibit_continue) {
 9333: 	    $env{'internal.head.redirect'} = $url;
 9334: 	}
 9335: 	$result.=<<"ADDMETA";
 9336: <meta http-equiv="pragma" content="no-cache" />
 9337: ADDMETA
 9338:         if ($to_opener) {
 9339:             $env{'internal.head.to_opener'} = 1;
 9340:             my $dest = &js_escape($url);
 9341:             my $timeout = int($time * 1000);
 9342:             $result .=<<"ENDJS";
 9343: <script type="text/javascript">
 9344: // <![CDATA[
 9345: function LC_To_Opener() {
 9346:     var dest = '$dest';
 9347:     if (dest != '') {
 9348:         if (window.opener != null && !window.opener.closed) {
 9349:             window.opener.location.href=dest;
 9350:             window.close();
 9351:         } else {
 9352:             window.location.href=dest;
 9353:         }
 9354:     }
 9355: }
 9356: \$(document).ready(function () {
 9357:     setTimeout('LC_To_Opener()',$timeout);
 9358: });
 9359: // ]]>
 9360: </script>
 9361: ENDJS
 9362:         } else {
 9363:             $result.=<<"ADDMETA";
 9364: <meta http-equiv="Refresh" content="$time; url=$url" />
 9365: ADDMETA
 9366:         }
 9367:     } else {
 9368:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
 9369:             my $requrl = $env{'request.uri'};
 9370:             if ($requrl eq '') {
 9371:                 $requrl = $ENV{'REQUEST_URI'};
 9372:                 $requrl =~ s/\?.+$//;
 9373:             }
 9374:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
 9375:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
 9376:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
 9377:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
 9378:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
 9379:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
 9380:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 9381:                     my ($offload,$offloadoth);
 9382:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
 9383:                         if ($domdefs{'offloadnow'}{$lonhost}) {
 9384:                             $offload = 1;
 9385:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
 9386:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
 9387:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
 9388:                                     $offloadoth = 1;
 9389:                                     $dom_in_use = $env{'user.domain'};
 9390:                                 }
 9391:                             }
 9392:                         }
 9393:                     }
 9394:                     unless ($offload) {
 9395:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
 9396:                             if ($domdefs{'offloadoth'}{$lonhost}) {
 9397:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
 9398:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
 9399:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
 9400:                                         $offload = 1;
 9401:                                         $offloadoth = 1;
 9402:                                         $dom_in_use = $env{'user.domain'};
 9403:                                     }
 9404:                                 }
 9405:                             }
 9406:                         }
 9407:                     }
 9408:                     if ($offload) {
 9409:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
 9410:                         if (($newserver eq '') && ($offloadoth)) {
 9411:                             my @domains = &Apache::lonnet::current_machine_domains();
 9412:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) { 
 9413:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
 9414:                             }
 9415:                         }
 9416:                         if (($newserver) && ($newserver ne $lonhost)) {
 9417:                             my $numsec = 5;
 9418:                             my $timeout = $numsec * 1000;
 9419:                             my ($newurl,$locknum,%locks,$msg);
 9420:                             if ($env{'request.role.adv'}) {
 9421:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
 9422:                             }
 9423:                             my $disable_submit = 0;
 9424:                             if ($requrl =~ /$LONCAPA::assess_re/) {
 9425:                                 $disable_submit = 1;
 9426:                             }
 9427:                             if ($locknum) {
 9428:                                 my @lockinfo = sort(values(%locks));
 9429:                                 $msg = &mt('Once the following tasks are complete:')." \n".
 9430:                                        join(", ",sort(values(%locks)))."\n";
 9431:                                 if (&show_course()) {
 9432:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
 9433:                                 } else {
 9434:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
 9435:                                 }
 9436:                             } else {
 9437:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
 9438:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
 9439:                                 }
 9440:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
 9441:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
 9442:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
 9443:                                     $newurl .= '&role='.$env{'request.role'};
 9444:                                 }
 9445:                                 if ($env{'request.symb'}) {
 9446:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
 9447:                                     if ($shownsymb =~ m{^/enc/}) {
 9448:                                         my $reqdmajor = 2;
 9449:                                         my $reqdminor = 11;
 9450:                                         my $reqdsubminor = 3;
 9451:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
 9452:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
 9453:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
 9454:                                         if (($major eq '' && $minor eq '') ||
 9455:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
 9456:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
 9457:                                              ($reqdsubminor > $subminor))))) {
 9458:                                             undef($shownsymb);
 9459:                                         }
 9460:                                     }
 9461:                                     if ($shownsymb) {
 9462:                                         &js_escape(\$shownsymb);
 9463:                                         $newurl .= '&symb='.$shownsymb;
 9464:                                     }
 9465:                                 } else {
 9466:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
 9467:                                     &js_escape(\$shownurl);
 9468:                                     $newurl .= '&origurl='.$shownurl;
 9469:                                 }
 9470:                             }
 9471:                             &js_escape(\$msg);
 9472:                             $result.=<<OFFLOAD
 9473: <meta http-equiv="pragma" content="no-cache" />
 9474: <script type="text/javascript">
 9475: // <![CDATA[
 9476: function LC_Offload_Now() {
 9477:     var dest = "$newurl";
 9478:     if (dest != '') {
 9479:         window.location.href="$newurl";
 9480:     }
 9481: }
 9482: \$(document).ready(function () {
 9483:     window.alert('$msg');
 9484:     if ($disable_submit) {
 9485:         \$(".LC_hwk_submit").prop("disabled", true);
 9486:         \$( ".LC_textline" ).prop( "readonly", "readonly");
 9487:     }
 9488:     setTimeout('LC_Offload_Now()', $timeout);
 9489: });
 9490: // ]]>
 9491: </script>
 9492: OFFLOAD
 9493:                         }
 9494:                     }
 9495:                 }
 9496:             }
 9497:         }
 9498:     }
 9499:     if (!defined($title)) {
 9500: 	$title = 'The LearningOnline Network with CAPA';
 9501:     }
 9502:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 9503:     $result .= '<title> LON-CAPA '.$title.'</title>'
 9504: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
 9505:     if (!$args->{'frameset'}) {
 9506:         $result .= ' /';
 9507:     }
 9508:     $result .= '>' 
 9509:         .$inhibitprint
 9510: 	.$head_extra;
 9511:     my $clientmobile;
 9512:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 9513:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
 9514:     } else {
 9515:         $clientmobile = $env{'browser.mobile'};
 9516:     }
 9517:     if ($clientmobile) {
 9518:         $result .= '
 9519: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 9520: <meta name="apple-mobile-web-app-capable" content="yes" />';
 9521:     }
 9522:     $result .= '<meta name="google" content="notranslate" />'."\n";
 9523:     return $result.'</head>';
 9524: }
 9525: 
 9526: =pod
 9527: 
 9528: =item * &font_settings()
 9529: 
 9530: Returns neccessary <meta> to set the proper encoding
 9531: 
 9532: Inputs: optional reference to HASH -- $args passed to &headtag()
 9533: 
 9534: =cut
 9535: 
 9536: sub font_settings {
 9537:     my ($args) = @_;
 9538:     my $headerstring='';
 9539:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
 9540:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
 9541:         $headerstring.=
 9542:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
 9543:         if (!$args->{'frameset'}) {
 9544: 	    $headerstring.= ' /';
 9545:         }
 9546: 	$headerstring .= '>'."\n";
 9547:     }
 9548:     return $headerstring;
 9549: }
 9550: 
 9551: =pod
 9552: 
 9553: =item * &print_suppression()
 9554: 
 9555: In course context returns css which causes the body to be blank when media="print",
 9556: if printout generation is unavailable for the current resource.
 9557: 
 9558: This could be because:
 9559: 
 9560: (a) printstartdate is in the future
 9561: 
 9562: (b) printenddate is in the past
 9563: 
 9564: (c) there is an active exam block with "printout"
 9565: functionality blocked
 9566: 
 9567: Users with pav, pfo or evb privileges are exempt.
 9568: 
 9569: Inputs: none
 9570: 
 9571: =cut
 9572: 
 9573: 
 9574: sub print_suppression {
 9575:     my $noprint;
 9576:     if ($env{'request.course.id'}) {
 9577:         my $scope = $env{'request.course.id'};
 9578:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 9579:             (&Apache::lonnet::allowed('pfo',$scope))) {
 9580:             return;
 9581:         }
 9582:         if ($env{'request.course.sec'} ne '') {
 9583:             $scope .= "/$env{'request.course.sec'}";
 9584:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 9585:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 9586:                 return;
 9587:             }
 9588:         }
 9589:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9590:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9591:         my $clientip = &Apache::lonnet::get_requestor_ip();
 9592:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
 9593:         if ($blocked) {
 9594:             my $checkrole = "cm./$cdom/$cnum";
 9595:             if ($env{'request.course.sec'} ne '') {
 9596:                 $checkrole .= "/$env{'request.course.sec'}";
 9597:             }
 9598:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 9599:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 9600:                 $noprint = 1;
 9601:             }
 9602:         }
 9603:         unless ($noprint) {
 9604:             my $symb = &Apache::lonnet::symbread();
 9605:             if ($symb ne '') {
 9606:                 my $navmap = Apache::lonnavmaps::navmap->new();
 9607:                 if (ref($navmap)) {
 9608:                     my $res = $navmap->getBySymb($symb);
 9609:                     if (ref($res)) {
 9610:                         if (!$res->resprintable()) {
 9611:                             $noprint = 1;
 9612:                         }
 9613:                     }
 9614:                 }
 9615:             }
 9616:         }
 9617:         if ($noprint) {
 9618:             return <<"ENDSTYLE";
 9619: <style type="text/css" media="print">
 9620:     body { display:none }
 9621: </style>
 9622: ENDSTYLE
 9623:         }
 9624:     }
 9625:     return;
 9626: }
 9627: 
 9628: =pod
 9629: 
 9630: =item * &xml_begin()
 9631: 
 9632: Returns the needed doctype and <html>
 9633: 
 9634: Inputs: none
 9635: 
 9636: =cut
 9637: 
 9638: sub xml_begin {
 9639:     my ($is_frameset) = @_;
 9640:     my $output='';
 9641: 
 9642:     if ($env{'browser.mathml'}) {
 9643: 	$output='<?xml version="1.0"?>'
 9644:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 9645: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 9646:             
 9647: #	    .'<!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">] >'
 9648: 	    .'<!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">'
 9649:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 9650: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 9651:     } elsif ($is_frameset) {
 9652:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
 9653:                 '<html>'."\n";
 9654:     } else {
 9655: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
 9656:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
 9657:     }
 9658:     return $output;
 9659: }
 9660: 
 9661: =pod
 9662: 
 9663: =item * &start_page()
 9664: 
 9665: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 9666: 
 9667: Inputs:
 9668: 
 9669: =over 4
 9670: 
 9671: $title - optional title for the page
 9672: 
 9673: $head_extra - optional extra HTML to incude inside the <head>
 9674: 
 9675: $args - additional optional args supported are:
 9676: 
 9677: =over 8
 9678: 
 9679:              only_body      -> is true will set &bodytag() onlybodytag
 9680:                                     arg on
 9681:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 9682:              add_entries    -> additional attributes to add to the  <body>
 9683:              domain         -> force to color decorate a page for a 
 9684:                                     specific domain
 9685:              function       -> force usage of a specific rolish color
 9686:                                     scheme
 9687:              redirect       -> see &headtag()
 9688:              bgcolor        -> override the default page bg color
 9689:              js_ready       -> return a string ready for being used in 
 9690:                                     a javascript writeln
 9691:              html_encode    -> return a string ready for being used in 
 9692:                                     a html attribute
 9693:              force_register -> if is true will turn on the &bodytag()
 9694:                                     $forcereg arg
 9695:              frameset       -> if true will start with a <frameset>
 9696:                                     rather than <body>
 9697:              skip_phases    -> hash ref of 
 9698:                                     head -> skip the <html><head> generation
 9699:                                     body -> skip all <body> generation
 9700:              no_auto_mt_title -> prevent &mt()ing the title arg
 9701:              bread_crumbs ->             Array containing breadcrumbs
 9702:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 9703:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
 9704:                                     to lonhtmlcommon::breadcrumbs
 9705:              group          -> includes the current group, if page is for a 
 9706:                                specific group
 9707:              use_absolute   -> for request for external resource or syllabus, this
 9708:                                will contain https://<hostname> if server uses
 9709:                                https (as per hosts.tab), but request is for http
 9710:              hostname       -> hostname, originally from $r->hostname(), (optional).
 9711:              links_disabled -> Links in primary and secondary menus are disabled
 9712:                                (Can enable them once page has loaded - see lonroles.pm
 9713:                                for an example).
 9714:              links_target   -> Target for links, e.g., _parent (optional).
 9715: 
 9716: =back
 9717: 
 9718: =back
 9719: 
 9720: =cut
 9721: 
 9722: sub start_page {
 9723:     my ($title,$head_extra,$args) = @_;
 9724:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 9725: 
 9726:     $env{'internal.start_page'}++;
 9727:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
 9728: 
 9729:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 9730:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
 9731:     }
 9732: 
 9733:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
 9734:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
 9735:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
 9736:                 $args->{'no_primary_menu'} = 1;
 9737:             }
 9738:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
 9739:                 $args->{'no_inline_menu'} = 1;
 9740:             }
 9741:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
 9742:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
 9743:             }
 9744:         } else {
 9745:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9746:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
 9747:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
 9748:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
 9749:                     $args->{'no_primary_menu'} = 1;
 9750:                 }
 9751:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
 9752:                     $args->{'no_inline_menu'} = 1;
 9753:                 }
 9754:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
 9755:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
 9756:                 }
 9757:             }
 9758:         }
 9759:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
 9760:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
 9761:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
 9762:     } elsif ($env{'request.course.id'}) {
 9763:         my $expiretime=600;
 9764:         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
 9765:             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
 9766:         }
 9767:         my ($deeplinkmenu,$menuref);
 9768:         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
 9769:         if ($menucoll) {
 9770:             if (ref($menuref) eq 'HASH') {
 9771:                 %menu = %{$menuref};
 9772:             }
 9773:             if ($menu{'top'} eq 'n') {
 9774:                 $args->{'no_primary_menu'} = 1;
 9775:             }
 9776:             if ($menu{'inline'} eq 'n') {
 9777:                 unless (&Apache::lonnet::allowed('opa')) {
 9778:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9779:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9780:                     my $crstype = &course_type();
 9781:                     my $now = time;
 9782:                     my $ccrole;
 9783:                     if ($crstype eq 'Community') {
 9784:                         $ccrole = 'co';
 9785:                     } else {
 9786:                         $ccrole = 'cc';
 9787:                     }
 9788:                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
 9789:                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
 9790:                         if ((($start) && ($start<0)) ||
 9791:                             (($end) && ($end<$now))  ||
 9792:                             (($start) && ($now<$start))) {
 9793:                             $args->{'no_inline_menu'} = 1;
 9794:                         }
 9795:                     } else {
 9796:                         $args->{'no_inline_menu'} = 1;
 9797:                     }
 9798:                 }
 9799:             }
 9800:         }
 9801:     }
 9802: 
 9803:     my $showncrumbs;
 9804:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 9805: 	if ($args->{'frameset'}) {
 9806: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 9807: 						$args->{'add_entries'});
 9808: 	    $result .= "\n<frameset $attr_string>\n";
 9809:         } else {
 9810:             $result .=
 9811:                 &bodytag($title, 
 9812:                          $args->{'function'},       $args->{'add_entries'},
 9813:                          $args->{'only_body'},      $args->{'domain'},
 9814:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 9815:                          $args->{'bgcolor'},        $args,
 9816:                          \@advtools,$ltiscope,$ltiuri,\%ltimenu,$menucoll,
 9817:                          \%menu,\$showncrumbs);
 9818:         }
 9819:     }
 9820: 
 9821:     if ($args->{'js_ready'}) {
 9822: 		$result = &js_ready($result);
 9823:     }
 9824:     if ($args->{'html_encode'}) {
 9825: 		$result = &html_encode($result);
 9826:     }
 9827: 
 9828:     # Preparation for new and consistent functionlist at top of screen
 9829:     # if ($args->{'functionlist'}) {
 9830:     #            $result .= &build_functionlist();
 9831:     #}
 9832: 
 9833:     # Don't add anything more if only_body wanted or in const space
 9834:     return $result if    $args->{'only_body'} 
 9835:                       || $env{'request.state'} eq 'construct';
 9836: 
 9837:     #Breadcrumbs
 9838:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 9839:         unless ($showncrumbs) {
 9840: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 9841: 		#if any br links exists, add them to the breadcrumbs
 9842: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 9843: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 9844: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 9845: 			}
 9846: 		}
 9847:                 # if @advtools array contains items add then to the breadcrumbs
 9848:                 if (@advtools > 0) {
 9849:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 9850:                 }
 9851:                 my $menulink;
 9852:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
 9853:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
 9854:                      ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
 9855:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
 9856:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
 9857:                      (!$env{'request.role.adv'}))) {
 9858:                     $menulink = 0;
 9859:                 } else {
 9860:                     undef($menulink);
 9861:                 }
 9862:                 my $linkprotout;
 9863:                 if ($env{'request.deeplink.login'}) {
 9864:                     my $linkprotout = &Apache::lonmenu::linkprot_exit();
 9865:                     if ($linkprotout) {
 9866:                         &Apache::lonhtmlcommon::add_breadcrumb_tool('tools',$linkprotout);
 9867:                     }
 9868:                 }
 9869: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 9870: 		if(exists($args->{'bread_crumbs_component'})){
 9871: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
 9872:                 } else {
 9873: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
 9874: 		}
 9875:         }
 9876:     }
 9877:     return $result;
 9878: }
 9879: 
 9880: sub end_page {
 9881:     my ($args) = @_;
 9882:     $env{'internal.end_page'}++;
 9883:     my $result;
 9884:     if ($args->{'discussion'}) {
 9885: 	my ($target,$parser);
 9886: 	if (ref($args->{'discussion'})) {
 9887: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 9888: 				$args->{'discussion'}{'parser'});
 9889: 	}
 9890: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 9891:     }
 9892:     if ($args->{'frameset'}) {
 9893: 	$result .= '</frameset>';
 9894:     } else {
 9895: 	$result .= &endbodytag($args);
 9896:     }
 9897:     unless ($args->{'notbody'}) {
 9898:         $result .= "\n</html>";
 9899:     }
 9900: 
 9901:     if ($args->{'js_ready'}) {
 9902: 	$result = &js_ready($result);
 9903:     }
 9904: 
 9905:     if ($args->{'html_encode'}) {
 9906: 	$result = &html_encode($result);
 9907:     }
 9908: 
 9909:     return $result;
 9910: }
 9911: 
 9912: sub menucoll_in_effect {
 9913:     my ($menucoll,$deeplinkmenu,%menu);
 9914:     if ($env{'request.course.id'}) {
 9915:         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
 9916:         if ($env{'request.deeplink.login'}) {
 9917:             my ($deeplink_symb,$deeplink,$check_login_symb);
 9918:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9919:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9920:             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
 9921:                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
 9922:                     my $navmap = Apache::lonnavmaps::navmap->new();
 9923:                     if (ref($navmap)) {
 9924:                         $deeplink = $navmap->get_mapparam(undef,
 9925:                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
 9926:                                                           '0.deeplink');
 9927:                     } else {
 9928:                         $check_login_symb = 1;
 9929:                     }
 9930:                 } else {
 9931:                     my $symb = &Apache::lonnet::symbread();
 9932:                     if ($symb) {
 9933:                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
 9934:                     } else {
 9935:                         $check_login_symb = 1;
 9936:                     }
 9937:                 }
 9938:             } else {
 9939:                 $check_login_symb = 1;
 9940:             }
 9941:             if ($check_login_symb) {
 9942:                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
 9943:                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
 9944:                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
 9945:                     my $navmap = Apache::lonnavmaps::navmap->new();
 9946:                     if (ref($navmap)) {
 9947:                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
 9948:                     }
 9949:                 } else {
 9950:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
 9951:                 }
 9952:             }
 9953:             if ($deeplink ne '') {
 9954:                 my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
 9955:                 if ($display =~ /^\d+$/) {
 9956:                     $deeplinkmenu = 1;
 9957:                     $menucoll = $display;
 9958:                 }
 9959:             }
 9960:         }
 9961:         if ($menucoll) {
 9962:             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
 9963:         }
 9964:     }
 9965:     return ($menucoll,$deeplinkmenu,\%menu);
 9966: }
 9967: 
 9968: sub deeplink_login_symb {
 9969:     my ($cnum,$cdom) = @_;
 9970:     my $login_symb;
 9971:     if ($env{'request.deeplink.login'}) {
 9972:         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
 9973:     }
 9974:     return $login_symb;
 9975: }
 9976: 
 9977: sub symb_from_tinyurl {
 9978:     my ($url,$cnum,$cdom) = @_;
 9979:     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
 9980:         my $key = $1;
 9981:         my ($tinyurl,$login);
 9982:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
 9983:         if (defined($cached)) {
 9984:             $tinyurl = $result;
 9985:         } else {
 9986:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
 9987:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
 9988:             if ($currtiny{$key} ne '') {
 9989:                 $tinyurl = $currtiny{$key};
 9990:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
 9991:             }
 9992:         }
 9993:         if ($tinyurl ne '') {
 9994:             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
 9995:             if (wantarray) {
 9996:                 return ($cnumreq,$symb);
 9997:             } elsif ($cnumreq eq $cnum) {
 9998:                 return $symb;
 9999:             }
10000:         }
10001:     }
10002:     if (wantarray) {
10003:         return ();
10004:     } else {
10005:         return;
10006:     }
10007: }
10008: 
10009: sub usable_exttools {
10010:     my %tooltypes;
10011:     if ($env{'request.course.id'}) {
10012:         if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'}) {
10013:            if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'both') {
10014:                %tooltypes = (
10015:                              crs => 1,
10016:                              dom => 1,
10017:                             );
10018:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'crs') {
10019:                $tooltypes{'crs'} = 1;
10020:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'dom') {
10021:                $tooltypes{'dom'} = 1;
10022:            }
10023:         } else {
10024:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10025:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10026:             my $crstype = lc($env{'course.'.$env{'request.course.id'}.'.type'});
10027:             if ($crstype eq '') {
10028:                 $crstype = 'course';
10029:             }
10030:             if ($crstype eq 'course') {
10031:                 if ($env{'course.'.$env{'request.course.id'}.'internal.coursecode'}) {
10032:                     $crstype = 'official';
10033:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.textbook'}) {
10034:                     $crstype = 'textbook';
10035:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.lti'}) {
10036:                     $crstype = 'lti';
10037:                 } else {
10038:                     $crstype = 'unofficial';
10039:                 }
10040:             }
10041:             my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
10042:             if ($domdefaults{$crstype.'domexttool'}) {
10043:                 $tooltypes{'dom'} = 1;
10044:             }
10045:             if ($domdefaults{$crstype.'exttool'}) {
10046:                 $tooltypes{'crs'} = 1;
10047:             }
10048:         }
10049:     }
10050:     return %tooltypes;
10051: }
10052: 
10053: sub wishlist_window {
10054:     return(<<'ENDWISHLIST');
10055: <script type="text/javascript">
10056: // <![CDATA[
10057: // <!-- BEGIN LON-CAPA Internal
10058: function set_wishlistlink(title, path) {
10059:     if (!title) {
10060:         title = document.title;
10061:         title = title.replace(/^LON-CAPA /,'');
10062:     }
10063:     title = encodeURIComponent(title);
10064:     title = title.replace("'","\\\'");
10065:     if (!path) {
10066:         path = location.pathname;
10067:     }
10068:     path = encodeURIComponent(path);
10069:     path = path.replace("'","\\\'");
10070:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
10071:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
10072: }
10073: // END LON-CAPA Internal -->
10074: // ]]>
10075: </script>
10076: ENDWISHLIST
10077: }
10078: 
10079: sub modal_window {
10080:     return(<<'ENDMODAL');
10081: <script type="text/javascript">
10082: // <![CDATA[
10083: // <!-- BEGIN LON-CAPA Internal
10084: var modalWindow = {
10085: 	parent:"body",
10086: 	windowId:null,
10087: 	content:null,
10088: 	width:null,
10089: 	height:null,
10090: 	close:function()
10091: 	{
10092: 	        $(".LCmodal-window").remove();
10093: 	        $(".LCmodal-overlay").remove();
10094: 	},
10095: 	open:function()
10096: 	{
10097: 		var modal = "";
10098: 		modal += "<div class=\"LCmodal-overlay\"></div>";
10099: 		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;\">";
10100: 		modal += this.content;
10101: 		modal += "</div>";	
10102: 
10103: 		$(this.parent).append(modal);
10104: 
10105: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
10106: 		$(".LCclose-window").click(function(){modalWindow.close();});
10107: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
10108: 	}
10109: };
10110: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
10111: 	{
10112:                 source = source.replace(/'/g,"&#39;");
10113: 		modalWindow.windowId = "myModal";
10114: 		modalWindow.width = width;
10115: 		modalWindow.height = height;
10116: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
10117: 		modalWindow.open();
10118: 	};
10119: // END LON-CAPA Internal -->
10120: // ]]>
10121: </script>
10122: ENDMODAL
10123: }
10124: 
10125: sub modal_link {
10126:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
10127:     unless ($width) { $width=480; }
10128:     unless ($height) { $height=400; }
10129:     unless ($scrolling) { $scrolling='yes'; }
10130:     unless ($transparency) { $transparency='true'; }
10131: 
10132:     my $target_attr;
10133:     if (defined($target)) {
10134:         $target_attr = 'target="'.$target.'"';
10135:     }
10136:     return <<"ENDLINK";
10137: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
10138: ENDLINK
10139: }
10140: 
10141: sub modal_adhoc_script {
10142:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
10143:     my $mathjax;
10144:     if ($possmathjax) {
10145:         $mathjax = <<'ENDJAX';
10146:                if (typeof MathJax == 'object') {
10147:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
10148:                }
10149: ENDJAX
10150:     }
10151:     return (<<ENDADHOC);
10152: <script type="text/javascript">
10153: // <![CDATA[
10154:         var $funcname = function()
10155:         {
10156:                 modalWindow.windowId = "myModal";
10157:                 modalWindow.width = $width;
10158:                 modalWindow.height = $height;
10159:                 modalWindow.content = '$content';
10160:                 modalWindow.open();
10161:                 $mathjax
10162:         };  
10163: // ]]>
10164: </script>
10165: ENDADHOC
10166: }
10167: 
10168: sub modal_adhoc_inner {
10169:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
10170:     my $innerwidth=$width-20;
10171:     $content=&js_ready(
10172:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
10173:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
10174:                  $content.
10175:                  &end_scrollbox().
10176:                  &end_page()
10177:              );
10178:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
10179: }
10180: 
10181: sub modal_adhoc_window {
10182:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
10183:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
10184:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
10185: }
10186: 
10187: sub modal_adhoc_launch {
10188:     my ($funcname,$width,$height,$content)=@_;
10189:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
10190: <script type="text/javascript">
10191: // <![CDATA[
10192: $funcname();
10193: // ]]>
10194: </script>
10195: ENDLAUNCH
10196: }
10197: 
10198: sub modal_adhoc_close {
10199:     return (<<ENDCLOSE);
10200: <script type="text/javascript">
10201: // <![CDATA[
10202: modalWindow.close();
10203: // ]]>
10204: </script>
10205: ENDCLOSE
10206: }
10207: 
10208: sub togglebox_script {
10209:    return(<<ENDTOGGLE);
10210: <script type="text/javascript"> 
10211: // <![CDATA[
10212: function LCtoggleDisplay(id,hidetext,showtext) {
10213:    link = document.getElementById(id + "link").childNodes[0];
10214:    with (document.getElementById(id).style) {
10215:       if (display == "none" ) {
10216:           display = "inline";
10217:           link.nodeValue = hidetext;
10218:         } else {
10219:           display = "none";
10220:           link.nodeValue = showtext;
10221:        }
10222:    }
10223: }
10224: // ]]>
10225: </script>
10226: ENDTOGGLE
10227: }
10228: 
10229: sub start_togglebox {
10230:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
10231:     unless ($heading) { $heading=''; } else { $heading.=' '; }
10232:     unless ($showtext) { $showtext=&mt('show'); }
10233:     unless ($hidetext) { $hidetext=&mt('hide'); }
10234:     unless ($headerbg) { $headerbg='#FFFFFF'; }
10235:     return &start_data_table().
10236:            &start_data_table_header_row().
10237:            '<td bgcolor="'.$headerbg.'">'.$heading.
10238:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
10239:            $showtext.'\')">'.$showtext.'</a>]</td>'.
10240:            &end_data_table_header_row().
10241:            '<tr id="'.$id.'" style="display:none""><td>';
10242: }
10243: 
10244: sub end_togglebox {
10245:     return '</td></tr>'.&end_data_table();
10246: }
10247: 
10248: sub LCprogressbar_script {
10249:    my ($id,$number_to_do)=@_;
10250:    if ($number_to_do) {
10251:        return(<<ENDPROGRESS);
10252: <script type="text/javascript">
10253: // <![CDATA[
10254: \$('#progressbar$id').progressbar({
10255:   value: 0,
10256:   change: function(event, ui) {
10257:     var newVal = \$(this).progressbar('option', 'value');
10258:     \$('.pblabel', this).text(LCprogressTxt);
10259:   }
10260: });
10261: // ]]>
10262: </script>
10263: ENDPROGRESS
10264:    } else {
10265:        return(<<ENDPROGRESS);
10266: <script type="text/javascript">
10267: // <![CDATA[
10268: \$('#progressbar$id').progressbar({
10269:   value: false,
10270:   create: function(event, ui) {
10271:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
10272:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
10273:   }
10274: });
10275: // ]]>
10276: </script>
10277: ENDPROGRESS
10278:    }
10279: }
10280: 
10281: sub LCprogressbarUpdate_script {
10282:    return(<<ENDPROGRESSUPDATE);
10283: <style type="text/css">
10284: .ui-progressbar { position:relative; }
10285: .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%; }
10286: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
10287: </style>
10288: <script type="text/javascript">
10289: // <![CDATA[
10290: var LCprogressTxt='---';
10291: 
10292: function LCupdateProgress(percent,progresstext,id,maxnum) {
10293:    LCprogressTxt=progresstext;
10294:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
10295:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
10296:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
10297:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
10298:    } else {
10299:        \$('#progressbar'+id).progressbar('value',percent);
10300:    }
10301: }
10302: // ]]>
10303: </script>
10304: ENDPROGRESSUPDATE
10305: }
10306: 
10307: my $LClastpercent;
10308: my $LCidcnt;
10309: my $LCcurrentid;
10310: 
10311: sub LCprogressbar {
10312:     my ($r,$number_to_do,$preamble)=@_;
10313:     $LClastpercent=0;
10314:     $LCidcnt++;
10315:     $LCcurrentid=$$.'_'.$LCidcnt;
10316:     my ($starting,$content);
10317:     if ($number_to_do) {
10318:         $starting=&mt('Starting');
10319:         $content=(<<ENDPROGBAR);
10320: $preamble
10321:   <div id="progressbar$LCcurrentid">
10322:     <span class="pblabel">$starting</span>
10323:   </div>
10324: ENDPROGBAR
10325:     } else {
10326:         $starting=&mt('Loading...');
10327:         $LClastpercent='false';
10328:         $content=(<<ENDPROGBAR);
10329: $preamble
10330:   <div id="progressbar$LCcurrentid">
10331:       <div class="progress-label">$starting</div>
10332:   </div>
10333: ENDPROGBAR
10334:     }
10335:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
10336: }
10337: 
10338: sub LCprogressbarUpdate {
10339:     my ($r,$val,$text,$number_to_do)=@_;
10340:     if ($number_to_do) {
10341:         unless ($val) { 
10342:             if ($LClastpercent) {
10343:                 $val=$LClastpercent;
10344:             } else {
10345:                 $val=0;
10346:             }
10347:         }
10348:         if ($val<0) { $val=0; }
10349:         if ($val>100) { $val=0; }
10350:         $LClastpercent=$val;
10351:         unless ($text) { $text=$val.'%'; }
10352:     } else {
10353:         $val = 'false';
10354:     }
10355:     $text=&js_ready($text);
10356:     &r_print($r,<<ENDUPDATE);
10357: <script type="text/javascript">
10358: // <![CDATA[
10359: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
10360: // ]]>
10361: </script>
10362: ENDUPDATE
10363: }
10364: 
10365: sub LCprogressbarClose {
10366:     my ($r)=@_;
10367:     $LClastpercent=0;
10368:     &r_print($r,<<ENDCLOSE);
10369: <script type="text/javascript">
10370: // <![CDATA[
10371: \$("#progressbar$LCcurrentid").hide('slow'); 
10372: // ]]>
10373: </script>
10374: ENDCLOSE
10375: }
10376: 
10377: sub r_print {
10378:     my ($r,$to_print)=@_;
10379:     if ($r) {
10380:       $r->print($to_print);
10381:       $r->rflush();
10382:     } else {
10383:       print($to_print);
10384:     }
10385: }
10386: 
10387: sub html_encode {
10388:     my ($result) = @_;
10389: 
10390:     $result = &HTML::Entities::encode($result,'<>&"');
10391:     
10392:     return $result;
10393: }
10394: 
10395: sub js_ready {
10396:     my ($result) = @_;
10397: 
10398:     $result =~ s/[\n\r]/ /xmsg;
10399:     $result =~ s/\\/\\\\/xmsg;
10400:     $result =~ s/'/\\'/xmsg;
10401:     $result =~ s{</}{<\\/}xmsg;
10402:     
10403:     return $result;
10404: }
10405: 
10406: sub validate_page {
10407:     if (  exists($env{'internal.start_page'})
10408: 	  &&     $env{'internal.start_page'} > 1) {
10409: 	&Apache::lonnet::logthis('start_page called multiple times '.
10410: 				 $env{'internal.start_page'}.' '.
10411: 				 $ENV{'request.filename'});
10412:     }
10413:     if (  exists($env{'internal.end_page'})
10414: 	  &&     $env{'internal.end_page'} > 1) {
10415: 	&Apache::lonnet::logthis('end_page called multiple times '.
10416: 				 $env{'internal.end_page'}.' '.
10417: 				 $env{'request.filename'});
10418:     }
10419:     if (     exists($env{'internal.start_page'})
10420: 	&& ! exists($env{'internal.end_page'})) {
10421: 	&Apache::lonnet::logthis('start_page called without end_page '.
10422: 				 $env{'request.filename'});
10423:     }
10424:     if (   ! exists($env{'internal.start_page'})
10425: 	&&   exists($env{'internal.end_page'})) {
10426: 	&Apache::lonnet::logthis('end_page called without start_page'.
10427: 				 $env{'request.filename'});
10428:     }
10429: }
10430: 
10431: 
10432: sub start_scrollbox {
10433:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
10434:     unless ($outerwidth) { $outerwidth='520px'; }
10435:     unless ($width) { $width='500px'; }
10436:     unless ($height) { $height='200px'; }
10437:     my ($table_id,$div_id,$tdcol);
10438:     if ($id ne '') {
10439:         $table_id = ' id="table_'.$id.'"';
10440:         $div_id = ' id="div_'.$id.'"';
10441:     }
10442:     if ($bgcolor ne '') {
10443:         $tdcol = "background-color: $bgcolor;";
10444:     }
10445:     my $nicescroll_js;
10446:     if ($env{'browser.mobile'}) {
10447:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
10448:     }
10449:     return <<"END";
10450: $nicescroll_js
10451: 
10452: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
10453: <div style="overflow:auto; width:$width; height:$height;"$div_id>
10454: END
10455: }
10456: 
10457: sub end_scrollbox {
10458:     return '</div></td></tr></table>';
10459: }
10460: 
10461: sub nicescroll_javascript {
10462:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
10463:     my %options;
10464:     if (ref($cursor) eq 'HASH') {
10465:         %options = %{$cursor};
10466:     }
10467:     unless ($options{'railalign'} =~ /^left|right$/) {
10468:         $options{'railalign'} = 'left';
10469:     }
10470:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
10471:         my $function  = &get_users_function();
10472:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
10473:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
10474:             $options{'cursorcolor'} = '#00F';
10475:         }
10476:     }
10477:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
10478:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
10479:             $options{'cursoropacity'}='1.0';
10480:         }
10481:     } else {
10482:         $options{'cursoropacity'}='1.0';
10483:     }
10484:     if ($options{'cursorfixedheight'} eq 'none') {
10485:         delete($options{'cursorfixedheight'});
10486:     } else {
10487:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
10488:     }
10489:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
10490:         delete($options{'railoffset'});
10491:     }
10492:     my @niceoptions;
10493:     while (my($key,$value) = each(%options)) {
10494:         if ($value =~ /^\{.+\}$/) {
10495:             push(@niceoptions,$key.':'.$value);
10496:         } else {
10497:             push(@niceoptions,$key.':"'.$value.'"');
10498:         }
10499:     }
10500:     my $nicescroll_js = '
10501: $(document).ready(
10502:       function() {
10503:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
10504:       }
10505: );
10506: ';
10507:     if ($framecheck) {
10508:         $nicescroll_js .= '
10509: function expand_div(caller) {
10510:     if (top === self) {
10511:         document.getElementById("'.$id.'").style.width = "auto";
10512:         document.getElementById("'.$id.'").style.height = "auto";
10513:     } else {
10514:         try {
10515:             if (parent.frames) {
10516:                 if (parent.frames.length > 1) {
10517:                     var framesrc = parent.frames[1].location.href;
10518:                     var currsrc = framesrc.replace(/\#.*$/,"");
10519:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
10520:                         document.getElementById("'.$id.'").style.width = "auto";
10521:                         document.getElementById("'.$id.'").style.height = "auto";
10522:                     }
10523:                 }
10524:             }
10525:         } catch (e) {
10526:             return;
10527:         }
10528:     }
10529:     return;
10530: }
10531: ';
10532:     }
10533:     if ($needjsready) {
10534:         $nicescroll_js = '
10535: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
10536:     } else {
10537:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
10538:     }
10539:     return $nicescroll_js;
10540: }
10541: 
10542: sub simple_error_page {
10543:     my ($r,$title,$msg,$args) = @_;
10544:     my %displayargs;
10545:     if (ref($args) eq 'HASH') {
10546:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
10547:         if ($args->{'only_body'}) {
10548:             $displayargs{'only_body'} = 1;
10549:         }
10550:         if ($args->{'no_nav_bar'}) {
10551:             $displayargs{'no_nav_bar'} = 1;
10552:         }
10553:     } else {
10554:         $msg = &mt($msg);
10555:     }
10556: 
10557:     my $page =
10558: 	&Apache::loncommon::start_page($title,'',\%displayargs).
10559: 	'<p class="LC_error">'.$msg.'</p>'.
10560: 	&Apache::loncommon::end_page();
10561:     if (ref($r)) {
10562: 	$r->print($page);
10563: 	return;
10564:     }
10565:     return $page;
10566: }
10567: 
10568: {
10569:     my @row_count;
10570: 
10571:     sub start_data_table_count {
10572:         unshift(@row_count, 0);
10573:         return;
10574:     }
10575: 
10576:     sub end_data_table_count {
10577:         shift(@row_count);
10578:         return;
10579:     }
10580: 
10581:     sub start_data_table {
10582: 	my ($add_class,$id) = @_;
10583: 	my $css_class = (join(' ','LC_data_table',$add_class));
10584:         my $table_id;
10585:         if (defined($id)) {
10586:             $table_id = ' id="'.$id.'"';
10587:         }
10588: 	&start_data_table_count();
10589: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
10590:     }
10591: 
10592:     sub end_data_table {
10593: 	&end_data_table_count();
10594: 	return '</table>'."\n";;
10595:     }
10596: 
10597:     sub start_data_table_row {
10598: 	my ($add_class, $id) = @_;
10599: 	$row_count[0]++;
10600: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
10601: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
10602:         $id = (' id="'.$id.'"') unless ($id eq '');
10603:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
10604:     }
10605:     
10606:     sub continue_data_table_row {
10607: 	my ($add_class, $id) = @_;
10608: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
10609: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
10610:         $id = (' id="'.$id.'"') unless ($id eq '');
10611:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
10612:     }
10613: 
10614:     sub end_data_table_row {
10615: 	return '</tr>'."\n";;
10616:     }
10617: 
10618:     sub start_data_table_empty_row {
10619: #	$row_count[0]++;
10620: 	return  '<tr class="LC_empty_row" >'."\n";;
10621:     }
10622: 
10623:     sub end_data_table_empty_row {
10624: 	return '</tr>'."\n";;
10625:     }
10626: 
10627:     sub start_data_table_header_row {
10628: 	return  '<tr class="LC_header_row">'."\n";;
10629:     }
10630: 
10631:     sub end_data_table_header_row {
10632: 	return '</tr>'."\n";;
10633:     }
10634: 
10635:     sub data_table_caption {
10636:         my $caption = shift;
10637:         return "<caption class=\"LC_caption\">$caption</caption>";
10638:     }
10639: }
10640: 
10641: =pod
10642: 
10643: =item * &inhibit_menu_check($arg)
10644: 
10645: Checks for a inhibitmenu state and generates output to preserve it
10646: 
10647: Inputs:         $arg - can be any of
10648:                      - undef - in which case the return value is a string 
10649:                                to add  into arguments list of a uri
10650:                      - 'input' - in which case the return value is a HTML
10651:                                  <form> <input> field of type hidden to
10652:                                  preserve the value
10653:                      - a url - in which case the return value is the url with
10654:                                the neccesary cgi args added to preserve the
10655:                                inhibitmenu state
10656:                      - a ref to a url - no return value, but the string is
10657:                                         updated to include the neccessary cgi
10658:                                         args to preserve the inhibitmenu state
10659: 
10660: =cut
10661: 
10662: sub inhibit_menu_check {
10663:     my ($arg) = @_;
10664:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
10665:     if ($arg eq 'input') {
10666: 	if ($env{'form.inhibitmenu'}) {
10667: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
10668: 	} else {
10669: 	    return
10670: 	}
10671:     }
10672:     if ($env{'form.inhibitmenu'}) {
10673: 	if (ref($arg)) {
10674: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
10675: 	} elsif ($arg eq '') {
10676: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
10677: 	} else {
10678: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
10679: 	}
10680:     }
10681:     if (!ref($arg)) {
10682: 	return $arg;
10683:     }
10684: }
10685: 
10686: ###############################################
10687: 
10688: =pod
10689: 
10690: =back
10691: 
10692: =head1 User Information Routines
10693: 
10694: =over 4
10695: 
10696: =item * &get_users_function()
10697: 
10698: Used by &bodytag to determine the current users primary role.
10699: Returns either 'student','coordinator','admin', or 'author'.
10700: 
10701: =cut
10702: 
10703: ###############################################
10704: sub get_users_function {
10705:     my $function = 'norole';
10706:     if ($env{'request.role'}=~/^(st)/) {
10707:         $function='student';
10708:     }
10709:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
10710:         $function='coordinator';
10711:     }
10712:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
10713:         $function='admin';
10714:     }
10715:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
10716:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
10717:         $function='author';
10718:     }
10719:     return $function;
10720: }
10721: 
10722: ###############################################
10723: 
10724: =pod
10725: 
10726: =item * &show_course()
10727: 
10728: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
10729: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
10730: 
10731: Inputs:
10732: None
10733: 
10734: Outputs:
10735: Scalar: 1 if 'Course' to be used, 0 otherwise.
10736: 
10737: =cut
10738: 
10739: ###############################################
10740: sub show_course {
10741:     my ($udom,$uname) = @_;
10742:     if (($udom ne '') && ($uname ne '')) {
10743:         if (($udom ne $env{'user.domain'}) || ($uname ne $env{'user.name'})) {
10744:             if (&Apache::lonnet::is_advanced_user($udom,$uname)) {
10745:                 return 0;
10746:             } else {
10747:                 return 1;
10748:             }
10749:         }
10750:     }
10751:     my $course = !$env{'user.adv'};
10752:     if (!$env{'user.adv'}) {
10753:         foreach my $env (keys(%env)) {
10754:             next if ($env !~ m/^user\.priv\./);
10755:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
10756:                 $course = 0;
10757:                 last;
10758:             }
10759:         }
10760:     }
10761:     return $course;
10762: }
10763: 
10764: ###############################################
10765: 
10766: =pod
10767: 
10768: =item * &check_user_status()
10769: 
10770: Determines current status of supplied role for a
10771: specific user. Roles can be active, previous or future.
10772: 
10773: Inputs: 
10774: user's domain, user's username, course's domain,
10775: course's number, optional section ID.
10776: 
10777: Outputs:
10778: role status: active, previous or future. 
10779: 
10780: =cut
10781: 
10782: sub check_user_status {
10783:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
10784:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
10785:     my @uroles = keys(%userinfo);
10786:     my $srchstr;
10787:     my $active_chk = 'none';
10788:     my $now = time;
10789:     if (@uroles > 0) {
10790:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
10791:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
10792:         } else {
10793:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
10794:         }
10795:         if (grep/^\Q$srchstr\E$/,@uroles) {
10796:             my $role_end = 0;
10797:             my $role_start = 0;
10798:             $active_chk = 'active';
10799:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
10800:                 $role_end = $1;
10801:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
10802:                     $role_start = $1;
10803:                 }
10804:             }
10805:             if ($role_start > 0) {
10806:                 if ($now < $role_start) {
10807:                     $active_chk = 'future';
10808:                 }
10809:             }
10810:             if ($role_end > 0) {
10811:                 if ($now > $role_end) {
10812:                     $active_chk = 'previous';
10813:                 }
10814:             }
10815:         }
10816:     }
10817:     return $active_chk;
10818: }
10819: 
10820: ###############################################
10821: 
10822: =pod
10823: 
10824: =item * &get_sections()
10825: 
10826: Determines all the sections for a course including
10827: sections with students and sections containing other roles.
10828: Incoming parameters: 
10829: 
10830: 1. domain
10831: 2. course number 
10832: 3. reference to array containing roles for which sections should 
10833: be gathered (optional).
10834: 4. reference to array containing status types for which sections 
10835: should be gathered (optional).
10836: 
10837: If the third argument is undefined, sections are gathered for any role. 
10838: If the fourth argument is undefined, sections are gathered for any status.
10839: Permissible values are 'active' or 'future' or 'previous'.
10840:  
10841: Returns section hash (keys are section IDs, values are
10842: number of users in each section), subject to the
10843: optional roles filter, optional status filter 
10844: 
10845: =cut
10846: 
10847: ###############################################
10848: sub get_sections {
10849:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
10850:     if (!defined($cdom) || !defined($cnum)) {
10851:         my $cid =  $env{'request.course.id'};
10852: 
10853: 	return if (!defined($cid));
10854: 
10855:         $cdom = $env{'course.'.$cid.'.domain'};
10856:         $cnum = $env{'course.'.$cid.'.num'};
10857:     }
10858: 
10859:     my %sectioncount;
10860:     my $now = time;
10861: 
10862:     my $check_students = 1;
10863:     my $only_students = 0;
10864:     if (ref($possible_roles) eq 'ARRAY') {
10865:         if (grep(/^st$/,@{$possible_roles})) {
10866:             if (@{$possible_roles} == 1) {
10867:                 $only_students = 1;
10868:             }
10869:         } else {
10870:             $check_students = 0;
10871:         }
10872:     }
10873: 
10874:     if ($check_students) { 
10875: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
10876: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
10877: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
10878:         my $start_index = &Apache::loncoursedata::CL_START();
10879:         my $end_index = &Apache::loncoursedata::CL_END();
10880:         my $status;
10881: 	while (my ($student,$data) = each(%$classlist)) {
10882: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
10883: 				                     $data->[$status_index],
10884:                                                      $data->[$start_index],
10885:                                                      $data->[$end_index]);
10886:             if ($stu_status eq 'Active') {
10887:                 $status = 'active';
10888:             } elsif ($end < $now) {
10889:                 $status = 'previous';
10890:             } elsif ($start > $now) {
10891:                 $status = 'future';
10892:             } 
10893: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
10894:                 if ((!defined($possible_status)) || (($status ne '') && 
10895:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
10896: 		    $sectioncount{$section}++;
10897:                 }
10898: 	    }
10899: 	}
10900:     }
10901:     if ($only_students) {
10902:         return %sectioncount;
10903:     }
10904:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10905:     foreach my $user (sort(keys(%courseroles))) {
10906: 	if ($user !~ /^(\w{2})/) { next; }
10907: 	my ($role) = ($user =~ /^(\w{2})/);
10908: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
10909: 	my ($section,$status);
10910: 	if ($role eq 'cr' &&
10911: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
10912: 	    $section=$1;
10913: 	}
10914: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
10915: 	if (!defined($section) || $section eq '-1') { next; }
10916:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
10917:         if ($end == -1 && $start == -1) {
10918:             next; #deleted role
10919:         }
10920:         if (!defined($possible_status)) { 
10921:             $sectioncount{$section}++;
10922:         } else {
10923:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
10924:                 $status = 'active';
10925:             } elsif ($end < $now) {
10926:                 $status = 'future';
10927:             } elsif ($start > $now) {
10928:                 $status = 'previous';
10929:             }
10930:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
10931:                 $sectioncount{$section}++;
10932:             }
10933:         }
10934:     }
10935:     return %sectioncount;
10936: }
10937: 
10938: ###############################################
10939: 
10940: =pod
10941: 
10942: =item * &get_course_users()
10943: 
10944: Retrieves usernames:domains for users in the specified course
10945: with specific role(s), and access status. 
10946: 
10947: Incoming parameters:
10948: 1. course domain
10949: 2. course number
10950: 3. access status: users must have - either active, 
10951: previous, future, or all.
10952: 4. reference to array of permissible roles
10953: 5. reference to array of section restrictions (optional)
10954: 6. reference to results object (hash of hashes).
10955: 7. reference to optional userdata hash
10956: 8. reference to optional statushash
10957: 9. flag if privileged users (except those set to unhide in
10958:    course settings) should be excluded    
10959: Keys of top level results hash are roles.
10960: Keys of inner hashes are username:domain, with 
10961: values set to access type.
10962: Optional userdata hash returns an array with arguments in the 
10963: same order as loncoursedata::get_classlist() for student data.
10964: 
10965: Optional statushash returns
10966: 
10967: Entries for end, start, section and status are blank because
10968: of the possibility of multiple values for non-student roles.
10969: 
10970: =cut
10971: 
10972: ###############################################
10973: 
10974: sub get_course_users {
10975:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
10976:     my %idx = ();
10977:     my %seclists;
10978: 
10979:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
10980:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
10981:     $idx{end} = &Apache::loncoursedata::CL_END();
10982:     $idx{start} = &Apache::loncoursedata::CL_START();
10983:     $idx{id} = &Apache::loncoursedata::CL_ID();
10984:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
10985:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
10986:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
10987: 
10988:     if (grep(/^st$/,@{$roles})) {
10989:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
10990:         my $now = time;
10991:         foreach my $student (keys(%{$classlist})) {
10992:             my $match = 0;
10993:             my $secmatch = 0;
10994:             my $section = $$classlist{$student}[$idx{section}];
10995:             my $status = $$classlist{$student}[$idx{status}];
10996:             if ($section eq '') {
10997:                 $section = 'none';
10998:             }
10999:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
11000:                 if (grep(/^all$/,@{$sections})) {
11001:                     $secmatch = 1;
11002:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
11003:                     if (grep(/^none$/,@{$sections})) {
11004:                         $secmatch = 1;
11005:                     }
11006:                 } else {  
11007: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
11008: 		        $secmatch = 1;
11009:                     }
11010: 		}
11011:                 if (!$secmatch) {
11012:                     next;
11013:                 }
11014:             }
11015:             if (defined($$types{'active'})) {
11016:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
11017:                     push(@{$$users{st}{$student}},'active');
11018:                     $match = 1;
11019:                 }
11020:             }
11021:             if (defined($$types{'previous'})) {
11022:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
11023:                     push(@{$$users{st}{$student}},'previous');
11024:                     $match = 1;
11025:                 }
11026:             }
11027:             if (defined($$types{'future'})) {
11028:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
11029:                     push(@{$$users{st}{$student}},'future');
11030:                     $match = 1;
11031:                 }
11032:             }
11033:             if ($match) {
11034:                 push(@{$seclists{$student}},$section);
11035:                 if (ref($userdata) eq 'HASH') {
11036:                     $$userdata{$student} = $$classlist{$student};
11037:                 }
11038:                 if (ref($statushash) eq 'HASH') {
11039:                     $statushash->{$student}{'st'}{$section} = $status;
11040:                 }
11041:             }
11042:         }
11043:     }
11044:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
11045:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
11046:         my $now = time;
11047:         my %displaystatus = ( previous => 'Expired',
11048:                               active   => 'Active',
11049:                               future   => 'Future',
11050:                             );
11051:         my (%nothide,@possdoms);
11052:         if ($hidepriv) {
11053:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
11054:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
11055:                 if ($user !~ /:/) {
11056:                     $nothide{join(':',split(/[\@]/,$user))}=1;
11057:                 } else {
11058:                     $nothide{$user} = 1;
11059:                 }
11060:             }
11061:             my @possdoms = ($cdom);
11062:             if ($coursehash{'checkforpriv'}) {
11063:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
11064:             }
11065:         }
11066:         foreach my $person (sort(keys(%coursepersonnel))) {
11067:             my $match = 0;
11068:             my $secmatch = 0;
11069:             my $status;
11070:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
11071:             $user =~ s/:$//;
11072:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
11073:             if ($end == -1 || $start == -1) {
11074:                 next;
11075:             }
11076:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
11077:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
11078:                 my ($uname,$udom) = split(/:/,$user);
11079:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
11080:                     if (grep(/^all$/,@{$sections})) {
11081:                         $secmatch = 1;
11082:                     } elsif ($usec eq '') {
11083:                         if (grep(/^none$/,@{$sections})) {
11084:                             $secmatch = 1;
11085:                         }
11086:                     } else {
11087:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
11088:                             $secmatch = 1;
11089:                         }
11090:                     }
11091:                     if (!$secmatch) {
11092:                         next;
11093:                     }
11094:                 }
11095:                 if ($usec eq '') {
11096:                     $usec = 'none';
11097:                 }
11098:                 if ($uname ne '' && $udom ne '') {
11099:                     if ($hidepriv) {
11100:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
11101:                             (!$nothide{$uname.':'.$udom})) {
11102:                             next;
11103:                         }
11104:                     }
11105:                     if ($end > 0 && $end < $now) {
11106:                         $status = 'previous';
11107:                     } elsif ($start > $now) {
11108:                         $status = 'future';
11109:                     } else {
11110:                         $status = 'active';
11111:                     }
11112:                     foreach my $type (keys(%{$types})) { 
11113:                         if ($status eq $type) {
11114:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
11115:                                 push(@{$$users{$role}{$user}},$type);
11116:                             }
11117:                             $match = 1;
11118:                         }
11119:                     }
11120:                     if (($match) && (ref($userdata) eq 'HASH')) {
11121:                         if (!exists($$userdata{$uname.':'.$udom})) {
11122: 			    &get_user_info($udom,$uname,\%idx,$userdata);
11123:                         }
11124:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
11125:                             push(@{$seclists{$uname.':'.$udom}},$usec);
11126:                         }
11127:                         if (ref($statushash) eq 'HASH') {
11128:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
11129:                         }
11130:                     }
11131:                 }
11132:             }
11133:         }
11134:         if (grep(/^ow$/,@{$roles})) {
11135:             if ((defined($cdom)) && (defined($cnum))) {
11136:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
11137:                 if ( defined($csettings{'internal.courseowner'}) ) {
11138:                     my $owner = $csettings{'internal.courseowner'};
11139:                     next if ($owner eq '');
11140:                     my ($ownername,$ownerdom);
11141:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
11142:                         $ownername = $1;
11143:                         $ownerdom = $2;
11144:                     } else {
11145:                         $ownername = $owner;
11146:                         $ownerdom = $cdom;
11147:                         $owner = $ownername.':'.$ownerdom;
11148:                     }
11149:                     @{$$users{'ow'}{$owner}} = 'any';
11150:                     if (defined($userdata) && 
11151: 			!exists($$userdata{$owner})) {
11152: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
11153:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
11154:                             push(@{$seclists{$owner}},'none');
11155:                         }
11156:                         if (ref($statushash) eq 'HASH') {
11157:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
11158:                         }
11159: 		    }
11160:                 }
11161:             }
11162:         }
11163:         foreach my $user (keys(%seclists)) {
11164:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
11165:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
11166:         }
11167:     }
11168:     return;
11169: }
11170: 
11171: sub get_user_info {
11172:     my ($udom,$uname,$idx,$userdata) = @_;
11173:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
11174: 	&plainname($uname,$udom,'lastname');
11175:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
11176:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
11177:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
11178:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
11179:     return;
11180: }
11181: 
11182: ###############################################
11183: 
11184: =pod
11185: 
11186: =item * &get_user_quota()
11187: 
11188: Retrieves quota assigned for storage of user files.
11189: Default is to report quota for portfolio files.
11190: 
11191: Incoming parameters:
11192: 1. user's username
11193: 2. user's domain
11194: 3. quota name - portfolio, author, or course
11195:    (if no quota name provided, defaults to portfolio).
11196: 4. crstype - official, unofficial, textbook, placement or community, 
11197:    if quota name is course
11198: 
11199: Returns:
11200: 1. Disk quota (in MB) assigned to student.
11201: 2. (Optional) Type of setting: custom or default
11202:    (individually assigned or default for user's 
11203:    institutional status).
11204: 3. (Optional) - User's institutional status (e.g., faculty, staff
11205:    or student - types as defined in localenroll::inst_usertypes 
11206:    for user's domain, which determines default quota for user.
11207: 4. (Optional) - Default quota which would apply to the user.
11208: 
11209: If a value has been stored in the user's environment, 
11210: it will return that, otherwise it returns the maximal default
11211: defined for the user's institutional status(es) in the domain.
11212: 
11213: =cut
11214: 
11215: ###############################################
11216: 
11217: 
11218: sub get_user_quota {
11219:     my ($uname,$udom,$quotaname,$crstype) = @_;
11220:     my ($quota,$quotatype,$settingstatus,$defquota);
11221:     if (!defined($udom)) {
11222:         $udom = $env{'user.domain'};
11223:     }
11224:     if (!defined($uname)) {
11225:         $uname = $env{'user.name'};
11226:     }
11227:     if (($udom eq '' || $uname eq '') ||
11228:         ($udom eq 'public') && ($uname eq 'public')) {
11229:         $quota = 0;
11230:         $quotatype = 'default';
11231:         $defquota = 0; 
11232:     } else {
11233:         my $inststatus;
11234:         if ($quotaname eq 'course') {
11235:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
11236:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
11237:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
11238:             } else {
11239:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
11240:                 $quota = $cenv{'internal.uploadquota'};
11241:             }
11242:         } else {
11243:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
11244:                 if ($quotaname eq 'author') {
11245:                     $quota = $env{'environment.authorquota'};
11246:                 } else {
11247:                     $quota = $env{'environment.portfolioquota'};
11248:                 }
11249:                 $inststatus = $env{'environment.inststatus'};
11250:             } else {
11251:                 my %userenv = 
11252:                     &Apache::lonnet::get('environment',['portfolioquota',
11253:                                          'authorquota','inststatus'],$udom,$uname);
11254:                 my ($tmp) = keys(%userenv);
11255:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11256:                     if ($quotaname eq 'author') {
11257:                         $quota = $userenv{'authorquota'};
11258:                     } else {
11259:                         $quota = $userenv{'portfolioquota'};
11260:                     }
11261:                     $inststatus = $userenv{'inststatus'};
11262:                 } else {
11263:                     undef(%userenv);
11264:                 }
11265:             }
11266:         }
11267:         if ($quota eq '' || wantarray) {
11268:             if ($quotaname eq 'course') {
11269:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
11270:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
11271:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
11272:                     ($crstype eq 'placement')) { 
11273:                     $defquota = $domdefs{$crstype.'quota'};
11274:                 }
11275:                 if ($defquota eq '') {
11276:                     $defquota = 500;
11277:                 }
11278:             } else {
11279:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
11280:             }
11281:             if ($quota eq '') {
11282:                 $quota = $defquota;
11283:                 $quotatype = 'default';
11284:             } else {
11285:                 $quotatype = 'custom';
11286:             }
11287:         }
11288:     }
11289:     if (wantarray) {
11290:         return ($quota,$quotatype,$settingstatus,$defquota);
11291:     } else {
11292:         return $quota;
11293:     }
11294: }
11295: 
11296: ###############################################
11297: 
11298: =pod
11299: 
11300: =item * &default_quota()
11301: 
11302: Retrieves default quota assigned for storage of user portfolio files,
11303: given an (optional) user's institutional status.
11304: 
11305: Incoming parameters:
11306: 
11307: 1. domain
11308: 2. (Optional) institutional status(es).  This is a : separated list of 
11309:    status types (e.g., faculty, staff, student etc.)
11310:    which apply to the user for whom the default is being retrieved.
11311:    If the institutional status string in undefined, the domain
11312:    default quota will be returned.
11313: 3.  quota name - portfolio, author, or course
11314:    (if no quota name provided, defaults to portfolio).
11315: 
11316: Returns:
11317: 
11318: 1. Default disk quota (in MB) for user portfolios in the domain.
11319: 2. (Optional) institutional type which determined the value of the
11320:    default quota.
11321: 
11322: If a value has been stored in the domain's configuration db,
11323: it will return that, otherwise it returns 20 (for backwards 
11324: compatibility with domains which have not set up a configuration
11325: db file; the original statically defined portfolio quota was 20 MB). 
11326: 
11327: If the user's status includes multiple types (e.g., staff and student),
11328: the largest default quota which applies to the user determines the
11329: default quota returned.
11330: 
11331: =cut
11332: 
11333: ###############################################
11334: 
11335: 
11336: sub default_quota {
11337:     my ($udom,$inststatus,$quotaname) = @_;
11338:     my ($defquota,$settingstatus);
11339:     my %quotahash = &Apache::lonnet::get_dom('configuration',
11340:                                             ['quotas'],$udom);
11341:     my $key = 'defaultquota';
11342:     if ($quotaname eq 'author') {
11343:         $key = 'authorquota';
11344:     }
11345:     if (ref($quotahash{'quotas'}) eq 'HASH') {
11346:         if ($inststatus ne '') {
11347:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
11348:             foreach my $item (@statuses) {
11349:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
11350:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
11351:                         if ($defquota eq '') {
11352:                             $defquota = $quotahash{'quotas'}{$key}{$item};
11353:                             $settingstatus = $item;
11354:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
11355:                             $defquota = $quotahash{'quotas'}{$key}{$item};
11356:                             $settingstatus = $item;
11357:                         }
11358:                     }
11359:                 } elsif ($key eq 'defaultquota') {
11360:                     if ($quotahash{'quotas'}{$item} ne '') {
11361:                         if ($defquota eq '') {
11362:                             $defquota = $quotahash{'quotas'}{$item};
11363:                             $settingstatus = $item;
11364:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
11365:                             $defquota = $quotahash{'quotas'}{$item};
11366:                             $settingstatus = $item;
11367:                         }
11368:                     }
11369:                 }
11370:             }
11371:         }
11372:         if ($defquota eq '') {
11373:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
11374:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
11375:             } elsif ($key eq 'defaultquota') {
11376:                 $defquota = $quotahash{'quotas'}{'default'};
11377:             }
11378:             $settingstatus = 'default';
11379:             if ($defquota eq '') {
11380:                 if ($quotaname eq 'author') {
11381:                     $defquota = 500;
11382:                 }
11383:             }
11384:         }
11385:     } else {
11386:         $settingstatus = 'default';
11387:         if ($quotaname eq 'author') {
11388:             $defquota = 500;
11389:         } else {
11390:             $defquota = 20;
11391:         }
11392:     }
11393:     if (wantarray) {
11394:         return ($defquota,$settingstatus);
11395:     } else {
11396:         return $defquota;
11397:     }
11398: }
11399: 
11400: ###############################################
11401: 
11402: =pod
11403: 
11404: =item * &excess_filesize_warning()
11405: 
11406: Returns warning message if upload of file to authoring space, or copying
11407: of existing file within authoring space will cause quota for the authoring
11408: space to be exceeded.
11409: 
11410: Same, if upload of a file directly to a course/community via Course Editor
11411: will cause quota for uploaded content for the course to be exceeded.
11412: 
11413: Inputs: 7 
11414: 1. username or coursenum
11415: 2. domain
11416: 3. context ('author' or 'course')
11417: 4. filename of file for which action is being requested
11418: 5. filesize (kB) of file
11419: 6. action being taken: copy or upload.
11420: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
11421: 
11422: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
11423:          otherwise return null.
11424: 
11425: =back
11426: 
11427: =cut
11428: 
11429: sub excess_filesize_warning {
11430:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
11431:     my $current_disk_usage = 0;
11432:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
11433:     if ($context eq 'author') {
11434:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
11435:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
11436:     } else {
11437:         foreach my $subdir ('docs','supplemental') {
11438:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
11439:         }
11440:     }
11441:     $disk_quota = int($disk_quota * 1000);
11442:     if (($current_disk_usage + $filesize) > $disk_quota) {
11443:         return '<p class="LC_warning">'.
11444:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
11445:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
11446:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
11447:                             $disk_quota,$current_disk_usage).
11448:                '</p>';
11449:     }
11450:     return;
11451: }
11452: 
11453: ###############################################
11454: 
11455: 
11456: 
11457: 
11458: sub get_secgrprole_info {
11459:     my ($cdom,$cnum,$needroles,$type)  = @_;
11460:     my %sections_count = &get_sections($cdom,$cnum);
11461:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
11462:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
11463:     my @groups = sort(keys(%curr_groups));
11464:     my $allroles = [];
11465:     my $rolehash;
11466:     my $accesshash = {
11467:                      active => 'Currently has access',
11468:                      future => 'Will have future access',
11469:                      previous => 'Previously had access',
11470:                   };
11471:     if ($needroles) {
11472:         $rolehash = {'all' => 'all'};
11473:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
11474: 	if (&Apache::lonnet::error(%user_roles)) {
11475: 	    undef(%user_roles);
11476: 	}
11477:         foreach my $item (keys(%user_roles)) {
11478:             my ($role)=split(/\:/,$item,2);
11479:             if ($role eq 'cr') { next; }
11480:             if ($role =~ /^cr/) {
11481:                 $$rolehash{$role} = (split('/',$role))[3];
11482:             } else {
11483:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
11484:             }
11485:         }
11486:         foreach my $key (sort(keys(%{$rolehash}))) {
11487:             push(@{$allroles},$key);
11488:         }
11489:         push (@{$allroles},'st');
11490:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
11491:     }
11492:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
11493: }
11494: 
11495: sub user_picker {
11496:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
11497:     my $currdom = $dom;
11498:     my @alldoms = &Apache::lonnet::all_domains();
11499:     if (@alldoms == 1) {
11500:         my %domsrch = &Apache::lonnet::get_dom('configuration',
11501:                                                ['directorysrch'],$alldoms[0]);
11502:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
11503:         my $showdom = $domdesc;
11504:         if ($showdom eq '') {
11505:             $showdom = $dom;
11506:         }
11507:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
11508:             if ((!$domsrch{'directorysrch'}{'available'}) &&
11509:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
11510:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
11511:             }
11512:         }
11513:     }
11514:     my %curr_selected = (
11515:                         srchin => 'dom',
11516:                         srchby => 'lastname',
11517:                       );
11518:     my $srchterm;
11519:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
11520:         if ($srch->{'srchby'} ne '') {
11521:             $curr_selected{'srchby'} = $srch->{'srchby'};
11522:         }
11523:         if ($srch->{'srchin'} ne '') {
11524:             $curr_selected{'srchin'} = $srch->{'srchin'};
11525:         }
11526:         if ($srch->{'srchtype'} ne '') {
11527:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
11528:         }
11529:         if ($srch->{'srchdomain'} ne '') {
11530:             $currdom = $srch->{'srchdomain'};
11531:         }
11532:         $srchterm = $srch->{'srchterm'};
11533:     }
11534:     my %html_lt=&Apache::lonlocal::texthash(
11535:                     'usr'       => 'Search criteria',
11536:                     'doma'      => 'Domain/institution to search',
11537:                     'uname'     => 'username',
11538:                     'lastname'  => 'last name',
11539:                     'lastfirst' => 'last name, first name',
11540:                     'crs'       => 'in this course',
11541:                     'dom'       => 'in selected LON-CAPA domain', 
11542:                     'alc'       => 'all LON-CAPA',
11543:                     'instd'     => 'in institutional directory for selected domain',
11544:                     'exact'     => 'is',
11545:                     'contains'  => 'contains',
11546:                     'begins'    => 'begins with',
11547:                                        );
11548:     my %js_lt=&Apache::lonlocal::texthash(
11549:                     'youm'      => "You must include some text to search for.",
11550:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
11551:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
11552:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
11553:                     'ymcd'      => "You must choose a domain when using a domain search.",
11554:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
11555:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
11556:                      'thfo'     => "The following need to be corrected before the search can be run:",
11557:                                        );
11558:     &html_escape(\%html_lt);
11559:     &js_escape(\%js_lt);
11560:     my $domform;
11561:     my $allow_blank = 1;
11562:     if ($fixeddom) {
11563:         $allow_blank = 0;
11564:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
11565:     } else {
11566:         my $defdom = $env{'request.role.domain'};
11567:         my ($trusted,$untrusted);
11568:         if (($context eq 'requestcrs') || ($context eq 'course')) {
11569:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
11570:         } elsif ($context eq 'author') {
11571:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
11572:         } elsif ($context eq 'domain') {
11573:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
11574:         }
11575:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
11576:     }
11577:     my $srchinsel = ' <select name="srchin">';
11578: 
11579:     my @srchins = ('crs','dom','alc','instd');
11580: 
11581:     foreach my $option (@srchins) {
11582:         # FIXME 'alc' option unavailable until 
11583:         #       loncreateuser::print_user_query_page()
11584:         #       has been completed.
11585:         next if ($option eq 'alc');
11586:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
11587:         next if ($option eq 'crs' && !$env{'request.course.id'});
11588:         next if (($option eq 'instd') && ($noinstd));
11589:         if ($curr_selected{'srchin'} eq $option) {
11590:             $srchinsel .= ' 
11591:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
11592:         } else {
11593:             $srchinsel .= '
11594:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
11595:         }
11596:     }
11597:     $srchinsel .= "\n  </select>\n";
11598: 
11599:     my $srchbysel =  ' <select name="srchby">';
11600:     foreach my $option ('lastname','lastfirst','uname') {
11601:         if ($curr_selected{'srchby'} eq $option) {
11602:             $srchbysel .= '
11603:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
11604:         } else {
11605:             $srchbysel .= '
11606:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
11607:          }
11608:     }
11609:     $srchbysel .= "\n  </select>\n";
11610: 
11611:     my $srchtypesel = ' <select name="srchtype">';
11612:     foreach my $option ('begins','contains','exact') {
11613:         if ($curr_selected{'srchtype'} eq $option) {
11614:             $srchtypesel .= '
11615:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
11616:         } else {
11617:             $srchtypesel .= '
11618:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
11619:         }
11620:     }
11621:     $srchtypesel .= "\n  </select>\n";
11622: 
11623:     my ($newuserscript,$new_user_create);
11624:     my $context_dom = $env{'request.role.domain'};
11625:     if ($context eq 'requestcrs') {
11626:         if ($env{'form.coursedom'} ne '') { 
11627:             $context_dom = $env{'form.coursedom'};
11628:         }
11629:     }
11630:     if ($forcenewuser) {
11631:         if (ref($srch) eq 'HASH') {
11632:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
11633:                 if ($cancreate) {
11634:                     $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>';
11635:                 } else {
11636:                     my $helplink = 'javascript:helpMenu('."'display'".')';
11637:                     my %usertypetext = (
11638:                         official   => 'institutional',
11639:                         unofficial => 'non-institutional',
11640:                     );
11641:                     $new_user_create = '<p class="LC_warning">'
11642:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
11643:                                       .' '
11644:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
11645:                                           ,'<a href="'.$helplink.'">','</a>')
11646:                                       .'</p><br />';
11647:                 }
11648:             }
11649:         }
11650: 
11651:         $newuserscript = <<"ENDSCRIPT";
11652: 
11653: function setSearch(createnew,callingForm) {
11654:     if (createnew == 1) {
11655:         for (var i=0; i<callingForm.srchby.length; i++) {
11656:             if (callingForm.srchby.options[i].value == 'uname') {
11657:                 callingForm.srchby.selectedIndex = i;
11658:             }
11659:         }
11660:         for (var i=0; i<callingForm.srchin.length; i++) {
11661:             if ( callingForm.srchin.options[i].value == 'dom') {
11662: 		callingForm.srchin.selectedIndex = i;
11663:             }
11664:         }
11665:         for (var i=0; i<callingForm.srchtype.length; i++) {
11666:             if (callingForm.srchtype.options[i].value == 'exact') {
11667:                 callingForm.srchtype.selectedIndex = i;
11668:             }
11669:         }
11670:         for (var i=0; i<callingForm.srchdomain.length; i++) {
11671:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
11672:                 callingForm.srchdomain.selectedIndex = i;
11673:             }
11674:         }
11675:     }
11676: }
11677: ENDSCRIPT
11678: 
11679:     }
11680: 
11681:     my $output = <<"END_BLOCK";
11682: <script type="text/javascript">
11683: // <![CDATA[
11684: function validateEntry(callingForm) {
11685: 
11686:     var checkok = 1;
11687:     var srchin;
11688:     for (var i=0; i<callingForm.srchin.length; i++) {
11689: 	if ( callingForm.srchin[i].checked ) {
11690: 	    srchin = callingForm.srchin[i].value;
11691: 	}
11692:     }
11693: 
11694:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
11695:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
11696:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
11697:     var srchterm =  callingForm.srchterm.value;
11698:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
11699:     var msg = "";
11700: 
11701:     if (srchterm == "") {
11702:         checkok = 0;
11703:         msg += "$js_lt{'youm'}\\n";
11704:     }
11705: 
11706:     if (srchtype== 'begins') {
11707:         if (srchterm.length < 2) {
11708:             checkok = 0;
11709:             msg += "$js_lt{'thte'}\\n";
11710:         }
11711:     }
11712: 
11713:     if (srchtype== 'contains') {
11714:         if (srchterm.length < 3) {
11715:             checkok = 0;
11716:             msg += "$js_lt{'thet'}\\n";
11717:         }
11718:     }
11719:     if (srchin == 'instd') {
11720:         if (srchdomain == '') {
11721:             checkok = 0;
11722:             msg += "$js_lt{'yomc'}\\n";
11723:         }
11724:     }
11725:     if (srchin == 'dom') {
11726:         if (srchdomain == '') {
11727:             checkok = 0;
11728:             msg += "$js_lt{'ymcd'}\\n";
11729:         }
11730:     }
11731:     if (srchby == 'lastfirst') {
11732:         if (srchterm.indexOf(",") == -1) {
11733:             checkok = 0;
11734:             msg += "$js_lt{'whus'}\\n";
11735:         }
11736:         if (srchterm.indexOf(",") == srchterm.length -1) {
11737:             checkok = 0;
11738:             msg += "$js_lt{'whse'}\\n";
11739:         }
11740:     }
11741:     if (checkok == 0) {
11742:         alert("$js_lt{'thfo'}\\n"+msg);
11743:         return;
11744:     }
11745:     if (checkok == 1) {
11746:         callingForm.submit();
11747:     }
11748: }
11749: 
11750: $newuserscript
11751: 
11752: // ]]>
11753: </script>
11754: 
11755: $new_user_create
11756: 
11757: END_BLOCK
11758: 
11759:     $output .= &Apache::lonhtmlcommon::start_pick_box().
11760:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
11761:                $domform.
11762:                &Apache::lonhtmlcommon::row_closure().
11763:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
11764:                $srchbysel.
11765:                $srchtypesel. 
11766:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
11767:                $srchinsel.
11768:                &Apache::lonhtmlcommon::row_closure(1). 
11769:                &Apache::lonhtmlcommon::end_pick_box().
11770:                '<br />';
11771:     return ($output,1);
11772: }
11773: 
11774: sub user_rule_check {
11775:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
11776:     my ($response,%inst_response);
11777:     if (ref($usershash) eq 'HASH') {
11778:         if (keys(%{$usershash}) > 1) {
11779:             my (%by_username,%by_id,%userdoms);
11780:             my $checkid; 
11781:             if (ref($checks) eq 'HASH') {
11782:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
11783:                     $checkid = 1;
11784:                 }
11785:             }
11786:             foreach my $user (keys(%{$usershash})) {
11787:                 my ($uname,$udom) = split(/:/,$user);
11788:                 if ($checkid) {
11789:                     if (ref($usershash->{$user}) eq 'HASH') {
11790:                         if ($usershash->{$user}->{'id'} ne '') {
11791:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
11792:                             $userdoms{$udom} = 1;
11793:                             if (ref($inst_results) eq 'HASH') {
11794:                                 $inst_results->{$uname.':'.$udom} = {};
11795:                             }
11796:                         }
11797:                     }
11798:                 } else {
11799:                     $by_username{$udom}{$uname} = 1;
11800:                     $userdoms{$udom} = 1;
11801:                     if (ref($inst_results) eq 'HASH') {
11802:                         $inst_results->{$uname.':'.$udom} = {};
11803:                     }
11804:                 }
11805:             }
11806:             foreach my $udom (keys(%userdoms)) {
11807:                 if (!$got_rules->{$udom}) {
11808:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
11809:                                                              ['usercreation'],$udom);
11810:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
11811:                         foreach my $item ('username','id') {
11812:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
11813:                                 $$curr_rules{$udom}{$item} =
11814:                                     $domconfig{'usercreation'}{$item.'_rule'};
11815:                             }
11816:                         }
11817:                     }
11818:                     $got_rules->{$udom} = 1;
11819:                 }
11820:             }
11821:             if ($checkid) {
11822:                 foreach my $udom (keys(%by_id)) {
11823:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
11824:                     if ($outcome eq 'ok') {
11825:                         foreach my $id (keys(%{$by_id{$udom}})) {
11826:                             my $uname = $by_id{$udom}{$id};
11827:                             $inst_response{$uname.':'.$udom} = $outcome;
11828:                         }
11829:                         if (ref($results) eq 'HASH') {
11830:                             foreach my $uname (keys(%{$results})) {
11831:                                 if (exists($inst_response{$uname.':'.$udom})) {
11832:                                     $inst_response{$uname.':'.$udom} = $outcome;
11833:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
11834:                                 }
11835:                             }
11836:                         }
11837:                     }
11838:                 }
11839:             } else {
11840:                 foreach my $udom (keys(%by_username)) {
11841:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
11842:                     if ($outcome eq 'ok') {
11843:                         foreach my $uname (keys(%{$by_username{$udom}})) {
11844:                             $inst_response{$uname.':'.$udom} = $outcome;
11845:                         }
11846:                         if (ref($results) eq 'HASH') {
11847:                             foreach my $uname (keys(%{$results})) {
11848:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
11849:                             }
11850:                         }
11851:                     }
11852:                 }
11853:             }
11854:         } elsif (keys(%{$usershash}) == 1) {
11855:             my $user = (keys(%{$usershash}))[0];
11856:             my ($uname,$udom) = split(/:/,$user);
11857:             if (($udom ne '') && ($uname ne '')) {
11858:                 if (ref($usershash->{$user}) eq 'HASH') {
11859:                     if (ref($checks) eq 'HASH') {
11860:                         if (defined($checks->{'username'})) {
11861:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
11862:                                 &Apache::lonnet::get_instuser($udom,$uname);
11863:                         } elsif (defined($checks->{'id'})) {
11864:                             if ($usershash->{$user}->{'id'} ne '') {
11865:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
11866:                                     &Apache::lonnet::get_instuser($udom,undef,
11867:                                                                   $usershash->{$user}->{'id'});
11868:                             } else {
11869:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
11870:                                     &Apache::lonnet::get_instuser($udom,$uname);
11871:                             }
11872:                         }
11873:                     } else {
11874:                        ($inst_response{$user},%{$inst_results->{$user}}) =
11875:                             &Apache::lonnet::get_instuser($udom,$uname);
11876:                        return;
11877:                     }
11878:                     if (!$got_rules->{$udom}) {
11879:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
11880:                                                                  ['usercreation'],$udom);
11881:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
11882:                             foreach my $item ('username','id') {
11883:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
11884:                                    $$curr_rules{$udom}{$item} = 
11885:                                        $domconfig{'usercreation'}{$item.'_rule'};
11886:                                 }
11887:                             }
11888:                         }
11889:                         $got_rules->{$udom} = 1;
11890:                     }
11891:                 }
11892:             } else {
11893:                 return;
11894:             }
11895:         } else {
11896:             return;
11897:         }
11898:         foreach my $user (keys(%{$usershash})) {
11899:             my ($uname,$udom) = split(/:/,$user);
11900:             next if (($udom eq '') || ($uname eq ''));
11901:             my $id;
11902:             if (ref($inst_results) eq 'HASH') {
11903:                 if (ref($inst_results->{$user}) eq 'HASH') {
11904:                     $id = $inst_results->{$user}->{'id'};
11905:                 }
11906:             }
11907:             if ($id eq '') { 
11908:                 if (ref($usershash->{$user})) {
11909:                     $id = $usershash->{$user}->{'id'};
11910:                 }
11911:             }
11912:             foreach my $item (keys(%{$checks})) {
11913:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
11914:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
11915:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
11916:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
11917:                                                                              $$curr_rules{$udom}{$item});
11918:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
11919:                                 if ($rule_check{$rule}) {
11920:                                     $$rulematch{$user}{$item} = $rule;
11921:                                     if ($inst_response{$user} eq 'ok') {
11922:                                         if (ref($inst_results) eq 'HASH') {
11923:                                             if (ref($inst_results->{$user}) eq 'HASH') {
11924:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
11925:                                                     $$alerts{$item}{$udom}{$uname} = 1;
11926:                                                 } elsif ($item eq 'id') {
11927:                                                     if ($inst_results->{$user}->{'id'} eq '') {
11928:                                                         $$alerts{$item}{$udom}{$uname} = 1;
11929:                                                     }
11930:                                                 }
11931:                                             }
11932:                                         }
11933:                                     }
11934:                                     last;
11935:                                 }
11936:                             }
11937:                         }
11938:                     }
11939:                 }
11940:             }
11941:         }
11942:     }
11943:     return;
11944: }
11945: 
11946: sub user_rule_formats {
11947:     my ($domain,$domdesc,$curr_rules,$check) = @_;
11948:     my %text = ( 
11949:                  'username' => 'Usernames',
11950:                  'id'       => 'IDs',
11951:                );
11952:     my $output;
11953:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
11954:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
11955:         if (@{$ruleorder} > 0) {
11956:             $output = '<br />'.
11957:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
11958:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
11959:                       ' <ul>';
11960:             foreach my $rule (@{$ruleorder}) {
11961:                 if (ref($curr_rules) eq 'ARRAY') {
11962:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
11963:                         if (ref($rules->{$rule}) eq 'HASH') {
11964:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
11965:                                         $rules->{$rule}{'desc'}.'</li>';
11966:                         }
11967:                     }
11968:                 }
11969:             }
11970:             $output .= '</ul>';
11971:         }
11972:     }
11973:     return $output;
11974: }
11975: 
11976: sub instrule_disallow_msg {
11977:     my ($checkitem,$domdesc,$count,$mode) = @_;
11978:     my $response;
11979:     my %text = (
11980:                   item   => 'username',
11981:                   items  => 'usernames',
11982:                   match  => 'matches',
11983:                   do     => 'does',
11984:                   action => 'a username',
11985:                   one    => 'one',
11986:                );
11987:     if ($count > 1) {
11988:         $text{'item'} = 'usernames';
11989:         $text{'match'} ='match';
11990:         $text{'do'} = 'do';
11991:         $text{'action'} = 'usernames',
11992:         $text{'one'} = 'ones';
11993:     }
11994:     if ($checkitem eq 'id') {
11995:         $text{'items'} = 'IDs';
11996:         $text{'item'} = 'ID';
11997:         $text{'action'} = 'an ID';
11998:         if ($count > 1) {
11999:             $text{'item'} = 'IDs';
12000:             $text{'action'} = 'IDs';
12001:         }
12002:     }
12003:     $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 />';
12004:     if ($mode eq 'upload') {
12005:         if ($checkitem eq 'username') {
12006:             $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'}.");
12007:         } elsif ($checkitem eq 'id') {
12008:             $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.");
12009:         }
12010:     } elsif ($mode eq 'selfcreate') {
12011:         if ($checkitem eq 'id') {
12012:             $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.");
12013:         }
12014:     } else {
12015:         if ($checkitem eq 'username') {
12016:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
12017:         } elsif ($checkitem eq 'id') {
12018:             $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.");
12019:         }
12020:     }
12021:     return $response;
12022: }
12023: 
12024: sub personal_data_fieldtitles {
12025:     my %fieldtitles = &Apache::lonlocal::texthash (
12026:                         id => 'Student/Employee ID',
12027:                         permanentemail => 'E-mail address',
12028:                         lastname => 'Last Name',
12029:                         firstname => 'First Name',
12030:                         middlename => 'Middle Name',
12031:                         generation => 'Generation',
12032:                         gen => 'Generation',
12033:                         inststatus => 'Affiliation',
12034:                    );
12035:     return %fieldtitles;
12036: }
12037: 
12038: sub sorted_inst_types {
12039:     my ($dom) = @_;
12040:     my ($usertypes,$order);
12041:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
12042:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
12043:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
12044:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
12045:     } else {
12046:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
12047:     }
12048:     my $othertitle = &mt('All users');
12049:     if ($env{'request.course.id'}) {
12050:         $othertitle  = &mt('Any users');
12051:     }
12052:     my @types;
12053:     if (ref($order) eq 'ARRAY') {
12054:         @types = @{$order};
12055:     }
12056:     if (@types == 0) {
12057:         if (ref($usertypes) eq 'HASH') {
12058:             @types = sort(keys(%{$usertypes}));
12059:         }
12060:     }
12061:     if (keys(%{$usertypes}) > 0) {
12062:         $othertitle = &mt('Other users');
12063:     }
12064:     return ($othertitle,$usertypes,\@types);
12065: }
12066: 
12067: sub get_institutional_codes {
12068:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
12069: # Get complete list of course sections to update
12070:     my @currsections = ();
12071:     my @currxlists = ();
12072:     my (%unclutteredsec,%unclutteredlcsec);
12073:     my $coursecode = $$settings{'internal.coursecode'};
12074:     my $crskey = $crs.':'.$coursecode;
12075:     @{$unclutteredsec{$crskey}} = ();
12076:     @{$unclutteredlcsec{$crskey}} = ();
12077: 
12078:     if ($$settings{'internal.sectionnums'} ne '') {
12079:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
12080:     }
12081: 
12082:     if ($$settings{'internal.crosslistings'} ne '') {
12083:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
12084:     }
12085: 
12086:     if (@currxlists > 0) {
12087:         foreach my $xl (@currxlists) {
12088:             if ($xl =~ /^([^:]+):(\w*)$/) {
12089:                 unless (grep/^$1$/,@{$allcourses}) {
12090:                     push(@{$allcourses},$1);
12091:                     $$LC_code{$1} = $2;
12092:                 }
12093:             }
12094:         }
12095:     }
12096: 
12097:     if (@currsections > 0) {
12098:         foreach my $sec (@currsections) {
12099:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
12100:                 my $instsec = $1;
12101:                 my $lc_sec = $2;
12102:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
12103:                     push(@{$unclutteredsec{$crskey}},$instsec);
12104:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
12105:                 }
12106:             }
12107:         }
12108:     }
12109: 
12110:     if (@{$unclutteredsec{$crskey}} > 0) {
12111:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
12112:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
12113:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
12114:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
12115:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
12116:                     push(@{$allcourses},$sec);
12117:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
12118:                 }
12119:             }
12120:         }
12121:     }
12122:     return;
12123: }
12124: 
12125: sub get_standard_codeitems {
12126:     return ('Year','Semester','Department','Number','Section');
12127: }
12128: 
12129: =pod
12130: 
12131: =head1 Slot Helpers
12132: 
12133: =over 4
12134: 
12135: =item * sorted_slots()
12136: 
12137: Sorts an array of slot names in order of an optional sort key,
12138: default sort is by slot start time (earliest first). 
12139: 
12140: Inputs:
12141: 
12142: =over 4
12143: 
12144: slotsarr  - Reference to array of unsorted slot names.
12145: 
12146: slots     - Reference to hash of hash, where outer hash keys are slot names.
12147: 
12148: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
12149: 
12150: =back
12151: 
12152: Returns:
12153: 
12154: =over 4
12155: 
12156: sorted   - An array of slot names sorted by a specified sort key 
12157:            (default sort key is start time of the slot).
12158: 
12159: =back
12160: 
12161: =cut
12162: 
12163: 
12164: sub sorted_slots {
12165:     my ($slotsarr,$slots,$sortkey) = @_;
12166:     if ($sortkey eq '') {
12167:         $sortkey = 'starttime';
12168:     }
12169:     my @sorted;
12170:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
12171:         @sorted =
12172:             sort {
12173:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
12174:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
12175:                      }
12176:                      if (ref($slots->{$a})) { return -1;}
12177:                      if (ref($slots->{$b})) { return 1;}
12178:                      return 0;
12179:                  } @{$slotsarr};
12180:     }
12181:     return @sorted;
12182: }
12183: 
12184: =pod
12185: 
12186: =item * get_future_slots()
12187: 
12188: Inputs:
12189: 
12190: =over 4
12191: 
12192: cnum - course number
12193: 
12194: cdom - course domain
12195: 
12196: now - current UNIX time
12197: 
12198: symb - optional symb
12199: 
12200: =back
12201: 
12202: Returns:
12203: 
12204: =over 4
12205: 
12206: sorted_reservable - ref to array of student_schedulable slots currently 
12207:                     reservable, ordered by end date of reservation period.
12208: 
12209: reservable_now - ref to hash of student_schedulable slots currently
12210:                  reservable.
12211: 
12212:     Keys in inner hash are:
12213:     (a) symb: either blank or symb to which slot use is restricted.
12214:     (b) endreserve: end date of reservation period.
12215:     (c) uniqueperiod: start,end dates when slot is to be uniquely
12216:         selected.
12217: 
12218: sorted_future - ref to array of student_schedulable slots reservable in
12219:                 the future, ordered by start date of reservation period.
12220: 
12221: future_reservable - ref to hash of student_schedulable slots reservable
12222:                     in the future.
12223: 
12224:     Keys in inner hash are:
12225:     (a) symb: either blank or symb to which slot use is restricted.
12226:     (b) startreserve: start date of reservation period.
12227:     (c) uniqueperiod: start,end dates when slot is to be uniquely
12228:         selected.
12229: 
12230: =back
12231: 
12232: =cut
12233: 
12234: sub get_future_slots {
12235:     my ($cnum,$cdom,$now,$symb) = @_;
12236:     my $map;
12237:     if ($symb) {
12238:         ($map) = &Apache::lonnet::decode_symb($symb);
12239:     }
12240:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
12241:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
12242:     foreach my $slot (keys(%slots)) {
12243:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
12244:         if ($symb) {
12245:             if ($slots{$slot}->{'symb'} ne '') {
12246:                 my $canuse;
12247:                 my %oksymbs;
12248:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
12249:                 map { $oksymbs{$_} = 1; } @slotsymbs;
12250:                 if ($oksymbs{$symb}) {
12251:                     $canuse = 1;
12252:                 } else {
12253:                     foreach my $item (@slotsymbs) {
12254:                         if ($item =~ /\.(page|sequence)$/) {
12255:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
12256:                             if (($map ne '') && ($map eq $sloturl)) {
12257:                                 $canuse = 1;
12258:                                 last;
12259:                             }
12260:                         }
12261:                     }
12262:                 }
12263:                 next unless ($canuse);
12264:             }
12265:         }
12266:         if (($slots{$slot}->{'starttime'} > $now) &&
12267:             ($slots{$slot}->{'endtime'} > $now)) {
12268:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
12269:                 my $userallowed = 0;
12270:                 if ($slots{$slot}->{'allowedsections'}) {
12271:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
12272:                     if (!defined($env{'request.role.sec'})
12273:                         && grep(/^No section assigned$/,@allowed_sec)) {
12274:                         $userallowed=1;
12275:                     } else {
12276:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
12277:                             $userallowed=1;
12278:                         }
12279:                     }
12280:                     unless ($userallowed) {
12281:                         if (defined($env{'request.course.groups'})) {
12282:                             my @groups = split(/:/,$env{'request.course.groups'});
12283:                             foreach my $group (@groups) {
12284:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
12285:                                     $userallowed=1;
12286:                                     last;
12287:                                 }
12288:                             }
12289:                         }
12290:                     }
12291:                 }
12292:                 if ($slots{$slot}->{'allowedusers'}) {
12293:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
12294:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
12295:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
12296:                         $userallowed = 1;
12297:                     }
12298:                 }
12299:                 next unless($userallowed);
12300:             }
12301:             my $startreserve = $slots{$slot}->{'startreserve'};
12302:             my $endreserve = $slots{$slot}->{'endreserve'};
12303:             my $symb = $slots{$slot}->{'symb'};
12304:             my $uniqueperiod;
12305:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
12306:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
12307:             }
12308:             if (($startreserve < $now) &&
12309:                 (!$endreserve || $endreserve > $now)) {
12310:                 my $lastres = $endreserve;
12311:                 if (!$lastres) {
12312:                     $lastres = $slots{$slot}->{'starttime'};
12313:                 }
12314:                 $reservable_now{$slot} = {
12315:                                            symb       => $symb,
12316:                                            endreserve => $lastres,
12317:                                            uniqueperiod => $uniqueperiod,
12318:                                          };
12319:             } elsif (($startreserve > $now) &&
12320:                      (!$endreserve || $endreserve > $startreserve)) {
12321:                 $future_reservable{$slot} = {
12322:                                               symb         => $symb,
12323:                                               startreserve => $startreserve,
12324:                                               uniqueperiod => $uniqueperiod,
12325:                                             };
12326:             }
12327:         }
12328:     }
12329:     my @unsorted_reservable = keys(%reservable_now);
12330:     if (@unsorted_reservable > 0) {
12331:         @sorted_reservable = 
12332:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
12333:     }
12334:     my @unsorted_future = keys(%future_reservable);
12335:     if (@unsorted_future > 0) {
12336:         @sorted_future =
12337:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
12338:     }
12339:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
12340: }
12341: 
12342: =pod
12343: 
12344: =back
12345: 
12346: =head1 HTTP Helpers
12347: 
12348: =over 4
12349: 
12350: =item * &get_unprocessed_cgi($query,$possible_names)
12351: 
12352: Modify the %env hash to contain unprocessed CGI form parameters held in
12353: $query.  The parameters listed in $possible_names (an array reference),
12354: will be set in $env{'form.name'} if they do not already exist.
12355: 
12356: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
12357: $possible_names is an ref to an array of form element names.  As an example:
12358: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
12359: will result in $env{'form.uname'} and $env{'form.udom'} being set.
12360: 
12361: =cut
12362: 
12363: sub get_unprocessed_cgi {
12364:   my ($query,$possible_names)= @_;
12365:   # $Apache::lonxml::debug=1;
12366:   foreach my $pair (split(/&/,$query)) {
12367:     my ($name, $value) = split(/=/,$pair);
12368:     $name = &unescape($name);
12369:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
12370:       $value =~ tr/+/ /;
12371:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
12372:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
12373:     }
12374:   }
12375: }
12376: 
12377: =pod
12378: 
12379: =item * &cacheheader() 
12380: 
12381: returns cache-controlling header code
12382: 
12383: =cut
12384: 
12385: sub cacheheader {
12386:     unless ($env{'request.method'} eq 'GET') { return ''; }
12387:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
12388:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
12389:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
12390:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
12391:     return $output;
12392: }
12393: 
12394: =pod
12395: 
12396: =item * &no_cache($r) 
12397: 
12398: specifies header code to not have cache
12399: 
12400: =cut
12401: 
12402: sub no_cache {
12403:     my ($r) = @_;
12404:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
12405: 	$env{'request.method'} ne 'GET') { return ''; }
12406:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
12407:     $r->no_cache(1);
12408:     $r->header_out("Expires" => $date);
12409:     $r->header_out("Pragma" => "no-cache");
12410: }
12411: 
12412: sub content_type {
12413:     my ($r,$type,$charset) = @_;
12414:     if ($r) {
12415: 	#  Note that printout.pl calls this with undef for $r.
12416: 	&no_cache($r);
12417:     }
12418:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
12419:     unless ($charset) {
12420: 	$charset=&Apache::lonlocal::current_encoding;
12421:     }
12422:     if ($charset) { $type.='; charset='.$charset; }
12423:     if ($r) {
12424: 	$r->content_type($type);
12425:     } else {
12426: 	print("Content-type: $type\n\n");
12427:     }
12428: }
12429: 
12430: =pod
12431: 
12432: =item * &add_to_env($name,$value) 
12433: 
12434: adds $name to the %env hash with value
12435: $value, if $name already exists, the entry is converted to an array
12436: reference and $value is added to the array.
12437: 
12438: =cut
12439: 
12440: sub add_to_env {
12441:   my ($name,$value)=@_;
12442:   if (defined($env{$name})) {
12443:     if (ref($env{$name})) {
12444:       #already have multiple values
12445:       push(@{ $env{$name} },$value);
12446:     } else {
12447:       #first time seeing multiple values, convert hash entry to an arrayref
12448:       my $first=$env{$name};
12449:       undef($env{$name});
12450:       push(@{ $env{$name} },$first,$value);
12451:     }
12452:   } else {
12453:     $env{$name}=$value;
12454:   }
12455: }
12456: 
12457: =pod
12458: 
12459: =item * &get_env_multiple($name) 
12460: 
12461: gets $name from the %env hash, it seemlessly handles the cases where multiple
12462: values may be defined and end up as an array ref.
12463: 
12464: returns an array of values
12465: 
12466: =cut
12467: 
12468: sub get_env_multiple {
12469:     my ($name) = @_;
12470:     my @values;
12471:     if (defined($env{$name})) {
12472:         # exists is it an array
12473:         if (ref($env{$name})) {
12474:             @values=@{ $env{$name} };
12475:         } else {
12476:             $values[0]=$env{$name};
12477:         }
12478:     }
12479:     return(@values);
12480: }
12481: 
12482: # Looks at given dependencies, and returns something depending on the context.
12483: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
12484: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
12485: # For all other contexts, returns ($output, $counter, $numpathchg).
12486: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
12487: # $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.
12488: # $numpathchg: integer with the number of cleaned up dependency paths.
12489: # \%existing: hash reference clean path -> 1 only for existing dependencies.
12490: # \%mapping: hash reference clean path -> original path for all dependencies.
12491: # @param {string} actionurl - The path to the handler, indicative of the context.
12492: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
12493: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
12494: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
12495: # @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)
12496: # @return {Array} - array depending on the context (not a reference)
12497: sub ask_for_embedded_content {
12498:     # NOTE: documentation was added afterwards, it could be wrong
12499:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
12500:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
12501:         %currsubfile,%unused,$rem);
12502:     my $counter = 0;
12503:     my $numnew = 0;
12504:     my $numremref = 0;
12505:     my $numinvalid = 0;
12506:     my $numpathchg = 0;
12507:     my $numexisting = 0;
12508:     my $numunused = 0;
12509:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
12510:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
12511:     my $heading = &mt('Upload embedded files');
12512:     my $buttontext = &mt('Upload');
12513: 
12514:     # fills these variables based on the context:
12515:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
12516:     # $path, $fileloc, $title, $rem, $filename
12517:     if ($env{'request.course.id'}) {
12518:         if ($actionurl eq '/adm/dependencies') {
12519:             $navmap = Apache::lonnavmaps::navmap->new();
12520:         }
12521:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12522:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12523:     }
12524:     if (($actionurl eq '/adm/portfolio') || 
12525:         ($actionurl eq '/adm/coursegrp_portfolio')) {
12526:         my $current_path='/';
12527:         if ($env{'form.currentpath'}) {
12528:             $current_path = $env{'form.currentpath'};
12529:         }
12530:         if ($actionurl eq '/adm/coursegrp_portfolio') {
12531:             $udom = $cdom;
12532:             $uname = $cnum;
12533:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
12534:         } else {
12535:             $udom = $env{'user.domain'};
12536:             $uname = $env{'user.name'};
12537:             $url = '/userfiles/portfolio';
12538:         }
12539:         $toplevel = $url.'/';
12540:         $url .= $current_path;
12541:         $getpropath = 1;
12542:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
12543:              ($actionurl eq '/adm/imsimport')) { 
12544:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
12545:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
12546:         $toplevel = $url;
12547:         if ($rest ne '') {
12548:             $url .= $rest;
12549:         }
12550:     } elsif ($actionurl eq '/adm/coursedocs') {
12551:         if (ref($args) eq 'HASH') {
12552:             $url = $args->{'docs_url'};
12553:             $toplevel = $url;
12554:             if ($args->{'context'} eq 'paste') {
12555:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
12556:                 ($path) = 
12557:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
12558:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
12559:                 $fileloc =~ s{^/}{};
12560:             }
12561:         }
12562:     } elsif ($actionurl eq '/adm/dependencies')  {
12563:         if ($env{'request.course.id'} ne '') {
12564:             if (ref($args) eq 'HASH') {
12565:                 $url = $args->{'docs_url'};
12566:                 $title = $args->{'docs_title'};
12567:                 $toplevel = $url; 
12568:                 unless ($toplevel =~ m{^/}) {
12569:                     $toplevel = "/$url";
12570:                 }
12571:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
12572:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
12573:                     $path = $1;
12574:                 } else {
12575:                     ($path) =
12576:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
12577:                 }
12578:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
12579:                     $fileloc = $toplevel;
12580:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
12581:                     my ($udom,$uname,$fname) =
12582:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
12583:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
12584:                 } else {
12585:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
12586:                 }
12587:                 $fileloc =~ s{^/}{};
12588:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
12589:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
12590:             }
12591:         }
12592:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
12593:         $udom = $cdom;
12594:         $uname = $cnum;
12595:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
12596:         $toplevel = $url;
12597:         $path = $url;
12598:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
12599:         $fileloc =~ s{^/}{};
12600:     }
12601:     
12602:     # parses the dependency paths to get some info
12603:     # fills $newfiles, $mapping, $subdependencies, $dependencies
12604:     # $newfiles: hash URL -> 1 for new files or external URLs
12605:     # (will be completed later)
12606:     # $mapping:
12607:     #   for external URLs: external URL -> external URL
12608:     #   for relative paths: clean path -> original path
12609:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
12610:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
12611:     foreach my $file (keys(%{$allfiles})) {
12612:         my $embed_file;
12613:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
12614:             $embed_file = $1;
12615:         } else {
12616:             $embed_file = $file;
12617:         }
12618:         my ($absolutepath,$cleaned_file);
12619:         if ($embed_file =~ m{^\w+://}) {
12620:             $cleaned_file = $embed_file;
12621:             $newfiles{$cleaned_file} = 1;
12622:             $mapping{$cleaned_file} = $embed_file;
12623:         } else {
12624:             $cleaned_file = &clean_path($embed_file);
12625:             if ($embed_file =~ m{^/}) {
12626:                 $absolutepath = $embed_file;
12627:             }
12628:             if ($cleaned_file =~ m{/}) {
12629:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
12630:                 $path = &check_for_traversal($path,$url,$toplevel);
12631:                 my $item = $fname;
12632:                 if ($path ne '') {
12633:                     $item = $path.'/'.$fname;
12634:                     $subdependencies{$path}{$fname} = 1;
12635:                 } else {
12636:                     $dependencies{$item} = 1;
12637:                 }
12638:                 if ($absolutepath) {
12639:                     $mapping{$item} = $absolutepath;
12640:                 } else {
12641:                     $mapping{$item} = $embed_file;
12642:                 }
12643:             } else {
12644:                 $dependencies{$embed_file} = 1;
12645:                 if ($absolutepath) {
12646:                     $mapping{$cleaned_file} = $absolutepath;
12647:                 } else {
12648:                     $mapping{$cleaned_file} = $embed_file;
12649:                 }
12650:             }
12651:         }
12652:     }
12653:     
12654:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
12655:     # and lists
12656:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
12657:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
12658:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
12659:     #                                    the path had to be cleaned up
12660:     # $existing: hash clean path -> 1 if the file exists
12661:     # $numexisting: number of keys in $existing
12662:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
12663:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
12664:     #                                      dependency subdirectories that are
12665:     #                                      not listed as dependencies, with some exceptions using $rem
12666:     my $dirptr = 16384;
12667:     foreach my $path (keys(%subdependencies)) {
12668:         $currsubfile{$path} = {};
12669:         if (($actionurl eq '/adm/portfolio') || 
12670:             ($actionurl eq '/adm/coursegrp_portfolio')) {
12671:             my ($sublistref,$listerror) =
12672:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
12673:             if (ref($sublistref) eq 'ARRAY') {
12674:                 foreach my $line (@{$sublistref}) {
12675:                     my ($file_name,$rest) = split(/\&/,$line,2);
12676:                     $currsubfile{$path}{$file_name} = 1;
12677:                 }
12678:             }
12679:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12680:             if (opendir(my $dir,$url.'/'.$path)) {
12681:                 my @subdir_list = grep(!/^\./,readdir($dir));
12682:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
12683:             }
12684:         } elsif (($actionurl eq '/adm/dependencies') ||
12685:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
12686:                   ($args->{'context'} eq 'paste')) ||
12687:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
12688:             if ($env{'request.course.id'} ne '') {
12689:                 my $dir;
12690:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
12691:                     $dir = $fileloc;
12692:                 } else {
12693:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
12694:                 }
12695:                 if ($dir ne '') {
12696:                     my ($sublistref,$listerror) =
12697:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
12698:                     if (ref($sublistref) eq 'ARRAY') {
12699:                         foreach my $line (@{$sublistref}) {
12700:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
12701:                                 undef,$mtime)=split(/\&/,$line,12);
12702:                             unless (($testdir&$dirptr) ||
12703:                                     ($file_name =~ /^\.\.?$/)) {
12704:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
12705:                             }
12706:                         }
12707:                     }
12708:                 }
12709:             }
12710:         }
12711:         foreach my $file (keys(%{$subdependencies{$path}})) {
12712:             if (exists($currsubfile{$path}{$file})) {
12713:                 my $item = $path.'/'.$file;
12714:                 unless ($mapping{$item} eq $item) {
12715:                     $pathchanges{$item} = 1;
12716:                 }
12717:                 $existing{$item} = 1;
12718:                 $numexisting ++;
12719:             } else {
12720:                 $newfiles{$path.'/'.$file} = 1;
12721:             }
12722:         }
12723:         if ($actionurl eq '/adm/dependencies') {
12724:             foreach my $path (keys(%currsubfile)) {
12725:                 if (ref($currsubfile{$path}) eq 'HASH') {
12726:                     foreach my $file (keys(%{$currsubfile{$path}})) {
12727:                          unless ($subdependencies{$path}{$file}) {
12728:                              next if (($rem ne '') &&
12729:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
12730:                                        (ref($navmap) &&
12731:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
12732:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
12733:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
12734:                              $unused{$path.'/'.$file} = 1; 
12735:                          }
12736:                     }
12737:                 }
12738:             }
12739:         }
12740:     }
12741:     
12742:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
12743:     # for files in $url or $fileloc (target directory) in some contexts
12744:     my %currfile;
12745:     if (($actionurl eq '/adm/portfolio') ||
12746:         ($actionurl eq '/adm/coursegrp_portfolio')) {
12747:         my ($dirlistref,$listerror) =
12748:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
12749:         if (ref($dirlistref) eq 'ARRAY') {
12750:             foreach my $line (@{$dirlistref}) {
12751:                 my ($file_name,$rest) = split(/\&/,$line,2);
12752:                 $currfile{$file_name} = 1;
12753:             }
12754:         }
12755:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12756:         if (opendir(my $dir,$url)) {
12757:             my @dir_list = grep(!/^\./,readdir($dir));
12758:             map {$currfile{$_} = 1;} @dir_list;
12759:         }
12760:     } elsif (($actionurl eq '/adm/dependencies') ||
12761:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
12762:               ($args->{'context'} eq 'paste')) ||
12763:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
12764:         if ($env{'request.course.id'} ne '') {
12765:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
12766:             if ($dir ne '') {
12767:                 my ($dirlistref,$listerror) =
12768:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
12769:                 if (ref($dirlistref) eq 'ARRAY') {
12770:                     foreach my $line (@{$dirlistref}) {
12771:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
12772:                             $size,undef,$mtime)=split(/\&/,$line,12);
12773:                         unless (($testdir&$dirptr) ||
12774:                                 ($file_name =~ /^\.\.?$/)) {
12775:                             $currfile{$file_name} = [$size,$mtime];
12776:                         }
12777:                     }
12778:                 }
12779:             }
12780:         }
12781:     }
12782:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
12783:     # are not in subdirectories, using $currfile
12784:     foreach my $file (keys(%dependencies)) {
12785:         if (exists($currfile{$file})) {
12786:             unless ($mapping{$file} eq $file) {
12787:                 $pathchanges{$file} = 1;
12788:             }
12789:             $existing{$file} = 1;
12790:             $numexisting ++;
12791:         } else {
12792:             $newfiles{$file} = 1;
12793:         }
12794:     }
12795:     foreach my $file (keys(%currfile)) {
12796:         unless (($file eq $filename) ||
12797:                 ($file eq $filename.'.bak') ||
12798:                 ($dependencies{$file})) {
12799:             if ($actionurl eq '/adm/dependencies') {
12800:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
12801:                     next if (($rem ne '') &&
12802:                              (($env{"httpref.$rem".$file} ne '') ||
12803:                               (ref($navmap) &&
12804:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
12805:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
12806:                                 ($navmap->getResourceByUrl($rem.$1)))))));
12807:                 }
12808:             }
12809:             $unused{$file} = 1;
12810:         }
12811:     }
12812:     
12813:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
12814:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
12815:         ($args->{'context'} eq 'paste')) {
12816:         $counter = scalar(keys(%existing));
12817:         $numpathchg = scalar(keys(%pathchanges));
12818:         return ($output,$counter,$numpathchg,\%existing);
12819:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
12820:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
12821:         $counter = scalar(keys(%existing));
12822:         $numpathchg = scalar(keys(%pathchanges));
12823:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
12824:     }
12825:     
12826:     # returns HTML otherwise, with dependency results and to ask for more uploads
12827:     
12828:     # $upload_output: missing dependencies (with upload form)
12829:     # $modify_output: uploaded dependencies (in use)
12830:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
12831:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
12832:         if ($actionurl eq '/adm/dependencies') {
12833:             next if ($embed_file =~ m{^\w+://});
12834:         }
12835:         $upload_output .= &start_data_table_row().
12836:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
12837:                           '<span class="LC_filename">'.$embed_file.'</span>';
12838:         unless ($mapping{$embed_file} eq $embed_file) {
12839:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
12840:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
12841:         }
12842:         $upload_output .= '</td>';
12843:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
12844:             $upload_output.='<td align="right">'.
12845:                             '<span class="LC_info LC_fontsize_medium">'.
12846:                             &mt("URL points to web address").'</span>';
12847:             $numremref++;
12848:         } elsif ($args->{'error_on_invalid_names'}
12849:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
12850:             $upload_output.='<td align="right"><span class="LC_warning">'.
12851:                             &mt('Invalid characters').'</span>';
12852:             $numinvalid++;
12853:         } else {
12854:             $upload_output .= '<td>'.
12855:                               &embedded_file_element('upload_embedded',$counter,
12856:                                                      $embed_file,\%mapping,
12857:                                                      $allfiles,$codebase,'upload');
12858:             $counter ++;
12859:             $numnew ++;
12860:         }
12861:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
12862:     }
12863:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
12864:         if ($actionurl eq '/adm/dependencies') {
12865:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
12866:             $modify_output .= &start_data_table_row().
12867:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
12868:                               '<img src="'.&icon($embed_file).'" border="0" />'.
12869:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
12870:                               '<td>'.$size.'</td>'.
12871:                               '<td>'.$mtime.'</td>'.
12872:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
12873:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
12874:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
12875:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
12876:                               &embedded_file_element('upload_embedded',$counter,
12877:                                                      $embed_file,\%mapping,
12878:                                                      $allfiles,$codebase,'modify').
12879:                               '</div></td>'.
12880:                               &end_data_table_row()."\n";
12881:             $counter ++;
12882:         } else {
12883:             $upload_output .= &start_data_table_row().
12884:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
12885:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
12886:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
12887:                               &Apache::loncommon::end_data_table_row()."\n";
12888:         }
12889:     }
12890:     my $delidx = $counter;
12891:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
12892:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
12893:         $delete_output .= &start_data_table_row().
12894:                           '<td><img src="'.&icon($oldfile).'" />'.
12895:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
12896:                           '<td>'.$size.'</td>'.
12897:                           '<td>'.$mtime.'</td>'.
12898:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
12899:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
12900:                           &embedded_file_element('upload_embedded',$delidx,
12901:                                                  $oldfile,\%mapping,$allfiles,
12902:                                                  $codebase,'delete').'</td>'.
12903:                           &end_data_table_row()."\n"; 
12904:         $numunused ++;
12905:         $delidx ++;
12906:     }
12907:     if ($upload_output) {
12908:         $upload_output = &start_data_table().
12909:                          $upload_output.
12910:                          &end_data_table()."\n";
12911:     }
12912:     if ($modify_output) {
12913:         $modify_output = &start_data_table().
12914:                          &start_data_table_header_row().
12915:                          '<th>'.&mt('File').'</th>'.
12916:                          '<th>'.&mt('Size (KB)').'</th>'.
12917:                          '<th>'.&mt('Modified').'</th>'.
12918:                          '<th>'.&mt('Upload replacement?').'</th>'.
12919:                          &end_data_table_header_row().
12920:                          $modify_output.
12921:                          &end_data_table()."\n";
12922:     }
12923:     if ($delete_output) {
12924:         $delete_output = &start_data_table().
12925:                          &start_data_table_header_row().
12926:                          '<th>'.&mt('File').'</th>'.
12927:                          '<th>'.&mt('Size (KB)').'</th>'.
12928:                          '<th>'.&mt('Modified').'</th>'.
12929:                          '<th>'.&mt('Delete?').'</th>'.
12930:                          &end_data_table_header_row().
12931:                          $delete_output.
12932:                          &end_data_table()."\n";
12933:     }
12934:     my $applies = 0;
12935:     if ($numremref) {
12936:         $applies ++;
12937:     }
12938:     if ($numinvalid) {
12939:         $applies ++;
12940:     }
12941:     if ($numexisting) {
12942:         $applies ++;
12943:     }
12944:     if ($counter || $numunused) {
12945:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
12946:                   ' method="post" enctype="multipart/form-data">'."\n".
12947:                   $state.'<h3>'.$heading.'</h3>'; 
12948:         if ($actionurl eq '/adm/dependencies') {
12949:             if ($numnew) {
12950:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
12951:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
12952:                            $upload_output.'<br />'."\n";
12953:             }
12954:             if ($numexisting) {
12955:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
12956:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
12957:                            $modify_output.'<br />'."\n";
12958:                            $buttontext = &mt('Save changes');
12959:             }
12960:             if ($numunused) {
12961:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
12962:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
12963:                            $delete_output.'<br />'."\n";
12964:                            $buttontext = &mt('Save changes');
12965:             }
12966:         } else {
12967:             $output .= $upload_output.'<br />'."\n";
12968:         }
12969:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
12970:                    $counter.'" />'."\n";
12971:         if ($actionurl eq '/adm/dependencies') { 
12972:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
12973:                        $numnew.'" />'."\n";
12974:         } elsif ($actionurl eq '') {
12975:             $output .=  '<input type="hidden" name="phase" value="three" />';
12976:         }
12977:     } elsif ($applies) {
12978:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
12979:         if ($applies > 1) {
12980:             $output .=  
12981:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
12982:             if ($numremref) {
12983:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
12984:             }
12985:             if ($numinvalid) {
12986:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
12987:             }
12988:             if ($numexisting) {
12989:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
12990:             }
12991:             $output .= '</ul><br />';
12992:         } elsif ($numremref) {
12993:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
12994:         } elsif ($numinvalid) {
12995:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
12996:         } elsif ($numexisting) {
12997:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
12998:         }
12999:         $output .= $upload_output.'<br />';
13000:     }
13001:     my ($pathchange_output,$chgcount);
13002:     $chgcount = $counter;
13003:     if (keys(%pathchanges) > 0) {
13004:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
13005:             if ($counter) {
13006:                 $output .= &embedded_file_element('pathchange',$chgcount,
13007:                                                   $embed_file,\%mapping,
13008:                                                   $allfiles,$codebase,'change');
13009:             } else {
13010:                 $pathchange_output .= 
13011:                     &start_data_table_row().
13012:                     '<td><input type ="checkbox" name="namechange" value="'.
13013:                     $chgcount.'" checked="checked" /></td>'.
13014:                     '<td>'.$mapping{$embed_file}.'</td>'.
13015:                     '<td>'.$embed_file.
13016:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
13017:                                            \%mapping,$allfiles,$codebase,'change').
13018:                     '</td>'.&end_data_table_row();
13019:             }
13020:             $numpathchg ++;
13021:             $chgcount ++;
13022:         }
13023:     }
13024:     if (($counter) || ($numunused)) {
13025:         if ($numpathchg) {
13026:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
13027:                        $numpathchg.'" />'."\n";
13028:         }
13029:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
13030:             ($actionurl eq '/adm/imsimport')) {
13031:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
13032:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
13033:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
13034:         } elsif ($actionurl eq '/adm/dependencies') {
13035:             $output .= '<input type="hidden" name="action" value="process_changes" />';
13036:         }
13037:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
13038:     } elsif ($numpathchg) {
13039:         my %pathchange = ();
13040:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
13041:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
13042:             $output .= '<p>'.&mt('or').'</p>'; 
13043:         }
13044:     }
13045:     return ($output,$counter,$numpathchg);
13046: }
13047: 
13048: =pod
13049: 
13050: =item * clean_path($name)
13051: 
13052: Performs clean-up of directories, subdirectories and filename in an
13053: embedded object, referenced in an HTML file which is being uploaded
13054: to a course or portfolio, where 
13055: "Upload embedded images/multimedia files if HTML file" checkbox was
13056: checked.
13057: 
13058: Clean-up is similar to replacements in lonnet::clean_filename()
13059: except each / between sub-directory and next level is preserved.
13060: 
13061: =cut
13062: 
13063: sub clean_path {
13064:     my ($embed_file) = @_;
13065:     $embed_file =~s{^/+}{};
13066:     my @contents;
13067:     if ($embed_file =~ m{/}) {
13068:         @contents = split(/\//,$embed_file);
13069:     } else {
13070:         @contents = ($embed_file);
13071:     }
13072:     my $lastidx = scalar(@contents)-1;
13073:     for (my $i=0; $i<=$lastidx; $i++) { 
13074:         $contents[$i]=~s{\\}{/}g;
13075:         $contents[$i]=~s/\s+/\_/g;
13076:         $contents[$i]=~s{[^/\w\.\-]}{}g;
13077:         if ($i == $lastidx) {
13078:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
13079:         }
13080:     }
13081:     if ($lastidx > 0) {
13082:         return join('/',@contents);
13083:     } else {
13084:         return $contents[0];
13085:     }
13086: }
13087: 
13088: sub embedded_file_element {
13089:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
13090:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
13091:                    (ref($codebase) eq 'HASH'));
13092:     my $output;
13093:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
13094:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
13095:     }
13096:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
13097:                &escape($embed_file).'" />';
13098:     unless (($context eq 'upload_embedded') && 
13099:             ($mapping->{$embed_file} eq $embed_file)) {
13100:         $output .='
13101:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
13102:     }
13103:     my $attrib;
13104:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
13105:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
13106:     }
13107:     $output .=
13108:         "\n\t\t".
13109:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
13110:         $attrib.'" />';
13111:     if (exists($codebase->{$mapping->{$embed_file}})) {
13112:         $output .=
13113:             "\n\t\t".
13114:             '<input name="codebase_'.$num.'" type="hidden" value="'.
13115:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
13116:     }
13117:     return $output;
13118: }
13119: 
13120: sub get_dependency_details {
13121:     my ($currfile,$currsubfile,$embed_file) = @_;
13122:     my ($size,$mtime,$showsize,$showmtime);
13123:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
13124:         if ($embed_file =~ m{/}) {
13125:             my ($path,$fname) = split(/\//,$embed_file);
13126:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
13127:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
13128:             }
13129:         } else {
13130:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
13131:                 ($size,$mtime) = @{$currfile->{$embed_file}};
13132:             }
13133:         }
13134:         $showsize = $size/1024.0;
13135:         $showsize = sprintf("%.1f",$showsize);
13136:         if ($mtime > 0) {
13137:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
13138:         }
13139:     }
13140:     return ($showsize,$showmtime);
13141: }
13142: 
13143: sub ask_embedded_js {
13144:     return <<"END";
13145: <script type="text/javascript"">
13146: // <![CDATA[
13147: function toggleBrowse(counter) {
13148:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
13149:     var fileid = document.getElementById('embedded_item_'+counter);
13150:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
13151:     if (chkboxid.checked == true) {
13152:         uploaddivid.style.display='block';
13153:     } else {
13154:         uploaddivid.style.display='none';
13155:         fileid.value = '';
13156:     }
13157: }
13158: // ]]>
13159: </script>
13160: 
13161: END
13162: }
13163: 
13164: sub upload_embedded {
13165:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
13166:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
13167:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
13168:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
13169:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
13170:         my $orig_uploaded_filename =
13171:             $env{'form.embedded_item_'.$i.'.filename'};
13172:         foreach my $type ('orig','ref','attrib','codebase') {
13173:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
13174:                 $env{'form.embedded_'.$type.'_'.$i} =
13175:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
13176:             }
13177:         }
13178:         my ($path,$fname) =
13179:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
13180:         # no path, whole string is fname
13181:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
13182:         $fname = &Apache::lonnet::clean_filename($fname);
13183:         # See if there is anything left
13184:         next if ($fname eq '');
13185: 
13186:         # Check if file already exists as a file or directory.
13187:         my ($state,$msg);
13188:         if ($context eq 'portfolio') {
13189:             my $port_path = $dirpath;
13190:             if ($group ne '') {
13191:                 $port_path = "groups/$group/$port_path";
13192:             }
13193:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
13194:                                               $fname,$group,'embedded_item_'.$i,
13195:                                               $dir_root,$port_path,$disk_quota,
13196:                                               $current_disk_usage,$uname,$udom);
13197:             if ($state eq 'will_exceed_quota'
13198:                 || $state eq 'file_locked') {
13199:                 $output .= $msg;
13200:                 next;
13201:             }
13202:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
13203:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
13204:             if ($state eq 'exists') {
13205:                 $output .= $msg;
13206:                 next;
13207:             }
13208:         }
13209:         # Check if extension is valid
13210:         if (($fname =~ /\.(\w+)$/) &&
13211:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
13212:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
13213:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
13214:             next;
13215:         } elsif (($fname =~ /\.(\w+)$/) &&
13216:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
13217:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
13218:             next;
13219:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
13220:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
13221:             next;
13222:         }
13223:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
13224:         my $subdir = $path;
13225:         $subdir =~ s{/+$}{};
13226:         if ($context eq 'portfolio') {
13227:             my $result;
13228:             if ($state eq 'existingfile') {
13229:                 $result=
13230:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
13231:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
13232:             } else {
13233:                 $result=
13234:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
13235:                                                     $dirpath.
13236:                                                     $env{'form.currentpath'}.$subdir);
13237:                 if ($result !~ m|^/uploaded/|) {
13238:                     $output .= '<span class="LC_error">'
13239:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
13240:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
13241:                                .'</span><br />';
13242:                     next;
13243:                 } else {
13244:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
13245:                                $path.$fname.'</span>').'<br />';     
13246:                 }
13247:             }
13248:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
13249:             my $extendedsubdir = $dirpath.'/'.$subdir;
13250:             $extendedsubdir =~ s{/+$}{};
13251:             my $result =
13252:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
13253:             if ($result !~ m|^/uploaded/|) {
13254:                 $output .= '<span class="LC_error">'
13255:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
13256:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
13257:                            .'</span><br />';
13258:                     next;
13259:             } else {
13260:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
13261:                            $path.$fname.'</span>').'<br />';
13262:                 if ($context eq 'syllabus') {
13263:                     &Apache::lonnet::make_public_indefinitely($result);
13264:                 }
13265:             }
13266:         } else {
13267: # Save the file
13268:             my $target = $env{'form.embedded_item_'.$i};
13269:             my $fullpath = $dir_root.$dirpath.'/'.$path;
13270:             my $dest = $fullpath.$fname;
13271:             my $url = $url_root.$dirpath.'/'.$path.$fname;
13272:             my @parts=split(/\//,"$dirpath/$path");
13273:             my $count;
13274:             my $filepath = $dir_root;
13275:             foreach my $subdir (@parts) {
13276:                 $filepath .= "/$subdir";
13277:                 if (!-e $filepath) {
13278:                     mkdir($filepath,0770);
13279:                 }
13280:             }
13281:             my $fh;
13282:             if (!open($fh,'>'.$dest)) {
13283:                 &Apache::lonnet::logthis('Failed to create '.$dest);
13284:                 $output .= '<span class="LC_error">'.
13285:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
13286:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
13287:                            '</span><br />';
13288:             } else {
13289:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
13290:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
13291:                     $output .= '<span class="LC_error">'.
13292:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
13293:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
13294:                               '</span><br />';
13295:                 } else {
13296:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
13297:                                $url.'</span>').'<br />';
13298:                     unless ($context eq 'testbank') {
13299:                         $footer .= &mt('View embedded file: [_1]',
13300:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
13301:                     }
13302:                 }
13303:                 close($fh);
13304:             }
13305:         }
13306:         if ($env{'form.embedded_ref_'.$i}) {
13307:             $pathchange{$i} = 1;
13308:         }
13309:     }
13310:     if ($output) {
13311:         $output = '<p>'.$output.'</p>';
13312:     }
13313:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
13314:     $returnflag = 'ok';
13315:     my $numpathchgs = scalar(keys(%pathchange));
13316:     if ($numpathchgs > 0) {
13317:         if ($context eq 'portfolio') {
13318:             $output .= '<p>'.&mt('or').'</p>';
13319:         } elsif ($context eq 'testbank') {
13320:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
13321:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
13322:             $returnflag = 'modify_orightml';
13323:         }
13324:     }
13325:     return ($output.$footer,$returnflag,$numpathchgs);
13326: }
13327: 
13328: sub modify_html_form {
13329:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
13330:     my $end = 0;
13331:     my $modifyform;
13332:     if ($context eq 'upload_embedded') {
13333:         return unless (ref($pathchange) eq 'HASH');
13334:         if ($env{'form.number_embedded_items'}) {
13335:             $end += $env{'form.number_embedded_items'};
13336:         }
13337:         if ($env{'form.number_pathchange_items'}) {
13338:             $end += $env{'form.number_pathchange_items'};
13339:         }
13340:         if ($end) {
13341:             for (my $i=0; $i<$end; $i++) {
13342:                 if ($i < $env{'form.number_embedded_items'}) {
13343:                     next unless($pathchange->{$i});
13344:                 }
13345:                 $modifyform .=
13346:                     &start_data_table_row().
13347:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
13348:                     'checked="checked" /></td>'.
13349:                     '<td>'.$env{'form.embedded_ref_'.$i}.
13350:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
13351:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
13352:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
13353:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
13354:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
13355:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
13356:                     '<td>'.$env{'form.embedded_orig_'.$i}.
13357:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
13358:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
13359:                     &end_data_table_row();
13360:             }
13361:         }
13362:     } else {
13363:         $modifyform = $pathchgtable;
13364:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
13365:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
13366:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
13367:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
13368:         }
13369:     }
13370:     if ($modifyform) {
13371:         if ($actionurl eq '/adm/dependencies') {
13372:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
13373:         }
13374:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
13375:                '<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".
13376:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
13377:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
13378:                '</ol></p>'."\n".'<p>'.
13379:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
13380:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
13381:                &start_data_table()."\n".
13382:                &start_data_table_header_row().
13383:                '<th>'.&mt('Change?').'</th>'.
13384:                '<th>'.&mt('Current reference').'</th>'.
13385:                '<th>'.&mt('Required reference').'</th>'.
13386:                &end_data_table_header_row()."\n".
13387:                $modifyform.
13388:                &end_data_table().'<br />'."\n".$hiddenstate.
13389:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
13390:                '</form>'."\n";
13391:     }
13392:     return;
13393: }
13394: 
13395: sub modify_html_refs {
13396:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
13397:     my $container;
13398:     if ($context eq 'portfolio') {
13399:         $container = $env{'form.container'};
13400:     } elsif ($context eq 'coursedoc') {
13401:         $container = $env{'form.primaryurl'};
13402:     } elsif ($context eq 'manage_dependencies') {
13403:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
13404:         $container = "/$container";
13405:     } elsif ($context eq 'syllabus') {
13406:         $container = $url;
13407:     } else {
13408:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
13409:     }
13410:     my (%allfiles,%codebase,$output,$content);
13411:     my @changes = &get_env_multiple('form.namechange');
13412:     unless ((@changes > 0) || ($context eq 'syllabus')) {
13413:         if (wantarray) {
13414:             return ('',0,0); 
13415:         } else {
13416:             return;
13417:         }
13418:     }
13419:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
13420:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
13421:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
13422:             if (wantarray) {
13423:                 return ('',0,0);
13424:             } else {
13425:                 return;
13426:             }
13427:         } 
13428:         $content = &Apache::lonnet::getfile($container);
13429:         if ($content eq '-1') {
13430:             if (wantarray) {
13431:                 return ('',0,0);
13432:             } else {
13433:                 return;
13434:             }
13435:         }
13436:     } else {
13437:         unless ($container =~ /^\Q$dir_root\E/) {
13438:             if (wantarray) {
13439:                 return ('',0,0);
13440:             } else {
13441:                 return;
13442:             }
13443:         } 
13444:         if (open(my $fh,'<',$container)) {
13445:             $content = join('', <$fh>);
13446:             close($fh);
13447:         } else {
13448:             if (wantarray) {
13449:                 return ('',0,0);
13450:             } else {
13451:                 return;
13452:             }
13453:         }
13454:     }
13455:     my ($count,$codebasecount) = (0,0);
13456:     my $mm = new File::MMagic;
13457:     my $mime_type = $mm->checktype_contents($content);
13458:     if ($mime_type eq 'text/html') {
13459:         my $parse_result = 
13460:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
13461:                                                     \%codebase,\$content);
13462:         if ($parse_result eq 'ok') {
13463:             foreach my $i (@changes) {
13464:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
13465:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
13466:                 if ($allfiles{$ref}) {
13467:                     my $newname =  $orig;
13468:                     my ($attrib_regexp,$codebase);
13469:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
13470:                     if ($attrib_regexp =~ /:/) {
13471:                         $attrib_regexp =~ s/\:/|/g;
13472:                     }
13473:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
13474:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
13475:                         $count += $numchg;
13476:                         $allfiles{$newname} = $allfiles{$ref};
13477:                         delete($allfiles{$ref});
13478:                     }
13479:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
13480:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
13481:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
13482:                         $codebasecount ++;
13483:                     }
13484:                 }
13485:             }
13486:             my $skiprewrites;
13487:             if ($count || $codebasecount) {
13488:                 my $saveresult;
13489:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
13490:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
13491:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
13492:                     if ($url eq $container) {
13493:                         my ($fname) = ($container =~ m{/([^/]+)$});
13494:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
13495:                                             $count,'<span class="LC_filename">'.
13496:                                             $fname.'</span>').'</p>';
13497:                     } else {
13498:                          $output = '<p class="LC_error">'.
13499:                                    &mt('Error: update failed for: [_1].',
13500:                                    '<span class="LC_filename">'.
13501:                                    $container.'</span>').'</p>';
13502:                     }
13503:                     if ($context eq 'syllabus') {
13504:                         unless ($saveresult eq 'ok') {
13505:                             $skiprewrites = 1;
13506:                         }
13507:                     }
13508:                 } else {
13509:                     if (open(my $fh,'>',$container)) {
13510:                         print $fh $content;
13511:                         close($fh);
13512:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
13513:                                   $count,'<span class="LC_filename">'.
13514:                                   $container.'</span>').'</p>';
13515:                     } else {
13516:                          $output = '<p class="LC_error">'.
13517:                                    &mt('Error: could not update [_1].',
13518:                                    '<span class="LC_filename">'.
13519:                                    $container.'</span>').'</p>';
13520:                     }
13521:                 }
13522:             }
13523:             if (($context eq 'syllabus') && (!$skiprewrites)) {
13524:                 my ($actionurl,$state);
13525:                 $actionurl = "/public/$udom/$uname/syllabus";
13526:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
13527:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
13528:                                               \%codebase,
13529:                                               {'context' => 'rewrites',
13530:                                                'ignore_remote_references' => 1,});
13531:                 if (ref($mapping) eq 'HASH') {
13532:                     my $rewrites = 0;
13533:                     foreach my $key (keys(%{$mapping})) {
13534:                         next if ($key =~ m{^https?://});
13535:                         my $ref = $mapping->{$key};
13536:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
13537:                         my $attrib;
13538:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
13539:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
13540:                         }
13541:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
13542:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
13543:                             $rewrites += $numchg;
13544:                         }
13545:                     }
13546:                     if ($rewrites) {
13547:                         my $saveresult; 
13548:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
13549:                         if ($url eq $container) {
13550:                             my ($fname) = ($container =~ m{/([^/]+)$});
13551:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
13552:                                             $count,'<span class="LC_filename">'.
13553:                                             $fname.'</span>').'</p>';
13554:                         } else {
13555:                             $output .= '<p class="LC_error">'.
13556:                                        &mt('Error: could not update links in [_1].',
13557:                                        '<span class="LC_filename">'.
13558:                                        $container.'</span>').'</p>';
13559: 
13560:                         }
13561:                     }
13562:                 }
13563:             }
13564:         } else {
13565:             &logthis('Failed to parse '.$container.
13566:                      ' to modify references: '.$parse_result);
13567:         }
13568:     }
13569:     if (wantarray) {
13570:         return ($output,$count,$codebasecount);
13571:     } else {
13572:         return $output;
13573:     }
13574: }
13575: 
13576: sub check_for_existing {
13577:     my ($path,$fname,$element) = @_;
13578:     my ($state,$msg);
13579:     if (-d $path.'/'.$fname) {
13580:         $state = 'exists';
13581:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
13582:     } elsif (-e $path.'/'.$fname) {
13583:         $state = 'exists';
13584:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
13585:     }
13586:     if ($state eq 'exists') {
13587:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
13588:     }
13589:     return ($state,$msg);
13590: }
13591: 
13592: sub check_for_upload {
13593:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
13594:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
13595:     my $filesize = length($env{'form.'.$element});
13596:     if (!$filesize) {
13597:         my $msg = '<span class="LC_error">'.
13598:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
13599:                       '<span class="LC_filename">'.$fname.'</span>',
13600:                       $filesize).'<br />'.
13601:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
13602:                   '</span>';
13603:         return ('zero_bytes',$msg);
13604:     }
13605:     $filesize =  $filesize/1000; #express in k (1024?)
13606:     my $getpropath = 1;
13607:     my ($dirlistref,$listerror) =
13608:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
13609:     my $found_file = 0;
13610:     my $locked_file = 0;
13611:     my @lockers;
13612:     my $navmap;
13613:     if ($env{'request.course.id'}) {
13614:         $navmap = Apache::lonnavmaps::navmap->new();
13615:     }
13616:     if (ref($dirlistref) eq 'ARRAY') {
13617:         foreach my $line (@{$dirlistref}) {
13618:             my ($file_name,$rest)=split(/\&/,$line,2);
13619:             if ($file_name eq $fname){
13620:                 $file_name = $path.$file_name;
13621:                 if ($group ne '') {
13622:                     $file_name = $group.$file_name;
13623:                 }
13624:                 $found_file = 1;
13625:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
13626:                     foreach my $lock (@lockers) {
13627:                         if (ref($lock) eq 'ARRAY') {
13628:                             my ($symb,$crsid) = @{$lock};
13629:                             if ($crsid eq $env{'request.course.id'}) {
13630:                                 if (ref($navmap)) {
13631:                                     my $res = $navmap->getBySymb($symb);
13632:                                     foreach my $part (@{$res->parts()}) { 
13633:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
13634:                                         unless (($slot_status == $res->RESERVED) ||
13635:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
13636:                                             $locked_file = 1;
13637:                                         }
13638:                                     }
13639:                                 } else {
13640:                                     $locked_file = 1;
13641:                                 }
13642:                             } else {
13643:                                 $locked_file = 1;
13644:                             }
13645:                         }
13646:                    }
13647:                 } else {
13648:                     my @info = split(/\&/,$rest);
13649:                     my $currsize = $info[6]/1000;
13650:                     if ($currsize < $filesize) {
13651:                         my $extra = $filesize - $currsize;
13652:                         if (($current_disk_usage + $extra) > $disk_quota) {
13653:                             my $msg = '<p class="LC_warning">'.
13654:                                       &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.',
13655:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
13656:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
13657:                                                    $disk_quota,$current_disk_usage).'</p>';
13658:                             return ('will_exceed_quota',$msg);
13659:                         }
13660:                     }
13661:                 }
13662:             }
13663:         }
13664:     }
13665:     if (($current_disk_usage + $filesize) > $disk_quota){
13666:         my $msg = '<p class="LC_warning">'.
13667:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
13668:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
13669:         return ('will_exceed_quota',$msg);
13670:     } elsif ($found_file) {
13671:         if ($locked_file) {
13672:             my $msg = '<p class="LC_warning">';
13673:             $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>');
13674:             $msg .= '</p>';
13675:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
13676:             return ('file_locked',$msg);
13677:         } else {
13678:             my $msg = '<p class="LC_error">';
13679:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
13680:             $msg .= '</p>';
13681:             return ('existingfile',$msg);
13682:         }
13683:     }
13684: }
13685: 
13686: sub check_for_traversal {
13687:     my ($path,$url,$toplevel) = @_;
13688:     my @parts=split(/\//,$path);
13689:     my $cleanpath;
13690:     my $fullpath = $url;
13691:     for (my $i=0;$i<@parts;$i++) {
13692:         next if ($parts[$i] eq '.');
13693:         if ($parts[$i] eq '..') {
13694:             $fullpath =~ s{([^/]+/)$}{};
13695:         } else {
13696:             $fullpath .= $parts[$i].'/';
13697:         }
13698:     }
13699:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
13700:         $cleanpath = $1;
13701:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
13702:         my $curr_toprel = $1;
13703:         my @parts = split(/\//,$curr_toprel);
13704:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
13705:         my @urlparts = split(/\//,$url_toprel);
13706:         my $doubledots;
13707:         my $startdiff = -1;
13708:         for (my $i=0; $i<@urlparts; $i++) {
13709:             if ($startdiff == -1) {
13710:                 unless ($urlparts[$i] eq $parts[$i]) {
13711:                     $startdiff = $i;
13712:                     $doubledots .= '../';
13713:                 }
13714:             } else {
13715:                 $doubledots .= '../';
13716:             }
13717:         }
13718:         if ($startdiff > -1) {
13719:             $cleanpath = $doubledots;
13720:             for (my $i=$startdiff; $i<@parts; $i++) {
13721:                 $cleanpath .= $parts[$i].'/';
13722:             }
13723:         }
13724:     }
13725:     $cleanpath =~ s{(/)$}{};
13726:     return $cleanpath;
13727: }
13728: 
13729: sub is_archive_file {
13730:     my ($mimetype) = @_;
13731:     if (($mimetype eq 'application/octet-stream') ||
13732:         ($mimetype eq 'application/x-stuffit') ||
13733:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
13734:         return 1;
13735:     }
13736:     return;
13737: }
13738: 
13739: sub decompress_form {
13740:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
13741:     my %lt = &Apache::lonlocal::texthash (
13742:         this => 'This file is an archive file.',
13743:         camt => 'This file is a Camtasia archive file.',
13744:         itsc => 'Its contents are as follows:',
13745:         youm => 'You may wish to extract its contents.',
13746:         extr => 'Extract contents',
13747:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
13748:         proa => 'Process automatically?',
13749:         yes  => 'Yes',
13750:         no   => 'No',
13751:         fold => 'Title for folder containing movie',
13752:         movi => 'Title for page containing embedded movie', 
13753:     );
13754:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
13755:     my ($is_camtasia,$topdir,%toplevel,@paths);
13756:     my $info = &list_archive_contents($fileloc,\@paths);
13757:     if (@paths) {
13758:         foreach my $path (@paths) {
13759:             $path =~ s{^/}{};
13760:             if ($path =~ m{^([^/]+)/$}) {
13761:                 $topdir = $1;
13762:             }
13763:             if ($path =~ m{^([^/]+)/}) {
13764:                 $toplevel{$1} = $path;
13765:             } else {
13766:                 $toplevel{$path} = $path;
13767:             }
13768:         }
13769:     }
13770:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
13771:         my @camtasia6 = ("$topdir/","$topdir/index.html",
13772:                         "$topdir/media/",
13773:                         "$topdir/media/$topdir.mp4",
13774:                         "$topdir/media/FirstFrame.png",
13775:                         "$topdir/media/player.swf",
13776:                         "$topdir/media/swfobject.js",
13777:                         "$topdir/media/expressInstall.swf");
13778:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
13779:                          "$topdir/$topdir.mp4",
13780:                          "$topdir/$topdir\_config.xml",
13781:                          "$topdir/$topdir\_controller.swf",
13782:                          "$topdir/$topdir\_embed.css",
13783:                          "$topdir/$topdir\_First_Frame.png",
13784:                          "$topdir/$topdir\_player.html",
13785:                          "$topdir/$topdir\_Thumbnails.png",
13786:                          "$topdir/playerProductInstall.swf",
13787:                          "$topdir/scripts/",
13788:                          "$topdir/scripts/config_xml.js",
13789:                          "$topdir/scripts/handlebars.js",
13790:                          "$topdir/scripts/jquery-1.7.1.min.js",
13791:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
13792:                          "$topdir/scripts/modernizr.js",
13793:                          "$topdir/scripts/player-min.js",
13794:                          "$topdir/scripts/swfobject.js",
13795:                          "$topdir/skins/",
13796:                          "$topdir/skins/configuration_express.xml",
13797:                          "$topdir/skins/express_show/",
13798:                          "$topdir/skins/express_show/player-min.css",
13799:                          "$topdir/skins/express_show/spritesheet.png");
13800:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
13801:                          "$topdir/$topdir.mp4",
13802:                          "$topdir/$topdir\_config.xml",
13803:                          "$topdir/$topdir\_controller.swf",
13804:                          "$topdir/$topdir\_embed.css",
13805:                          "$topdir/$topdir\_First_Frame.png",
13806:                          "$topdir/$topdir\_player.html",
13807:                          "$topdir/$topdir\_Thumbnails.png",
13808:                          "$topdir/playerProductInstall.swf",
13809:                          "$topdir/scripts/",
13810:                          "$topdir/scripts/config_xml.js",
13811:                          "$topdir/scripts/techsmith-smart-player.min.js",
13812:                          "$topdir/skins/",
13813:                          "$topdir/skins/configuration_express.xml",
13814:                          "$topdir/skins/express_show/",
13815:                          "$topdir/skins/express_show/spritesheet.min.css",
13816:                          "$topdir/skins/express_show/spritesheet.png",
13817:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
13818:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
13819:         if (@diffs == 0) {
13820:             $is_camtasia = 6;
13821:         } else {
13822:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
13823:             if (@diffs == 0) {
13824:                 $is_camtasia = 8;
13825:             } else {
13826:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
13827:                 if (@diffs == 0) {
13828:                     $is_camtasia = 8;
13829:                 }
13830:             }
13831:         }
13832:     }
13833:     my $output;
13834:     if ($is_camtasia) {
13835:         $output = <<"ENDCAM";
13836: <script type="text/javascript" language="Javascript">
13837: // <![CDATA[
13838: 
13839: function camtasiaToggle() {
13840:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
13841:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
13842:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
13843:                 document.getElementById('camtasia_titles').style.display='block';
13844:             } else {
13845:                 document.getElementById('camtasia_titles').style.display='none';
13846:             }
13847:         }
13848:     }
13849:     return;
13850: }
13851: 
13852: // ]]>
13853: </script>
13854: <p>$lt{'camt'}</p>
13855: ENDCAM
13856:     } else {
13857:         $output = '<p>'.$lt{'this'};
13858:         if ($info eq '') {
13859:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
13860:         } else {
13861:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
13862:                        '<div><pre>'.$info.'</pre></div>';
13863:         }
13864:     }
13865:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
13866:     my $duplicates;
13867:     my $num = 0;
13868:     if (ref($dirlist) eq 'ARRAY') {
13869:         foreach my $item (@{$dirlist}) {
13870:             if (ref($item) eq 'ARRAY') {
13871:                 if (exists($toplevel{$item->[0]})) {
13872:                     $duplicates .= 
13873:                         &start_data_table_row().
13874:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
13875:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
13876:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
13877:                         'value="1" />'.&mt('Yes').'</label>'.
13878:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
13879:                         '<td>'.$item->[0].'</td>';
13880:                     if ($item->[2]) {
13881:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
13882:                     } else {
13883:                         $duplicates .= '<td>'.&mt('File').'</td>';
13884:                     }
13885:                     $duplicates .= '<td>'.$item->[3].'</td>'.
13886:                                    '<td>'.
13887:                                    &Apache::lonlocal::locallocaltime($item->[4]).
13888:                                    '</td>'.
13889:                                    &end_data_table_row();
13890:                     $num ++;
13891:                 }
13892:             }
13893:         }
13894:     }
13895:     my $itemcount;
13896:     if (@paths > 0) {
13897:         $itemcount = scalar(@paths);
13898:     } else {
13899:         $itemcount = 1;
13900:     }
13901:     if ($is_camtasia) {
13902:         $output .= $lt{'auto'}.'<br />'.
13903:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
13904:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
13905:                    $lt{'yes'}.'</label>&nbsp;<label>'.
13906:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
13907:                    $lt{'no'}.'</label></span><br />'.
13908:                    '<div id="camtasia_titles" style="display:block">'.
13909:                    &Apache::lonhtmlcommon::start_pick_box().
13910:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
13911:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
13912:                    &Apache::lonhtmlcommon::row_closure().
13913:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
13914:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
13915:                    &Apache::lonhtmlcommon::row_closure(1).
13916:                    &Apache::lonhtmlcommon::end_pick_box().
13917:                    '</div>';
13918:     }
13919:     $output .= 
13920:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
13921:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
13922:         "\n";
13923:     if ($duplicates ne '') {
13924:         $output .= '<p><span class="LC_warning">'.
13925:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
13926:                    &start_data_table().
13927:                    &start_data_table_header_row().
13928:                    '<th>'.&mt('Overwrite?').'</th>'.
13929:                    '<th>'.&mt('Name').'</th>'.
13930:                    '<th>'.&mt('Type').'</th>'.
13931:                    '<th>'.&mt('Size').'</th>'.
13932:                    '<th>'.&mt('Last modified').'</th>'.
13933:                    &end_data_table_header_row().
13934:                    $duplicates.
13935:                    &end_data_table().
13936:                    '</p>';
13937:     }
13938:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
13939:     if (ref($hiddenelements) eq 'HASH') {
13940:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
13941:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
13942:         }
13943:     }
13944:     $output .= <<"END";
13945: <br />
13946: <input type="submit" name="decompress" value="$lt{'extr'}" />
13947: </form>
13948: $noextract
13949: END
13950:     return $output;
13951: }
13952: 
13953: sub decompression_utility {
13954:     my ($program) = @_;
13955:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
13956:     my $location;
13957:     if (grep(/^\Q$program\E$/,@utilities)) { 
13958:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
13959:                          '/usr/sbin/') {
13960:             if (-x $dir.$program) {
13961:                 $location = $dir.$program;
13962:                 last;
13963:             }
13964:         }
13965:     }
13966:     return $location;
13967: }
13968: 
13969: sub list_archive_contents {
13970:     my ($file,$pathsref) = @_;
13971:     my (@cmd,$output);
13972:     my $needsregexp;
13973:     if ($file =~ /\.zip$/) {
13974:         @cmd = (&decompression_utility('unzip'),"-l");
13975:         $needsregexp = 1;
13976:     } elsif (($file =~ m/\.tar\.gz$/) ||
13977:              ($file =~ /\.tgz$/)) {
13978:         @cmd = (&decompression_utility('tar'),"-ztf");
13979:     } elsif ($file =~ /\.tar\.bz2$/) {
13980:         @cmd = (&decompression_utility('tar'),"-jtf");
13981:     } elsif ($file =~ m|\.tar$|) {
13982:         @cmd = (&decompression_utility('tar'),"-tf");
13983:     }
13984:     if (@cmd) {
13985:         undef($!);
13986:         undef($@);
13987:         if (open(my $fh,"-|", @cmd, $file)) {
13988:             while (my $line = <$fh>) {
13989:                 $output .= $line;
13990:                 chomp($line);
13991:                 my $item;
13992:                 if ($needsregexp) {
13993:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
13994:                 } else {
13995:                     $item = $line;
13996:                 }
13997:                 if ($item ne '') {
13998:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
13999:                         push(@{$pathsref},$item);
14000:                     } 
14001:                 }
14002:             }
14003:             close($fh);
14004:         }
14005:     }
14006:     return $output;
14007: }
14008: 
14009: sub decompress_uploaded_file {
14010:     my ($file,$dir) = @_;
14011:     &Apache::lonnet::appenv({'cgi.file' => $file});
14012:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
14013:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
14014:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
14015:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
14016:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
14017:     my $decompressed = $env{'cgi.decompressed'};
14018:     &Apache::lonnet::delenv('cgi.file');
14019:     &Apache::lonnet::delenv('cgi.dir');
14020:     &Apache::lonnet::delenv('cgi.decompressed');
14021:     return ($decompressed,$result);
14022: }
14023: 
14024: sub process_decompression {
14025:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
14026:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
14027:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
14028:                &mt('Unexpected file path.').'</p>'."\n";
14029:     }
14030:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
14031:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
14032:                &mt('Unexpected course context.').'</p>'."\n";
14033:     }
14034:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
14035:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
14036:                &mt('Filename contained unexpected characters.').'</p>'."\n";
14037:     }
14038:     my ($dir,$error,$warning,$output);
14039:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
14040:         $error = &mt('Filename not a supported archive file type.').
14041:                  '<br />'.&mt('Filename should end with one of: [_1].',
14042:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
14043:     } else {
14044:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
14045:         if ($docuhome eq 'no_host') {
14046:             $error = &mt('Could not determine home server for course.');
14047:         } else {
14048:             my @ids=&Apache::lonnet::current_machine_ids();
14049:             my $currdir = "$dir_root/$destination";
14050:             if (grep(/^\Q$docuhome\E$/,@ids)) {
14051:                 $dir = &LONCAPA::propath($docudom,$docuname).
14052:                        "$dir_root/$destination";
14053:             } else {
14054:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
14055:                        "$dir_root/$docudom/$docuname/$destination";
14056:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
14057:                     $error = &mt('Archive file not found.');
14058:                 }
14059:             }
14060:             my (@to_overwrite,@to_skip);
14061:             if ($env{'form.archive_overwrite_total'} > 0) {
14062:                 my $total = $env{'form.archive_overwrite_total'};
14063:                 for (my $i=0; $i<$total; $i++) {
14064:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
14065:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
14066:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
14067:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
14068:                     }
14069:                 }
14070:             }
14071:             my $numskip = scalar(@to_skip);
14072:             my $numoverwrite = scalar(@to_overwrite);
14073:             if (($numskip) && (!$numoverwrite)) { 
14074:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
14075:             } elsif ($dir eq '') {
14076:                 $error = &mt('Directory containing archive file unavailable.');
14077:             } elsif (!$error) {
14078:                 my ($decompressed,$display);
14079:                 if (($numskip) || ($numoverwrite)) {
14080:                     my $tempdir = time.'_'.$$.int(rand(10000));
14081:                     mkdir("$dir/$tempdir",0755);
14082:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
14083:                         ($decompressed,$display) = 
14084:                             &decompress_uploaded_file($file,"$dir/$tempdir");
14085:                         foreach my $item (@to_skip) {
14086:                             if (($item ne '') && ($item !~ /\.\./)) {
14087:                                 if (-f "$dir/$tempdir/$item") { 
14088:                                     unlink("$dir/$tempdir/$item");
14089:                                 } elsif (-d "$dir/$tempdir/$item") {
14090:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
14091:                                 }
14092:                             }
14093:                         }
14094:                         foreach my $item (@to_overwrite) {
14095:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
14096:                                 if (($item ne '') && ($item !~ /\.\./)) {
14097:                                     if (-f "$dir/$item") {
14098:                                         unlink("$dir/$item");
14099:                                     } elsif (-d "$dir/$item") {
14100:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
14101:                                     }
14102:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
14103:                                 }
14104:                             }
14105:                         }
14106:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
14107:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
14108:                         }
14109:                     }
14110:                 } else {
14111:                     ($decompressed,$display) = 
14112:                         &decompress_uploaded_file($file,$dir);
14113:                 }
14114:                 if ($decompressed eq 'ok') {
14115:                     $output = '<p class="LC_info">'.
14116:                               &mt('Files extracted successfully from archive.').
14117:                               '</p>'."\n";
14118:                     my ($warning,$result,@contents);
14119:                     my ($newdirlistref,$newlisterror) =
14120:                         &Apache::lonnet::dirlist($currdir,$docudom,
14121:                                                  $docuname,1);
14122:                     my (%is_dir,%changes,@newitems);
14123:                     my $dirptr = 16384;
14124:                     if (ref($newdirlistref) eq 'ARRAY') {
14125:                         foreach my $dir_line (@{$newdirlistref}) {
14126:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
14127:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
14128:                                 push(@newitems,$item);
14129:                                 if ($dirptr&$testdir) {
14130:                                     $is_dir{$item} = 1;
14131:                                 }
14132:                                 $changes{$item} = 1;
14133:                             }
14134:                         }
14135:                     }
14136:                     if (keys(%changes) > 0) {
14137:                         foreach my $item (sort(@newitems)) {
14138:                             if ($changes{$item}) {
14139:                                 push(@contents,$item);
14140:                             }
14141:                         }
14142:                     }
14143:                     if (@contents > 0) {
14144:                         my $wantform;
14145:                         unless ($env{'form.autoextract_camtasia'}) {
14146:                             $wantform = 1;
14147:                         }
14148:                         my (%children,%parent,%dirorder,%titles);
14149:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
14150:                                                                 $currdir,\%is_dir,
14151:                                                                 \%children,\%parent,
14152:                                                                 \@contents,\%dirorder,
14153:                                                                 \%titles,$wantform);
14154:                         if ($datatable ne '') {
14155:                             $output .= &archive_options_form('decompressed',$datatable,
14156:                                                              $count,$hiddenelem);
14157:                             my $startcount = 6;
14158:                             $output .= &archive_javascript($startcount,$count,
14159:                                                            \%titles,\%children);
14160:                         }
14161:                         if ($env{'form.autoextract_camtasia'}) {
14162:                             my $version = $env{'form.autoextract_camtasia'};
14163:                             my %displayed;
14164:                             my $total = 1;
14165:                             $env{'form.archive_directory'} = [];
14166:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
14167:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
14168:                                 $path =~ s{/$}{};
14169:                                 my $item;
14170:                                 if ($path ne '') {
14171:                                     $item = "$path/$titles{$i}";
14172:                                 } else {
14173:                                     $item = $titles{$i};
14174:                                 }
14175:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
14176:                                 if ($item eq $contents[0]) {
14177:                                     push(@{$env{'form.archive_directory'}},$i);
14178:                                     $env{'form.archive_'.$i} = 'display';
14179:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
14180:                                     $displayed{'folder'} = $i;
14181:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
14182:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
14183:                                     $env{'form.archive_'.$i} = 'display';
14184:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
14185:                                     $displayed{'web'} = $i;
14186:                                 } else {
14187:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
14188:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
14189:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
14190:                                         push(@{$env{'form.archive_directory'}},$i);
14191:                                     }
14192:                                     $env{'form.archive_'.$i} = 'dependency';
14193:                                 }
14194:                                 $total ++;
14195:                             }
14196:                             for (my $i=1; $i<$total; $i++) {
14197:                                 next if ($i == $displayed{'web'});
14198:                                 next if ($i == $displayed{'folder'});
14199:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
14200:                             }
14201:                             $env{'form.phase'} = 'decompress_cleanup';
14202:                             $env{'form.archivedelete'} = 1;
14203:                             $env{'form.archive_count'} = $total-1;
14204:                             $output .=
14205:                                 &process_extracted_files('coursedocs',$docudom,
14206:                                                          $docuname,$destination,
14207:                                                          $dir_root,$hiddenelem);
14208:                         }
14209:                     } else {
14210:                         $warning = &mt('No new items extracted from archive file.');
14211:                     }
14212:                 } else {
14213:                     $output = $display;
14214:                     $error = &mt('An error occurred during extraction from the archive file.');
14215:                 }
14216:             }
14217:         }
14218:     }
14219:     if ($error) {
14220:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
14221:                    $error.'</p>'."\n";
14222:     }
14223:     if ($warning) {
14224:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
14225:     }
14226:     return $output;
14227: }
14228: 
14229: sub get_extracted {
14230:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
14231:         $titles,$wantform) = @_;
14232:     my $count = 0;
14233:     my $depth = 0;
14234:     my $datatable;
14235:     my @hierarchy;
14236:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
14237:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
14238:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
14239:     foreach my $item (@{$contents}) {
14240:         $count ++;
14241:         @{$dirorder->{$count}} = @hierarchy;
14242:         $titles->{$count} = $item;
14243:         &archive_hierarchy($depth,$count,$parent,$children);
14244:         if ($wantform) {
14245:             $datatable .= &archive_row($is_dir->{$item},$item,
14246:                                        $currdir,$depth,$count);
14247:         }
14248:         if ($is_dir->{$item}) {
14249:             $depth ++;
14250:             push(@hierarchy,$count);
14251:             $parent->{$depth} = $count;
14252:             $datatable .=
14253:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
14254:                                            \$depth,\$count,\@hierarchy,$dirorder,
14255:                                            $children,$parent,$titles,$wantform);
14256:             $depth --;
14257:             pop(@hierarchy);
14258:         }
14259:     }
14260:     return ($count,$datatable);
14261: }
14262: 
14263: sub recurse_extracted_archive {
14264:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
14265:         $children,$parent,$titles,$wantform) = @_;
14266:     my $result='';
14267:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
14268:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
14269:             (ref($dirorder) eq 'HASH')) {
14270:         return $result;
14271:     }
14272:     my $dirptr = 16384;
14273:     my ($newdirlistref,$newlisterror) =
14274:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
14275:     if (ref($newdirlistref) eq 'ARRAY') {
14276:         foreach my $dir_line (@{$newdirlistref}) {
14277:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
14278:             unless ($item =~ /^\.+$/) {
14279:                 $$count ++;
14280:                 @{$dirorder->{$$count}} = @{$hierarchy};
14281:                 $titles->{$$count} = $item;
14282:                 &archive_hierarchy($$depth,$$count,$parent,$children);
14283: 
14284:                 my $is_dir;
14285:                 if ($dirptr&$testdir) {
14286:                     $is_dir = 1;
14287:                 }
14288:                 if ($wantform) {
14289:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
14290:                 }
14291:                 if ($is_dir) {
14292:                     $$depth ++;
14293:                     push(@{$hierarchy},$$count);
14294:                     $parent->{$$depth} = $$count;
14295:                     $result .=
14296:                         &recurse_extracted_archive("$currdir/$item",$docudom,
14297:                                                    $docuname,$depth,$count,
14298:                                                    $hierarchy,$dirorder,$children,
14299:                                                    $parent,$titles,$wantform);
14300:                     $$depth --;
14301:                     pop(@{$hierarchy});
14302:                 }
14303:             }
14304:         }
14305:     }
14306:     return $result;
14307: }
14308: 
14309: sub archive_hierarchy {
14310:     my ($depth,$count,$parent,$children) =@_;
14311:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
14312:         if (exists($parent->{$depth})) {
14313:              $children->{$parent->{$depth}} .= $count.':';
14314:         }
14315:     }
14316:     return;
14317: }
14318: 
14319: sub archive_row {
14320:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
14321:     my ($name) = ($item =~ m{([^/]+)$});
14322:     my %choices = &Apache::lonlocal::texthash (
14323:                                        'display'    => 'Add as file',
14324:                                        'dependency' => 'Include as dependency',
14325:                                        'discard'    => 'Discard',
14326:                                       );
14327:     if ($is_dir) {
14328:         $choices{'display'} = &mt('Add as folder'); 
14329:     }
14330:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
14331:     my $offset = 0;
14332:     foreach my $action ('display','dependency','discard') {
14333:         $offset ++;
14334:         if ($action ne 'display') {
14335:             $offset ++;
14336:         }  
14337:         $output .= '<td><span class="LC_nobreak">'.
14338:                    '<label><input type="radio" name="archive_'.$count.
14339:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
14340:         my $text = $choices{$action};
14341:         if ($is_dir) {
14342:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
14343:             if ($action eq 'display') {
14344:                 $text = &mt('Add as folder');
14345:             }
14346:         } else {
14347:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
14348: 
14349:         }
14350:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
14351:         if ($action eq 'dependency') {
14352:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
14353:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
14354:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
14355:                        '<option value=""></option>'."\n".
14356:                        '</select>'."\n".
14357:                        '</div>';
14358:         } elsif ($action eq 'display') {
14359:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
14360:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
14361:                        '</div>';
14362:         }
14363:         $output .= '</td>';
14364:     }
14365:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
14366:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
14367:     for (my $i=0; $i<$depth; $i++) {
14368:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
14369:     }
14370:     if ($is_dir) {
14371:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
14372:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
14373:     } else {
14374:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
14375:     }
14376:     $output .= '&nbsp;'.$name.'</td>'."\n".
14377:                &end_data_table_row();
14378:     return $output;
14379: }
14380: 
14381: sub archive_options_form {
14382:     my ($form,$display,$count,$hiddenelem) = @_;
14383:     my %lt = &Apache::lonlocal::texthash(
14384:                perm => 'Permanently remove archive file?',
14385:                hows => 'How should each extracted item be incorporated in the course?',
14386:                cont => 'Content actions for all',
14387:                addf => 'Add as folder/file',
14388:                incd => 'Include as dependency for a displayed file',
14389:                disc => 'Discard',
14390:                no   => 'No',
14391:                yes  => 'Yes',
14392:                save => 'Save',
14393:     );
14394:     my $output = <<"END";
14395: <form name="$form" method="post" action="">
14396: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
14397: <label>
14398:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
14399: </label>
14400: &nbsp;
14401: <label>
14402:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
14403: </span>
14404: </p>
14405: <input type="hidden" name="phase" value="decompress_cleanup" />
14406: <br />$lt{'hows'}
14407: <div class="LC_columnSection">
14408:   <fieldset>
14409:     <legend>$lt{'cont'}</legend>
14410:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
14411:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
14412:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
14413:   </fieldset>
14414: </div>
14415: END
14416:     return $output.
14417:            &start_data_table()."\n".
14418:            $display."\n".
14419:            &end_data_table()."\n".
14420:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
14421:            $hiddenelem.
14422:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
14423:            '</form>';
14424: }
14425: 
14426: sub archive_javascript {
14427:     my ($startcount,$numitems,$titles,$children) = @_;
14428:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
14429:     my $maintitle = $env{'form.comment'};
14430:     my $scripttag = <<START;
14431: <script type="text/javascript">
14432: // <![CDATA[
14433: 
14434: function checkAll(form,prefix) {
14435:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
14436:     for (var i=0; i < form.elements.length; i++) {
14437:         var id = form.elements[i].id;
14438:         if ((id != '') && (id != undefined)) {
14439:             if (idstr.test(id)) {
14440:                 if (form.elements[i].type == 'radio') {
14441:                     form.elements[i].checked = true;
14442:                     var nostart = i-$startcount;
14443:                     var offset = nostart%7;
14444:                     var count = (nostart-offset)/7;    
14445:                     dependencyCheck(form,count,offset);
14446:                 }
14447:             }
14448:         }
14449:     }
14450: }
14451: 
14452: function propagateCheck(form,count) {
14453:     if (count > 0) {
14454:         var startelement = $startcount + ((count-1) * 7);
14455:         for (var j=1; j<6; j++) {
14456:             if ((j != 2) && (j != 4)) {
14457:                 var item = startelement + j; 
14458:                 if (form.elements[item].type == 'radio') {
14459:                     if (form.elements[item].checked) {
14460:                         containerCheck(form,count,j);
14461:                         break;
14462:                     }
14463:                 }
14464:             }
14465:         }
14466:     }
14467: }
14468: 
14469: numitems = $numitems
14470: var titles = new Array(numitems);
14471: var parents = new Array(numitems);
14472: for (var i=0; i<numitems; i++) {
14473:     parents[i] = new Array;
14474: }
14475: var maintitle = '$maintitle';
14476: 
14477: START
14478: 
14479:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
14480:         my @contents = split(/:/,$children->{$container});
14481:         for (my $i=0; $i<@contents; $i ++) {
14482:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
14483:         }
14484:     }
14485: 
14486:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
14487:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
14488:     }
14489: 
14490:     $scripttag .= <<END;
14491: 
14492: function containerCheck(form,count,offset) {
14493:     if (count > 0) {
14494:         dependencyCheck(form,count,offset);
14495:         var item = (offset+$startcount)+7*(count-1);
14496:         form.elements[item].checked = true;
14497:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
14498:             if (parents[count].length > 0) {
14499:                 for (var j=0; j<parents[count].length; j++) {
14500:                     containerCheck(form,parents[count][j],offset);
14501:                 }
14502:             }
14503:         }
14504:     }
14505: }
14506: 
14507: function dependencyCheck(form,count,offset) {
14508:     if (count > 0) {
14509:         var chosen = (offset+$startcount)+7*(count-1);
14510:         var depitem = $startcount + ((count-1) * 7) + 4;
14511:         var currtype = form.elements[depitem].type;
14512:         if (form.elements[chosen].value == 'dependency') {
14513:             document.getElementById('arc_depon_'+count).style.display='block'; 
14514:             form.elements[depitem].options.length = 0;
14515:             form.elements[depitem].options[0] = new Option('Select','',true,true);
14516:             for (var i=1; i<=numitems; i++) {
14517:                 if (i == count) {
14518:                     continue;
14519:                 }
14520:                 var startelement = $startcount + (i-1) * 7;
14521:                 for (var j=1; j<6; j++) {
14522:                     if ((j != 2) && (j!= 4)) {
14523:                         var item = startelement + j;
14524:                         if (form.elements[item].type == 'radio') {
14525:                             if (form.elements[item].checked) {
14526:                                 if (form.elements[item].value == 'display') {
14527:                                     var n = form.elements[depitem].options.length;
14528:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
14529:                                 }
14530:                             }
14531:                         }
14532:                     }
14533:                 }
14534:             }
14535:         } else {
14536:             document.getElementById('arc_depon_'+count).style.display='none';
14537:             form.elements[depitem].options.length = 0;
14538:             form.elements[depitem].options[0] = new Option('Select','',true,true);
14539:         }
14540:         titleCheck(form,count,offset);
14541:     }
14542: }
14543: 
14544: function propagateSelect(form,count,offset) {
14545:     if (count > 0) {
14546:         var item = (1+offset+$startcount)+7*(count-1);
14547:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
14548:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
14549:             if (parents[count].length > 0) {
14550:                 for (var j=0; j<parents[count].length; j++) {
14551:                     containerSelect(form,parents[count][j],offset,picked);
14552:                 }
14553:             }
14554:         }
14555:     }
14556: }
14557: 
14558: function containerSelect(form,count,offset,picked) {
14559:     if (count > 0) {
14560:         var item = (offset+$startcount)+7*(count-1);
14561:         if (form.elements[item].type == 'radio') {
14562:             if (form.elements[item].value == 'dependency') {
14563:                 if (form.elements[item+1].type == 'select-one') {
14564:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
14565:                         if (form.elements[item+1].options[i].value == picked) {
14566:                             form.elements[item+1].selectedIndex = i;
14567:                             break;
14568:                         }
14569:                     }
14570:                 }
14571:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
14572:                     if (parents[count].length > 0) {
14573:                         for (var j=0; j<parents[count].length; j++) {
14574:                             containerSelect(form,parents[count][j],offset,picked);
14575:                         }
14576:                     }
14577:                 }
14578:             }
14579:         }
14580:     }
14581: }
14582: 
14583: function titleCheck(form,count,offset) {
14584:     if (count > 0) {
14585:         var chosen = (offset+$startcount)+7*(count-1);
14586:         var depitem = $startcount + ((count-1) * 7) + 2;
14587:         var currtype = form.elements[depitem].type;
14588:         if (form.elements[chosen].value == 'display') {
14589:             document.getElementById('arc_title_'+count).style.display='block';
14590:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
14591:                 document.getElementById('archive_title_'+count).value=maintitle;
14592:             }
14593:         } else {
14594:             document.getElementById('arc_title_'+count).style.display='none';
14595:             if (currtype == 'text') { 
14596:                 document.getElementById('archive_title_'+count).value='';
14597:             }
14598:         }
14599:     }
14600:     return;
14601: }
14602: 
14603: // ]]>
14604: </script>
14605: END
14606:     return $scripttag;
14607: }
14608: 
14609: sub process_extracted_files {
14610:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
14611:     my $numitems = $env{'form.archive_count'};
14612:     return if ((!$numitems) || ($numitems =~ /\D/));
14613:     my @ids=&Apache::lonnet::current_machine_ids();
14614:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
14615:         %folders,%containers,%mapinner,%prompttofetch);
14616:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
14617:     if (grep(/^\Q$docuhome\E$/,@ids)) {
14618:         $prefix = &LONCAPA::propath($docudom,$docuname);
14619:         $pathtocheck = "$dir_root/$destination";
14620:         $dir = $dir_root;
14621:         $ishome = 1;
14622:     } else {
14623:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
14624:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
14625:         $dir = "$dir_root/$docudom/$docuname";
14626:     }
14627:     my $currdir = "$dir_root/$destination";
14628:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
14629:     if ($env{'form.folderpath'}) {
14630:         my @items = split('&',$env{'form.folderpath'});
14631:         $folders{'0'} = $items[-2];
14632:         if ($env{'form.folderpath'} =~ /\:1$/) {
14633:             $containers{'0'}='page';
14634:         } else {  
14635:             $containers{'0'}='sequence';
14636:         }
14637:     }
14638:     my @archdirs = &get_env_multiple('form.archive_directory');
14639:     if ($numitems) {
14640:         for (my $i=1; $i<=$numitems; $i++) {
14641:             my $path = $env{'form.archive_content_'.$i};
14642:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
14643:                 my $item = $1;
14644:                 $toplevelitems{$item} = $i;
14645:                 if (grep(/^\Q$i\E$/,@archdirs)) {
14646:                     $is_dir{$item} = 1;
14647:                 }
14648:             }
14649:         }
14650:     }
14651:     my ($output,%children,%parent,%titles,%dirorder,$result);
14652:     if (keys(%toplevelitems) > 0) {
14653:         my @contents = sort(keys(%toplevelitems));
14654:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
14655:                                            \%parent,\@contents,\%dirorder,\%titles);
14656:     }
14657:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
14658:     if ($numitems) {
14659:         for (my $i=1; $i<=$numitems; $i++) {
14660:             next if ($env{'form.archive_'.$i} eq 'dependency');
14661:             my $path = $env{'form.archive_content_'.$i};
14662:             if ($path =~ /^\Q$pathtocheck\E/) {
14663:                 if ($env{'form.archive_'.$i} eq 'discard') {
14664:                     if ($prefix ne '' && $path ne '') {
14665:                         if (-e $prefix.$path) {
14666:                             if ((@archdirs > 0) && 
14667:                                 (grep(/^\Q$i\E$/,@archdirs))) {
14668:                                 $todeletedir{$prefix.$path} = 1;
14669:                             } else {
14670:                                 $todelete{$prefix.$path} = 1;
14671:                             }
14672:                         }
14673:                     }
14674:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
14675:                     my ($docstitle,$title,$url,$outer);
14676:                     ($title) = ($path =~ m{/([^/]+)$});
14677:                     $docstitle = $env{'form.archive_title_'.$i};
14678:                     if ($docstitle eq '') {
14679:                         $docstitle = $title;
14680:                     }
14681:                     $outer = 0;
14682:                     if (ref($dirorder{$i}) eq 'ARRAY') {
14683:                         if (@{$dirorder{$i}} > 0) {
14684:                             foreach my $item (reverse(@{$dirorder{$i}})) {
14685:                                 if ($env{'form.archive_'.$item} eq 'display') {
14686:                                     $outer = $item;
14687:                                     last;
14688:                                 }
14689:                             }
14690:                         }
14691:                     }
14692:                     my ($errtext,$fatal) = 
14693:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
14694:                                                '/'.$folders{$outer}.'.'.
14695:                                                $containers{$outer});
14696:                     next if ($fatal);
14697:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
14698:                         if ($context eq 'coursedocs') {
14699:                             $mapinner{$i} = time;
14700:                             $folders{$i} = 'default_'.$mapinner{$i};
14701:                             $containers{$i} = 'sequence';
14702:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
14703:                                       $folders{$i}.'.'.$containers{$i};
14704:                             my $newidx = &LONCAPA::map::getresidx();
14705:                             $LONCAPA::map::resources[$newidx]=
14706:                                 $docstitle.':'.$url.':false:normal:res';
14707:                             push(@LONCAPA::map::order,$newidx);
14708:                             my ($outtext,$errtext) =
14709:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
14710:                                                         $docuname.'/'.$folders{$outer}.
14711:                                                         '.'.$containers{$outer},1,1);
14712:                             $newseqid{$i} = $newidx;
14713:                             unless ($errtext) {
14714:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
14715:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
14716:                                             '</li>'."\n";
14717:                             }
14718:                         }
14719:                     } else {
14720:                         if ($context eq 'coursedocs') {
14721:                             my $newidx=&LONCAPA::map::getresidx();
14722:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
14723:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
14724:                                       $title;
14725:                             if (($outer !~ /\D/) &&
14726:                                 (($mapinner{$outer} eq 'default') || ($mapinner{$outer} !~ /\D/)) &&
14727:                                 ($newidx !~ /\D/)) {
14728:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
14729:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
14730:                                 }
14731:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
14732:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
14733:                                 }
14734:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
14735:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
14736:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
14737:                                         unless ($ishome) {
14738:                                             my $fetch = "$newdest{$i}/$title";
14739:                                             $fetch =~ s/^\Q$prefix$dir\E//;
14740:                                             $prompttofetch{$fetch} = 1;
14741:                                         }
14742:                                     }
14743:                                 }
14744:                                 $LONCAPA::map::resources[$newidx]=
14745:                                     $docstitle.':'.$url.':false:normal:res';
14746:                                 push(@LONCAPA::map::order, $newidx);
14747:                                 my ($outtext,$errtext)=
14748:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
14749:                                                             $docuname.'/'.$folders{$outer}.
14750:                                                             '.'.$containers{$outer},1,1);
14751:                                 unless ($errtext) {
14752:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
14753:                                         $result .= '<li>'.&mt('File: [_1] added to course',
14754:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
14755:                                                    '</li>'."\n";
14756:                                     }
14757:                                 }
14758:                             } else {
14759:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
14760:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
14761:                             }
14762:                         }
14763:                     }
14764:                 }
14765:             } else {
14766:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
14767:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
14768:             }
14769:         }
14770:         for (my $i=1; $i<=$numitems; $i++) {
14771:             next unless ($env{'form.archive_'.$i} eq 'dependency');
14772:             my $path = $env{'form.archive_content_'.$i};
14773:             if ($path =~ /^\Q$pathtocheck\E/) {
14774:                 my ($title) = ($path =~ m{/([^/]+)$});
14775:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
14776:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
14777:                     if (ref($dirorder{$i}) eq 'ARRAY') {
14778:                         my ($itemidx,$fullpath,$relpath);
14779:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
14780:                             my $container = $dirorder{$referrer{$i}}->[-1];
14781:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
14782:                                 if ($dirorder{$i}->[$j] eq $container) {
14783:                                     $itemidx = $j;
14784:                                 }
14785:                             }
14786:                         }
14787:                         if ($itemidx eq '') {
14788:                             $itemidx =  0;
14789:                         } 
14790:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
14791:                             if ($mapinner{$referrer{$i}}) {
14792:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
14793:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
14794:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
14795:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
14796:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
14797:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
14798:                                             if (!-e $fullpath) {
14799:                                                 mkdir($fullpath,0755);
14800:                                             }
14801:                                         }
14802:                                     } else {
14803:                                         last;
14804:                                     }
14805:                                 }
14806:                             }
14807:                         } elsif ($newdest{$referrer{$i}}) {
14808:                             $fullpath = $newdest{$referrer{$i}};
14809:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
14810:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
14811:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
14812:                                     last;
14813:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
14814:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
14815:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
14816:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
14817:                                         if (!-e $fullpath) {
14818:                                             mkdir($fullpath,0755);
14819:                                         }
14820:                                     }
14821:                                 } else {
14822:                                     last;
14823:                                 }
14824:                             }
14825:                         }
14826:                         if ($fullpath ne '') {
14827:                             if (-e "$prefix$path") {
14828:                                 unless (rename("$prefix$path","$fullpath/$title")) {
14829:                                      $warning .= &mt('Failed to rename dependency').'<br />';
14830:                                 }
14831:                             }
14832:                             if (-e "$fullpath/$title") {
14833:                                 my $showpath;
14834:                                 if ($relpath ne '') {
14835:                                     $showpath = "$relpath/$title";
14836:                                 } else {
14837:                                     $showpath = "/$title";
14838:                                 } 
14839:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
14840:                                                       &HTML::Entities::encode($showpath,'<>&"')).
14841:                                            '</li>'."\n";
14842:                                 unless ($ishome) {
14843:                                     my $fetch = "$fullpath/$title";
14844:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
14845:                                     $prompttofetch{$fetch} = 1;
14846:                                 }
14847:                             }
14848:                         }
14849:                     }
14850:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
14851:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
14852:                                     &HTML::Entities::encode($path,'<>&"'),
14853:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
14854:                                 '<br />';
14855:                 }
14856:             } else {
14857:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
14858:                                 &HTML::Entities::encode($path)).'<br />';
14859:             }
14860:         }
14861:         if (keys(%todelete)) {
14862:             foreach my $key (keys(%todelete)) {
14863:                 unlink($key);
14864:             }
14865:         }
14866:         if (keys(%todeletedir)) {
14867:             foreach my $key (keys(%todeletedir)) {
14868:                 rmdir($key);
14869:             }
14870:         }
14871:         foreach my $dir (sort(keys(%is_dir))) {
14872:             if (($pathtocheck ne '') && ($dir ne ''))  {
14873:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
14874:             }
14875:         }
14876:         if ($result ne '') {
14877:             $output .= '<ul>'."\n".
14878:                        $result."\n".
14879:                        '</ul>';
14880:         }
14881:         unless ($ishome) {
14882:             my $replicationfail;
14883:             foreach my $item (keys(%prompttofetch)) {
14884:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
14885:                 unless ($fetchresult eq 'ok') {
14886:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
14887:                 }
14888:             }
14889:             if ($replicationfail) {
14890:                 $output .= '<p class="LC_error">'.
14891:                            &mt('Course home server failed to retrieve:').'<ul>'.
14892:                            $replicationfail.
14893:                            '</ul></p>';
14894:             }
14895:         }
14896:     } else {
14897:         $warning = &mt('No items found in archive.');
14898:     }
14899:     if ($error) {
14900:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
14901:                    $error.'</p>'."\n";
14902:     }
14903:     if ($warning) {
14904:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
14905:     }
14906:     return $output;
14907: }
14908: 
14909: sub cleanup_empty_dirs {
14910:     my ($path) = @_;
14911:     if (($path ne '') && (-d $path)) {
14912:         if (opendir(my $dirh,$path)) {
14913:             my @dircontents = grep(!/^\./,readdir($dirh));
14914:             my $numitems = 0;
14915:             foreach my $item (@dircontents) {
14916:                 if (-d "$path/$item") {
14917:                     &cleanup_empty_dirs("$path/$item");
14918:                     if (-e "$path/$item") {
14919:                         $numitems ++;
14920:                     }
14921:                 } else {
14922:                     $numitems ++;
14923:                 }
14924:             }
14925:             if ($numitems == 0) {
14926:                 rmdir($path);
14927:             }
14928:             closedir($dirh);
14929:         }
14930:     }
14931:     return;
14932: }
14933: 
14934: =pod
14935: 
14936: =item * &get_folder_hierarchy()
14937: 
14938: Provides hierarchy of names of folders/sub-folders containing the current
14939: item,
14940: 
14941: Inputs: 3
14942:      - $navmap - navmaps object
14943: 
14944:      - $map - url for map (either the trigger itself, or map containing
14945:                            the resource, which is the trigger).
14946: 
14947:      - $showitem - 1 => show title for map itself; 0 => do not show.
14948: 
14949: Outputs: 1 @pathitems - array of folder/subfolder names.
14950: 
14951: =cut
14952: 
14953: sub get_folder_hierarchy {
14954:     my ($navmap,$map,$showitem) = @_;
14955:     my @pathitems;
14956:     if (ref($navmap)) {
14957:         my $mapres = $navmap->getResourceByUrl($map);
14958:         if (ref($mapres)) {
14959:             my $pcslist = $mapres->map_hierarchy();
14960:             if ($pcslist ne '') {
14961:                 my @pcs = split(/,/,$pcslist);
14962:                 foreach my $pc (@pcs) {
14963:                     if ($pc == 1) {
14964:                         push(@pathitems,&mt('Main Content'));
14965:                     } else {
14966:                         my $res = $navmap->getByMapPc($pc);
14967:                         if (ref($res)) {
14968:                             my $title = $res->compTitle();
14969:                             $title =~ s/\W+/_/g;
14970:                             if ($title ne '') {
14971:                                 push(@pathitems,$title);
14972:                             }
14973:                         }
14974:                     }
14975:                 }
14976:             }
14977:             if ($showitem) {
14978:                 if ($mapres->{ID} eq '0.0') {
14979:                     push(@pathitems,&mt('Main Content'));
14980:                 } else {
14981:                     my $maptitle = $mapres->compTitle();
14982:                     $maptitle =~ s/\W+/_/g;
14983:                     if ($maptitle ne '') {
14984:                         push(@pathitems,$maptitle);
14985:                     }
14986:                 }
14987:             }
14988:         }
14989:     }
14990:     return @pathitems;
14991: }
14992: 
14993: =pod
14994: 
14995: =item * &get_turnedin_filepath()
14996: 
14997: Determines path in a user's portfolio file for storage of files uploaded
14998: to a specific essayresponse or dropbox item.
14999: 
15000: Inputs: 3 required + 1 optional.
15001: $symb is symb for resource, $uname and $udom are for current user (required).
15002: $caller is optional (can be "submission", if routine is called when storing
15003: an upoaded file when "Submit Answer" button was pressed).
15004: 
15005: Returns array containing $path and $multiresp. 
15006: $path is path in portfolio.  $multiresp is 1 if this resource contains more
15007: than one file upload item.  Callers of routine should append partid as a 
15008: subdirectory to $path in cases where $multiresp is 1.
15009: 
15010: Called by: homework/essayresponse.pm and homework/structuretags.pm
15011: 
15012: =cut
15013: 
15014: sub get_turnedin_filepath {
15015:     my ($symb,$uname,$udom,$caller) = @_;
15016:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
15017:     my $turnindir;
15018:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
15019:     $turnindir = $userhash{'turnindir'};
15020:     my ($path,$multiresp);
15021:     if ($turnindir eq '') {
15022:         if ($caller eq 'submission') {
15023:             $turnindir = &mt('turned in');
15024:             $turnindir =~ s/\W+/_/g;
15025:             my %newhash = (
15026:                             'turnindir' => $turnindir,
15027:                           );
15028:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
15029:         }
15030:     }
15031:     if ($turnindir ne '') {
15032:         $path = '/'.$turnindir.'/';
15033:         my ($multipart,$turnin,@pathitems);
15034:         my $navmap = Apache::lonnavmaps::navmap->new();
15035:         if (defined($navmap)) {
15036:             my $mapres = $navmap->getResourceByUrl($map);
15037:             if (ref($mapres)) {
15038:                 my $pcslist = $mapres->map_hierarchy();
15039:                 if ($pcslist ne '') {
15040:                     foreach my $pc (split(/,/,$pcslist)) {
15041:                         my $res = $navmap->getByMapPc($pc);
15042:                         if (ref($res)) {
15043:                             my $title = $res->compTitle();
15044:                             $title =~ s/\W+/_/g;
15045:                             if ($title ne '') {
15046:                                 if (($pc > 1) && (length($title) > 12)) {
15047:                                     $title = substr($title,0,12);
15048:                                 }
15049:                                 push(@pathitems,$title);
15050:                             }
15051:                         }
15052:                     }
15053:                 }
15054:                 my $maptitle = $mapres->compTitle();
15055:                 $maptitle =~ s/\W+/_/g;
15056:                 if ($maptitle ne '') {
15057:                     if (length($maptitle) > 12) {
15058:                         $maptitle = substr($maptitle,0,12);
15059:                     }
15060:                     push(@pathitems,$maptitle);
15061:                 }
15062:                 unless ($env{'request.state'} eq 'construct') {
15063:                     my $res = $navmap->getBySymb($symb);
15064:                     if (ref($res)) {
15065:                         my $partlist = $res->parts();
15066:                         my $totaluploads = 0;
15067:                         if (ref($partlist) eq 'ARRAY') {
15068:                             foreach my $part (@{$partlist}) {
15069:                                 my @types = $res->responseType($part);
15070:                                 my @ids = $res->responseIds($part);
15071:                                 for (my $i=0; $i < scalar(@ids); $i++) {
15072:                                     if ($types[$i] eq 'essay') {
15073:                                         my $partid = $part.'_'.$ids[$i];
15074:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
15075:                                             $totaluploads ++;
15076:                                         }
15077:                                     }
15078:                                 }
15079:                             }
15080:                             if ($totaluploads > 1) {
15081:                                 $multiresp = 1;
15082:                             }
15083:                         }
15084:                     }
15085:                 }
15086:             } else {
15087:                 return;
15088:             }
15089:         } else {
15090:             return;
15091:         }
15092:         my $restitle=&Apache::lonnet::gettitle($symb);
15093:         $restitle =~ s/\W+/_/g;
15094:         if ($restitle eq '') {
15095:             $restitle = ($resurl =~ m{/[^/]+$});
15096:             if ($restitle eq '') {
15097:                 $restitle = time;
15098:             }
15099:         }
15100:         if (length($restitle) > 12) {
15101:             $restitle = substr($restitle,0,12);
15102:         }
15103:         push(@pathitems,$restitle);
15104:         $path .= join('/',@pathitems);
15105:     }
15106:     return ($path,$multiresp);
15107: }
15108: 
15109: =pod
15110: 
15111: =back
15112: 
15113: =head1 CSV Upload/Handling functions
15114: 
15115: =over 4
15116: 
15117: =item * &upfile_store($r)
15118: 
15119: Store uploaded file, $r should be the HTTP Request object,
15120: needs $env{'form.upfile'}
15121: returns $datatoken to be put into hidden field
15122: 
15123: =cut
15124: 
15125: sub upfile_store {
15126:     my $r=shift;
15127:     $env{'form.upfile'}=~s/\r/\n/gs;
15128:     $env{'form.upfile'}=~s/\f/\n/gs;
15129:     $env{'form.upfile'}=~s/\n+/\n/gs;
15130:     $env{'form.upfile'}=~s/\n+$//gs;
15131: 
15132:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
15133:                                      '_enroll_'.$env{'request.course.id'}.'_'.
15134:                                      time.'_'.$$);
15135:     return if ($datatoken eq '');
15136: 
15137:     {
15138:         my $datafile = $r->dir_config('lonDaemons').
15139:                            '/tmp/'.$datatoken.'.tmp';
15140:         if ( open(my $fh,'>',$datafile) ) {
15141:             print $fh $env{'form.upfile'};
15142:             close($fh);
15143:         }
15144:     }
15145:     return $datatoken;
15146: }
15147: 
15148: =pod
15149: 
15150: =item * &load_tmp_file($r,$datatoken)
15151: 
15152: Load uploaded file from tmp, $r should be the HTTP Request object,
15153: $datatoken is the name to assign to the temporary file.
15154: sets $env{'form.upfile'} to the contents of the file
15155: 
15156: =cut
15157: 
15158: sub load_tmp_file {
15159:     my ($r,$datatoken) = @_;
15160:     return if ($datatoken eq '');
15161:     my @studentdata=();
15162:     {
15163:         my $studentfile = $r->dir_config('lonDaemons').
15164:                               '/tmp/'.$datatoken.'.tmp';
15165:         if ( open(my $fh,'<',$studentfile) ) {
15166:             @studentdata=<$fh>;
15167:             close($fh);
15168:         }
15169:     }
15170:     $env{'form.upfile'}=join('',@studentdata);
15171: }
15172: 
15173: sub valid_datatoken {
15174:     my ($datatoken) = @_;
15175:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
15176:         return $datatoken;
15177:     }
15178:     return;
15179: }
15180: 
15181: =pod
15182: 
15183: =item * &upfile_record_sep()
15184: 
15185: Separate uploaded file into records
15186: returns array of records,
15187: needs $env{'form.upfile'} and $env{'form.upfiletype'}
15188: 
15189: =cut
15190: 
15191: sub upfile_record_sep {
15192:     if ($env{'form.upfiletype'} eq 'xml') {
15193:     } else {
15194: 	my @records;
15195: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
15196: 	    if ($line=~/^\s*$/) { next; }
15197: 	    push(@records,$line);
15198: 	}
15199: 	return @records;
15200:     }
15201: }
15202: 
15203: =pod
15204: 
15205: =item * &record_sep($record)
15206: 
15207: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
15208: 
15209: =cut
15210: 
15211: sub takeleft {
15212:     my $index=shift;
15213:     return substr('0000'.$index,-4,4);
15214: }
15215: 
15216: sub record_sep {
15217:     my $record=shift;
15218:     my %components=();
15219:     if ($env{'form.upfiletype'} eq 'xml') {
15220:     } elsif ($env{'form.upfiletype'} eq 'space') {
15221:         my $i=0;
15222:         foreach my $field (split(/\s+/,$record)) {
15223:             $field=~s/^(\"|\')//;
15224:             $field=~s/(\"|\')$//;
15225:             $components{&takeleft($i)}=$field;
15226:             $i++;
15227:         }
15228:     } elsif ($env{'form.upfiletype'} eq 'tab') {
15229:         my $i=0;
15230:         foreach my $field (split(/\t/,$record)) {
15231:             $field=~s/^(\"|\')//;
15232:             $field=~s/(\"|\')$//;
15233:             $components{&takeleft($i)}=$field;
15234:             $i++;
15235:         }
15236:     } else {
15237:         my $separator=',';
15238:         if ($env{'form.upfiletype'} eq 'semisv') {
15239:             $separator=';';
15240:         }
15241:         my $i=0;
15242: # the character we are looking for to indicate the end of a quote or a record 
15243:         my $looking_for=$separator;
15244: # do not add the characters to the fields
15245:         my $ignore=0;
15246: # we just encountered a separator (or the beginning of the record)
15247:         my $just_found_separator=1;
15248: # store the field we are working on here
15249:         my $field='';
15250: # work our way through all characters in record
15251:         foreach my $character ($record=~/(.)/g) {
15252:             if ($character eq $looking_for) {
15253:                if ($character ne $separator) {
15254: # Found the end of a quote, again looking for separator
15255:                   $looking_for=$separator;
15256:                   $ignore=1;
15257:                } else {
15258: # Found a separator, store away what we got
15259:                   $components{&takeleft($i)}=$field;
15260: 	          $i++;
15261:                   $just_found_separator=1;
15262:                   $ignore=0;
15263:                   $field='';
15264:                }
15265:                next;
15266:             }
15267: # single or double quotation marks after a separator indicate beginning of a quote
15268: # we are now looking for the end of the quote and need to ignore separators
15269:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
15270:                $looking_for=$character;
15271:                next;
15272:             }
15273: # ignore would be true after we reached the end of a quote
15274:             if ($ignore) { next; }
15275:             if (($just_found_separator) && ($character=~/\s/)) { next; }
15276:             $field.=$character;
15277:             $just_found_separator=0; 
15278:         }
15279: # catch the very last entry, since we never encountered the separator
15280:         $components{&takeleft($i)}=$field;
15281:     }
15282:     return %components;
15283: }
15284: 
15285: ######################################################
15286: ######################################################
15287: 
15288: =pod
15289: 
15290: =item * &upfile_select_html()
15291: 
15292: Return HTML code to select a file from the users machine and specify 
15293: the file type.
15294: 
15295: =cut
15296: 
15297: ######################################################
15298: ######################################################
15299: sub upfile_select_html {
15300:     my %Types = (
15301:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
15302:                  semisv => &mt('Semicolon separated values'),
15303:                  space => &mt('Space separated'),
15304:                  tab   => &mt('Tabulator separated'),
15305: #                 xml   => &mt('HTML/XML'),
15306:                  );
15307:     my $Str = '<input type="file" name="upfile" size="50" />'.
15308:         '<br />'.&mt('Type').': <select name="upfiletype">';
15309:     foreach my $type (sort(keys(%Types))) {
15310:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
15311:     }
15312:     $Str .= "</select>\n";
15313:     return $Str;
15314: }
15315: 
15316: sub get_samples {
15317:     my ($records,$toget) = @_;
15318:     my @samples=({});
15319:     my $got=0;
15320:     foreach my $rec (@$records) {
15321: 	my %temp = &record_sep($rec);
15322: 	if (! grep(/\S/, values(%temp))) { next; }
15323: 	if (%temp) {
15324: 	    $samples[$got]=\%temp;
15325: 	    $got++;
15326: 	    if ($got == $toget) { last; }
15327: 	}
15328:     }
15329:     return \@samples;
15330: }
15331: 
15332: ######################################################
15333: ######################################################
15334: 
15335: =pod
15336: 
15337: =item * &csv_print_samples($r,$records)
15338: 
15339: Prints a table of sample values from each column uploaded $r is an
15340: Apache Request ref, $records is an arrayref from
15341: &Apache::loncommon::upfile_record_sep
15342: 
15343: =cut
15344: 
15345: ######################################################
15346: ######################################################
15347: sub csv_print_samples {
15348:     my ($r,$records) = @_;
15349:     my $samples = &get_samples($records,5);
15350: 
15351:     $r->print(&mt('Samples').'<br />'.&start_data_table().
15352:               &start_data_table_header_row());
15353:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
15354:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
15355:     $r->print(&end_data_table_header_row());
15356:     foreach my $hash (@$samples) {
15357: 	$r->print(&start_data_table_row());
15358: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
15359: 	    $r->print('<td>');
15360: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
15361: 	    $r->print('</td>');
15362: 	}
15363: 	$r->print(&end_data_table_row());
15364:     }
15365:     $r->print(&end_data_table().'<br />'."\n");
15366: }
15367: 
15368: ######################################################
15369: ######################################################
15370: 
15371: =pod
15372: 
15373: =item * &csv_print_select_table($r,$records,$d)
15374: 
15375: Prints a table to create associations between values and table columns.
15376: 
15377: $r is an Apache Request ref,
15378: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
15379: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
15380: 
15381: =cut
15382: 
15383: ######################################################
15384: ######################################################
15385: sub csv_print_select_table {
15386:     my ($r,$records,$d) = @_;
15387:     my $i=0;
15388:     my $samples = &get_samples($records,1);
15389:     $r->print(&mt('Associate columns with student attributes.')."\n".
15390: 	      &start_data_table().&start_data_table_header_row().
15391:               '<th>'.&mt('Attribute').'</th>'.
15392:               '<th>'.&mt('Column').'</th>'.
15393:               &end_data_table_header_row()."\n");
15394:     foreach my $array_ref (@$d) {
15395: 	my ($value,$display,$defaultcol)=@{ $array_ref };
15396: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
15397: 
15398: 	$r->print('<td><select name="f'.$i.'"'.
15399: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
15400: 	$r->print('<option value="none"></option>');
15401: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
15402: 	    $r->print('<option value="'.$sample.'"'.
15403:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
15404:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
15405: 	}
15406: 	$r->print('</select></td>'.&end_data_table_row()."\n");
15407: 	$i++;
15408:     }
15409:     $r->print(&end_data_table());
15410:     $i--;
15411:     return $i;
15412: }
15413: 
15414: ######################################################
15415: ######################################################
15416: 
15417: =pod
15418: 
15419: =item * &csv_samples_select_table($r,$records,$d)
15420: 
15421: Prints a table of sample values from the upload and can make associate samples to internal names.
15422: 
15423: $r is an Apache Request ref,
15424: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
15425: $d is an array of 2 element arrays (internal name, displayed name)
15426: 
15427: =cut
15428: 
15429: ######################################################
15430: ######################################################
15431: sub csv_samples_select_table {
15432:     my ($r,$records,$d) = @_;
15433:     my $i=0;
15434:     #
15435:     my $max_samples = 5;
15436:     my $samples = &get_samples($records,$max_samples);
15437:     $r->print(&start_data_table().
15438:               &start_data_table_header_row().'<th>'.
15439:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
15440:               &end_data_table_header_row());
15441: 
15442:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
15443: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
15444: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
15445: 	foreach my $option (@$d) {
15446: 	    my ($value,$display,$defaultcol)=@{ $option };
15447: 	    $r->print('<option value="'.$value.'"'.
15448:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
15449:                       $display.'</option>');
15450: 	}
15451: 	$r->print('</select></td><td>');
15452: 	foreach my $line (0..($max_samples-1)) {
15453: 	    if (defined($samples->[$line]{$key})) { 
15454: 		$r->print($samples->[$line]{$key}."<br />\n"); 
15455: 	    }
15456: 	}
15457: 	$r->print('</td>'.&end_data_table_row());
15458: 	$i++;
15459:     }
15460:     $r->print(&end_data_table());
15461:     $i--;
15462:     return($i);
15463: }
15464: 
15465: ######################################################
15466: ######################################################
15467: 
15468: =pod
15469: 
15470: =item * &clean_excel_name($name)
15471: 
15472: Returns a replacement for $name which does not contain any illegal characters.
15473: 
15474: =cut
15475: 
15476: ######################################################
15477: ######################################################
15478: sub clean_excel_name {
15479:     my ($name) = @_;
15480:     $name =~ s/[:\*\?\/\\]//g;
15481:     if (length($name) > 31) {
15482:         $name = substr($name,0,31);
15483:     }
15484:     return $name;
15485: }
15486: 
15487: =pod
15488: 
15489: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
15490: 
15491: Returns either 1 or undef
15492: 
15493: 1 if the part is to be hidden, undef if it is to be shown
15494: 
15495: Arguments are:
15496: 
15497: $id the id of the part to be checked
15498: $symb, optional the symb of the resource to check
15499: $udom, optional the domain of the user to check for
15500: $uname, optional the username of the user to check for
15501: 
15502: =cut
15503: 
15504: sub check_if_partid_hidden {
15505:     my ($id,$symb,$udom,$uname) = @_;
15506:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
15507: 					 $symb,$udom,$uname);
15508:     my $truth=1;
15509:     #if the string starts with !, then the list is the list to show not hide
15510:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
15511:     my @hiddenlist=split(/,/,$hiddenparts);
15512:     foreach my $checkid (@hiddenlist) {
15513: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
15514:     }
15515:     return !$truth;
15516: }
15517: 
15518: 
15519: ############################################################
15520: ############################################################
15521: 
15522: =pod
15523: 
15524: =back 
15525: 
15526: =head1 cgi-bin script and graphing routines
15527: 
15528: =over 4
15529: 
15530: =item * &get_cgi_id()
15531: 
15532: Inputs: none
15533: 
15534: Returns an id which can be used to pass environment variables
15535: to various cgi-bin scripts.  These environment variables will
15536: be removed from the users environment after a given time by
15537: the routine &Apache::lonnet::transfer_profile_to_env.
15538: 
15539: =cut
15540: 
15541: ############################################################
15542: ############################################################
15543: my $uniq=0;
15544: sub get_cgi_id {
15545:     $uniq=($uniq+1)%100000;
15546:     return (time.'_'.$$.'_'.$uniq);
15547: }
15548: 
15549: ############################################################
15550: ############################################################
15551: 
15552: =pod
15553: 
15554: =item * &DrawBarGraph()
15555: 
15556: Facilitates the plotting of data in a (stacked) bar graph.
15557: Puts plot definition data into the users environment in order for 
15558: graph.png to plot it.  Returns an <img> tag for the plot.
15559: The bars on the plot are labeled '1','2',...,'n'.
15560: 
15561: Inputs:
15562: 
15563: =over 4
15564: 
15565: =item $Title: string, the title of the plot
15566: 
15567: =item $xlabel: string, text describing the X-axis of the plot
15568: 
15569: =item $ylabel: string, text describing the Y-axis of the plot
15570: 
15571: =item $Max: scalar, the maximum Y value to use in the plot
15572: If $Max is < any data point, the graph will not be rendered.
15573: 
15574: =item $colors: array ref holding the colors to be used for the data sets when
15575: they are plotted.  If undefined, default values will be used.
15576: 
15577: =item $labels: array ref holding the labels to use on the x-axis for the bars.
15578: 
15579: =item @Values: An array of array references.  Each array reference holds data
15580: to be plotted in a stacked bar chart.
15581: 
15582: =item If the final element of @Values is a hash reference the key/value
15583: pairs will be added to the graph definition.
15584: 
15585: =back
15586: 
15587: Returns:
15588: 
15589: An <img> tag which references graph.png and the appropriate identifying
15590: information for the plot.
15591: 
15592: =cut
15593: 
15594: ############################################################
15595: ############################################################
15596: sub DrawBarGraph {
15597:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
15598:     #
15599:     if (! defined($colors)) {
15600:         $colors = ['#33ff00', 
15601:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
15602:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
15603:                   ]; 
15604:     }
15605:     my $extra_settings = {};
15606:     if (ref($Values[-1]) eq 'HASH') {
15607:         $extra_settings = pop(@Values);
15608:     }
15609:     #
15610:     my $identifier = &get_cgi_id();
15611:     my $id = 'cgi.'.$identifier;        
15612:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
15613:         return '';
15614:     }
15615:     #
15616:     my @Labels;
15617:     if (defined($labels)) {
15618:         @Labels = @$labels;
15619:     } else {
15620:         for (my $i=0;$i<@{$Values[0]};$i++) {
15621:             push(@Labels,$i+1);
15622:         }
15623:     }
15624:     #
15625:     my $NumBars = scalar(@{$Values[0]});
15626:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
15627:     my %ValuesHash;
15628:     my $NumSets=1;
15629:     foreach my $array (@Values) {
15630:         next if (! ref($array));
15631:         $ValuesHash{$id.'.data.'.$NumSets++} = 
15632:             join(',',@$array);
15633:     }
15634:     #
15635:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
15636:     if ($NumBars < 3) {
15637:         $width = 120+$NumBars*32;
15638:         $xskip = 1;
15639:         $bar_width = 30;
15640:     } elsif ($NumBars < 5) {
15641:         $width = 120+$NumBars*20;
15642:         $xskip = 1;
15643:         $bar_width = 20;
15644:     } elsif ($NumBars < 10) {
15645:         $width = 120+$NumBars*15;
15646:         $xskip = 1;
15647:         $bar_width = 15;
15648:     } elsif ($NumBars <= 25) {
15649:         $width = 120+$NumBars*11;
15650:         $xskip = 5;
15651:         $bar_width = 8;
15652:     } elsif ($NumBars <= 50) {
15653:         $width = 120+$NumBars*8;
15654:         $xskip = 5;
15655:         $bar_width = 4;
15656:     } else {
15657:         $width = 120+$NumBars*8;
15658:         $xskip = 5;
15659:         $bar_width = 4;
15660:     }
15661:     #
15662:     $Max = 1 if ($Max < 1);
15663:     if ( int($Max) < $Max ) {
15664:         $Max++;
15665:         $Max = int($Max);
15666:     }
15667:     $Title  = '' if (! defined($Title));
15668:     $xlabel = '' if (! defined($xlabel));
15669:     $ylabel = '' if (! defined($ylabel));
15670:     $ValuesHash{$id.'.title'}    = &escape($Title);
15671:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
15672:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
15673:     $ValuesHash{$id.'.y_max_value'} = $Max;
15674:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
15675:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
15676:     $ValuesHash{$id.'.PlotType'} = 'bar';
15677:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
15678:     $ValuesHash{$id.'.height'}   = $height;
15679:     $ValuesHash{$id.'.width'}    = $width;
15680:     $ValuesHash{$id.'.xskip'}    = $xskip;
15681:     $ValuesHash{$id.'.bar_width'} = $bar_width;
15682:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
15683:     #
15684:     # Deal with other parameters
15685:     while (my ($key,$value) = each(%$extra_settings)) {
15686:         $ValuesHash{$id.'.'.$key} = $value;
15687:     }
15688:     #
15689:     &Apache::lonnet::appenv(\%ValuesHash);
15690:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15691: }
15692: 
15693: ############################################################
15694: ############################################################
15695: 
15696: =pod
15697: 
15698: =item * &DrawXYGraph()
15699: 
15700: Facilitates the plotting of data in an XY graph.
15701: Puts plot definition data into the users environment in order for 
15702: graph.png to plot it.  Returns an <img> tag for the plot.
15703: 
15704: Inputs:
15705: 
15706: =over 4
15707: 
15708: =item $Title: string, the title of the plot
15709: 
15710: =item $xlabel: string, text describing the X-axis of the plot
15711: 
15712: =item $ylabel: string, text describing the Y-axis of the plot
15713: 
15714: =item $Max: scalar, the maximum Y value to use in the plot
15715: If $Max is < any data point, the graph will not be rendered.
15716: 
15717: =item $colors: Array ref containing the hex color codes for the data to be 
15718: plotted in.  If undefined, default values will be used.
15719: 
15720: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
15721: 
15722: =item $Ydata: Array ref containing Array refs.  
15723: Each of the contained arrays will be plotted as a separate curve.
15724: 
15725: =item %Values: hash indicating or overriding any default values which are 
15726: passed to graph.png.  
15727: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
15728: 
15729: =back
15730: 
15731: Returns:
15732: 
15733: An <img> tag which references graph.png and the appropriate identifying
15734: information for the plot.
15735: 
15736: =cut
15737: 
15738: ############################################################
15739: ############################################################
15740: sub DrawXYGraph {
15741:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
15742:     #
15743:     # Create the identifier for the graph
15744:     my $identifier = &get_cgi_id();
15745:     my $id = 'cgi.'.$identifier;
15746:     #
15747:     $Title  = '' if (! defined($Title));
15748:     $xlabel = '' if (! defined($xlabel));
15749:     $ylabel = '' if (! defined($ylabel));
15750:     my %ValuesHash = 
15751:         (
15752:          $id.'.title'  => &escape($Title),
15753:          $id.'.xlabel' => &escape($xlabel),
15754:          $id.'.ylabel' => &escape($ylabel),
15755:          $id.'.y_max_value'=> $Max,
15756:          $id.'.labels'     => join(',',@$Xlabels),
15757:          $id.'.PlotType'   => 'XY',
15758:          );
15759:     #
15760:     if (defined($colors) && ref($colors) eq 'ARRAY') {
15761:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
15762:     }
15763:     #
15764:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
15765:         return '';
15766:     }
15767:     my $NumSets=1;
15768:     foreach my $array (@{$Ydata}){
15769:         next if (! ref($array));
15770:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
15771:     }
15772:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
15773:     #
15774:     # Deal with other parameters
15775:     while (my ($key,$value) = each(%Values)) {
15776:         $ValuesHash{$id.'.'.$key} = $value;
15777:     }
15778:     #
15779:     &Apache::lonnet::appenv(\%ValuesHash);
15780:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15781: }
15782: 
15783: ############################################################
15784: ############################################################
15785: 
15786: =pod
15787: 
15788: =item * &DrawXYYGraph()
15789: 
15790: Facilitates the plotting of data in an XY graph with two Y axes.
15791: Puts plot definition data into the users environment in order for 
15792: graph.png to plot it.  Returns an <img> tag for the plot.
15793: 
15794: Inputs:
15795: 
15796: =over 4
15797: 
15798: =item $Title: string, the title of the plot
15799: 
15800: =item $xlabel: string, text describing the X-axis of the plot
15801: 
15802: =item $ylabel: string, text describing the Y-axis of the plot
15803: 
15804: =item $colors: Array ref containing the hex color codes for the data to be 
15805: plotted in.  If undefined, default values will be used.
15806: 
15807: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
15808: 
15809: =item $Ydata1: The first data set
15810: 
15811: =item $Min1: The minimum value of the left Y-axis
15812: 
15813: =item $Max1: The maximum value of the left Y-axis
15814: 
15815: =item $Ydata2: The second data set
15816: 
15817: =item $Min2: The minimum value of the right Y-axis
15818: 
15819: =item $Max2: The maximum value of the left Y-axis
15820: 
15821: =item %Values: hash indicating or overriding any default values which are 
15822: passed to graph.png.  
15823: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
15824: 
15825: =back
15826: 
15827: Returns:
15828: 
15829: An <img> tag which references graph.png and the appropriate identifying
15830: information for the plot.
15831: 
15832: =cut
15833: 
15834: ############################################################
15835: ############################################################
15836: sub DrawXYYGraph {
15837:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
15838:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
15839:     #
15840:     # Create the identifier for the graph
15841:     my $identifier = &get_cgi_id();
15842:     my $id = 'cgi.'.$identifier;
15843:     #
15844:     $Title  = '' if (! defined($Title));
15845:     $xlabel = '' if (! defined($xlabel));
15846:     $ylabel = '' if (! defined($ylabel));
15847:     my %ValuesHash = 
15848:         (
15849:          $id.'.title'  => &escape($Title),
15850:          $id.'.xlabel' => &escape($xlabel),
15851:          $id.'.ylabel' => &escape($ylabel),
15852:          $id.'.labels' => join(',',@$Xlabels),
15853:          $id.'.PlotType' => 'XY',
15854:          $id.'.NumSets' => 2,
15855:          $id.'.two_axes' => 1,
15856:          $id.'.y1_max_value' => $Max1,
15857:          $id.'.y1_min_value' => $Min1,
15858:          $id.'.y2_max_value' => $Max2,
15859:          $id.'.y2_min_value' => $Min2,
15860:          );
15861:     #
15862:     if (defined($colors) && ref($colors) eq 'ARRAY') {
15863:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
15864:     }
15865:     #
15866:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
15867:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
15868:         return '';
15869:     }
15870:     my $NumSets=1;
15871:     foreach my $array ($Ydata1,$Ydata2){
15872:         next if (! ref($array));
15873:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
15874:     }
15875:     #
15876:     # Deal with other parameters
15877:     while (my ($key,$value) = each(%Values)) {
15878:         $ValuesHash{$id.'.'.$key} = $value;
15879:     }
15880:     #
15881:     &Apache::lonnet::appenv(\%ValuesHash);
15882:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15883: }
15884: 
15885: ############################################################
15886: ############################################################
15887: 
15888: =pod
15889: 
15890: =back 
15891: 
15892: =head1 Statistics helper routines?  
15893: 
15894: Bad place for them but what the hell.
15895: 
15896: =over 4
15897: 
15898: =item * &chartlink()
15899: 
15900: Returns a link to the chart for a specific student.  
15901: 
15902: Inputs:
15903: 
15904: =over 4
15905: 
15906: =item $linktext: The text of the link
15907: 
15908: =item $sname: The students username
15909: 
15910: =item $sdomain: The students domain
15911: 
15912: =back
15913: 
15914: =back
15915: 
15916: =cut
15917: 
15918: ############################################################
15919: ############################################################
15920: sub chartlink {
15921:     my ($linktext, $sname, $sdomain) = @_;
15922:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
15923:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
15924:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
15925:        '">'.$linktext.'</a>';
15926: }
15927: 
15928: #######################################################
15929: #######################################################
15930: 
15931: =pod
15932: 
15933: =head1 Course Environment Routines
15934: 
15935: =over 4
15936: 
15937: =item * &restore_course_settings()
15938: 
15939: =item * &store_course_settings()
15940: 
15941: Restores/Store indicated form parameters from the course environment.
15942: Will not overwrite existing values of the form parameters.
15943: 
15944: Inputs: 
15945: a scalar describing the data (e.g. 'chart', 'problem_analysis')
15946: 
15947: a hash ref describing the data to be stored.  For example:
15948:    
15949: %Save_Parameters = ('Status' => 'scalar',
15950:     'chartoutputmode' => 'scalar',
15951:     'chartoutputdata' => 'scalar',
15952:     'Section' => 'array',
15953:     'Group' => 'array',
15954:     'StudentData' => 'array',
15955:     'Maps' => 'array');
15956: 
15957: Returns: both routines return nothing
15958: 
15959: =back
15960: 
15961: =cut
15962: 
15963: #######################################################
15964: #######################################################
15965: sub store_course_settings {
15966:     return &store_settings($env{'request.course.id'},@_);
15967: }
15968: 
15969: sub store_settings {
15970:     # save to the environment
15971:     # appenv the same items, just to be safe
15972:     my $udom  = $env{'user.domain'};
15973:     my $uname = $env{'user.name'};
15974:     my ($context,$prefix,$Settings) = @_;
15975:     my %SaveHash;
15976:     my %AppHash;
15977:     while (my ($setting,$type) = each(%$Settings)) {
15978:         my $basename = join('.','internal',$context,$prefix,$setting);
15979:         my $envname = 'environment.'.$basename;
15980:         if (exists($env{'form.'.$setting})) {
15981:             # Save this value away
15982:             if ($type eq 'scalar' &&
15983:                 (! exists($env{$envname}) || 
15984:                  $env{$envname} ne $env{'form.'.$setting})) {
15985:                 $SaveHash{$basename} = $env{'form.'.$setting};
15986:                 $AppHash{$envname}   = $env{'form.'.$setting};
15987:             } elsif ($type eq 'array') {
15988:                 my $stored_form;
15989:                 if (ref($env{'form.'.$setting})) {
15990:                     $stored_form = join(',',
15991:                                         map {
15992:                                             &escape($_);
15993:                                         } sort(@{$env{'form.'.$setting}}));
15994:                 } else {
15995:                     $stored_form = 
15996:                         &escape($env{'form.'.$setting});
15997:                 }
15998:                 # Determine if the array contents are the same.
15999:                 if ($stored_form ne $env{$envname}) {
16000:                     $SaveHash{$basename} = $stored_form;
16001:                     $AppHash{$envname}   = $stored_form;
16002:                 }
16003:             }
16004:         }
16005:     }
16006:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
16007:                                           $udom,$uname);
16008:     if ($put_result !~ /^(ok|delayed)/) {
16009:         &Apache::lonnet::logthis('unable to save form parameters, '.
16010:                                  'got error:'.$put_result);
16011:     }
16012:     # Make sure these settings stick around in this session, too
16013:     &Apache::lonnet::appenv(\%AppHash);
16014:     return;
16015: }
16016: 
16017: sub restore_course_settings {
16018:     return &restore_settings($env{'request.course.id'},@_);
16019: }
16020: 
16021: sub restore_settings {
16022:     my ($context,$prefix,$Settings) = @_;
16023:     while (my ($setting,$type) = each(%$Settings)) {
16024:         next if (exists($env{'form.'.$setting}));
16025:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
16026:             '.'.$setting;
16027:         if (exists($env{$envname})) {
16028:             if ($type eq 'scalar') {
16029:                 $env{'form.'.$setting} = $env{$envname};
16030:             } elsif ($type eq 'array') {
16031:                 $env{'form.'.$setting} = [ 
16032:                                            map { 
16033:                                                &unescape($_); 
16034:                                            } split(',',$env{$envname})
16035:                                            ];
16036:             }
16037:         }
16038:     }
16039: }
16040: 
16041: #######################################################
16042: #######################################################
16043: 
16044: =pod
16045: 
16046: =head1 Domain E-mail Routines  
16047: 
16048: =over 4
16049: 
16050: =item * &build_recipient_list()
16051: 
16052: Build recipient lists for following types of e-mail:
16053: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
16054: (d) Help requests, (e) Course requests needing approval, (f) loncapa
16055: module change checking, student/employee ID conflict checks, as
16056: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
16057: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
16058: 
16059: Inputs:
16060: defmail (scalar - email address of default recipient), 
16061: mailing type (scalar: errormail, packagesmail, helpdeskmail,
16062: requestsmail, updatesmail, or idconflictsmail).
16063: 
16064: defdom (domain for which to retrieve configuration settings),
16065: 
16066: origmail (scalar - email address of recipient from loncapa.conf, 
16067: i.e., predates configuration by DC via domainprefs.pm
16068: 
16069: $requname username of requester (if mailing type is helpdeskmail)
16070: 
16071: $requdom domain of requester (if mailing type is helpdeskmail)
16072: 
16073: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
16074: 
16075: 
16076: Returns: comma separated list of addresses to which to send e-mail.
16077: 
16078: =back
16079: 
16080: =cut
16081: 
16082: ############################################################
16083: ############################################################
16084: sub build_recipient_list {
16085:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
16086:     my @recipients;
16087:     my ($otheremails,$lastresort,$allbcc,$addtext);
16088:     my %domconfig =
16089:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
16090:     if (ref($domconfig{'contacts'}) eq 'HASH') {
16091:         if (exists($domconfig{'contacts'}{$mailing})) {
16092:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
16093:                 my @contacts = ('adminemail','supportemail');
16094:                 foreach my $item (@contacts) {
16095:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
16096:                         my $addr = $domconfig{'contacts'}{$item}; 
16097:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
16098:                             push(@recipients,$addr);
16099:                         }
16100:                     }
16101:                 }
16102:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
16103:                 if ($mailing eq 'helpdeskmail') {
16104:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
16105:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
16106:                         my @ok_bccs;
16107:                         foreach my $bcc (@bccs) {
16108:                             $bcc =~ s/^\s+//g;
16109:                             $bcc =~ s/\s+$//g;
16110:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
16111:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
16112:                                     push(@ok_bccs,$bcc);
16113:                                 }
16114:                             }
16115:                         }
16116:                         if (@ok_bccs > 0) {
16117:                             $allbcc = join(', ',@ok_bccs);
16118:                         }
16119:                     }
16120:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
16121:                 }
16122:             }
16123:         } elsif ($origmail ne '') {
16124:             $lastresort = $origmail;
16125:         }
16126:         if ($mailing eq 'helpdeskmail') {
16127:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
16128:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
16129:                 my ($inststatus,$inststatus_checked);
16130:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
16131:                     ($env{'user.domain'} ne 'public')) {
16132:                     $inststatus_checked = 1;
16133:                     $inststatus = $env{'environment.inststatus'};
16134:                 }
16135:                 unless ($inststatus_checked) {
16136:                     if (($requname ne '') && ($requdom ne '')) {
16137:                         if (($requname =~ /^$match_username$/) &&
16138:                             ($requdom =~ /^$match_domain$/) &&
16139:                             (&Apache::lonnet::domain($requdom))) {
16140:                             my $requhome = &Apache::lonnet::homeserver($requname,
16141:                                                                       $requdom);
16142:                             unless ($requhome eq 'no_host') {
16143:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
16144:                                 $inststatus = $userenv{'inststatus'};
16145:                                 $inststatus_checked = 1;
16146:                             }
16147:                         }
16148:                     }
16149:                 }
16150:                 unless ($inststatus_checked) {
16151:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
16152:                         my %srch = (srchby     => 'email',
16153:                                     srchdomain => $defdom,
16154:                                     srchterm   => $reqemail,
16155:                                     srchtype   => 'exact');
16156:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
16157:                         foreach my $uname (keys(%srch_results)) {
16158:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
16159:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
16160:                                 $inststatus_checked = 1;
16161:                                 last;
16162:                             }
16163:                         }
16164:                         unless ($inststatus_checked) {
16165:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
16166:                             if ($dirsrchres eq 'ok') {
16167:                                 foreach my $uname (keys(%srch_results)) {
16168:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
16169:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
16170:                                         $inststatus_checked = 1;
16171:                                         last;
16172:                                     }
16173:                                 }
16174:                             }
16175:                         }
16176:                     }
16177:                 }
16178:                 if ($inststatus ne '') {
16179:                     foreach my $status (split(/\:/,$inststatus)) {
16180:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
16181:                             my @contacts = ('adminemail','supportemail');
16182:                             foreach my $item (@contacts) {
16183:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
16184:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
16185:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
16186:                                         push(@recipients,$addr);
16187:                                     }
16188:                                 }
16189:                             }
16190:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
16191:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
16192:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
16193:                                 my @ok_bccs;
16194:                                 foreach my $bcc (@bccs) {
16195:                                     $bcc =~ s/^\s+//g;
16196:                                     $bcc =~ s/\s+$//g;
16197:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
16198:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
16199:                                             push(@ok_bccs,$bcc);
16200:                                         }
16201:                                     }
16202:                                 }
16203:                                 if (@ok_bccs > 0) {
16204:                                     $allbcc = join(', ',@ok_bccs);
16205:                                 }
16206:                             }
16207:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
16208:                             last;
16209:                         }
16210:                     }
16211:                 }
16212:             }
16213:         }
16214:     } elsif ($origmail ne '') {
16215:         $lastresort = $origmail;
16216:     }
16217:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
16218:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
16219:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
16220:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
16221:             my %what = (
16222:                           perlvar => 1,
16223:                        );
16224:             my $primary = &Apache::lonnet::domain($defdom,'primary');
16225:             if ($primary) {
16226:                 my $gotaddr;
16227:                 my ($result,$returnhash) =
16228:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
16229:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
16230:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
16231:                         $lastresort = $returnhash->{'lonSupportEMail'};
16232:                         $gotaddr = 1;
16233:                     }
16234:                 }
16235:                 unless ($gotaddr) {
16236:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
16237:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
16238:                     unless ($uintdom eq $intdom) {
16239:                         my %domconfig =
16240:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
16241:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
16242:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
16243:                                 my @contacts = ('adminemail','supportemail');
16244:                                 foreach my $item (@contacts) {
16245:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
16246:                                         my $addr = $domconfig{'contacts'}{$item};
16247:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
16248:                                             push(@recipients,$addr);
16249:                                         }
16250:                                     }
16251:                                 }
16252:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
16253:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
16254:                                 }
16255:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
16256:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
16257:                                     my @ok_bccs;
16258:                                     foreach my $bcc (@bccs) {
16259:                                         $bcc =~ s/^\s+//g;
16260:                                         $bcc =~ s/\s+$//g;
16261:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
16262:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
16263:                                                 push(@ok_bccs,$bcc);
16264:                                             }
16265:                                         }
16266:                                     }
16267:                                     if (@ok_bccs > 0) {
16268:                                         $allbcc = join(', ',@ok_bccs);
16269:                                     }
16270:                                 }
16271:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
16272:                             }
16273:                         }
16274:                     }
16275:                 }
16276:             }
16277:         }
16278:     }
16279:     if (defined($defmail)) {
16280:         if ($defmail ne '') {
16281:             push(@recipients,$defmail);
16282:         }
16283:     }
16284:     if ($otheremails) {
16285:         my @others;
16286:         if ($otheremails =~ /,/) {
16287:             @others = split(/,/,$otheremails);
16288:         } else {
16289:             push(@others,$otheremails);
16290:         }
16291:         foreach my $addr (@others) {
16292:             if (!grep(/^\Q$addr\E$/,@recipients)) {
16293:                 push(@recipients,$addr);
16294:             }
16295:         }
16296:     }
16297:     if ($mailing eq 'helpdeskmail') {
16298:         if ((!@recipients) && ($lastresort ne '')) {
16299:             push(@recipients,$lastresort);
16300:         }
16301:     } elsif ($lastresort ne '') {
16302:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
16303:             push(@recipients,$lastresort);
16304:         }
16305:     }
16306:     my $recipientlist = join(',',@recipients);
16307:     if (wantarray) {
16308:         return ($recipientlist,$allbcc,$addtext);
16309:     } else {
16310:         return $recipientlist;
16311:     }
16312: }
16313: 
16314: ############################################################
16315: ############################################################
16316: 
16317: =pod
16318: 
16319: =over 4
16320: 
16321: =item * &mime_email()
16322: 
16323: Sends an email with a possible attachment
16324: 
16325: Inputs:
16326: 
16327: =over 4
16328: 
16329: from -              Sender's email address
16330: 
16331: replyto -           Reply-To email address
16332: 
16333: to -                Email address of recipient
16334: 
16335: subject -           Subject of email
16336: 
16337: body -              Body of email
16338: 
16339: cc_string -         Carbon copy email address
16340: 
16341: bcc -               Blind carbon copy email address
16342: 
16343: attachment_path -   Path of file to be attached
16344: 
16345: file_name -         Name of file to be attached
16346: 
16347: attachment_text -   The body of an attachment of type "TEXT"
16348: 
16349: =back
16350: 
16351: =back
16352: 
16353: =cut
16354: 
16355: ############################################################
16356: ############################################################
16357: 
16358: sub mime_email {
16359:     my ($from,$replyto,$to,$subject,$body,$cc_string,$bcc,$attachment_path, 
16360:         $file_name,$attachment_text) = @_;
16361:  
16362:     my $msg = MIME::Lite->new(
16363:              From    => $from,
16364:              To      => $to,
16365:              Subject => $subject,
16366:              Type    =>'TEXT',
16367:              Data    => $body,
16368:              );
16369:     if ($replyto ne '') {
16370:         $msg->add("Reply-To" => $replyto);
16371:     }
16372:     if ($cc_string ne '') {
16373:         $msg->add("Cc" => $cc_string);
16374:     }
16375:     if ($bcc ne '') {
16376:         $msg->add("Bcc" => $bcc);
16377:     }
16378:     $msg->attr("content-type"         => "text/plain");
16379:     $msg->attr("content-type.charset" => "UTF-8");
16380:     # Attach file if given
16381:     if ($attachment_path) {
16382:         unless ($file_name) {
16383:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
16384:         }
16385:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
16386:         $msg->attach(Type     => $type,
16387:                      Path     => $attachment_path,
16388:                      Filename => $file_name
16389:                      );
16390:     # Otherwise attach text if given
16391:     } elsif ($attachment_text) {
16392:         $msg->attach(Type => 'TEXT',
16393:                      Data => $attachment_text);
16394:     }
16395:     # Send it
16396:     $msg->send('sendmail');
16397: }
16398: 
16399: ############################################################
16400: ############################################################
16401: 
16402: =pod
16403: 
16404: =head1 Course Catalog Routines
16405: 
16406: =over 4
16407: 
16408: =item * &gather_categories()
16409: 
16410: Converts category definitions - keys of categories hash stored in  
16411: coursecategories in configuration.db on the primary library server in a 
16412: domain - to an array.  Also generates javascript and idx hash used to 
16413: generate Domain Coordinator interface for editing Course Categories.
16414: 
16415: Inputs:
16416: 
16417: categories (reference to hash of category definitions).
16418: 
16419: cats (reference to array of arrays/hashes which encapsulates hierarchy of
16420:       categories and subcategories).
16421: 
16422: idx (reference to hash of counters used in Domain Coordinator interface for 
16423:       editing Course Categories).
16424: 
16425: jsarray (reference to array of categories used to create Javascript arrays for
16426:          Domain Coordinator interface for editing Course Categories).
16427: 
16428: Returns: nothing
16429: 
16430: Side effects: populates cats, idx and jsarray. 
16431: 
16432: =cut
16433: 
16434: sub gather_categories {
16435:     my ($categories,$cats,$idx,$jsarray) = @_;
16436:     my %counters;
16437:     my $num = 0;
16438:     foreach my $item (keys(%{$categories})) {
16439:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
16440:         if ($container eq '' && $depth == 0) {
16441:             $cats->[$depth][$categories->{$item}] = $cat;
16442:         } else {
16443:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
16444:         }
16445:         my ($escitem,$tail) = split(/:/,$item,2);
16446:         if ($counters{$tail} eq '') {
16447:             $counters{$tail} = $num;
16448:             $num ++;
16449:         }
16450:         if (ref($idx) eq 'HASH') {
16451:             $idx->{$item} = $counters{$tail};
16452:         }
16453:         if (ref($jsarray) eq 'ARRAY') {
16454:             push(@{$jsarray->[$counters{$tail}]},$item);
16455:         }
16456:     }
16457:     return;
16458: }
16459: 
16460: =pod
16461: 
16462: =item * &extract_categories()
16463: 
16464: Used to generate breadcrumb trails for course categories.
16465: 
16466: Inputs:
16467: 
16468: categories (reference to hash of category definitions).
16469: 
16470: cats (reference to array of arrays/hashes which encapsulates hierarchy of
16471:       categories and subcategories).
16472: 
16473: trails (reference to array of breacrumb trails for each category).
16474: 
16475: allitems (reference to hash - key is category key 
16476:          (format: escaped(name):escaped(parent category):depth in hierarchy).
16477: 
16478: idx (reference to hash of counters used in Domain Coordinator interface for
16479:       editing Course Categories).
16480: 
16481: jsarray (reference to array of categories used to create Javascript arrays for
16482:          Domain Coordinator interface for editing Course Categories).
16483: 
16484: subcats (reference to hash of arrays containing all subcategories within each 
16485:          category, -recursive)
16486: 
16487: maxd (reference to hash used to hold max depth for all top-level categories).
16488: 
16489: Returns: nothing
16490: 
16491: Side effects: populates trails and allitems hash references.
16492: 
16493: =cut
16494: 
16495: sub extract_categories {
16496:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
16497:     if (ref($categories) eq 'HASH') {
16498:         &gather_categories($categories,$cats,$idx,$jsarray);
16499:         if (ref($cats->[0]) eq 'ARRAY') {
16500:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
16501:                 my $name = $cats->[0][$i];
16502:                 my $item = &escape($name).'::0';
16503:                 my $trailstr;
16504:                 if ($name eq 'instcode') {
16505:                     $trailstr = &mt('Official courses (with institutional codes)');
16506:                 } elsif ($name eq 'communities') {
16507:                     $trailstr = &mt('Communities');
16508:                 } elsif ($name eq 'placement') {
16509:                     $trailstr = &mt('Placement Tests');
16510:                 } else {
16511:                     $trailstr = $name;
16512:                 }
16513:                 if ($allitems->{$item} eq '') {
16514:                     push(@{$trails},$trailstr);
16515:                     $allitems->{$item} = scalar(@{$trails})-1;
16516:                 }
16517:                 my @parents = ($name);
16518:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
16519:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
16520:                         my $category = $cats->[1]{$name}[$j];
16521:                         if (ref($subcats) eq 'HASH') {
16522:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
16523:                         }
16524:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
16525:                     }
16526:                 } else {
16527:                     if (ref($subcats) eq 'HASH') {
16528:                         $subcats->{$item} = [];
16529:                     }
16530:                     if (ref($maxd) eq 'HASH') {
16531:                         $maxd->{$name} = 1;
16532:                     }
16533:                 }
16534:             }
16535:         }
16536:     }
16537:     return;
16538: }
16539: 
16540: =pod
16541: 
16542: =item * &recurse_categories()
16543: 
16544: Recursively used to generate breadcrumb trails for course categories.
16545: 
16546: Inputs:
16547: 
16548: cats (reference to array of arrays/hashes which encapsulates hierarchy of
16549:       categories and subcategories).
16550: 
16551: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
16552: 
16553: category (current course category, for which breadcrumb trail is being generated).
16554: 
16555: trails (reference to array of breadcrumb trails for each category).
16556: 
16557: allitems (reference to hash - key is category key
16558:          (format: escaped(name):escaped(parent category):depth in hierarchy).
16559: 
16560: parents (array containing containers directories for current category, 
16561:          back to top level). 
16562: 
16563: Returns: nothing
16564: 
16565: Side effects: populates trails and allitems hash references
16566: 
16567: =cut
16568: 
16569: sub recurse_categories {
16570:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
16571:     my $shallower = $depth - 1;
16572:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
16573:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
16574:             my $name = $cats->[$depth]{$category}[$k];
16575:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
16576:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
16577:             if ($allitems->{$item} eq '') {
16578:                 push(@{$trails},$trailstr);
16579:                 $allitems->{$item} = scalar(@{$trails})-1;
16580:             }
16581:             my $deeper = $depth+1;
16582:             push(@{$parents},$category);
16583:             if (ref($subcats) eq 'HASH') {
16584:                 my $subcat = &escape($name).':'.$category.':'.$depth;
16585:                 for (my $j=@{$parents}; $j>=0; $j--) {
16586:                     my $higher;
16587:                     if ($j > 0) {
16588:                         $higher = &escape($parents->[$j]).':'.
16589:                                   &escape($parents->[$j-1]).':'.$j;
16590:                     } else {
16591:                         $higher = &escape($parents->[$j]).'::'.$j;
16592:                     }
16593:                     push(@{$subcats->{$higher}},$subcat);
16594:                 }
16595:             }
16596:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
16597:                                 $subcats,$maxd);
16598:             pop(@{$parents});
16599:         }
16600:     } else {
16601:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
16602:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
16603:         if ($allitems->{$item} eq '') {
16604:             push(@{$trails},$trailstr);
16605:             $allitems->{$item} = scalar(@{$trails})-1;
16606:         }
16607:         if (ref($maxd) eq 'HASH') {
16608:             if ($depth > $maxd->{$parents->[0]}) {
16609:                 $maxd->{$parents->[0]} = $depth;
16610:             }
16611:         }
16612:     }
16613:     return;
16614: }
16615: 
16616: =pod
16617: 
16618: =item * &assign_categories_table()
16619: 
16620: Create a datatable for display of hierarchical categories in a domain,
16621: with checkboxes to allow a course to be categorized. 
16622: 
16623: Inputs:
16624: 
16625: cathash - reference to hash of categories defined for the domain (from
16626:           configuration.db)
16627: 
16628: currcat - scalar with an & separated list of categories assigned to a course. 
16629: 
16630: type    - scalar contains course type (Course or Community).
16631: 
16632: disabled - scalar (optional) contains disabled="disabled" if input elements are
16633:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
16634: 
16635: Returns: $output (markup to be displayed) 
16636: 
16637: =cut
16638: 
16639: sub assign_categories_table {
16640:     my ($cathash,$currcat,$type,$disabled) = @_;
16641:     my $output;
16642:     if (ref($cathash) eq 'HASH') {
16643:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
16644:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
16645:         $maxdepth = scalar(@cats);
16646:         if (@cats > 0) {
16647:             my $itemcount = 0;
16648:             if (ref($cats[0]) eq 'ARRAY') {
16649:                 my @currcategories;
16650:                 if ($currcat ne '') {
16651:                     @currcategories = split('&',$currcat);
16652:                 }
16653:                 my $table;
16654:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
16655:                     my $parent = $cats[0][$i];
16656:                     next if ($parent eq 'instcode');
16657:                     if ($type eq 'Community') {
16658:                         next unless ($parent eq 'communities');
16659:                     } elsif ($type eq 'Placement') {
16660:                         next unless ($parent eq 'placement');
16661:                     } else {
16662:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
16663:                     }
16664:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
16665:                     my $item = &escape($parent).'::0';
16666:                     my $checked = '';
16667:                     if (@currcategories > 0) {
16668:                         if (grep(/^\Q$item\E$/,@currcategories)) {
16669:                             $checked = ' checked="checked"';
16670:                         }
16671:                     }
16672:                     my $parent_title = $parent;
16673:                     if ($parent eq 'communities') {
16674:                         $parent_title = &mt('Communities');
16675:                     } elsif ($parent eq 'placement') {
16676:                         $parent_title = &mt('Placement Tests');
16677:                     }
16678:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
16679:                               '<input type="checkbox" name="usecategory" value="'.
16680:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
16681:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
16682:                     my $depth = 1;
16683:                     push(@path,$parent);
16684:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
16685:                     pop(@path);
16686:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
16687:                     $itemcount ++;
16688:                 }
16689:                 if ($itemcount) {
16690:                     $output = &Apache::loncommon::start_data_table().
16691:                               $table.
16692:                               &Apache::loncommon::end_data_table();
16693:                 }
16694:             }
16695:         }
16696:     }
16697:     return $output;
16698: }
16699: 
16700: =pod
16701: 
16702: =item * &assign_category_rows()
16703: 
16704: Create a datatable row for display of nested categories in a domain,
16705: with checkboxes to allow a course to be categorized,called recursively.
16706: 
16707: Inputs:
16708: 
16709: itemcount - track row number for alternating colors
16710: 
16711: cats - reference to array of arrays/hashes which encapsulates hierarchy of
16712:       categories and subcategories.
16713: 
16714: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
16715: 
16716: parent - parent of current category item
16717: 
16718: path - Array containing all categories back up through the hierarchy from the
16719:        current category to the top level.
16720: 
16721: currcategories - reference to array of current categories assigned to the course
16722: 
16723: disabled - scalar (optional) contains disabled="disabled" if input elements are
16724:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
16725: 
16726: Returns: $output (markup to be displayed).
16727: 
16728: =cut
16729: 
16730: sub assign_category_rows {
16731:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
16732:     my ($text,$name,$item,$chgstr);
16733:     if (ref($cats) eq 'ARRAY') {
16734:         my $maxdepth = scalar(@{$cats});
16735:         if (ref($cats->[$depth]) eq 'HASH') {
16736:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
16737:                 my $numchildren = @{$cats->[$depth]{$parent}};
16738:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
16739:                 $text .= '<td><table class="LC_data_table">';
16740:                 for (my $j=0; $j<$numchildren; $j++) {
16741:                     $name = $cats->[$depth]{$parent}[$j];
16742:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
16743:                     my $deeper = $depth+1;
16744:                     my $checked = '';
16745:                     if (ref($currcategories) eq 'ARRAY') {
16746:                         if (@{$currcategories} > 0) {
16747:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
16748:                                 $checked = ' checked="checked"';
16749:                             }
16750:                         }
16751:                     }
16752:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
16753:                              '<input type="checkbox" name="usecategory" value="'.
16754:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
16755:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
16756:                              '</td><td>';
16757:                     if (ref($path) eq 'ARRAY') {
16758:                         push(@{$path},$name);
16759:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
16760:                         pop(@{$path});
16761:                     }
16762:                     $text .= '</td></tr>';
16763:                 }
16764:                 $text .= '</table></td>';
16765:             }
16766:         }
16767:     }
16768:     return $text;
16769: }
16770: 
16771: =pod
16772: 
16773: =back
16774: 
16775: =cut
16776: 
16777: ############################################################
16778: ############################################################
16779: 
16780: 
16781: sub commit_customrole {
16782:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context,$othdomby,$requester) = @_;
16783:     my $result = &Apache::lonnet::assigncustomrole(
16784:                      $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,
16785:                      $context,$othdomby,$requester);
16786:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
16787:                          ($start?', '.&mt('starting').' '.localtime($start):'').
16788:                          ($end?', ending '.localtime($end):'').': <b>'.$result.'</b><br />';
16789:     if (wantarray) {
16790:         return ($output,$result);
16791:     } else {
16792:         return $output;
16793:     }
16794: }
16795: 
16796: sub commit_standardrole {
16797:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits,
16798:         $othdomby,$requester) = @_;
16799:     my ($output,$logmsg,$linefeed,$result);
16800:     if ($context eq 'auto') {
16801:         $linefeed = "\n";
16802:     } else {
16803:         $linefeed = "<br />\n";
16804:     }  
16805:     if ($three eq 'st') {
16806:         $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
16807:                                       $one,$two,$sec,$context,$credits,$othdomby,
16808:                                       $requester);
16809:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
16810:             ($result eq 'unknown_course') || ($result eq 'refused')) {
16811:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
16812:         } else {
16813:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
16814:                ($start?', '.&mt('starting').' '.localtime($start):'').
16815:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
16816:             if ($context eq 'auto') {
16817:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
16818:             } else {
16819:                $output .= '<b>'.$result.'</b>'.$linefeed.
16820:                &mt('Add to classlist').': <b>ok</b>';
16821:             }
16822:             $output .= $linefeed;
16823:         }
16824:     } else {
16825:         $output = &mt('Assigning').' '.$three.' in '.$url.
16826:                ($start?', '.&mt('starting').' '.localtime($start):'').
16827:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
16828:         $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,
16829:                                               '','',$context,$othdomby,$requester);
16830:         if ($context eq 'auto') {
16831:             $output .= $result.$linefeed;
16832:         } else {
16833:             $output .= '<b>'.$result.'</b>'.$linefeed;
16834:         }
16835:     }
16836:     if (wantarray) {
16837:         return ($output,$result);
16838:     } else {
16839:         return $output;
16840:     }
16841: }
16842: 
16843: sub commit_studentrole {
16844:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
16845:         $credits,$othdomby,$requester) = @_;
16846:     my ($result,$linefeed,$oldsecurl,$newsecurl);
16847:     if ($context eq 'auto') {
16848:         $linefeed = "\n";
16849:     } else {
16850:         $linefeed = '<br />'."\n";
16851:     }
16852:     if (defined($one) && defined($two)) {
16853:         my $cid=$one.'_'.$two;
16854:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
16855:         my $secchange = 0;
16856:         my $expire_role_result;
16857:         my $modify_section_result;
16858:         if ($oldsec ne '-1') { 
16859:             if ($oldsec ne $sec) {
16860:                 $secchange = 1;
16861:                 my $now = time;
16862:                 my $uurl='/'.$cid;
16863:                 $uurl=~s/\_/\//g;
16864:                 if ($oldsec) {
16865:                     $uurl.='/'.$oldsec;
16866:                 }
16867:                 $oldsecurl = $uurl;
16868:                 $expire_role_result = 
16869:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,
16870:                                                 '','','',$context,$othdomby,$requester);
16871:                 if ($env{'request.course.sec'} ne '') {
16872:                     if ($expire_role_result eq 'refused') {
16873:                         my @roles = ('st');
16874:                         my @statuses = ('previous');
16875:                         my @roledoms = ($one);
16876:                         my $withsec = 1;
16877:                         my %roleshash = 
16878:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
16879:                                               \@statuses,\@roles,\@roledoms,$withsec);
16880:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
16881:                             my ($oldstart,$oldend) = 
16882:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
16883:                             if ($oldend > 0 && $oldend <= $now) {
16884:                                 $expire_role_result = 'ok';
16885:                             }
16886:                         }
16887:                     }
16888:                 }
16889:                 $result = $expire_role_result;
16890:             }
16891:         }
16892:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
16893:             $modify_section_result = 
16894:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
16895:                                                            undef,undef,undef,$sec,
16896:                                                            $end,$start,'','',$cid,
16897:                                                            '',$context,$credits,'',
16898:                                                            $othdomby,$requester);
16899:             if ($modify_section_result =~ /^ok/) {
16900:                 if ($secchange == 1) {
16901:                     if ($sec eq '') {
16902:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
16903:                     } else {
16904:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
16905:                     }
16906:                 } elsif ($oldsec eq '-1') {
16907:                     if ($sec eq '') {
16908:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
16909:                     } else {
16910:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
16911:                     }
16912:                 } else {
16913:                     if ($sec eq '') {
16914:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
16915:                     } else {
16916:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
16917:                     }
16918:                 }
16919:             } else {
16920:                 if ($secchange) { 
16921:                     $$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;
16922:                 } else {
16923:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
16924:                 }
16925:             }
16926:             $result = $modify_section_result;
16927:         } elsif ($secchange == 1) {
16928:             if ($oldsec eq '') {
16929:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
16930:             } else {
16931:                 $$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;
16932:             }
16933:             if ($expire_role_result eq 'refused') {
16934:                 my $newsecurl = '/'.$cid;
16935:                 $newsecurl =~ s/\_/\//g;
16936:                 if ($sec ne '') {
16937:                     $newsecurl.='/'.$sec;
16938:                 }
16939:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
16940:                     if ($sec eq '') {
16941:                         $$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;
16942:                     } else {
16943:                         $$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;
16944:                     }
16945:                 }
16946:             }
16947:         }
16948:     } else {
16949:         $$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;
16950:         $result = "error: incomplete course id\n";
16951:     }
16952:     return $result;
16953: }
16954: 
16955: sub show_role_extent {
16956:     my ($scope,$context,$role) = @_;
16957:     $scope =~ s{^/}{};
16958:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
16959:     push(@courseroles,'co');
16960:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
16961:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
16962:         $scope =~ s{/}{_};
16963:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
16964:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
16965:         my ($audom,$auname) = split(/\//,$scope);
16966:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
16967:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
16968:     } else {
16969:         $scope =~ s{/$}{};
16970:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
16971:                    &Apache::lonnet::domain($scope,'description').'</span>');
16972:     }
16973: }
16974: 
16975: ############################################################
16976: ############################################################
16977: 
16978: sub check_clone {
16979:     my ($args,$linefeed) = @_;
16980:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
16981:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
16982:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
16983:     my $clonetitle;
16984:     my @clonemsg;
16985:     my $can_clone = 0;
16986:     my $lctype = lc($args->{'crstype'});
16987:     if ($lctype ne 'community') {
16988:         $lctype = 'course';
16989:     }
16990:     if ($clonehome eq 'no_host') {
16991:         if ($args->{'crstype'} eq 'Community') {
16992:             push(@clonemsg,({
16993:                               mt => 'No new community created.',
16994:                               args => [],
16995:                             },
16996:                             {
16997:                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
16998:                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
16999:                             }));
17000:         } else {
17001:             push(@clonemsg,({
17002:                               mt => 'No new course created.',
17003:                               args => [],
17004:                             },
17005:                             {
17006:                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
17007:                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
17008:                             }));
17009:         }
17010:     } else {
17011: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
17012:         $clonetitle = $clonedesc{'description'};
17013:         if ($args->{'crstype'} eq 'Community') {
17014:             if ($clonedesc{'type'} ne 'Community') {
17015:                 push(@clonemsg,({
17016:                                   mt => 'No new community created.',
17017:                                   args => [],
17018:                                 },
17019:                                 {
17020:                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
17021:                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
17022:                                 }));
17023:                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
17024:             }
17025:         }
17026: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
17027:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
17028: 	    $can_clone = 1;
17029: 	} else {
17030: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
17031: 						 $args->{'clonedomain'},$args->{'clonecourse'});
17032:             if ($clonehash{'cloners'} eq '') {
17033:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
17034:                 if ($domdefs{'canclone'}) {
17035:                     unless ($domdefs{'canclone'} eq 'none') {
17036:                         if ($domdefs{'canclone'} eq 'domain') {
17037:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
17038:                                 $can_clone = 1;
17039:                             }
17040:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
17041:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
17042:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
17043:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
17044:                                 $can_clone = 1;
17045:                             }
17046:                         }
17047:                     }
17048:                 }
17049:             } else {
17050: 	        my @cloners = split(/,/,$clonehash{'cloners'});
17051:                 if (grep(/^\*$/,@cloners)) {
17052:                     $can_clone = 1;
17053:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
17054:                     $can_clone = 1;
17055:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
17056:                     $can_clone = 1;
17057:                 }
17058:                 unless ($can_clone) {
17059:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
17060:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
17061:                         my (%gotdomdefaults,%gotcodedefaults);
17062:                         foreach my $cloner (@cloners) {
17063:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
17064:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
17065:                                 my (%codedefaults,@code_order);
17066:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
17067:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
17068:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
17069:                                     }
17070:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
17071:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
17072:                                     }
17073:                                 } else {
17074:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
17075:                                                                             \%codedefaults,
17076:                                                                             \@code_order);
17077:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
17078:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
17079:                                 }
17080:                                 if (@code_order > 0) {
17081:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
17082:                                                                                 $cloner,$clonehash{'internal.coursecode'},
17083:                                                                                 $args->{'crscode'})) {
17084:                                         $can_clone = 1;
17085:                                         last;
17086:                                     }
17087:                                 }
17088:                             }
17089:                         }
17090:                     }
17091:                 }
17092:             }
17093:             unless ($can_clone) {
17094:                 my $ccrole = 'cc';
17095:                 if ($args->{'crstype'} eq 'Community') {
17096:                     $ccrole = 'co';
17097:                 }
17098: 	        my %roleshash =
17099: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
17100: 					          $args->{'ccdomain'},
17101:                                                   'userroles',['active'],[$ccrole],
17102: 					          [$args->{'clonedomain'}]);
17103: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
17104:                     $can_clone = 1;
17105:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
17106:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
17107:                     $can_clone = 1;
17108:                 }
17109:             }
17110:             unless ($can_clone) {
17111:                 if ($args->{'crstype'} eq 'Community') {
17112:                     push(@clonemsg,({
17113:                                       mt => 'No new community created.',
17114:                                       args => [],
17115:                                     },
17116:                                     {
17117:                                       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]).',
17118:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
17119:                                     }));
17120:                 } else {
17121:                     push(@clonemsg,({
17122:                                       mt => 'No new course created.',
17123:                                       args => [],
17124:                                     },
17125:                                     {
17126:                                       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]).',
17127:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
17128:                                     }));
17129:                 }
17130: 	    }
17131:         }
17132:     }
17133:     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
17134: }
17135: 
17136: sub construct_course {
17137:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
17138:         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
17139:     my ($outcome,$msgref,$clonemsgref);
17140:     my $linefeed =  '<br />'."\n";
17141:     if ($context eq 'auto') {
17142:         $linefeed = "\n";
17143:     }
17144: 
17145: #
17146: # Are we cloning?
17147: #
17148:     my ($can_clone,$cloneid,$clonehome,$clonetitle);
17149:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
17150: 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
17151:         if (!$can_clone) {
17152: 	    return (0,$outcome,$clonemsgref);
17153: 	}
17154:     }
17155: 
17156: #
17157: # Open course
17158: #
17159:     my $showncrstype;
17160:     if ($args->{'crstype'} eq 'Placement') {
17161:         $showncrstype = 'placement test'; 
17162:     } else {  
17163:         $showncrstype = lc($args->{'crstype'});
17164:     }
17165:     my %cenv=();
17166:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
17167:                                              $args->{'cdescr'},
17168:                                              $args->{'curl'},
17169:                                              $args->{'course_home'},
17170:                                              $args->{'nonstandard'},
17171:                                              $args->{'crscode'},
17172:                                              $args->{'ccuname'}.':'.
17173:                                              $args->{'ccdomain'},
17174:                                              $args->{'crstype'},
17175:                                              $cnum,$context,$category,
17176:                                              $callercontext);
17177: 
17178:     # Note: The testing routines depend on this being output; see 
17179:     # Utils::Course. This needs to at least be output as a comment
17180:     # if anyone ever decides to not show this, and Utils::Course::new
17181:     # will need to be suitably modified.
17182:     if (($callercontext eq 'auto') && ($user_lh ne '')) {
17183:         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
17184:     } else {
17185:         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
17186:     }
17187:     if ($$courseid =~ /^error:/) {
17188:         return (0,$outcome,$clonemsgref);
17189:     }
17190: 
17191: #
17192: # Check if created correctly
17193: #
17194:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
17195:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
17196:     if ($crsuhome eq 'no_host') {
17197:         if (($callercontext eq 'auto') && ($user_lh ne '')) {
17198:             $outcome .= &mt_user($user_lh,
17199:                             'Course creation failed, unrecognized course home server.');
17200:         } else {
17201:             $outcome .= &mt('Course creation failed, unrecognized course home server.');
17202:         }
17203:         $outcome .= $linefeed;
17204:         return (0,$outcome,$clonemsgref);
17205:     }
17206:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
17207: 
17208: #
17209: # Do the cloning
17210: #   
17211:     my @clonemsg;
17212:     if ($can_clone && $cloneid) {
17213:         push(@clonemsg,
17214:                       {
17215:                           mt => 'Created [_1] by cloning from [_2]',
17216:                           args => [$showncrstype,$clonetitle],
17217:                       });
17218: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
17219: # Copy all files
17220:         my @info =
17221: 	    &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
17222: 	                                             $args->{'dateshift'},$args->{'crscode'},
17223:                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
17224:                                                      $args->{'tinyurls'});
17225:         if (@info) {
17226:             push(@clonemsg,@info);
17227:         }
17228: # Restore URL
17229: 	$cenv{'url'}=$oldcenv{'url'};
17230: # Restore title
17231: 	$cenv{'description'}=$oldcenv{'description'};
17232: # Restore creation date, creator and creation context.
17233:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
17234:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
17235:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
17236: # Mark as cloned
17237: 	$cenv{'clonedfrom'}=$cloneid;
17238: # Need to clone grading mode
17239:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
17240:         $cenv{'grading'}=$newenv{'grading'};
17241: # Do not clone these environment entries
17242:         &Apache::lonnet::del('environment',
17243:                   ['default_enrollment_start_date',
17244:                    'default_enrollment_end_date',
17245:                    'question.email',
17246:                    'policy.email',
17247:                    'comment.email',
17248:                    'pch.users.denied',
17249:                    'plc.users.denied',
17250:                    'hidefromcat',
17251:                    'checkforpriv',
17252:                    'categories'],
17253:                    $$crsudom,$$crsunum);
17254:         if ($args->{'textbook'}) {
17255:             $cenv{'internal.textbook'} = $args->{'textbook'};
17256:         }
17257:     }
17258: 
17259: #
17260: # Set environment (will override cloned, if existing)
17261: #
17262:     my @sections = ();
17263:     my @xlists = ();
17264:     if ($args->{'crstype'}) {
17265:         $cenv{'type'}=$args->{'crstype'};
17266:     }
17267:     if ($args->{'lti'}) {
17268:         $cenv{'internal.lti'}=$args->{'lti'};
17269:     }
17270:     if ($args->{'crsid'}) {
17271:         $cenv{'courseid'}=$args->{'crsid'};
17272:     }
17273:     if ($args->{'crscode'}) {
17274:         $cenv{'internal.coursecode'}=$args->{'crscode'};
17275:     }
17276:     if ($args->{'crsquota'} ne '') {
17277:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
17278:     } else {
17279:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
17280:     }
17281:     if ($args->{'ccuname'}) {
17282:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
17283:                                         ':'.$args->{'ccdomain'};
17284:     } else {
17285:         $cenv{'internal.courseowner'} = $args->{'curruser'};
17286:     }
17287:     if ($args->{'defaultcredits'}) {
17288:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
17289:     }
17290:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
17291:     my @oklcsecs = (); # Used to accumulate LON-CAPA sections for validated institutional sections.
17292:     if ($args->{'crssections'}) {
17293:         $cenv{'internal.sectionnums'} = '';
17294:         if ($args->{'crssections'} =~ m/,/) {
17295:             @sections = split/,/,$args->{'crssections'};
17296:         } else {
17297:             $sections[0] = $args->{'crssections'};
17298:         }
17299:         if (@sections > 0) {
17300:             foreach my $item (@sections) {
17301:                 my ($sec,$gp) = split/:/,$item;
17302:                 my $class = $args->{'crscode'}.$sec;
17303:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
17304:                 $cenv{'internal.sectionnums'} .= $item.',';
17305:                 if ($addcheck eq 'ok') {
17306:                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
17307:                         push(@oklcsecs,$gp);
17308:                     }
17309:                 } else {
17310:                     push(@badclasses,$class);
17311:                 }
17312:             }
17313:             $cenv{'internal.sectionnums'} =~ s/,$//;
17314:         }
17315:     }
17316: # do not hide course coordinator from staff listing, 
17317: # even if privileged
17318:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
17319: # add course coordinator's domain to domains to check for privileged users
17320: # if different to course domain
17321:     if ($$crsudom ne $args->{'ccdomain'}) {
17322:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
17323:     }
17324: # add crosslistings
17325:     if ($args->{'crsxlist'}) {
17326:         $cenv{'internal.crosslistings'}='';
17327:         if ($args->{'crsxlist'} =~ m/,/) {
17328:             @xlists = split/,/,$args->{'crsxlist'};
17329:         } else {
17330:             $xlists[0] = $args->{'crsxlist'};
17331:         }
17332:         if (@xlists > 0) {
17333:             foreach my $item (@xlists) {
17334:                 my ($xl,$gp) = split/:/,$item;
17335:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
17336:                 $cenv{'internal.crosslistings'} .= $item.',';
17337:                 if ($addcheck eq 'ok') {
17338:                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
17339:                         push(@oklcsecs,$gp);
17340:                     }
17341:                 } else {
17342:                     push(@badclasses,$xl);
17343:                 }
17344:             }
17345:             $cenv{'internal.crosslistings'} =~ s/,$//;
17346:         }
17347:     }
17348:     if ($args->{'autoadds'}) {
17349:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
17350:     }
17351:     if ($args->{'autodrops'}) {
17352:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
17353:     }
17354: # check for notification of enrollment changes
17355:     my @notified = ();
17356:     if ($args->{'notify_owner'}) {
17357:         if ($args->{'ccuname'} ne '') {
17358:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
17359:         }
17360:     }
17361:     if ($args->{'notify_dc'}) {
17362:         if ($uname ne '') { 
17363:             push(@notified,$uname.':'.$udom);
17364:         }
17365:     }
17366:     if (@notified > 0) {
17367:         my $notifylist;
17368:         if (@notified > 1) {
17369:             $notifylist = join(',',@notified);
17370:         } else {
17371:             $notifylist = $notified[0];
17372:         }
17373:         $cenv{'internal.notifylist'} = $notifylist;
17374:     }
17375:     if (@badclasses > 0) {
17376:         my %lt=&Apache::lonlocal::texthash(
17377:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
17378:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
17379:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
17380:         );
17381:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
17382:                            &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'};
17383:         if ($context eq 'auto') {
17384:             $outcome .= $badclass_msg.$linefeed;
17385:         } else {
17386:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
17387:         }
17388:         foreach my $item (@badclasses) {
17389:             if ($context eq 'auto') {
17390:                 $outcome .= " - $item\n";
17391:             } else {
17392:                 $outcome .= "<li>$item</li>\n";
17393:             }
17394:         }
17395:         if ($context eq 'auto') {
17396:             $outcome .= $linefeed;
17397:         } else {
17398:             $outcome .= "</ul><br /><br /></div>\n";
17399:         } 
17400:     }
17401:     if ($args->{'no_end_date'}) {
17402:         $args->{'endaccess'} = 0;
17403:     }
17404: #  If an official course with institutional sections is created by cloning 
17405: #  an existing course, section-specific hiding of course totals in student's
17406: #  view of grades as copied from cloned course, will be checked for valid 
17407: #  sections.
17408:     if (($can_clone && $cloneid) &&
17409:         ($cenv{'internal.coursecode'} ne '') &&
17410:         ($cenv{'grading'} eq 'standard') &&
17411:         ($cenv{'hidetotals'} ne '') &&
17412:         ($cenv{'hidetotals'} ne 'all')) {
17413:         my @hidesecs;
17414:         my $deletehidetotals;
17415:         if (@oklcsecs) {
17416:             foreach my $sec (split(/,/,$cenv{'hidetotals'})) {
17417:                 if (grep(/^\Q$sec$/,@oklcsecs)) {
17418:                     push(@hidesecs,$sec);
17419:                 }
17420:             }
17421:             if (@hidesecs) {
17422:                 $cenv{'hidetotals'} = join(',',@hidesecs);
17423:             } else {
17424:                 $deletehidetotals = 1;
17425:             }
17426:         } else {
17427:             $deletehidetotals = 1;
17428:         }
17429:         if ($deletehidetotals) {
17430:             delete($cenv{'hidetotals'});
17431:             &Apache::lonnet::del('environment',['hidetotals'],$$crsudom,$$crsunum);
17432:         }
17433:     }
17434:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
17435:     $cenv{'internal.autoend'}=$args->{'enrollend'};
17436:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
17437:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
17438:     if ($args->{'showphotos'}) {
17439:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
17440:     }
17441:     $cenv{'internal.authtype'} = $args->{'authtype'};
17442:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
17443:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
17444:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
17445:             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'); 
17446:             if ($context eq 'auto') {
17447:                 $outcome .= $krb_msg;
17448:             } else {
17449:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
17450:             }
17451:             $outcome .= $linefeed;
17452:         }
17453:     }
17454:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
17455:        if ($args->{'setpolicy'}) {
17456:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
17457:        }
17458:        if ($args->{'setcontent'}) {
17459:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
17460:        }
17461:        if ($args->{'setcomment'}) {
17462:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
17463:        }
17464:     }
17465:     if ($args->{'reshome'}) {
17466: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
17467: 	$cenv{'reshome'}=~s/\/+$/\//;
17468:     }
17469: #
17470: # course has keyed access
17471: #
17472:     if ($args->{'setkeys'}) {
17473:        $cenv{'keyaccess'}='yes';
17474:     }
17475: # if specified, key authority is not course, but user
17476: # only active if keyaccess is yes
17477:     if ($args->{'keyauth'}) {
17478: 	my ($user,$domain) = split(':',$args->{'keyauth'});
17479: 	$user = &LONCAPA::clean_username($user);
17480: 	$domain = &LONCAPA::clean_username($domain);
17481: 	if ($user ne '' && $domain ne '') {
17482: 	    $cenv{'keyauth'}=$user.':'.$domain;
17483: 	}
17484:     }
17485: 
17486: #
17487: #  generate and store uniquecode (available to course requester), if course should have one.
17488: #
17489:     if ($args->{'uniquecode'}) {
17490:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
17491:         if ($code) {
17492:             $cenv{'internal.uniquecode'} = $code;
17493:             my %crsinfo =
17494:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
17495:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
17496:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
17497:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
17498:             } 
17499:             if (ref($coderef)) {
17500:                 $$coderef = $code;
17501:             }
17502:         }
17503:     }
17504: 
17505:     if ($args->{'disresdis'}) {
17506:         $cenv{'pch.roles.denied'}='st';
17507:     }
17508:     if ($args->{'disablechat'}) {
17509:         $cenv{'plc.roles.denied'}='st';
17510:     }
17511: 
17512:     # Record we've not yet viewed the Course Initialization Helper for this 
17513:     # course
17514:     $cenv{'course.helper.not.run'} = 1;
17515:     #
17516:     # Use new Randomseed
17517:     #
17518:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
17519:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
17520:     #
17521:     # The encryption code and receipt prefix for this course
17522:     #
17523:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
17524:     $cenv{'internal.encpref'}=100+int(9*rand(99));
17525:     #
17526:     # By default, use standard grading
17527:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
17528: 
17529:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
17530:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
17531: #
17532: # Open all assignments
17533: #
17534:     if ($args->{'openall'}) {
17535:        my $opendate = time;
17536:        if ($args->{'openallfrom'} =~ /^\d+$/) {
17537:            $opendate = $args->{'openallfrom'};
17538:        }
17539:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
17540:        my %storecontent = ($storeunder         => $opendate,
17541:                            $storeunder.'.type' => 'date_start');
17542:        $outcome .= &mt('All assignments open starting [_1]',
17543:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
17544:                    &Apache::lonnet::cput
17545:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
17546:    }
17547: #
17548: # Set first page
17549: #
17550:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
17551: 	    || ($cloneid)) {
17552: 	$outcome .= &mt('Setting first resource').': ';
17553: 
17554: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
17555:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
17556: 
17557:         $outcome .= ($fatal?$errtext:'read ok').' - ';
17558:         my $title; my $url;
17559:         if ($args->{'firstres'} eq 'syl') {
17560: 	    $title=&mt('Syllabus');
17561:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
17562:         } else {
17563:             $title=&mt('Table of Contents');
17564:             $url='/adm/navmaps';
17565:         }
17566: 
17567:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
17568: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
17569: 
17570: 	if ($errtext) { $fatal=2; }
17571:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
17572:     }
17573: 
17574: # 
17575: # Set params for Placement Tests
17576: #
17577:     if ($args->{'crstype'} eq 'Placement') {
17578:        my %storecontent; 
17579:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
17580:        my %defaults = (
17581:                         buttonshide   => { value => 'yes',
17582:                                            type => 'string_yesno',},
17583:                         type          => { value => 'randomizetry',
17584:                                            type  => 'string_questiontype',},
17585:                         maxtries      => { value => 1,
17586:                                            type => 'int_pos',},
17587:                         problemstatus => { value => 'no',
17588:                                            type  => 'string_problemstatus',},
17589:                       );
17590:        foreach my $key (keys(%defaults)) {
17591:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
17592:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
17593:        }
17594:        &Apache::lonnet::cput
17595:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
17596:     }
17597: 
17598:     return (1,$outcome,\@clonemsg);
17599: }
17600: 
17601: sub make_unique_code {
17602:     my ($cdom,$cnum) = @_;
17603:     # get lock on uniquecodes db
17604:     my $lockhash = {
17605:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
17606:                                                   ':'.$env{'user.domain'},
17607:                    };
17608:     my $tries = 0;
17609:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
17610:     my ($code,$error);
17611:   
17612:     while (($gotlock ne 'ok') && ($tries<3)) {
17613:         $tries ++;
17614:         sleep 1;
17615:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
17616:     }
17617:     if ($gotlock eq 'ok') {
17618:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
17619:         my $gotcode;
17620:         my $attempts = 0;
17621:         while ((!$gotcode) && ($attempts < 100)) {
17622:             $code = &generate_code();
17623:             if (!exists($currcodes{$code})) {
17624:                 $gotcode = 1;
17625:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
17626:                     $error = 'nostore';
17627:                 }
17628:             }
17629:             $attempts ++;
17630:         }
17631:         my @del_lock = ($cnum."\0".'uniquecodes');
17632:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
17633:     } else {
17634:         $error = 'nolock';
17635:     }
17636:     return ($code,$error);
17637: }
17638: 
17639: sub generate_code {
17640:     my $code;
17641:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
17642:     for (my $i=0; $i<6; $i++) {
17643:         my $lettnum = int (rand 2);
17644:         my $item = '';
17645:         if ($lettnum) {
17646:             $item = $letts[int( rand(18) )];
17647:         } else {
17648:             $item = 1+int( rand(8) );
17649:         }
17650:         $code .= $item;
17651:     }
17652:     return $code;
17653: }
17654: 
17655: ############################################################
17656: ############################################################
17657: 
17658: # Community, Course and Placement Test
17659: sub course_type {
17660:     my ($cid) = @_;
17661:     if (!defined($cid)) {
17662:         $cid = $env{'request.course.id'};
17663:     }
17664:     if (defined($env{'course.'.$cid.'.type'})) {
17665:         return $env{'course.'.$cid.'.type'};
17666:     } else {
17667:         return 'Course';
17668:     }
17669: }
17670: 
17671: sub group_term {
17672:     my $crstype = &course_type();
17673:     my %names = (
17674:                   'Course' => 'group',
17675:                   'Community' => 'group',
17676:                   'Placement' => 'group',
17677:                 );
17678:     return $names{$crstype};
17679: }
17680: 
17681: sub course_types {
17682:     my @types = ('official','unofficial','community','textbook','placement','lti');
17683:     my %typename = (
17684:                          official   => 'Official course',
17685:                          unofficial => 'Unofficial course',
17686:                          community  => 'Community',
17687:                          textbook   => 'Textbook course',
17688:                          placement  => 'Placement test',
17689:                          lti        => 'LTI provider',
17690:                    );
17691:     return (\@types,\%typename);
17692: }
17693: 
17694: sub icon {
17695:     my ($file)=@_;
17696:     my $curfext = lc((split(/\./,$file))[-1]);
17697:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
17698:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
17699:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
17700: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
17701: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
17702: 	            $curfext.".gif") {
17703: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
17704: 		$curfext.".gif";
17705: 	}
17706:     }
17707:     return &lonhttpdurl($iconname);
17708: } 
17709: 
17710: sub lonhttpdurl {
17711: #
17712: # Had been used for "small fry" static images on separate port 8080.
17713: # Modify here if lightweight http functionality desired again.
17714: # Currently eliminated due to increasing firewall issues.
17715: #
17716:     my ($url)=@_;
17717:     return $url;
17718: }
17719: 
17720: sub connection_aborted {
17721:     my ($r)=@_;
17722:     $r->print(" ");$r->rflush();
17723:     my $c = $r->connection;
17724:     return $c->aborted();
17725: }
17726: 
17727: #    Escapes strings that may have embedded 's that will be put into
17728: #    strings as 'strings'.
17729: sub escape_single {
17730:     my ($input) = @_;
17731:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
17732:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
17733:     return $input;
17734: }
17735: 
17736: #  Same as escape_single, but escape's "'s  This 
17737: #  can be used for  "strings"
17738: sub escape_double {
17739:     my ($input) = @_;
17740:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
17741:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
17742:     return $input;
17743: }
17744:  
17745: #   Escapes the last element of a full URL.
17746: sub escape_url {
17747:     my ($url)   = @_;
17748:     my @urlslices = split(/\//, $url,-1);
17749:     my $lastitem = &escape(pop(@urlslices));
17750:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
17751: }
17752: 
17753: sub compare_arrays {
17754:     my ($arrayref1,$arrayref2) = @_;
17755:     my (@difference,%count);
17756:     @difference = ();
17757:     %count = ();
17758:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
17759:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
17760:         foreach my $element (keys(%count)) {
17761:             if ($count{$element} == 1) {
17762:                 push(@difference,$element);
17763:             }
17764:         }
17765:     }
17766:     return @difference;
17767: }
17768: 
17769: sub lon_status_items {
17770:     my %defaults = (
17771:                      E         => 100,
17772:                      W         => 4,
17773:                      N         => 1,
17774:                      U         => 5,
17775:                      threshold => 200,
17776:                      sysmail   => 2500,
17777:                    );
17778:     my %names = (
17779:                    E => 'Errors',
17780:                    W => 'Warnings',
17781:                    N => 'Notices',
17782:                    U => 'Unsent',
17783:                 );
17784:     return (\%defaults,\%names);
17785: }
17786: 
17787: # -------------------------------------------------------- Initialize user login
17788: sub init_user_environment {
17789:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
17790:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
17791: 
17792:     my $public=($username eq 'public' && $domain eq 'public');
17793: 
17794:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv,
17795:         $coauthorenv);
17796:     my $now=time;
17797: 
17798:     if ($public) {
17799: 	my $max_public=100;
17800: 	my $oldest;
17801: 	my $oldest_time=0;
17802: 	for(my $next=1;$next<=$max_public;$next++) {
17803: 	    if (-e $lonids."/publicuser_$next.id") {
17804: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
17805: 		if ($mtime<$oldest_time || !$oldest_time) {
17806: 		    $oldest_time=$mtime;
17807: 		    $oldest=$next;
17808: 		}
17809: 	    } else {
17810: 		$cookie="publicuser_$next";
17811: 		last;
17812: 	    }
17813: 	}
17814: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
17815:     } else {
17816: 	# See if old ID present, if so, remove if this isn't a robot,
17817: 	# killing any existing non-robot sessions
17818: 	if (!$args->{'robot'}) {
17819: 	    opendir(DIR,$lonids);
17820: 	    while ($filename=readdir(DIR)) {
17821: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
17822:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
17823:                             &GDBM_READER(),0640)) {
17824:                         my $linkedfile;
17825:                         if (exists($oldenv{'user.linkedenv'})) {
17826:                             $linkedfile = $oldenv{'user.linkedenv'};
17827:                         }
17828:                         untie(%oldenv);
17829:                         if (unlink("$lonids/$filename")) {
17830:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
17831:                                 if (-l "$lonids/$linkedfile.id") {
17832:                                     unlink("$lonids/$linkedfile.id");
17833:                                 }
17834:                             }
17835:                         }
17836:                     } else {
17837:                         unlink($lonids.'/'.$filename);
17838:                     }
17839: 		}
17840: 	    }
17841: 	    closedir(DIR);
17842: # If there is a undeleted lockfile for the user's paste buffer remove it.
17843:             my $namespace = 'nohist_courseeditor';
17844:             my $lockingkey = 'paste'."\0".'locked_num';
17845:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
17846:                                                 $domain,$username);
17847:             if (exists($lockhash{$lockingkey})) {
17848:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
17849:                 unless ($delresult eq 'ok') {
17850:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
17851:                 }
17852:             }
17853: 	}
17854: # Give them a new cookie
17855: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
17856: 		                   : $now.$$.int(rand(10000)));
17857: 	$cookie="$username\_$id\_$domain\_$authhost";
17858:     
17859: # Initialize roles
17860: 
17861: 	($userroles,$firstaccenv,$timerintenv,$coauthorenv) = 
17862:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
17863:     }
17864: # ------------------------------------ Check browser type and MathML capability
17865: 
17866:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
17867:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
17868: 
17869: # ------------------------------------------------------------- Get environment
17870: 
17871:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
17872:     my ($tmp) = keys(%userenv);
17873:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
17874: 	undef(%userenv);
17875:     }
17876:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
17877: 	$form->{'interface'}=$userenv{'interface'};
17878:     }
17879:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
17880: 
17881: # --------------- Do not trust query string to be put directly into environment
17882:     foreach my $option ('interface','localpath','localres') {
17883:         $form->{$option}=~s/[\n\r\=]//gs;
17884:     }
17885: # --------------------------------------------------------- Write first profile
17886: 
17887:     {
17888:         my $ip = &Apache::lonnet::get_requestor_ip($r);
17889: 	my %initial_env = 
17890: 	    ("user.name"          => $username,
17891: 	     "user.domain"        => $domain,
17892: 	     "user.home"          => $authhost,
17893: 	     "browser.type"       => $clientbrowser,
17894: 	     "browser.version"    => $clientversion,
17895: 	     "browser.mathml"     => $clientmathml,
17896: 	     "browser.unicode"    => $clientunicode,
17897: 	     "browser.os"         => $clientos,
17898:              "browser.mobile"     => $clientmobile,
17899:              "browser.info"       => $clientinfo,
17900:              "browser.osversion"  => $clientosversion,
17901: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
17902: 	     "request.course.fn"  => '',
17903: 	     "request.course.uri" => '',
17904: 	     "request.course.sec" => '',
17905: 	     "request.role"       => 'cm',
17906: 	     "request.role.adv"   => $env{'user.adv'},
17907: 	     "request.host"       => $ip,);
17908: 
17909:         if ($form->{'localpath'}) {
17910: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
17911: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
17912:         }
17913: 	
17914: 	if ($form->{'interface'}) {
17915: 	    $form->{'interface'}=~s/\W//gs;
17916: 	    $initial_env{"browser.interface"} = $form->{'interface'};
17917: 	    $env{'browser.interface'}=$form->{'interface'};
17918: 	}
17919: 
17920:         if ($form->{'iptoken'}) {
17921:             my $lonhost = $r->dir_config('lonHostID');
17922:             $initial_env{"user.noloadbalance"} = $lonhost;
17923:             $env{'user.noloadbalance'} = $lonhost;
17924:         }
17925: 
17926:         if ($form->{'noloadbalance'}) {
17927:             my @hosts = &Apache::lonnet::current_machine_ids();
17928:             my $hosthere = $form->{'noloadbalance'};
17929:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
17930:                 $initial_env{"user.noloadbalance"} = $hosthere;
17931:                 $env{'user.noloadbalance'} = $hosthere;
17932:             }
17933:         }
17934: 
17935:         unless ($domain eq 'public') {
17936:             my %is_adv = ( is_adv => $env{'user.adv'} );
17937:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
17938: 
17939:             foreach my $tool ('aboutme','blog','webdav','portfolio','portaccess','timezone') {
17940:                 $userenv{'availabletools.'.$tool} =
17941:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
17942:                                                       undef,\%userenv,\%domdef,\%is_adv);
17943:             }
17944: 
17945:             foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
17946:                 $userenv{'canrequest.'.$crstype} =
17947:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
17948:                                                       'reload','requestcourses',
17949:                                                       \%userenv,\%domdef,\%is_adv);
17950:             }
17951: 
17952:             if ((ref($userroles) eq 'HASH') && ($userroles->{'user.author'}) &&
17953:                 (exists($userroles->{"user.role.au./$domain/"}))) {
17954:                 if ($userenv{'authoreditors'}) {
17955:                     $userenv{'editors'} = $userenv{'authoreditors'};
17956:                 } elsif ($domdef{'editors'} ne '') {
17957:                     $userenv{'editors'} = $domdef{'editors'};
17958:                 } else {
17959:                     $userenv{'editors'} = 'edit,xml';
17960:                 }
17961:             }
17962: 
17963:             $userenv{'canrequest.author'} =
17964:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
17965:                                                   'reload','requestauthor',
17966:                                                   \%userenv,\%domdef,\%is_adv);
17967:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
17968:                                                  $domain,$username);
17969:             my $reqstatus = $reqauthor{'author_status'};
17970:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
17971:                 if (ref($reqauthor{'author'}) eq 'HASH') {
17972:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
17973:                                                       $reqauthor{'author'}{'timestamp'};
17974:                 }
17975:             }
17976:             my ($types,$typename) = &course_types();
17977:             if (ref($types) eq 'ARRAY') {
17978:                 my @options = ('approval','validate','autolimit');
17979:                 my $optregex = join('|',@options);
17980:                 my (%willtrust,%trustchecked);
17981:                 foreach my $type (@{$types}) {
17982:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
17983:                     if ($dom_str ne '') {
17984:                         my $updatedstr = '';
17985:                         my @possdomains = split(',',$dom_str);
17986:                         foreach my $entry (@possdomains) {
17987:                             my ($extdom,$extopt) = split(':',$entry);
17988:                             unless ($trustchecked{$extdom}) {
17989:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
17990:                                 $trustchecked{$extdom} = 1;
17991:                             }
17992:                             if ($willtrust{$extdom}) {
17993:                                 $updatedstr .= $entry.',';
17994:                             }
17995:                         }
17996:                         $updatedstr =~ s/,$//;
17997:                         if ($updatedstr) {
17998:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
17999:                         } else {
18000:                             delete($userenv{'reqcrsotherdom.'.$type});
18001:                         }
18002:                     }
18003:                 }
18004:             }
18005:         }
18006: 	$env{'user.environment'} = "$lonids/$cookie.id";
18007: 
18008: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
18009: 		 &GDBM_WRCREAT(),0640)) {
18010: 	    &_add_to_env(\%disk_env,\%initial_env);
18011: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
18012: 	    &_add_to_env(\%disk_env,$userroles);
18013:             if (ref($firstaccenv) eq 'HASH') {
18014:                 &_add_to_env(\%disk_env,$firstaccenv);
18015:             }
18016:             if (ref($timerintenv) eq 'HASH') {
18017:                 &_add_to_env(\%disk_env,$timerintenv);
18018:             }
18019:             if (ref($coauthorenv) eq 'HASH') {
18020:                 if (keys(%{$coauthorenv})) {
18021:                     &_add_to_env(\%disk_env,$coauthorenv);
18022:                 }
18023:             }
18024: 	    if (ref($args->{'extra_env'})) {
18025: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
18026: 	    }
18027: 	    untie(%disk_env);
18028: 	} else {
18029: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
18030: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
18031: 	    return 'error: '.$!;
18032: 	}
18033:     }
18034:     $env{'request.role'}='cm';
18035:     $env{'request.role.adv'}=$env{'user.adv'};
18036:     $env{'browser.type'}=$clientbrowser;
18037: 
18038:     return $cookie;
18039: 
18040: }
18041: 
18042: sub _add_to_env {
18043:     my ($idf,$env_data,$prefix) = @_;
18044:     if (ref($env_data) eq 'HASH') {
18045:         while (my ($key,$value) = each(%$env_data)) {
18046: 	    $idf->{$prefix.$key} = $value;
18047: 	    $env{$prefix.$key}   = $value;
18048:         }
18049:     }
18050: }
18051: 
18052: # --- Get the symbolic name of a problem and the url
18053: sub get_symb {
18054:     my ($request,$silent) = @_;
18055:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
18056:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
18057:     if ($symb eq '') {
18058:         if (!$silent) {
18059:             if (ref($request)) { 
18060:                 $request->print("Unable to handle ambiguous references:$url:.");
18061:             }
18062:             return ();
18063:         }
18064:     }
18065:     &Apache::lonenc::check_decrypt(\$symb);
18066:     return ($symb);
18067: }
18068: 
18069: # --------------------------------------------------------------Get annotation
18070: 
18071: sub get_annotation {
18072:     my ($symb,$enc) = @_;
18073: 
18074:     my $key = $symb;
18075:     if (!$enc) {
18076:         $key =
18077:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
18078:     }
18079:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
18080:     return $annotation{$key};
18081: }
18082: 
18083: sub clean_symb {
18084:     my ($symb,$delete_enc) = @_;
18085: 
18086:     &Apache::lonenc::check_decrypt(\$symb);
18087:     my $enc = $env{'request.enc'};
18088:     if ($delete_enc) {
18089:         delete($env{'request.enc'});
18090:     }
18091: 
18092:     return ($symb,$enc);
18093: }
18094: 
18095: ############################################################
18096: ############################################################
18097: 
18098: =pod
18099: 
18100: =head1 Routines for building display used to search for courses
18101: 
18102: 
18103: =over 4
18104: 
18105: =item * &build_filters()
18106: 
18107: Create markup for a table used to set filters to use when selecting
18108: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
18109: and quotacheck.pl
18110: 
18111: 
18112: Inputs:
18113: 
18114: filterlist - anonymous array of fields to include as potential filters 
18115: 
18116: crstype - course type
18117: 
18118: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
18119:               to pop-open a course selector (will contain "extra element"). 
18120: 
18121: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
18122: 
18123: filter - anonymous hash of criteria and their values
18124: 
18125: action - form action
18126: 
18127: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
18128: 
18129: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
18130: 
18131: cloneruname - username of owner of new course who wants to clone
18132: 
18133: clonerudom - domain of owner of new course who wants to clone
18134: 
18135: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
18136: 
18137: codetitlesref - reference to array of titles of components in institutional codes (official courses)
18138: 
18139: codedom - domain
18140: 
18141: formname - value of form element named "form". 
18142: 
18143: fixeddom - domain, if fixed.
18144: 
18145: prevphase - value to assign to form element named "phase" when going back to the previous screen  
18146: 
18147: cnameelement - name of form element in form on opener page which will receive title of selected course 
18148: 
18149: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
18150: 
18151: cdomelement - name of form element in form on opener page which will receive domain of selected course
18152: 
18153: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
18154: 
18155: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
18156: 
18157: clonewarning - warning message about missing information for intended course owner when DC creates a course
18158: 
18159: 
18160: Returns: $output - HTML for display of search criteria, and hidden form elements.
18161: 
18162: 
18163: Side Effects: None
18164: 
18165: =cut
18166: 
18167: # ---------------------------------------------- search for courses based on last activity etc.
18168: 
18169: sub build_filters {
18170:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
18171:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
18172:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
18173:         $cnameelement,$cnumelement,$cdomelement,$setroles,
18174:         $clonetext,$clonewarning) = @_;
18175:     my ($list,$jscript);
18176:     my $onchange = 'javascript:updateFilters(this)';
18177:     my ($domainselectform,$sincefilterform,$createdfilterform,
18178:         $ownerdomselectform,$persondomselectform,$instcodeform,
18179:         $typeselectform,$instcodetitle);
18180:     if ($formname eq '') {
18181:         $formname = $caller;
18182:     }
18183:     foreach my $item (@{$filterlist}) {
18184:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
18185:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
18186:             if ($item eq 'domainfilter') {
18187:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
18188:             } elsif ($item eq 'coursefilter') {
18189:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
18190:             } elsif ($item eq 'ownerfilter') {
18191:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
18192:             } elsif ($item eq 'ownerdomfilter') {
18193:                 $filter->{'ownerdomfilter'} =
18194:                     &LONCAPA::clean_domain($filter->{$item});
18195:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
18196:                                                        'ownerdomfilter',1);
18197:             } elsif ($item eq 'personfilter') {
18198:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
18199:             } elsif ($item eq 'persondomfilter') {
18200:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
18201:                                                         'persondomfilter',1);
18202:             } else {
18203:                 $filter->{$item} =~ s/\W//g;
18204:             }
18205:             if (!$filter->{$item}) {
18206:                 $filter->{$item} = '';
18207:             }
18208:         }
18209:         if ($item eq 'domainfilter') {
18210:             my $allow_blank = 1;
18211:             if ($formname eq 'portform') {
18212:                 $allow_blank=0;
18213:             } elsif ($formname eq 'studentform') {
18214:                 $allow_blank=0;
18215:             }
18216:             if ($fixeddom) {
18217:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
18218:                                     ' value="'.$codedom.'" />'.
18219:                                     &Apache::lonnet::domain($codedom,'description');
18220:             } else {
18221:                 $domainselectform = &select_dom_form($filter->{$item},
18222:                                                      'domainfilter',
18223:                                                       $allow_blank,'',$onchange);
18224:             }
18225:         } else {
18226:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
18227:         }
18228:     }
18229: 
18230:     # last course activity filter and selection
18231:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
18232: 
18233:     # course created filter and selection
18234:     if (exists($filter->{'createdfilter'})) {
18235:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
18236:     }
18237: 
18238:     my $prefix = $crstype;
18239:     if ($crstype eq 'Placement') {
18240:         $prefix = 'Placement Test'
18241:     }
18242:     my %lt = &Apache::lonlocal::texthash(
18243:                 'cac' => "$prefix Activity",
18244:                 'ccr' => "$prefix Created",
18245:                 'cde' => "$prefix Title",
18246:                 'cdo' => "$prefix Domain",
18247:                 'ins' => 'Institutional Code',
18248:                 'inc' => 'Institutional Categorization',
18249:                 'cow' => "$prefix Owner/Co-owner",
18250:                 'cop' => "$prefix Personnel Includes",
18251:                 'cog' => 'Type',
18252:              );
18253: 
18254:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
18255:         my $typeval = 'Course';
18256:         if ($crstype eq 'Community') {
18257:             $typeval = 'Community';
18258:         } elsif ($crstype eq 'Placement') {
18259:             $typeval = 'Placement';
18260:         }
18261:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
18262:     } else {
18263:         $typeselectform =  '<select name="type" size="1"';
18264:         if ($onchange) {
18265:             $typeselectform .= ' onchange="'.$onchange.'"';
18266:         }
18267:         $typeselectform .= '>'."\n";
18268:         foreach my $posstype ('Course','Community','Placement') {
18269:             my $shown;
18270:             if ($posstype eq 'Placement') {
18271:                 $shown = &mt('Placement Test');
18272:             } else {
18273:                 $shown = &mt($posstype);
18274:             }
18275:             $typeselectform.='<option value="'.$posstype.'"'.
18276:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
18277:         }
18278:         $typeselectform.="</select>";
18279:     }
18280: 
18281:     my ($cloneableonlyform,$cloneabletitle);
18282:     if (exists($filter->{'cloneableonly'})) {
18283:         my $cloneableon = '';
18284:         my $cloneableoff = ' checked="checked"';
18285:         if ($filter->{'cloneableonly'}) {
18286:             $cloneableon = $cloneableoff;
18287:             $cloneableoff = '';
18288:         }
18289:         $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>';
18290:         if ($formname eq 'ccrs') {
18291:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
18292:         } else {
18293:             $cloneabletitle = &mt('Cloneable by you');
18294:         }
18295:     }
18296:     my $officialjs;
18297:     if ($crstype eq 'Course') {
18298:         if (exists($filter->{'instcodefilter'})) {
18299: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
18300: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
18301:             if ($codedom) { 
18302:                 $officialjs = 1;
18303:                 ($instcodeform,$jscript,$$numtitlesref) =
18304:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
18305:                                                                   $officialjs,$codetitlesref);
18306:                 if ($jscript) {
18307:                     $jscript = '<script type="text/javascript">'."\n".
18308:                                '// <![CDATA['."\n".
18309:                                $jscript."\n".
18310:                                '// ]]>'."\n".
18311:                                '</script>'."\n";
18312:                 }
18313:             }
18314:             if ($instcodeform eq '') {
18315:                 $instcodeform =
18316:                     '<input type="text" name="instcodefilter" size="10" value="'.
18317:                     $list->{'instcodefilter'}.'" />';
18318:                 $instcodetitle = $lt{'ins'};
18319:             } else {
18320:                 $instcodetitle = $lt{'inc'};
18321:             }
18322:             if ($fixeddom) {
18323:                 $instcodetitle .= '<br />('.$codedom.')';
18324:             }
18325:         }
18326:     }
18327:     my $output = qq|
18328: <form method="post" name="filterpicker" action="$action">
18329: <input type="hidden" name="form" value="$formname" />
18330: |;
18331:     if ($formname eq 'modifycourse') {
18332:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
18333:                    '<input type="hidden" name="prevphase" value="'.
18334:                    $prevphase.'" />'."\n";
18335:     } elsif ($formname eq 'quotacheck') {
18336:         $output .= qq|
18337: <input type="hidden" name="sortby" value="" />
18338: <input type="hidden" name="sortorder" value="" />
18339: |;
18340:     } else {
18341:         my $name_input;
18342:         if ($cnameelement ne '') {
18343:             $name_input = '<input type="hidden" name="cnameelement" value="'.
18344:                           $cnameelement.'" />';
18345:         }
18346:         $output .= qq|
18347: <input type="hidden" name="cnumelement" value="$cnumelement" />
18348: <input type="hidden" name="cdomelement" value="$cdomelement" />
18349: $name_input
18350: $roleelement
18351: $multelement
18352: $typeelement
18353: |;
18354:         if ($formname eq 'portform') {
18355:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
18356:         }
18357:     }
18358:     if ($fixeddom) {
18359:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
18360:     }
18361:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
18362:     if ($sincefilterform) {
18363:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
18364:                   .$sincefilterform
18365:                   .&Apache::lonhtmlcommon::row_closure();
18366:     }
18367:     if ($createdfilterform) {
18368:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
18369:                   .$createdfilterform
18370:                   .&Apache::lonhtmlcommon::row_closure();
18371:     }
18372:     if ($domainselectform) {
18373:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
18374:                   .$domainselectform
18375:                   .&Apache::lonhtmlcommon::row_closure();
18376:     }
18377:     if ($typeselectform) {
18378:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
18379:             $output .= $typeselectform;
18380:         } else {
18381:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
18382:                       .$typeselectform
18383:                       .&Apache::lonhtmlcommon::row_closure();
18384:         }
18385:     }
18386:     if ($instcodeform) {
18387:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
18388:                   .$instcodeform
18389:                   .&Apache::lonhtmlcommon::row_closure();
18390:     }
18391:     if (exists($filter->{'ownerfilter'})) {
18392:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
18393:                    '<table><tr><td>'.&mt('Username').'<br />'.
18394:                    '<input type="text" name="ownerfilter" size="20" value="'.
18395:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
18396:                    $ownerdomselectform.'</td></tr></table>'.
18397:                    &Apache::lonhtmlcommon::row_closure();
18398:     }
18399:     if (exists($filter->{'personfilter'})) {
18400:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
18401:                    '<table><tr><td>'.&mt('Username').'<br />'.
18402:                    '<input type="text" name="personfilter" size="20" value="'.
18403:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
18404:                    $persondomselectform.'</td></tr></table>'.
18405:                    &Apache::lonhtmlcommon::row_closure();
18406:     }
18407:     if (exists($filter->{'coursefilter'})) {
18408:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
18409:                   .'<input type="text" name="coursefilter" size="25" value="'
18410:                   .$list->{'coursefilter'}.'" />'
18411:                   .&Apache::lonhtmlcommon::row_closure();
18412:     }
18413:     if ($cloneableonlyform) {
18414:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
18415:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
18416:     }
18417:     if (exists($filter->{'descriptfilter'})) {
18418:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
18419:                   .'<input type="text" name="descriptfilter" size="40" value="'
18420:                   .$list->{'descriptfilter'}.'" />'
18421:                   .&Apache::lonhtmlcommon::row_closure(1);
18422:     }
18423:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
18424:                '<input type="hidden" name="updater" value="" />'."\n".
18425:                '<input type="submit" name="gosearch" value="'.
18426:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
18427:     return $jscript.$clonewarning.$output;
18428: }
18429: 
18430: =pod 
18431: 
18432: =item * &timebased_select_form()
18433: 
18434: Create markup for a dropdown list used to select a time-based
18435: filter e.g., Course Activity, Course Created, when searching for courses
18436: or communities
18437: 
18438: Inputs:
18439: 
18440: item - name of form element (sincefilter or createdfilter)
18441: 
18442: filter - anonymous hash of criteria and their values
18443: 
18444: Returns: HTML for a select box contained a blank, then six time selections,
18445:          with value set in incoming form variables currently selected. 
18446: 
18447: Side Effects: None
18448: 
18449: =cut
18450: 
18451: sub timebased_select_form {
18452:     my ($item,$filter) = @_;
18453:     if (ref($filter) eq 'HASH') {
18454:         $filter->{$item} =~ s/[^\d-]//g;
18455:         if (!$filter->{$item}) { $filter->{$item}=-1; }
18456:         return &select_form(
18457:                             $filter->{$item},
18458:                             $item,
18459:                             {      '-1' => '',
18460:                                 '86400' => &mt('today'),
18461:                                '604800' => &mt('last week'),
18462:                               '2592000' => &mt('last month'),
18463:                               '7776000' => &mt('last three months'),
18464:                              '15552000' => &mt('last six months'),
18465:                              '31104000' => &mt('last year'),
18466:                     'select_form_order' =>
18467:                            ['-1','86400','604800','2592000','7776000',
18468:                             '15552000','31104000']});
18469:     }
18470: }
18471: 
18472: =pod
18473: 
18474: =item * &js_changer()
18475: 
18476: Create script tag containing Javascript used to submit course search form
18477: when course type or domain is changed, and also to hide 'Searching ...' on
18478: page load completion for page showing search result.
18479: 
18480: Inputs: None
18481: 
18482: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
18483: 
18484: Side Effects: None
18485: 
18486: =cut
18487: 
18488: sub js_changer {
18489:     return <<ENDJS;
18490: <script type="text/javascript">
18491: // <![CDATA[
18492: function updateFilters(caller) {
18493:     if (typeof(caller) != "undefined") {
18494:         document.filterpicker.updater.value = caller.name;
18495:     }
18496:     document.filterpicker.submit();
18497: }
18498: 
18499: function hideSearching() {
18500:     if (document.getElementById('searching')) {
18501:         document.getElementById('searching').style.display = 'none';
18502:     }
18503:     return;
18504: }
18505: 
18506: // ]]>
18507: </script>
18508: 
18509: ENDJS
18510: }
18511: 
18512: =pod
18513: 
18514: =item * &search_courses()
18515: 
18516: Process selected filters form course search form and pass to lonnet::courseiddump
18517: to retrieve a hash for which keys are courseIDs which match the selected filters.
18518: 
18519: Inputs:
18520: 
18521: dom - domain being searched 
18522: 
18523: type - course type ('Course' or 'Community' or '.' if any).
18524: 
18525: filter - anonymous hash of criteria and their values
18526: 
18527: numtitles - for institutional codes - number of categories
18528: 
18529: cloneruname - optional username of new course owner
18530: 
18531: clonerudom - optional domain of new course owner
18532: 
18533: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
18534:             (used when DC is using course creation form)
18535: 
18536: codetitles - reference to array of titles of components in institutional codes (official courses).
18537: 
18538: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
18539:            (and so can clone automatically)
18540: 
18541: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
18542: 
18543: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
18544:               courses to clone 
18545: 
18546: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
18547: 
18548: 
18549: Side Effects: None
18550: 
18551: =cut
18552: 
18553: 
18554: sub search_courses {
18555:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
18556:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
18557:     my (%courses,%showcourses,$cloner);
18558:     if (($filter->{'ownerfilter'} ne '') ||
18559:         ($filter->{'ownerdomfilter'} ne '')) {
18560:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
18561:                                        $filter->{'ownerdomfilter'};
18562:     }
18563:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
18564:         if (!$filter->{$item}) {
18565:             $filter->{$item}='.';
18566:         }
18567:     }
18568:     my $now = time;
18569:     my $timefilter =
18570:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
18571:     my ($createdbefore,$createdafter);
18572:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
18573:         $createdbefore = $now;
18574:         $createdafter = $now-$filter->{'createdfilter'};
18575:     }
18576:     my ($instcodefilter,$regexpok);
18577:     if ($numtitles) {
18578:         if ($env{'form.official'} eq 'on') {
18579:             $instcodefilter =
18580:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
18581:             $regexpok = 1;
18582:         } elsif ($env{'form.official'} eq 'off') {
18583:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
18584:             unless ($instcodefilter eq '') {
18585:                 $regexpok = -1;
18586:             }
18587:         }
18588:     } else {
18589:         $instcodefilter = $filter->{'instcodefilter'};
18590:     }
18591:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
18592:     if ($type eq '') { $type = '.'; }
18593: 
18594:     if (($clonerudom ne '') && ($cloneruname ne '')) {
18595:         $cloner = $cloneruname.':'.$clonerudom;
18596:     }
18597:     %courses = &Apache::lonnet::courseiddump($dom,
18598:                                              $filter->{'descriptfilter'},
18599:                                              $timefilter,
18600:                                              $instcodefilter,
18601:                                              $filter->{'combownerfilter'},
18602:                                              $filter->{'coursefilter'},
18603:                                              undef,undef,$type,$regexpok,undef,undef,
18604:                                              undef,undef,$cloner,$cc_clone,
18605:                                              $filter->{'cloneableonly'},
18606:                                              $createdbefore,$createdafter,undef,
18607:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
18608:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
18609:         my $ccrole;
18610:         if ($type eq 'Community') {
18611:             $ccrole = 'co';
18612:         } else {
18613:             $ccrole = 'cc';
18614:         }
18615:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
18616:                                                      $filter->{'persondomfilter'},
18617:                                                      'userroles',undef,
18618:                                                      [$ccrole,'in','ad','ep','ta','cr'],
18619:                                                      $dom);
18620:         foreach my $role (keys(%rolehash)) {
18621:             my ($cnum,$cdom,$courserole) = split(':',$role);
18622:             my $cid = $cdom.'_'.$cnum;
18623:             if (exists($courses{$cid})) {
18624:                 if (ref($courses{$cid}) eq 'HASH') {
18625:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
18626:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
18627:                             push(@{$courses{$cid}{roles}},$courserole);
18628:                         }
18629:                     } else {
18630:                         $courses{$cid}{roles} = [$courserole];
18631:                     }
18632:                     $showcourses{$cid} = $courses{$cid};
18633:                 }
18634:             }
18635:         }
18636:         %courses = %showcourses;
18637:     }
18638:     return %courses;
18639: }
18640: 
18641: =pod
18642: 
18643: =back
18644: 
18645: =head1 Routines for version requirements for current course.
18646: 
18647: =over 4
18648: 
18649: =item * &check_release_required()
18650: 
18651: Compares required LON-CAPA version with version on server, and
18652: if required version is newer looks for a server with the required version.
18653: 
18654: Looks first at servers in user's owen domain; if none suitable, looks at
18655: servers in course's domain are permitted to host sessions for user's domain.
18656: 
18657: Inputs:
18658: 
18659: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
18660: 
18661: $courseid - Course ID of current course
18662: 
18663: $rolecode - User's current role in course (for switchserver query string).
18664: 
18665: $required - LON-CAPA version needed by course (format: Major.Minor).
18666: 
18667: 
18668: Returns:
18669: 
18670: $switchserver - query string tp append to /adm/switchserver call (if 
18671:                 current server's LON-CAPA version is too old. 
18672: 
18673: $warning - Message is displayed if no suitable server could be found.
18674: 
18675: =cut
18676: 
18677: sub check_release_required {
18678:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
18679:     my ($switchserver,$warning);
18680:     if ($required ne '') {
18681:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
18682:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
18683:         if ($reqdmajor ne '' && $reqdminor ne '') {
18684:             my $otherserver;
18685:             if (($major eq '' && $minor eq '') ||
18686:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
18687:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
18688:                 my $switchlcrev =
18689:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
18690:                                                            $userdomserver);
18691:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
18692:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
18693:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
18694:                     my $cdom = $env{'course.'.$courseid.'.domain'};
18695:                     if ($cdom ne $env{'user.domain'}) {
18696:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
18697:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
18698:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
18699:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
18700:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
18701:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
18702:                         my $canhost =
18703:                             &Apache::lonnet::can_host_session($env{'user.domain'},
18704:                                                               $coursedomserver,
18705:                                                               $remoterev,
18706:                                                               $udomdefaults{'remotesessions'},
18707:                                                               $defdomdefaults{'hostedsessions'});
18708: 
18709:                         if ($canhost) {
18710:                             $otherserver = $coursedomserver;
18711:                         } else {
18712:                             $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.");
18713:                         }
18714:                     } else {
18715:                         $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).");
18716:                     }
18717:                 } else {
18718:                     $otherserver = $userdomserver;
18719:                 }
18720:             }
18721:             if ($otherserver ne '') {
18722:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
18723:             }
18724:         }
18725:     }
18726:     return ($switchserver,$warning);
18727: }
18728: 
18729: =pod
18730: 
18731: =item * &check_release_result()
18732: 
18733: Inputs:
18734: 
18735: $switchwarning - Warning message if no suitable server found to host session.
18736: 
18737: $switchserver - query string to append to /adm/switchserver containing lonHostID
18738:                 and current role.
18739: 
18740: Returns: HTML to display with information about requirement to switch server.
18741:          Either displaying warning with link to Roles/Courses screen or
18742:          display link to switchserver.
18743: 
18744: =cut
18745: 
18746: sub check_release_result {
18747:     my ($switchwarning,$switchserver) = @_;
18748:     my $output = &start_page('Selected course unavailable on this server').
18749:                  '<p class="LC_warning">';
18750:     if ($switchwarning) {
18751:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
18752:         if (&show_course()) {
18753:             $output .= &mt('Display courses');
18754:         } else {
18755:             $output .= &mt('Display roles');
18756:         }
18757:         $output .= '</a>';
18758:     } elsif ($switchserver) {
18759:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
18760:                    '<br />'.
18761:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
18762:                    &mt('Switch Server').
18763:                    '</a>';
18764:     }
18765:     $output .= '</p>'.&end_page();
18766:     return $output;
18767: }
18768: 
18769: =pod
18770: 
18771: =item * &needs_coursereinit()
18772: 
18773: Determine if course contents stored for user's session needs to be
18774: refreshed, because content has changed since "Big Hash" last tied.
18775: 
18776: Check for change is made if time last checked is more than 10 minutes ago
18777: (by default).
18778: 
18779: Inputs:
18780: 
18781: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
18782: 
18783: $interval (optional) - Time which may elapse (in s) between last check for content
18784:                        change in current course. (default: 600 s).  
18785: 
18786: Returns: an array; first element is:
18787: 
18788: =over 4
18789: 
18790: 'switch' - if content updates mean user's session
18791:            needs to be switched to a server running a newer LON-CAPA version
18792:  
18793: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
18794:            on current server hosting user's session                
18795: 
18796: ''       - if no action required.
18797: 
18798: =back
18799: 
18800: If first item element is 'switch':
18801: 
18802: second item is $switchwarning - Warning message if no suitable server found to host session. 
18803: 
18804: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
18805:                               and current role. 
18806: 
18807: otherwise: no other elements returned.
18808: 
18809: =back
18810: 
18811: =cut
18812: 
18813: sub needs_coursereinit {
18814:     my ($loncaparev,$interval) = @_;
18815:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
18816:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
18817:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
18818:     my $now = time;
18819:     if ($interval eq '') {
18820:         $interval = 600;
18821:     }
18822:     if (($now-$env{'request.course.timechecked'})>$interval) {
18823:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
18824:         my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
18825:         if ($blocked) {
18826:             return ();
18827:         }
18828:         my $update;
18829:         my $lastmainchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
18830:         my $lastsuppchange = &Apache::lonnet::get_suppchange($cdom,$cnum);
18831:         if ($lastmainchange > $env{'request.course.tied'}) {
18832:             my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
18833:             if ($needswitch) {
18834:                 return ('switch',$switchwarning,$switchserver);
18835:             }
18836:             $update = 'main';
18837:         }
18838:         if ($lastsuppchange > $env{'request.course.suppupdated'}) {
18839:             if ($update) {
18840:                 $update = 'both';
18841:             } else {
18842:                 my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
18843:                 if ($needswitch) {
18844:                     return ('switch',$switchwarning,$switchserver);
18845:                 } else {
18846:                     $update = 'supp';
18847:                 }
18848:             }
18849:             return ($update);
18850:         }
18851:     }
18852:     return ();
18853: }
18854: 
18855: sub switch_for_update {
18856:     my ($loncaparev,$cdom,$cnum) = @_;
18857:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
18858:     if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
18859:         my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
18860:         if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
18861:             &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
18862:                                     $curr_reqd_hash{'internal.releaserequired'}});
18863:             my ($switchserver,$switchwarning) =
18864:                 &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
18865:                                         $curr_reqd_hash{'internal.releaserequired'});
18866:             if ($switchwarning ne '' || $switchserver ne '') {
18867:                 return ('switch',$switchwarning,$switchserver);
18868:             }
18869:         }
18870:     }
18871:     return ();
18872: }
18873: 
18874: sub update_content_constraints {
18875:     my ($cdom,$cnum,$chome,$cid) = @_;
18876:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
18877:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
18878:     my (%checkresponsetypes,%checkcrsrestypes);
18879:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
18880:         my ($item,$name,$value) = split(/:/,$key);
18881:         if ($item eq 'resourcetag') {
18882:             if ($name eq 'responsetype') {
18883:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
18884:             }
18885:         } elsif ($item eq 'course') {
18886:             if ($name eq 'courserestype') {
18887:                 $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
18888:             }
18889:         }
18890:     }
18891:     my $navmap = Apache::lonnavmaps::navmap->new();
18892:     if (defined($navmap)) {
18893:         my (%allresponses,%allcrsrestypes);
18894:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
18895:             if ($res->is_tool()) {
18896:                 if ($allcrsrestypes{'exttool'}) {
18897:                     $allcrsrestypes{'exttool'} ++;
18898:                 } else {
18899:                     $allcrsrestypes{'exttool'} = 1;
18900:                 }
18901:                 next;
18902:             }
18903:             my %responses = $res->responseTypes();
18904:             foreach my $key (keys(%responses)) {
18905:                 next unless(exists($checkresponsetypes{$key}));
18906:                 $allresponses{$key} += $responses{$key};
18907:             }
18908:         }
18909:         foreach my $key (keys(%allresponses)) {
18910:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
18911:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
18912:                 ($reqdmajor,$reqdminor) = ($major,$minor);
18913:             }
18914:         }
18915:         foreach my $key (keys(%allcrsrestypes)) {
18916:             my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
18917:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
18918:                 ($reqdmajor,$reqdminor) = ($major,$minor);
18919:             }
18920:         }
18921:         undef($navmap);
18922:     }
18923:     if (&Apache::lonnet::count_supptools($cnum,$cdom,1)) {
18924:         my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
18925:         if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
18926:             ($reqdmajor,$reqdminor) = ($major,$minor);
18927:         }
18928:     }
18929:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
18930:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
18931:     }
18932:     return;
18933: }
18934: 
18935: sub allmaps_incourse {
18936:     my ($cdom,$cnum,$chome,$cid) = @_;
18937:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
18938:         $cid = $env{'request.course.id'};
18939:         $cdom = $env{'course.'.$cid.'.domain'};
18940:         $cnum = $env{'course.'.$cid.'.num'};
18941:         $chome = $env{'course.'.$cid.'.home'};
18942:     }
18943:     my %allmaps = ();
18944:     my $lastchange =
18945:         &Apache::lonnet::get_coursechange($cdom,$cnum);
18946:     if ($lastchange > $env{'request.course.tied'}) {
18947:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
18948:         unless ($ferr) {
18949:             &update_content_constraints($cdom,$cnum,$chome,$cid);
18950:         }
18951:     }
18952:     my $navmap = Apache::lonnavmaps::navmap->new();
18953:     if (defined($navmap)) {
18954:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
18955:             $allmaps{$res->src()} = 1;
18956:         }
18957:     }
18958:     return \%allmaps;
18959: }
18960: 
18961: sub parse_supplemental_title {
18962:     my ($title) = @_;
18963: 
18964:     my ($foldertitle,$renametitle);
18965:     if ($title =~ /&amp;&amp;&amp;/) {
18966:         $title = &HTML::Entites::decode($title);
18967:     }
18968:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
18969:         $renametitle=$4;
18970:         my ($time,$uname,$udom) = ($1,$2,$3);
18971:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
18972:         my $name =  &plainname($uname,$udom);
18973:         $name = &HTML::Entities::encode($name,'"<>&\'');
18974:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
18975:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.$name;
18976:         if ($foldertitle ne '') {
18977:             $title .= ': <br />'.$foldertitle;
18978:         }
18979:     }
18980:     if (wantarray) {
18981:         return ($title,$foldertitle,$renametitle);
18982:     }
18983:     return $title;
18984: }
18985: 
18986: sub get_supplemental {
18987:     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
18988:     my $hashid=$cnum.':'.$cdom;
18989:     my ($supplemental,$cached,$set_httprefs);
18990:     unless ($ignorecache) {
18991:         ($supplemental,$cached) = &Apache::lonnet::is_cached_new('supplemental',$hashid);
18992:     }
18993:     unless (defined($cached)) {
18994:         my $chome=&Apache::lonnet::homeserver($cnum,$cdom);
18995:         unless ($chome eq 'no_host') {
18996:             my @order = @LONCAPA::map::order;
18997:             my @resources = @LONCAPA::map::resources;
18998:             my @resparms = @LONCAPA::map::resparms;
18999:             my @zombies = @LONCAPA::map::zombies;
19000:             my ($errors,%ids,%hidden);
19001:             $errors =
19002:                 &recurse_supplemental($cnum,$cdom,'supplemental.sequence',
19003:                                       $errors,$possdel,\%ids,\%hidden);
19004:             @LONCAPA::map::order = @order;
19005:             @LONCAPA::map::resources = @resources;
19006:             @LONCAPA::map::resparms = @resparms;
19007:             @LONCAPA::map::zombies = @zombies;
19008:             $set_httprefs = 1;
19009:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
19010:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
19011:             }
19012:             $supplemental = {
19013:                                ids => \%ids,
19014:                                hidden => \%hidden,
19015:                             };
19016:             &Apache::lonnet::do_cache_new('supplemental',$hashid,$supplemental,600);
19017:         }
19018:     }
19019:     return ($supplemental,$set_httprefs);
19020: }
19021: 
19022: sub recurse_supplemental {
19023:     my ($cnum,$cdom,$suppmap,$errors,$possdel,$suppids,$hiddensupp,$hidden) = @_;
19024:     if (($suppmap) && (ref($suppids) eq 'HASH') && (ref($hiddensupp) eq 'HASH')) {
19025:         my $mapnum;
19026:         if ($suppmap eq 'supplemental.sequence') {
19027:             $mapnum = 0;
19028:         } else {
19029:             ($mapnum) = ($suppmap =~ /^supplemental_(\d+)\.sequence$/);
19030:         }
19031:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
19032:         if ($fatal) {
19033:             $errors ++;
19034:         } else {
19035:             my @order = @LONCAPA::map::order;
19036:             if (@order > 0) {
19037:                 my @resources = @LONCAPA::map::resources;
19038:                 my @resparms = @LONCAPA::map::resparms;
19039:                 foreach my $idx (@order) {
19040:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$resources[$idx]);
19041:                     if (($src ne '') && ($status eq 'res')) {
19042:                         my $id = $mapnum.':'.$idx;
19043:                         push(@{$suppids->{$src}},$id);
19044:                         if (($hidden) || (&get_supp_parameter($resparms[$idx],'parameter_hiddenresource') =~ /^yes/i)) {
19045:                             $hiddensupp->{$id} = 1;
19046:                         }
19047:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
19048:                             $errors = &recurse_supplemental($cnum,$cdom,$1,$errors,$possdel,$suppids,
19049:                                                             $hiddensupp,$hiddensupp->{$id});
19050:                         } else {
19051:                             my $allowed;
19052:                             if (($env{'request.role.adv'}) || (!$hiddensupp->{$id})) {
19053:                                 $allowed = 1;
19054:                             } elsif ($possdel) {
19055:                                 foreach my $item (@{$suppids->{$src}}) {
19056:                                     next if ($item eq $id);
19057:                                     unless ($hiddensupp->{$item}) {
19058:                                        $allowed = 1;
19059:                                        last;
19060:                                     }
19061:                                 }
19062:                                 if ((!$allowed) && (exists($env{'httpref.'.$src}))) {
19063:                                     &Apache::lonnet::delenv('httpref.'.$src);
19064:                                 }
19065:                             }
19066:                             if ($allowed && (!exists($env{'httpref.'.$src}))) {
19067:                                 &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
19068:                             }
19069:                         }
19070:                     }
19071:                 }
19072:             }
19073:         }
19074:     }
19075:     return $errors;
19076: }
19077: 
19078: sub set_supp_httprefs {
19079:     my ($cnum,$cdom,$supplemental,$possdel) = @_;
19080:     if (ref($supplemental) eq 'HASH') {
19081:         if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
19082:             foreach my $src (keys(%{$supplemental->{'ids'}})) {
19083:                 next if ($src =~ /\.sequence$/);
19084:                 if (ref($supplemental->{'ids'}->{$src}) eq 'ARRAY') {
19085:                     my $allowed;
19086:                     if ($env{'request.role.adv'}) {
19087:                         $allowed = 1;
19088:                     } else {
19089:                         foreach my $id (@{$supplemental->{'ids'}->{$src}}) {
19090:                             unless ($supplemental->{'hidden'}->{$id}) {
19091:                                 $allowed = 1;
19092:                                 last;
19093:                             }
19094:                         }
19095:                     }
19096:                     if (exists($env{'httpref.'.$src})) {
19097:                         if ($possdel) {
19098:                             unless ($allowed) {
19099:                                 &Apache::lonnet::delenv('httpref.'.$src);
19100:                             }
19101:                         }
19102:                     } elsif ($allowed) {
19103:                         &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
19104:                     }
19105:                 }
19106:             }
19107:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
19108:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
19109:             }
19110:         }
19111:     }
19112: }
19113: 
19114: sub get_supp_parameter {
19115:     my ($resparm,$name)=@_;
19116:     return if ($resparm eq '');
19117:     my $value=undef;
19118:     my $ptype=undef;
19119:     foreach (split('&&&',$resparm)) {
19120:         my ($thistype,$thisname,$thisvalue)=split('___',$_);
19121:         if ($thisname eq $name) {
19122:             $value=$thisvalue;
19123:             $ptype=$thistype;
19124:         }
19125:     }
19126:     return $value;
19127: }
19128: 
19129: sub symb_to_docspath {
19130:     my ($symb,$navmapref) = @_;
19131:     return unless ($symb && ref($navmapref));
19132:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
19133:     if ($resurl=~/\.(sequence|page)$/) {
19134:         $mapurl=$resurl;
19135:     } elsif ($resurl eq 'adm/navmaps') {
19136:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
19137:     }
19138:     my $mapresobj;
19139:     unless (ref($$navmapref)) {
19140:         $$navmapref = Apache::lonnavmaps::navmap->new();
19141:     }
19142:     if (ref($$navmapref)) {
19143:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
19144:     }
19145:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
19146:     my $type=$2;
19147:     my $path;
19148:     if (ref($mapresobj)) {
19149:         my $pcslist = $mapresobj->map_hierarchy();
19150:         if ($pcslist ne '') {
19151:             foreach my $pc (split(/,/,$pcslist)) {
19152:                 next if ($pc <= 1);
19153:                 my $res = $$navmapref->getByMapPc($pc);
19154:                 if (ref($res)) {
19155:                     my $thisurl = $res->src();
19156:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
19157:                     my $thistitle = $res->title();
19158:                     $path .= '&'.
19159:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
19160:                              &escape($thistitle).
19161:                              ':'.$res->randompick().
19162:                              ':'.$res->randomout().
19163:                              ':'.$res->encrypted().
19164:                              ':'.$res->randomorder().
19165:                              ':'.$res->is_page();
19166:                 }
19167:             }
19168:         }
19169:         $path =~ s/^\&//;
19170:         my $maptitle = $mapresobj->title();
19171:         if ($mapurl eq 'default') {
19172:             $maptitle = 'Main Content';
19173:         }
19174:         $path .= (($path ne '')? '&' : '').
19175:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
19176:                  &escape($maptitle).
19177:                  ':'.$mapresobj->randompick().
19178:                  ':'.$mapresobj->randomout().
19179:                  ':'.$mapresobj->encrypted().
19180:                  ':'.$mapresobj->randomorder().
19181:                  ':'.$mapresobj->is_page();
19182:     } else {
19183:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
19184:         my $ispage = (($type eq 'page')? 1 : '');
19185:         if ($mapurl eq 'default') {
19186:             $maptitle = 'Main Content';
19187:         }
19188:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
19189:                 &escape($maptitle).':::::'.$ispage;
19190:     }
19191:     unless ($mapurl eq 'default') {
19192:         $path = 'default&'.
19193:                 &escape('Main Content').
19194:                 ':::::&'.$path;
19195:     }
19196:     return $path;
19197: }
19198: 
19199: sub validate_folderpath {
19200:     my ($supplementalflag,$allowed,$coursenum,$coursedom) = @_;
19201:     if ($env{'form.folderpath'} ne '') {
19202:         my @items = split(/\&/,$env{'form.folderpath'});
19203:         my ($badpath,$changed,$got_supp,$supppath,%supphidden,%suppids);
19204:         for (my $i=0; $i<@items; $i++) {
19205:             my $odd = $i%2;
19206:             if (($odd) && (!$supplementalflag) && ($items[$i] !~ /^[^:]*:(|\d+):(|1):(|1):(|1):(|1)$/)) {
19207:                 $badpath = 1;
19208:             } elsif ($odd && $supplementalflag) {
19209:                 my $idx = $i-1;
19210:                 if ($items[$i] =~ /^([^:]*)::(|1):::$/) {
19211:                     my $esc_name = $1;
19212:                     if ((!$allowed) || ($items[$idx] eq 'supplemental')) {
19213:                         $supppath .= '&'.$esc_name;
19214:                         $changed = 1;
19215:                     } else {
19216:                         $supppath .= '&'.$items[$i];
19217:                     }
19218:                 } elsif (($allowed) && ($items[$idx] ne 'supplemental')) {
19219:                     $changed = 1;
19220:                     my $is_hidden;
19221:                     unless ($got_supp) {
19222:                         my ($supplemental) = &get_supplemental($coursenum,$coursedom);
19223:                         if (ref($supplemental) eq 'HASH') {
19224:                             if (ref($supplemental->{'hidden'}) eq 'HASH') {
19225:                                 %supphidden = %{$supplemental->{'hidden'}};
19226:                             }
19227:                             if (ref($supplemental->{'ids'}) eq 'HASH') {
19228:                                 %suppids = %{$supplemental->{'ids'}};
19229:                             }
19230:                         }
19231:                         $got_supp = 1;
19232:                     }
19233:                     if (ref($suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}) eq 'ARRAY') {
19234:                         my $mapid = $suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}->[0];
19235:                         if ($supphidden{$mapid}) {
19236:                             $is_hidden = 1;
19237:                         }
19238:                     }
19239:                     $supppath .= '&'.$items[$i].'::'.$is_hidden.':::';
19240:                 } else {
19241:                     $supppath .= '&'.$items[$i];
19242:                 }
19243:             } elsif ((!$odd) && ($items[$i] !~ /^(default|supplemental)(|_\d+)$/)) {
19244:                 $badpath = 1;
19245:             } elsif ($supplementalflag) {
19246:                 $supppath .= '&'.$items[$i];
19247:             }
19248:             last if ($badpath);
19249:         }
19250:         if ($badpath) {
19251:             delete($env{'form.folderpath'});
19252:         } elsif ($changed && $supplementalflag) {
19253:             $supppath =~ s/^\&//;
19254:             $env{'form.folderpath'} = $supppath;
19255:         }
19256:     }
19257:     return;
19258: }
19259: 
19260: sub captcha_display {
19261:     my ($context,$lonhost,$defdom) = @_;
19262:     my ($output,$error);
19263:     my ($captcha,$pubkey,$privkey,$version) = 
19264:         &get_captcha_config($context,$lonhost,$defdom);
19265:     if ($captcha eq 'original') {
19266:         $output = &create_captcha();
19267:         unless ($output) {
19268:             $error = 'captcha';
19269:         }
19270:     } elsif ($captcha eq 'recaptcha') {
19271:         $output = &create_recaptcha($pubkey,$version);
19272:         unless ($output) {
19273:             $error = 'recaptcha';
19274:         }
19275:     }
19276:     return ($output,$error,$captcha,$version);
19277: }
19278: 
19279: sub captcha_response {
19280:     my ($context,$lonhost,$defdom) = @_;
19281:     my ($captcha_chk,$captcha_error);
19282:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
19283:     if ($captcha eq 'original') {
19284:         ($captcha_chk,$captcha_error) = &check_captcha();
19285:     } elsif ($captcha eq 'recaptcha') {
19286:         $captcha_chk = &check_recaptcha($privkey,$version);
19287:     } else {
19288:         $captcha_chk = 1;
19289:     }
19290:     return ($captcha_chk,$captcha_error);
19291: }
19292: 
19293: sub get_captcha_config {
19294:     my ($context,$lonhost,$dom_in_effect) = @_;
19295:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
19296:     my $hostname = &Apache::lonnet::hostname($lonhost);
19297:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
19298:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
19299:     if ($context eq 'usercreation') {
19300:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
19301:         if (ref($domconfig{$context}) eq 'HASH') {
19302:             $hashtocheck = $domconfig{$context}{'cancreate'};
19303:             if (ref($hashtocheck) eq 'HASH') {
19304:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
19305:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
19306:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
19307:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
19308:                     }
19309:                     if ($privkey && $pubkey) {
19310:                         $captcha = 'recaptcha';
19311:                         $version = $hashtocheck->{'recaptchaversion'};
19312:                         if ($version ne '2') {
19313:                             $version = 1;
19314:                         }
19315:                     } else {
19316:                         $captcha = 'original';
19317:                     }
19318:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
19319:                     $captcha = 'original';
19320:                 }
19321:             }
19322:         } else {
19323:             $captcha = 'captcha';
19324:         }
19325:     } elsif ($context eq 'login') {
19326:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
19327:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
19328:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
19329:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
19330:             if ($privkey && $pubkey) {
19331:                 $captcha = 'recaptcha';
19332:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
19333:                 if ($version ne '2') {
19334:                     $version = 1; 
19335:                 }
19336:             } else {
19337:                 $captcha = 'original';
19338:             }
19339:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
19340:             $captcha = 'original';
19341:         }
19342:     } elsif ($context eq 'passwords') {
19343:         if ($dom_in_effect) {
19344:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
19345:             if ($passwdconf{'captcha'} eq 'recaptcha') {
19346:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
19347:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
19348:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
19349:                 }
19350:                 if ($privkey && $pubkey) {
19351:                     $captcha = 'recaptcha';
19352:                     $version = $passwdconf{'recaptchaversion'};
19353:                     if ($version ne '2') {
19354:                         $version = 1;
19355:                     }
19356:                 } else {
19357:                     $captcha = 'original';
19358:                 }
19359:             } elsif ($passwdconf{'captcha'} ne 'notused') {
19360:                 $captcha = 'original';
19361:             }
19362:         }
19363:     } 
19364:     return ($captcha,$pubkey,$privkey,$version);
19365: }
19366: 
19367: sub create_captcha {
19368:     my %captcha_params = &captcha_settings();
19369:     my ($output,$maxtries,$tries) = ('',10,0);
19370:     while ($tries < $maxtries) {
19371:         $tries ++;
19372:         my $captcha = Authen::Captcha->new (
19373:                                            output_folder => $captcha_params{'output_dir'},
19374:                                            data_folder   => $captcha_params{'db_dir'},
19375:                                           );
19376:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
19377: 
19378:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
19379:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
19380:                       '<span class="LC_nobreak">'.
19381:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
19382:                       '<input type="text" size="5" name="code" value="" autocomplete="new-password" />'.
19383:                       '</span><br />'.
19384:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
19385:             last;
19386:         }
19387:     }
19388:     if ($output eq '') {
19389:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
19390:     }
19391:     return $output;
19392: }
19393: 
19394: sub captcha_settings {
19395:     my %captcha_params = (
19396:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
19397:                            www_output_dir => "/captchaspool",
19398:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
19399:                            numchars       => '5',
19400:                          );
19401:     return %captcha_params;
19402: }
19403: 
19404: sub check_captcha {
19405:     my ($captcha_chk,$captcha_error);
19406:     my $code = $env{'form.code'};
19407:     my $md5sum = $env{'form.crypt'};
19408:     my %captcha_params = &captcha_settings();
19409:     my $captcha = Authen::Captcha->new(
19410:                       output_folder => $captcha_params{'output_dir'},
19411:                       data_folder   => $captcha_params{'db_dir'},
19412:                   );
19413:     $captcha_chk = $captcha->check_code($code,$md5sum);
19414:     my %captcha_hash = (
19415:                         0       => 'Code not checked (file error)',
19416:                        -1      => 'Failed: code expired',
19417:                        -2      => 'Failed: invalid code (not in database)',
19418:                        -3      => 'Failed: invalid code (code does not match crypt)',
19419:     );
19420:     if ($captcha_chk != 1) {
19421:         $captcha_error = $captcha_hash{$captcha_chk}
19422:     }
19423:     return ($captcha_chk,$captcha_error);
19424: }
19425: 
19426: sub create_recaptcha {
19427:     my ($pubkey,$version) = @_;
19428:     if ($version >= 2) {
19429:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
19430:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
19431:     } else {
19432:         my $use_ssl;
19433:         if ($ENV{'SERVER_PORT'} == 443) {
19434:             $use_ssl = 1;
19435:         }
19436:         my $captcha = Captcha::reCAPTCHA->new;
19437:         return $captcha->get_options_setter({theme => 'white'})."\n".
19438:                $captcha->get_html($pubkey,undef,$use_ssl).
19439:                &mt('If the text is hard to read, [_1] will replace them.',
19440:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
19441:                '<br /><br />';
19442:     }
19443: }
19444: 
19445: sub check_recaptcha {
19446:     my ($privkey,$version) = @_;
19447:     my $captcha_chk;
19448:     my $ip = &Apache::lonnet::get_requestor_ip();
19449:     if ($version >= 2) {
19450:         my %info = (
19451:                      secret   => $privkey, 
19452:                      response => $env{'form.g-recaptcha-response'},
19453:                      remoteip => $ip,
19454:                    );
19455:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
19456:         $request->content(join('&',map {
19457:                          my $name = escape($_);
19458:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
19459:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
19460:                          : &escape($info{$_}) );
19461:         } keys(%info)));
19462:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
19463:         if ($response->is_success)  {
19464:             my $data = JSON::DWIW->from_json($response->decoded_content);
19465:             if (ref($data) eq 'HASH') {
19466:                 if ($data->{'success'}) {
19467:                     $captcha_chk = 1;
19468:                 }
19469:             }
19470:         }
19471:     } else {
19472:         my $captcha = Captcha::reCAPTCHA->new;
19473:         my $captcha_result =
19474:             $captcha->check_answer(
19475:                                     $privkey,
19476:                                     $ip,
19477:                                     $env{'form.recaptcha_challenge_field'},
19478:                                     $env{'form.recaptcha_response_field'},
19479:                                   );
19480:         if ($captcha_result->{is_valid}) {
19481:             $captcha_chk = 1;
19482:         }
19483:     }
19484:     return $captcha_chk;
19485: }
19486: 
19487: sub emailusername_info {
19488:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
19489:     my %titles = &Apache::lonlocal::texthash (
19490:                      lastname      => 'Last Name',
19491:                      firstname     => 'First Name',
19492:                      institution   => 'School/college/university',
19493:                      location      => "School's city, state/province, country",
19494:                      web           => "School's web address",
19495:                      officialemail => 'E-mail address at institution (if different)',
19496:                      id            => 'Student/Employee ID',
19497:                  );
19498:     return (\@fields,\%titles);
19499: }
19500: 
19501: sub cleanup_html {
19502:     my ($incoming) = @_;
19503:     my $outgoing;
19504:     if ($incoming ne '') {
19505:         $outgoing = $incoming;
19506:         $outgoing =~ s/;/&#059;/g;
19507:         $outgoing =~ s/\#/&#035;/g;
19508:         $outgoing =~ s/\&/&#038;/g;
19509:         $outgoing =~ s/</&#060;/g;
19510:         $outgoing =~ s/>/&#062;/g;
19511:         $outgoing =~ s/\(/&#040/g;
19512:         $outgoing =~ s/\)/&#041;/g;
19513:         $outgoing =~ s/"/&#034;/g;
19514:         $outgoing =~ s/'/&#039;/g;
19515:         $outgoing =~ s/\$/&#036;/g;
19516:         $outgoing =~ s{/}{&#047;}g;
19517:         $outgoing =~ s/=/&#061;/g;
19518:         $outgoing =~ s/\\/&#092;/g
19519:     }
19520:     return $outgoing;
19521: }
19522: 
19523: # Checks for critical messages and returns a redirect url if one exists.
19524: # $interval indicates how often to check for messages.
19525: # $context is the calling context -- roles, grades, contents, menu or flip. 
19526: sub critical_redirect {
19527:     my ($interval,$context) = @_;
19528:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
19529:         return ();
19530:     }
19531:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
19532:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
19533:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
19534:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
19535:             my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
19536:             if ($blocked) {
19537:                 my $checkrole = "cm./$cdom/$cnum";
19538:                 if ($env{'request.course.sec'} ne '') {
19539:                     $checkrole .= "/$env{'request.course.sec'}";
19540:                 }
19541:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
19542:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
19543:                     return;
19544:                 }
19545:             }
19546:         }
19547:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
19548:                                         $env{'user.name'});
19549:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
19550:         my $redirecturl;
19551:         if ($what[0]) {
19552: 	    if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
19553: 	        $redirecturl='/adm/email?critical=display';
19554: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
19555:                 return (1, $url);
19556:             }
19557:         }
19558:     } 
19559:     return ();
19560: }
19561: 
19562: # Use:
19563: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
19564: #
19565: ##################################################
19566: #          password associated functions         #
19567: ##################################################
19568: sub des_keys {
19569:     # Make a new key for DES encryption.
19570:     # Each key has two parts which are returned separately.
19571:     # Please note:  Each key must be passed through the &hex function
19572:     # before it is output to the web browser.  The hex versions cannot
19573:     # be used to decrypt.
19574:     my @hexstr=('0','1','2','3','4','5','6','7',
19575:                 '8','9','a','b','c','d','e','f');
19576:     my $lkey='';
19577:     for (0..7) {
19578:         $lkey.=$hexstr[rand(15)];
19579:     }
19580:     my $ukey='';
19581:     for (0..7) {
19582:         $ukey.=$hexstr[rand(15)];
19583:     }
19584:     return ($lkey,$ukey);
19585: }
19586: 
19587: sub des_decrypt {
19588:     my ($key,$cyphertext) = @_;
19589:     my $keybin=pack("H16",$key);
19590:     my $cypher;
19591:     if ($Crypt::DES::VERSION>=2.03) {
19592:         $cypher=new Crypt::DES $keybin;
19593:     } else {
19594:         $cypher=new DES $keybin;
19595:     }
19596:     my $plaintext='';
19597:     my $cypherlength = length($cyphertext);
19598:     my $numchunks = int($cypherlength/32);
19599:     for (my $j=0; $j<$numchunks; $j++) {
19600:         my $start = $j*32;
19601:         my $cypherblock = substr($cyphertext,$start,32);
19602:         my $chunk =
19603:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
19604:         $chunk .=
19605:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
19606:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
19607:         $plaintext .= $chunk;
19608:     }
19609:     return $plaintext;
19610: }
19611: 
19612: sub get_requested_shorturls {
19613:     my ($cdom,$cnum,$navmap) = @_;
19614:     return unless (ref($navmap));
19615:     my ($numnew,$errors);
19616:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
19617:     if (@toshorten) {
19618:         my (%maps,%resources,%titles);
19619:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
19620:                                                                'shorturls',$cdom,$cnum);
19621:         if (keys(%resources)) {
19622:             my %tocreate;
19623:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
19624:                 my $symb = $resources{$item};
19625:                 if ($symb) {
19626:                     $tocreate{$cnum.'&'.$symb} = 1;
19627:                 }
19628:             }
19629:             if (keys(%tocreate)) {
19630:                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
19631:                                                       \%tocreate);
19632:             }
19633:         }
19634:     }
19635:     return ($numnew,$errors);
19636: }
19637: 
19638: sub make_short_symbs {
19639:     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
19640:     my ($numnew,@errors);
19641:     if (ref($tocreateref) eq 'HASH') {
19642:         my %tocreate = %{$tocreateref};
19643:         if (keys(%tocreate)) {
19644:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
19645:             my $su = Short::URL->new(no_vowels => 1);
19646:             my $init = '';
19647:             my (%newunique,%addcourse,%courseonly,%failed);
19648:             # get lock on tiny db
19649:             my $now = time;
19650:             if ($lockuser eq '') {
19651:                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
19652:             }
19653:             my $lockhash = {
19654:                                 "lock\0$now" => $lockuser,
19655:                             };
19656:             my $tries = 0;
19657:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
19658:             my ($code,$error);
19659:             while (($gotlock ne 'ok') && ($tries<3)) {
19660:                 $tries ++;
19661:                 sleep 1;
19662:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
19663:             }
19664:             if ($gotlock eq 'ok') {
19665:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
19666:                                        \%addcourse,\%courseonly,\%failed);
19667:                 if (keys(%failed)) {
19668:                     my $numfailed = scalar(keys(%failed));
19669:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
19670:                 }
19671:                 if (keys(%newunique)) {
19672:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
19673:                     if ($putres eq 'ok') {
19674:                         $numnew = scalar(keys(%newunique));
19675:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
19676:                         unless ($newputres eq 'ok') {
19677:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
19678:                         }
19679:                     } else {
19680:                         push(@errors,&mt('error: could not store unique six character URLs'));
19681:                     }
19682:                 }
19683:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
19684:                 unless ($dellockres eq 'ok') {
19685:                     push(@errors,&mt('error: could not release lockfile'));
19686:                 }
19687:             } else {
19688:                 push(@errors,&mt('error: could not obtain lockfile'));
19689:             }
19690:             if (keys(%courseonly)) {
19691:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
19692:                 if ($result ne 'ok') {
19693:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
19694:                 }
19695:             }
19696:         }
19697:     }
19698:     return ($numnew,\@errors);
19699: }
19700: 
19701: sub shorten_symbs {
19702:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
19703:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
19704:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
19705:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
19706:     my (%possibles,%collisions);
19707:     foreach my $key (keys(%{$tocreate})) {
19708:         my $num = String::CRC32::crc32($key);
19709:         my $tiny = $su->encode($num,$init);
19710:         if ($tiny) {
19711:             $possibles{$tiny} = $key;
19712:         }
19713:     }
19714:     if (!$init) {
19715:         $init = 1;
19716:     } else {
19717:         $init ++;
19718:     }
19719:     if (keys(%possibles)) {
19720:         my @posstiny = keys(%possibles);
19721:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
19722:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
19723:         if (keys(%currtiny)) {
19724:             foreach my $key (keys(%currtiny)) {
19725:                 next if ($currtiny{$key} eq '');
19726:                 if ($currtiny{$key} eq $possibles{$key}) {
19727:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
19728:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
19729:                         $courseonly->{$tsymb} = $key;
19730:                     }
19731:                 } else {
19732:                     $collisions{$possibles{$key}} = 1;
19733:                 }
19734:                 delete($possibles{$key});
19735:             }
19736:         }
19737:         foreach my $key (keys(%possibles)) {
19738:             $newunique->{$key} = $possibles{$key};
19739:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
19740:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
19741:                 $addcourse->{$tsymb} = $key;
19742:             }
19743:         }
19744:     }
19745:     if (keys(%collisions)) {
19746:         if ($init <5) {
19747:             if (!$init) {
19748:                 $init = 1;
19749:             } else {
19750:                 $init ++;
19751:             }
19752:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
19753:                                    $newunique,$addcourse,$courseonly,$failed);
19754:         } else {
19755:             foreach my $key (keys(%collisions)) {
19756:                 $failed->{$key} = 1;
19757:             }
19758:         }
19759:     }
19760:     return $init;
19761: }
19762: 
19763: sub is_nonframeable {
19764:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
19765:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
19766:     return if (($remprotocol eq '') || ($remhost eq ''));
19767: 
19768:     $remprotocol = lc($remprotocol);
19769:     $remhost = lc($remhost);
19770:     my $remport = 80;
19771:     if ($remprotocol eq 'https') {
19772:         $remport = 443;
19773:     }
19774:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
19775:     if ($cached) {
19776:         unless ($nocache) {
19777:             if ($result) {
19778:                 return 1;
19779:             } else {
19780:                 return 0;
19781:             }
19782:         }
19783:     }
19784:     my $uselink;
19785:     my $request = new HTTP::Request('HEAD',$url);
19786:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
19787:     if ($response->is_success()) {
19788:         my $secpolicy = lc($response->header('content-security-policy'));
19789:         my $xframeop = lc($response->header('x-frame-options'));
19790:         $secpolicy =~ s/^\s+|\s+$//g;
19791:         $xframeop =~ s/^\s+|\s+$//g;
19792:         if (($secpolicy ne '') || ($xframeop ne '')) {
19793:             my $remotehost = $remprotocol.'://'.$remhost;
19794:             my ($origin,$protocol,$port);
19795:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
19796:                 $port = $ENV{'SERVER_PORT'};
19797:             } else {
19798:                 $port = 80;
19799:             }
19800:             if ($absolute eq '') {
19801:                 $protocol = 'http:';
19802:                 if ($port == 443) {
19803:                     $protocol = 'https:';
19804:                 }
19805:                 $origin = $protocol.'//'.lc($hostname);
19806:             } else {
19807:                 $origin = lc($absolute);
19808:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
19809:             }
19810:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
19811:                 my $framepolicy = $1;
19812:                 $framepolicy =~ s/^\s+|\s+$//g;
19813:                 my @policies = split(/\s+/,$framepolicy);
19814:                 if (@policies) {
19815:                     if (grep(/^\Q'none'\E$/,@policies)) {
19816:                         $uselink = 1;
19817:                     } else {
19818:                         $uselink = 1;
19819:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
19820:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
19821:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
19822:                             undef($uselink);
19823:                         }
19824:                         if ($uselink) {
19825:                             if (grep(/^\Q'self'\E$/,@policies)) {
19826:                                 if (($origin ne '') && ($remotehost eq $origin)) {
19827:                                     undef($uselink);
19828:                                 }
19829:                             }
19830:                         }
19831:                         if ($uselink) {
19832:                             my @possok;
19833:                             if ($ip ne '') {
19834:                                 push(@possok,$ip);
19835:                             }
19836:                             my $hoststr = '';
19837:                             foreach my $part (reverse(split(/\./,$hostname))) {
19838:                                 if ($hoststr eq '') {
19839:                                     $hoststr = $part;
19840:                                 } else {
19841:                                     $hoststr = "$part.$hoststr";
19842:                                 }
19843:                                 if ($hoststr eq $hostname) {
19844:                                     push(@possok,$hostname);
19845:                                 } else {
19846:                                     push(@possok,"*.$hoststr");
19847:                                 }
19848:                             }
19849:                             if (@possok) {
19850:                                 foreach my $poss (@possok) {
19851:                                     last if (!$uselink);
19852:                                     foreach my $policy (@policies) {
19853:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
19854:                                             undef($uselink);
19855:                                             last;
19856:                                         }
19857:                                     }
19858:                                 }
19859:                             }
19860:                         }
19861:                     }
19862:                 }
19863:             } elsif ($xframeop ne '') {
19864:                 $uselink = 1;
19865:                 my @policies = split(/\s*,\s*/,$xframeop);
19866:                 if (@policies) {
19867:                     unless (grep(/^deny$/,@policies)) {
19868:                         if ($origin ne '') {
19869:                             if (grep(/^sameorigin$/,@policies)) {
19870:                                 if ($remotehost eq $origin) {
19871:                                     undef($uselink);
19872:                                 }
19873:                             }
19874:                             if ($uselink) {
19875:                                 foreach my $policy (@policies) {
19876:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
19877:                                         my $allowfrom = $1;
19878:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
19879:                                             undef($uselink);
19880:                                             last;
19881:                                         }
19882:                                     }
19883:                                 }
19884:                             }
19885:                         }
19886:                     }
19887:                 }
19888:             }
19889:         }
19890:     }
19891:     if ($nocache) {
19892:         if ($cached) {
19893:             my $devalidate;
19894:             if ($uselink && !$result) {
19895:                 $devalidate = 1;
19896:             } elsif (!$uselink && $result) {
19897:                 $devalidate = 1;
19898:             }
19899:             if ($devalidate) {
19900:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
19901:             }
19902:         }
19903:     } else {
19904:         if ($uselink) {
19905:             $result = 1;
19906:         } else {
19907:             $result = 0;
19908:         }
19909:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
19910:     }
19911:     return $uselink;
19912: }
19913: 
19914: sub page_menu {
19915:     my ($menucolls,$menunum) = @_;
19916:     my %menu;
19917:     foreach my $item (split(/;/,$menucolls)) {
19918:         my ($num,$value) = split(/\%/,$item);
19919:         if ($num eq $menunum) {
19920:             my @entries = split(/\&/,$value);
19921:             foreach my $entry (@entries) {
19922:                 my ($name,$fields) = split(/=/,$entry);
19923:                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
19924:                     $menu{$name} = $fields;
19925:                 } else {
19926:                     my @shown;
19927:                     if ($fields =~ /,/) {
19928:                         @shown = split(/,/,$fields);
19929:                     } else {
19930:                         @shown = ($fields);
19931:                     }
19932:                     if (@shown) {
19933:                         foreach my $field (@shown) {
19934:                             next if ($field eq '');
19935:                             $menu{$field} = 1;
19936:                         }
19937:                     }
19938:                 }
19939:             }
19940:         }
19941:     }
19942:     return %menu;
19943: }
19944: 
19945: 1;
19946: __END__;
19947: 

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