File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1429: download - view: text, annotated - select for diffs
Sun Apr 14 17:12:27 2024 UTC (4 weeks, 6 days ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Available editors in Course Authoring Space, or when editing an html file
  created in a course folder using the Course Editor is a domain default,
  which can be overridden in specific course(s) by a Domain Coordinator.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1429 2024/04/14 17:12:27 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('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: =cut
 1768: 
 1769: sub resize_textarea_js {
 1770:     my $geometry = &viewport_geometry_js();
 1771:     return <<"RESIZE";
 1772:     <script type="text/javascript">
 1773: // <![CDATA[
 1774: $geometry
 1775: 
 1776: function getX(element) {
 1777:     var x = 0;
 1778:     while (element) {
 1779: 	x += element.offsetLeft;
 1780: 	element = element.offsetParent;
 1781:     }
 1782:     return x;
 1783: }
 1784: function getY(element) {
 1785:     var y = 0;
 1786:     while (element) {
 1787: 	y += element.offsetTop;
 1788: 	element = element.offsetParent;
 1789:     }
 1790:     return y;
 1791: }
 1792: 
 1793: 
 1794: function resize_textarea(textarea_id,bottom_id) {
 1795:     init_geometry();
 1796:     var textarea        = document.getElementById(textarea_id);
 1797:     //alert(textarea);
 1798: 
 1799:     var textarea_top    = getY(textarea);
 1800:     var textarea_height = textarea.offsetHeight;
 1801:     var bottom          = document.getElementById(bottom_id);
 1802:     var bottom_top      = getY(bottom);
 1803:     var bottom_height   = bottom.offsetHeight;
 1804:     var window_height   = Geometry.getViewportHeight();
 1805:     var fudge           = 23;
 1806:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1807:     if (new_height < 300) {
 1808: 	new_height = 300;
 1809:     }
 1810:     textarea.style.height=new_height+'px';
 1811: }
 1812: // ]]>
 1813: </script>
 1814: RESIZE
 1815: 
 1816: }
 1817: 
 1818: sub colorfuleditor_js {
 1819:     my $browse_or_search;
 1820:     my $respath;
 1821:     my ($cnum,$cdom) = &crsauthor_url();
 1822:     if ($cnum) {
 1823:         $respath = "/res/$cdom/$cnum/";
 1824:         my %js_lt = &Apache::lonlocal::texthash(
 1825:             sunm => 'Sub-directory name',
 1826:             save => 'Save page to make this permanent',
 1827:         );
 1828:         &js_escape(\%js_lt);
 1829:         my $showfile_js = &show_crsfiles_js();
 1830:         $browse_or_search = <<"END";
 1831: 
 1832:     $showfile_js
 1833: 
 1834:     function toggleChooser(form,element,titleid,only,search) {
 1835:         var disp = 'none';
 1836:         if (document.getElementById('chooser_'+element)) {
 1837:             var curr = document.getElementById('chooser_'+element).style.display;
 1838:             if (curr == 'none') {
 1839:                 disp='inline';
 1840:                 if (form.elements['chooser_'+element].length) {
 1841:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
 1842:                         form.elements['chooser_'+element][i].checked = false;
 1843:                     }
 1844:                 }
 1845:                 toggleResImport(form,element);
 1846:             }
 1847:             document.getElementById('chooser_'+element).style.display = disp;
 1848:             var dirsel = '';
 1849:             var filesel = '';
 1850:             if (document.getElementById('chooser_'+element+'_crsres')) {
 1851:                 var currcrsres = document.getElementById('chooser_'+element+'_crsres').style.display;
 1852:                 if (currcrsres == 'none') {
 1853:                     dirsel = 'coursepath_'+element;
 1854:                     var filesel = 'coursefile_'+element;
 1855:                     var include;
 1856:                     if (document.getElementById('crsres_include_'+element)) {
 1857:                         include = document.getElementById('crsres_include_'+element).value;
 1858:                     }
 1859:                     populateCrsSelects(form,dirsel,filesel,1,include,1,0,1,1,0);
 1860:                 }
 1861:             }
 1862:             if (document.getElementById('chooser_'+element+'_upload')) {
 1863:                 var currcrsupload = document.getElementById('chooser_'+element+'_upload').style.display;
 1864:                 if (currcrsupload == 'none') {
 1865:                     dirsel = 'crsauthorpath_'+element;
 1866:                     filesel = '';
 1867:                     populateCrsSelects(form,dirsel,filesel,0,'',1,0,1,0,1);
 1868:                 }
 1869:             }
 1870:         }
 1871:     }
 1872: 
 1873:     function toggleCrsFile(form,element) {
 1874:         if (document.getElementById('chooser_'+element+'_crsres')) {
 1875:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
 1876:             if (curr == 'none') {
 1877:                 if (document.getElementById('coursepath_'+element)) {
 1878:                     var numdirs;
 1879:                     if (document.getElementById('coursepath_'+element).length) {
 1880:                         numdirs = document.getElementById('coursepath_'+element).length;
 1881:                     }
 1882:                     if ((document.getElementById('hascrsres_'+element)) &&
 1883:                         (document.getElementById('nocrsres_'+element))) {
 1884:                         if (numdirs) {
 1885:                             document.getElementById('hascrsres_'+element).style.display='inline-block';
 1886:                             document.getElementById('nocrsres_'+element).style.display='none';
 1887:                         } else {
 1888:                             document.getElementById('hascrsres_'+element).style.display='none';
 1889:                             document.getElementById('nocrsres_'+element).style.display='inline-block';
 1890:                         }
 1891:                     }
 1892:                     form.elements['coursepath_'+element].selectedIndex = 0;
 1893:                     if (numdirs > 1) {
 1894:                         var selelem = form.elements['coursefile_'+element];
 1895:                         var i, len = selelem.options.length -1;
 1896:                         if (len >=0) {
 1897:                             for (i = len; i >= 0; i--) {
 1898:                                 selelem.remove(i);
 1899:                             }
 1900:                             selelem.options[0] = new Option('','');
 1901:                         }
 1902:                     }
 1903:                 }
 1904:             }
 1905:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
 1906:         }
 1907:         if (document.getElementById('chooser_'+element+'_upload')) {
 1908:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
 1909:             if (document.getElementById('uploadcrsres_'+element)) {
 1910:                 document.getElementById('uploadcrsres_'+element).value = '';
 1911:             }
 1912:         }
 1913:         return;
 1914:     }
 1915: 
 1916:     function toggleCrsUpload(form,element) {
 1917:         if (document.getElementById('chooser_'+element+'_crsres')) {
 1918:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
 1919:         }
 1920:         if (document.getElementById('chooser_'+element+'_upload')) {
 1921:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
 1922:             if (curr == 'none') {
 1923:                 form.elements['newsubdir_'+element][0].checked = true;
 1924:                 toggleNewsubdir(form,element);
 1925:                 document.getElementById('chooser_'+element+'_upload').style.display = 'block';
 1926:                 if (document.getElementById('uploadcrsres_'+element)) {
 1927:                     document.getElementById('uploadcrsres_'+element).value = '';
 1928:                 }
 1929:             }
 1930:         }
 1931:         return;
 1932:     }
 1933: 
 1934:     function toggleResImport(form,element) {
 1935:         var choices = new Array('crsres','upload');
 1936:         for (var i=0; i<choices.length; i++) {
 1937:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
 1938:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
 1939:             }
 1940:         }
 1941:     }
 1942: 
 1943:     function toggleNewsubdir(form,element) {
 1944:         var newsub = form.elements['newsubdir_'+element];
 1945:         if (newsub) {
 1946:             if (newsub.length) {
 1947:                 for (var j=0; j<newsub.length; j++) {
 1948:                     if (newsub[j].checked) {
 1949:                         if (document.getElementById('newsubdirname_'+element)) {
 1950:                             if (newsub[j].value == '1') {
 1951:                                 document.getElementById('newsubdirname_'+element).type = "text";
 1952:                                 if (document.getElementById('newsubdir_'+element)) {
 1953:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
 1954:                                 }
 1955:                             } else {
 1956:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
 1957:                                 document.getElementById('newsubdirname_'+element).value = "";
 1958:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
 1959:                             }
 1960:                         }
 1961:                         break; 
 1962:                     }
 1963:                 }
 1964:             }
 1965:         }
 1966:     }
 1967: 
 1968:     function updateCrsFile(form,element) {
 1969:         var directory = form.elements['coursepath_'+element];
 1970:         var filename = form.elements['coursefile_'+element];
 1971:         var path = directory.options[directory.selectedIndex].value;
 1972:         var file = filename.options[filename.selectedIndex].value;
 1973:         if (file != '') {
 1974:             form.elements[element].value = '$respath';
 1975:             if (path == '/') {
 1976:                 form.elements[element].value += file;
 1977:             } else {
 1978:                 form.elements[element].value += path+'/'+file;
 1979:             }
 1980:             unClean();
 1981:             if (document.getElementById('previewimg_'+element)) {
 1982:                 document.getElementById('previewimg_'+element).src = form.elements[element].value;
 1983:                 var newsrc = document.getElementById('previewimg_'+element).src; 
 1984:             }
 1985:             if (document.getElementById('showimg_'+element)) {
 1986:                 document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
 1987:             }
 1988:         }
 1989:         toggleChooser(form,element);
 1990:         return;
 1991:     }
 1992: 
 1993:     function uploadDone(suffix,name) {
 1994:         if (name) {
 1995: 	    document.forms["lonhomework"].elements[suffix].value = name;
 1996:             unClean();
 1997:             toggleChooser(document.forms["lonhomework"],suffix);
 1998:         }
 1999:     }
 2000: 
 2001: \$(document).ready(function(){
 2002: 
 2003:     \$(document).delegate('form :submit', 'click', function( event ) {
 2004:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
 2005:             var buttonId = this.id;
 2006:             var suffix = buttonId.toString();
 2007:             suffix = suffix.replace(/^crsupload_/,'');
 2008:             event.preventDefault();
 2009:             document.lonhomework.target = 'crsupload_target_'+suffix;
 2010:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
 2011:             \$(this.form).submit();
 2012:             document.lonhomework.target = '';
 2013:             if (document.getElementById('crsuploadto_'+suffix)) {
 2014:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
 2015:             }
 2016:             return false;
 2017:         }
 2018:     });
 2019: });
 2020: END
 2021:     }
 2022:     return <<"COLORFULEDIT"
 2023: <script type="text/javascript">
 2024: // <![CDATA[>
 2025:     function fold_box(curDepth, lastresource){
 2026: 
 2027:     // we need a list because there can be several blocks you need to fold in one tag
 2028:         var block = document.getElementsByName('foldblock_'+curDepth);
 2029:     // but there is only one folding button per tag
 2030:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
 2031: 
 2032:         if(block.item(0).style.display == 'none'){
 2033: 
 2034:             foldbutton.value = '@{[&mt("Hide")]}';
 2035:             for (i = 0; i < block.length; i++){
 2036:                 block.item(i).style.display = '';
 2037:             }
 2038:         }else{
 2039: 
 2040:             foldbutton.value = '@{[&mt("Show")]}';
 2041:             for (i = 0; i < block.length; i++){
 2042:                 // block.item(i).style.visibility = 'collapse';
 2043:                 block.item(i).style.display = 'none';
 2044:             }
 2045:         };
 2046:         saveState(lastresource);
 2047:     }
 2048: 
 2049:     function saveState (lastresource) {
 2050: 
 2051:         var tag_list = getTagList();
 2052:         if(tag_list != null){
 2053:             var timestamp = new Date().getTime();
 2054:             var key = lastresource;
 2055: 
 2056:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
 2057:             // starting with timestamp
 2058:             var value = timestamp+';';
 2059: 
 2060:             // building the list of key-value pairs
 2061:             for(var i = 0; i < tag_list.length; i++){
 2062:                 value += tag_list[i]+',';
 2063:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
 2064:             }
 2065: 
 2066:             // only iterate whole storage if nothing to override
 2067:             if(localStorage.getItem(key) == null){        
 2068: 
 2069:                 // prevent storage from growing large
 2070:                 if(localStorage.length > 50){
 2071:                     var regex_getTimestamp = /^(?:\d)+;/;
 2072:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
 2073:                     var oldest_key;
 2074:                     
 2075:                     for(var i = 1; i < localStorage.length; i++){
 2076:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
 2077:                             oldest_key = localStorage.key(i);
 2078:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
 2079:                         }
 2080:                     }
 2081:                     localStorage.removeItem(oldest_key);
 2082:                 }
 2083:             }
 2084:             localStorage.setItem(key,value);
 2085:         }
 2086:     }
 2087: 
 2088:     // restore folding status of blocks (on page load)
 2089:     function restoreState (lastresource) {
 2090:         if(localStorage.getItem(lastresource) != null){
 2091:             var key = lastresource;
 2092:             var value = localStorage.getItem(key);
 2093:             var regex_delTimestamp = /^\d+;/;
 2094: 
 2095:             value.replace(regex_delTimestamp, '');
 2096: 
 2097:             var valueArr = value.split(';');
 2098:             var pairs;
 2099:             var elements;
 2100:             for (var i = 0; i < valueArr.length; i++){
 2101:                 pairs = valueArr[i].split(',');
 2102:                 elements = document.getElementsByName(pairs[0]);
 2103: 
 2104:                 for (var j = 0; j < elements.length; j++){  
 2105:                     elements[j].style.display = pairs[1];
 2106:                     if (pairs[1] == "none"){
 2107:                         var regex_id = /([_\\d]+)\$/;
 2108:                         regex_id.exec(pairs[0]);
 2109:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
 2110:                     }
 2111:                 }
 2112:             }
 2113:         }
 2114:     }
 2115: 
 2116:     function getTagList () {
 2117:         
 2118:         var stringToSearch = document.lonhomework.innerHTML;
 2119: 
 2120:         var ret = new Array();
 2121:         var regex_findBlock = /(foldblock_.*?)"/g;
 2122:         var tag_list = stringToSearch.match(regex_findBlock);
 2123: 
 2124:         if(tag_list != null){
 2125:             for(var i = 0; i < tag_list.length; i++){            
 2126:                 ret.push(tag_list[i].replace(/"/, ''));
 2127:             }
 2128:         }
 2129:         return ret;
 2130:     }
 2131: 
 2132:     function saveScrollPosition (resource) {
 2133:         var tag_list = getTagList();
 2134: 
 2135:         // we dont always want to jump to the first block
 2136:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
 2137:         if(\$(window).scrollTop() > 170){
 2138:             if(tag_list != null){
 2139:                 var result;
 2140:                 for(var i = 0; i < tag_list.length; i++){
 2141:                     if(isElementInViewport(tag_list[i])){
 2142:                         result += tag_list[i]+';';
 2143:                     }
 2144:                 }
 2145:                 sessionStorage.setItem('anchor_'+resource, result);
 2146:             }
 2147:         } else {
 2148:             // we dont need to save zero, just delete the item to leave everything tidy
 2149:             sessionStorage.removeItem('anchor_'+resource);
 2150:         }
 2151:     }
 2152: 
 2153:     function restoreScrollPosition(resource){
 2154: 
 2155:         var elem = sessionStorage.getItem('anchor_'+resource);
 2156:         if(elem != null){
 2157:             var tag_list = elem.split(';');
 2158:             var elem_list;
 2159: 
 2160:             for(var i = 0; i < tag_list.length; i++){
 2161:                 elem_list = document.getElementsByName(tag_list[i]);
 2162:                 
 2163:                 if(elem_list.length > 0){
 2164:                     elem = elem_list[0];
 2165:                     break;
 2166:                 }
 2167:             }
 2168:             elem.scrollIntoView();
 2169:         }
 2170:     }
 2171: 
 2172:     function isElementInViewport(el) {
 2173: 
 2174:         // change to last element instead of first
 2175:         var elem = document.getElementsByName(el);
 2176:         var rect = elem[0].getBoundingClientRect();
 2177: 
 2178:         return (
 2179:             rect.top >= 0 &&
 2180:             rect.left >= 0 &&
 2181:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
 2182:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
 2183:         );
 2184:     }
 2185:     
 2186:     function autosize(depth){
 2187:         var cmInst = window['cm'+depth];
 2188:         var fitsizeButton = document.getElementById('fitsize'+depth);
 2189: 
 2190:         // is fixed size, switching to dynamic
 2191:         if (sessionStorage.getItem("autosized_"+depth) == null) {
 2192:             cmInst.setSize("","auto");
 2193:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
 2194:             sessionStorage.setItem("autosized_"+depth, "yes");
 2195: 
 2196:         // is dynamic size, switching to fixed
 2197:         } else {
 2198:             cmInst.setSize("","300px");
 2199:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
 2200:             sessionStorage.removeItem("autosized_"+depth);
 2201:         }
 2202:     }
 2203: 
 2204: $browse_or_search
 2205: 
 2206: // ]]>
 2207: </script>
 2208: COLORFULEDIT
 2209: }
 2210: 
 2211: sub xmleditor_js {
 2212:     return <<XMLEDIT
 2213: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
 2214: <script type="text/javascript">
 2215: // <![CDATA[>
 2216: 
 2217:     function saveScrollPosition (resource) {
 2218: 
 2219:         var scrollPos = \$(window).scrollTop();
 2220:         sessionStorage.setItem(resource,scrollPos);
 2221:     }
 2222: 
 2223:     function restoreScrollPosition(resource){
 2224: 
 2225:         var scrollPos = sessionStorage.getItem(resource);
 2226:         \$(window).scrollTop(scrollPos);
 2227:     }
 2228: 
 2229:     // unless internet explorer
 2230:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
 2231: 
 2232:         \$(document).ready(function() {
 2233:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
 2234:         });
 2235:     }
 2236: 
 2237:     // inserts text at cursor position into codemirror (xml editor only)
 2238:     function insertText(text){
 2239:         cm.focus();
 2240:         var curPos = cm.getCursor();
 2241:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
 2242:     }
 2243: // ]]>
 2244: </script>
 2245: XMLEDIT
 2246: }
 2247: 
 2248: sub insert_folding_button {
 2249:     my $curDepth = $Apache::lonxml::curdepth;
 2250:     my $lastresource = $env{'request.ambiguous'};
 2251: 
 2252:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
 2253:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
 2254: }
 2255: 
 2256: sub crsauthor_url {
 2257:     my ($url) = @_;
 2258:     if ($url eq '') {
 2259:         $url = $ENV{'REQUEST_URI'};
 2260:     }
 2261:     my ($cnum,$cdom);
 2262:     if ($env{'request.course.id'}) {
 2263:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
 2264:         if ($audom ne '' && $auname ne '') {
 2265:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
 2266:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
 2267:                 $cnum = $auname;
 2268:                 $cdom = $audom;
 2269:             }
 2270:         }
 2271:     }
 2272:     return ($cnum,$cdom);
 2273: }
 2274: 
 2275: sub import_crsauthor_form {
 2276:     my ($firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
 2277:     return (0) unless ($env{'request.course.id'});
 2278:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2279:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2280:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
 2281:     return (0) unless (($cnum ne '') && ($cdom ne ''));
 2282:     my @ids=&Apache::lonnet::current_machine_ids();
 2283:     my ($output,$is_home,$toppath,%subdirs,%files,%selimport_menus,$include,$exclude);
 2284: 
 2285:     if (grep(/^\Q$crshome\E$/,@ids)) {
 2286:         $is_home = 1;
 2287:     }
 2288:     $toppath = "/priv/$cdom/$cnum";
 2289:     my $nonemptydir = 1;
 2290:     my $js_only;
 2291:     if ($only) {
 2292:         map { $include->{$_} = 1; } split(/\s*,\s*/,$only);
 2293:         $js_only = join(',',map { &js_escape($_); } sort(keys(%{$include})));
 2294:     }
 2295:     $exclude = &Apache::lonnet::priv_exclude();
 2296:     &Apache::lonnet::recursedirs($is_home,1,$include,$exclude,1,0,$toppath,'',\%subdirs,\%files);
 2297:     my $numdirs = scalar(keys(%files));
 2298:     my %lt = &Apache::lonlocal::texthash (
 2299:         fnam => 'Filename',
 2300:         dire => 'Directory',
 2301:         se   => 'Select',
 2302:     );
 2303:     $output = $lt{'dire'}.':&nbsp;'.
 2304:               '<select id="'.$firstselectname.'" name="'.$firstselectname.'" '.
 2305:               'onchange="populateCrsSelects(this.form,'."'$firstselectname','$secondselectname',1,'$js_only',0,1,0,0,0".');">'.
 2306:               '<option value="" selected="selected">'.$lt{'se'}.'</option>';
 2307:     if ($files{'/'}) {
 2308:         $output .= '<option value="/">/</option>'."\n";
 2309:     }
 2310:     foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
 2311:         next if ($key eq '/');
 2312:         $output .= '<option value="'.$key.'">'.$key.'</option>'."\n";
 2313:     }
 2314:     $output .= '</select><br />'."\n".
 2315:                $lt{'fnam'}.':&nbsp;<select id="'.$secondselectname.'" name="'.$secondselectname.'">'."\n".
 2316:                '<option value="" selected="selected"></option>'."\n".
 2317:                '</select>'."\n".
 2318:                '<input type="hidden" id="crsres_include_'.$suffix.'" value="'.$only.'" />';
 2319:     return ($numdirs,$output);
 2320: }
 2321: 
 2322: sub show_crsfiles_js {
 2323:     my $excluderef = &Apache::lonnet::priv_exclude();
 2324:     my $se = &js_escape(&mt('Select'));
 2325:     my $exclude;
 2326:     if (ref($excluderef) eq 'HASH') {
 2327:         $exclude = join(',', map { &js_escape($_); } sort(keys(%{$excluderef})));
 2328:     }
 2329:     my $js = <<"END";
 2330: 
 2331: 
 2332:     function populateCrsSelects (form,dirsel,filesel,exc,include,setdir,setfile,recurse,nonemptydir,addtopdir) {
 2333:         var relpath = '';
 2334:         if ((setfile) && (dirsel != null) && (dirsel != 'undefined') && (dirsel != '')) {
 2335:             var currdir = form.elements[dirsel].options[form.elements[dirsel].selectedIndex].value;
 2336:             if (currdir == '') {
 2337:                 if ((filesel != null) && (filesel != 'undefined') && (filesel != '')) {
 2338:                     selelem = form.elements[filesel];
 2339:                     var j, numfiles = selelem.options.length -1;
 2340:                     if (numfiles >=0) {
 2341:                         for (j = numfiles; j >= 0; j--) {
 2342:                             selelem.remove(j);
 2343:                         }
 2344:                     }
 2345:                     if (selelem.options.length == 0) {
 2346:                         selelem.options[selelem.options.length] = new Option('','');
 2347:                         selelem.selectedIndex = 0;
 2348:                     }
 2349:                 }
 2350:                 return;
 2351:             } else {
 2352:                 relpath = encodeURIComponent(form.elements[dirsel].options[form.elements[dirsel].selectedIndex].value);
 2353:             }
 2354:         }
 2355:         var http = new XMLHttpRequest();
 2356:         var url = "/adm/courseauthor";
 2357:         var crsrole = "$env{'request.role'}";
 2358:         var exclude = '';
 2359:         if (exc) {
 2360:             exclude = '$exclude';
 2361:         }
 2362:         var params = "role=course&files=1&rec="+recurse+"&nonempty="+nonemptydir+"&exc="+exclude+"&inc="+include+"&addtop="+addtopdir+"&path="+relpath;
 2363:         http.open("POST", url, true);
 2364:         http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 2365:         http.onreadystatechange = function() {
 2366:             if (http.readyState == 4 && http.status == 200) {
 2367:                 var data = JSON.parse(http.responseText);
 2368:                 var selelem;
 2369:                 if ((setdir) && (dirsel != null) && (dirsel != 'undefined') && (dirsel != '')) {
 2370:                     if (Array.isArray(data.dirs)) {
 2371:                         selelem = form.elements[dirsel];
 2372:                         var i, numdirs = selelem.options.length -1;
 2373:                         if (numdirs >=0) {
 2374:                             for (i = numdirs; i >= 0; i--) {
 2375:                                 selelem.remove(i);
 2376:                             }
 2377:                         }
 2378:                         var len = data.dirs.length;
 2379:                         if (len) {
 2380:                             selelem.options[selelem.options.length] = new Option('$se','');
 2381:                             var j;
 2382:                             for (j = 0; j < len; j++) {
 2383:                                 selelem.options[selelem.options.length] = new Option(data.dirs[j],data.dirs[j]);
 2384:                             }
 2385:                             selelem.selectedIndex = 0;
 2386:                         }
 2387:                         if (!setfile) {
 2388:                             if ((filesel != null) && (filesel != 'undefined') && (filesel != '')) {
 2389:                                 selelem = form.elements[filesel];
 2390:                                 var j, numfiles = selelem.options.length -1;
 2391:                                 if (numfiles >=0) {
 2392:                                     for (j = numfiles; j >= 0; j--) {
 2393:                                         selelem.remove(j);
 2394:                                     }
 2395:                                 }
 2396:                                 if (selelem.options.length == 0) {
 2397:                                     selelem.options[selelem.options.length] = new Option('','');
 2398:                                     selelem.selectedIndex = 0;
 2399:                                 }
 2400:                             }
 2401:                         }
 2402:                     }
 2403:                 }
 2404:                 if ((setfile) && (filesel != null) && (filesel != 'undefined') && (filesel != '')) {
 2405:                     selelem = form.elements[filesel];
 2406:                     var i, numfiles = selelem.options.length -1;
 2407:                     if (numfiles >=0) {
 2408:                         for (i = numfiles; i >= 0; i--) {
 2409:                             selelem.remove(i);
 2410:                         }
 2411:                     }
 2412:                     var x;
 2413:                     for (x in data.files) {
 2414:                         if (Array.isArray(data.files[x])) {
 2415:                             if (data.files[x].length > 1) {
 2416:                                 selelem.options[selelem.options.length] = new Option('$se','');
 2417:                             }
 2418:                             var len = data.files[x].length;
 2419:                             if (len) {
 2420:                                 var k;
 2421:                                 for (k = 0; k < len; k++) {
 2422:                                     selelem.options[selelem.options.length] = new Option(data.files[x][k],data.files[x][k]);
 2423:                                 }
 2424:                                 selelem.selectedIndex = 0;
 2425:                             }
 2426:                         }
 2427:                     }
 2428:                     if (selelem.options.length == 0) {
 2429:                         selelem.options[selelem.options.length] = new Option('','');
 2430:                         selelem.selectedIndex = 0;
 2431:                     }
 2432:                 }
 2433:             }
 2434:         }
 2435:         http.send(params);
 2436:     }
 2437: END
 2438: }
 2439: 
 2440: sub crsauthor_rights {
 2441:     my ($rightsfile,$path,$docroot,$cnum,$cdom) = @_;
 2442:     my $sourcerights = "$path/$rightsfile";
 2443:     my $now = time;
 2444:     if (!-e $sourcerights) {
 2445:         my $cid = $cdom.'_'.$cnum;
 2446:         if (!-e "$docroot/priv/$cdom") {
 2447:             mkdir("$docroot/priv/$cdom",0755);
 2448:         }
 2449:         if (!-e "$docroot/priv/$cdom/$cnum") {
 2450:             mkdir("$docroot/priv/$cdom/$cnum",0755);
 2451:         }
 2452:         if (open(my $fh,">$sourcerights")) {
 2453:             print $fh <<END;
 2454: <accessrule effect="deny" realm="" type="course" role="" />
 2455: <accessrule effect="allow" realm="$cid" type="course" role="" />
 2456: END
 2457:             close($fh);
 2458:         }
 2459:     }
 2460:     if (!-e "$sourcerights.meta") {
 2461:         if (open(my $fh,">$sourcerights.meta")) {
 2462:             my $author=$env{'environment.firstname'}.' '.
 2463:                        $env{'environment.middlename'}.' '.
 2464:                        $env{'environment.lastname'}.' '.
 2465:                        $env{'environment.generation'};
 2466:             $author =~ s/\s+$//;
 2467:             print $fh <<"END";
 2468: 
 2469: <abstract></abstract>
 2470: <author>$author</author>
 2471: <authorspace>$cnum:$cdom</authorspace>
 2472: <copyright>private</copyright>
 2473: <creationdate>$now</creationdate>
 2474: <customdistributionfile></customdistributionfile>
 2475: <dependencies></dependencies>
 2476: <domain>$cdom</domain>
 2477: <highestgradelevel>0</highestgradelevel>
 2478: <keywords></keywords>
 2479: <language>notset </language>
 2480: <lastrevisiondate>$now</lastrevisiondate>
 2481: <lowestgradelevel>0</lowestgradelevel>
 2482: <mime>rights</mime>
 2483: <modifyinguser>$env{'user.name'}:$env{'user.domain'}</modifyinguser>
 2484: <notes></notes>
 2485: <obsolete></obsolete>
 2486: <obsoletereplacement></obsoletereplacement>
 2487: <owner>$cnum:$cdom</owner>
 2488: <rule>deny:::course,allow:$cid::course</rule>
 2489: <sourceavail></sourceavail>
 2490: <standards></standards>
 2491: <subject></subject>
 2492: <title>Course Authoring Rights</title>
 2493: END
 2494:             close($fh);
 2495:         }
 2496:     }
 2497:     return;
 2498: }
 2499: 
 2500: =pod
 2501: 
 2502: =item * &iframe_wrapper_headjs()
 2503: 
 2504: emits javascript containing two global vars to facilitate handling of resizing
 2505: by code in iframe_wrapper_resizejs() used when an iframe is present in a page
 2506: with standard LON-CAPA menus.
 2507: 
 2508: =cut
 2509: 
 2510: #
 2511: # Where iframe is in use, if window.onload() executes before the custom resize function
 2512: # has been defined (jQuery), two global javascript vars (LCnotready and LCresizedef)
 2513: # are used to ensure document.ready() triggers a call to resize, so the iframe contents
 2514: # do not obscure the Functions menu.
 2515: #
 2516: 
 2517: sub iframe_wrapper_headjs {
 2518:     return <<"ENDJS";
 2519: <script type="text/javascript">
 2520: // <![CDATA[
 2521: var LCnotready = 0;
 2522: var LCresizedef = 0;
 2523: // ]]>
 2524: </script>
 2525: 
 2526: ENDJS
 2527: 
 2528: }
 2529: 
 2530: =pod
 2531: 
 2532: =item * &iframe_wrapper_resizejs()
 2533: 
 2534: emits javascript used to handle resizing for a page containing
 2535: an iframe, to ensure that the iframe does not obscure any
 2536: standard LON-CAPA menu items.
 2537: 
 2538: =back
 2539: 
 2540: =cut
 2541: 
 2542: #
 2543: # jQuery to use when iframe is in use and a page resize occurs.
 2544: # This script will ensure that the iframe does not obscure any
 2545: # standard LON-CAPA inline menus (primary, secondary, and/or
 2546: # breadcrumbs and Functions menus. Expects javascript from
 2547: # &iframe_wrapper_headjs() to be in head portion of the web page,
 2548: # e.g., by inclusion in second arg passed to &start_page().
 2549: #
 2550: 
 2551: sub iframe_wrapper_resizejs {
 2552:     my $offset = 5;
 2553:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['inhibitmenu']);
 2554:     if (($env{'form.inhibitmenu'} eq 'yes') || ($env{'form.only_body'})) {
 2555:         $offset = 0;
 2556:     }
 2557:     return &Apache::lonhtmlcommon::scripttag(<<SCRIPT);
 2558:     \$(document).ready( function() {
 2559:         \$(window).unbind('resize').resize(function(){
 2560:             var header = null;
 2561:             var offset = $offset;
 2562:             var height = 0;
 2563:             var hdrtop = 0;
 2564:             if (\$('div.LC_menus_content:first').length) {
 2565:                 if (\$('div.LC_menus_content:first').hasClass ("shown")) {
 2566:                     header = \$('div.LC_menus_content:first');
 2567:                     offset = 12;
 2568:                 }
 2569:             } else if (\$('div.LC_head_subbox:first').length) {
 2570:                 header = \$('div.LC_head_subbox:first');
 2571:                 offset = 9;
 2572:             } else {
 2573:                 if (\$('#LC_breadcrumbs').length) {
 2574:                     header = \$('#LC_breadcrumbs');
 2575:                 }
 2576:             }
 2577:             if (header != null && header.length) {
 2578:                 height = header.height();
 2579:                 hdrtop = header.position().top;
 2580:             }
 2581:             var pos = height + hdrtop + offset;
 2582:             \$('.LC_iframecontainer').css('top', pos);
 2583:         });
 2584:         LCresizedef = 1;
 2585:         if (LCnotready == 1) {
 2586:             LCnotready = 0;
 2587:             \$(window).trigger('resize');
 2588:         }
 2589:     });
 2590:     window.onload = function(){
 2591:          if (LCresizedef) {
 2592:              LCnotready = 0;
 2593:              \$(window).trigger('resize');
 2594:          } else {
 2595:              LCnotready = 1;
 2596:          }
 2597:     };
 2598: SCRIPT
 2599: 
 2600: }
 2601: 
 2602: =pod
 2603: 
 2604: =head1 Excel and CSV file utility routines
 2605: 
 2606: =cut
 2607: 
 2608: ###############################################################
 2609: ###############################################################
 2610: 
 2611: =pod
 2612: 
 2613: =over 4
 2614: 
 2615: =item * &csv_translate($text) 
 2616: 
 2617: Translate $text to allow it to be output as a 'comma separated values' 
 2618: format.
 2619: 
 2620: =cut
 2621: 
 2622: ###############################################################
 2623: ###############################################################
 2624: sub csv_translate {
 2625:     my $text = shift;
 2626:     $text =~ s/\"/\"\"/g;
 2627:     $text =~ s/\n/ /g;
 2628:     return $text;
 2629: }
 2630: 
 2631: ###############################################################
 2632: ###############################################################
 2633: 
 2634: =pod
 2635: 
 2636: =item * &define_excel_formats()
 2637: 
 2638: Define some commonly used Excel cell formats.
 2639: 
 2640: Currently supported formats:
 2641: 
 2642: =over 4
 2643: 
 2644: =item header
 2645: 
 2646: =item bold
 2647: 
 2648: =item h1
 2649: 
 2650: =item h2
 2651: 
 2652: =item h3
 2653: 
 2654: =item h4
 2655: 
 2656: =item i
 2657: 
 2658: =item date
 2659: 
 2660: =back
 2661: 
 2662: Inputs: $workbook
 2663: 
 2664: Returns: $format, a hash reference.
 2665: 
 2666: 
 2667: =cut
 2668: 
 2669: ###############################################################
 2670: ###############################################################
 2671: sub define_excel_formats {
 2672:     my ($workbook) = @_;
 2673:     my $format;
 2674:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 2675:                                                 bottom    => 1,
 2676:                                                 align     => 'center');
 2677:     $format->{'bold'} = $workbook->add_format(bold=>1);
 2678:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 2679:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 2680:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 2681:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 2682:     $format->{'i'}    = $workbook->add_format(italic=>1);
 2683:     $format->{'date'} = $workbook->add_format(num_format=>
 2684:                                             'mm/dd/yyyy hh:mm:ss');
 2685:     return $format;
 2686: }
 2687: 
 2688: ###############################################################
 2689: ###############################################################
 2690: 
 2691: =pod
 2692: 
 2693: =item * &create_workbook()
 2694: 
 2695: Create an Excel worksheet.  If it fails, output message on the
 2696: request object and return undefs.
 2697: 
 2698: Inputs: Apache request object
 2699: 
 2700: Returns (undef) on failure, 
 2701:     Excel worksheet object, scalar with filename, and formats 
 2702:     from &Apache::loncommon::define_excel_formats on success
 2703: 
 2704: =cut
 2705: 
 2706: ###############################################################
 2707: ###############################################################
 2708: sub create_workbook {
 2709:     my ($r) = @_;
 2710:         #
 2711:     # Create the excel spreadsheet
 2712:     my $filename = '/prtspool/'.
 2713:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2714:         time.'_'.rand(1000000000).'.xls';
 2715:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 2716:     if (! defined($workbook)) {
 2717:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 2718:         $r->print(
 2719:             '<p class="LC_error">'
 2720:            .&mt('Problems occurred in creating the new Excel file.')
 2721:            .' '.&mt('This error has been logged.')
 2722:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2723:            .'</p>'
 2724:         );
 2725:         return (undef);
 2726:     }
 2727:     #
 2728:     $workbook->set_tempdir(LONCAPA::tempdir());
 2729:     #
 2730:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 2731:     return ($workbook,$filename,$format);
 2732: }
 2733: 
 2734: ###############################################################
 2735: ###############################################################
 2736: 
 2737: =pod
 2738: 
 2739: =item * &create_text_file()
 2740: 
 2741: Create a file to write to and eventually make available to the user.
 2742: If file creation fails, outputs an error message on the request object and 
 2743: return undefs.
 2744: 
 2745: Inputs: Apache request object, and file suffix
 2746: 
 2747: Returns (undef) on failure, 
 2748:     Filehandle and filename on success.
 2749: 
 2750: =cut
 2751: 
 2752: ###############################################################
 2753: ###############################################################
 2754: sub create_text_file {
 2755:     my ($r,$suffix) = @_;
 2756:     if (! defined($suffix)) { $suffix = 'txt'; };
 2757:     my $fh;
 2758:     my $filename = '/prtspool/'.
 2759:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2760:         time.'_'.rand(1000000000).'.'.$suffix;
 2761:     $fh = Apache::File->new('>/home/httpd'.$filename);
 2762:     if (! defined($fh)) {
 2763:         $r->log_error("Couldn't open $filename for output $!");
 2764:         $r->print(
 2765:             '<p class="LC_error">'
 2766:            .&mt('Problems occurred in creating the output file.')
 2767:            .' '.&mt('This error has been logged.')
 2768:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2769:            .'</p>'
 2770:         );
 2771:     }
 2772:     return ($fh,$filename)
 2773: }
 2774: 
 2775: 
 2776: =pod 
 2777: 
 2778: =back
 2779: 
 2780: =cut
 2781: 
 2782: ###############################################################
 2783: ##        Home server <option> list generating code          ##
 2784: ###############################################################
 2785: 
 2786: # ------------------------------------------
 2787: 
 2788: sub domain_select {
 2789:     my ($name,$value,$multiple,$incdoms,$excdoms)=@_;
 2790:     my @possdoms;
 2791:     if (ref($incdoms) eq 'ARRAY') {
 2792:         @possdoms = @{$incdoms};
 2793:     } else {
 2794:         @possdoms = &Apache::lonnet::all_domains();
 2795:     }
 2796: 
 2797:     my %domains=map { 
 2798: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 2799:     } @possdoms;
 2800: 
 2801:     if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
 2802:         foreach my $dom (@{$excdoms}) {
 2803:             delete($domains{$dom});
 2804:         }
 2805:     }
 2806: 
 2807:     if ($multiple) {
 2808: 	$domains{''}=&mt('Any domain');
 2809: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2810: 	return &multiple_select_form($name,$value,4,\%domains);
 2811:     } else {
 2812: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2813: 	return &select_form($name,$value,\%domains);
 2814:     }
 2815: }
 2816: 
 2817: #-------------------------------------------
 2818: 
 2819: =pod
 2820: 
 2821: =head1 Routines for form select boxes
 2822: 
 2823: =over 4
 2824: 
 2825: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 2826: 
 2827: Returns a string containing a <select> element int multiple mode
 2828: 
 2829: 
 2830: Args:
 2831:   $name - name of the <select> element
 2832:   $value - scalar or array ref of values that should already be selected
 2833:   $size - number of rows long the select element is
 2834:   $hash - the elements should be 'option' => 'shown text'
 2835:           (shown text should already have been &mt())
 2836:   $order - (optional) array ref of the order to show the elements in
 2837: 
 2838: =cut
 2839: 
 2840: #-------------------------------------------
 2841: sub multiple_select_form {
 2842:     my ($name,$value,$size,$hash,$order)=@_;
 2843:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 2844:     my $output='';
 2845:     if (! defined($size)) {
 2846:         $size = 4;
 2847:         if (scalar(keys(%$hash))<4) {
 2848:             $size = scalar(keys(%$hash));
 2849:         }
 2850:     }
 2851:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 2852:     my @order;
 2853:     if (ref($order) eq 'ARRAY')  {
 2854:         @order = @{$order};
 2855:     } else {
 2856:         @order = sort(keys(%$hash));
 2857:     }
 2858:     if (exists($$hash{'select_form_order'})) {
 2859:         @order = @{$$hash{'select_form_order'}};
 2860:     }
 2861:         
 2862:     foreach my $key (@order) {
 2863:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 2864:         $output.='selected="selected" ' if ($selected{$key});
 2865:         $output.='>'.$hash->{$key}."</option>\n";
 2866:     }
 2867:     $output.="</select>\n";
 2868:     return $output;
 2869: }
 2870: 
 2871: #-------------------------------------------
 2872: 
 2873: =pod
 2874: 
 2875: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
 2876: 
 2877: Returns a string containing a <select name='$name' size='1'> form to 
 2878: allow a user to select options from a ref to a hash containing:
 2879: option_name => displayed text. An optional $onchange can include
 2880: a javascript onchange item, e.g., onchange="this.form.submit();".
 2881: An optional arg -- $readonly -- if true will cause the select form
 2882: to be disabled, e.g., for the case where an instructor has a section-
 2883: specific role, and is viewing/modifying parameters. 
 2884: 
 2885: See lonrights.pm for an example invocation and use.
 2886: 
 2887: =cut
 2888: 
 2889: #-------------------------------------------
 2890: sub select_form {
 2891:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
 2892:     return unless (ref($hashref) eq 'HASH');
 2893:     if ($onchange) {
 2894:         $onchange = ' onchange="'.$onchange.'"';
 2895:     }
 2896:     my $disabled;
 2897:     if ($readonly) {
 2898:         $disabled = ' disabled="disabled"';
 2899:     }
 2900:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2901:     my @keys;
 2902:     if (exists($hashref->{'select_form_order'})) {
 2903: 	@keys=@{$hashref->{'select_form_order'}};
 2904:     } else {
 2905: 	@keys=sort(keys(%{$hashref}));
 2906:     }
 2907:     foreach my $key (@keys) {
 2908:         $selectform.=
 2909: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2910:             ($key eq $def ? 'selected="selected" ' : '').
 2911:                 ">".$hashref->{$key}."</option>\n";
 2912:     }
 2913:     $selectform.="</select>";
 2914:     return $selectform;
 2915: }
 2916: 
 2917: # For display filters
 2918: 
 2919: sub display_filter {
 2920:     my ($context) = @_;
 2921:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2922:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2923:     my $phraseinput = 'hidden';
 2924:     my $includeinput = 'hidden';
 2925:     my ($checked,$includetypestext);
 2926:     if ($env{'form.displayfilter'} eq 'containing') {
 2927:         $phraseinput = 'text'; 
 2928:         if ($context eq 'parmslog') {
 2929:             $includeinput = 'checkbox';
 2930:             if ($env{'form.includetypes'}) {
 2931:                 $checked = ' checked="checked"';
 2932:             }
 2933:             $includetypestext = &mt('Include parameter types');
 2934:         }
 2935:     } else {
 2936:         $includetypestext = '&nbsp;';
 2937:     }
 2938:     my ($additional,$secondid,$thirdid);
 2939:     if ($context eq 'parmslog') {
 2940:         $additional = 
 2941:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2942:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2943:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2944:             '</label>';
 2945:         $secondid = 'includetypes';
 2946:         $thirdid = 'includetypestext';
 2947:     }
 2948:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2949:                                                     '$secondid','$thirdid')";
 2950:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2951: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},'',undef,
 2952: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2953: 	   '</label></span> <span class="LC_nobreak">'.
 2954:            &mt('Filter: [_1]',
 2955: 	   &select_form($env{'form.displayfilter'},
 2956: 			'displayfilter',
 2957: 			{'currentfolder' => 'Current folder/page',
 2958: 			 'containing' => 'Containing phrase',
 2959: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2960: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2961:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2962:                          '" />'.$additional;
 2963: }
 2964: 
 2965: sub display_filter_js {
 2966:     my $includetext = &mt('Include parameter types');
 2967:     return <<"ENDJS";
 2968:   
 2969: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2970:     var firstType = 'hidden';
 2971:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2972:         firstType = 'text';
 2973:     }
 2974:     firstObject = document.getElementById(firstid);
 2975:     if (typeof(firstObject) == 'object') {
 2976:         if (firstObject.type != firstType) {
 2977:             changeInputType(firstObject,firstType);
 2978:         }
 2979:     }
 2980:     if (context == 'parmslog') {
 2981:         var secondType = 'hidden';
 2982:         if (firstType == 'text') {
 2983:             secondType = 'checkbox';
 2984:         }
 2985:         secondObject = document.getElementById(secondid);  
 2986:         if (typeof(secondObject) == 'object') {
 2987:             if (secondObject.type != secondType) {
 2988:                 changeInputType(secondObject,secondType);
 2989:             }
 2990:         }
 2991:         var textItem = document.getElementById(thirdid);
 2992:         var currtext = textItem.innerHTML;
 2993:         var newtext;
 2994:         if (firstType == 'text') {
 2995:             newtext = '$includetext';
 2996:         } else {
 2997:             newtext = '&nbsp;';
 2998:         }
 2999:         if (currtext != newtext) {
 3000:             textItem.innerHTML = newtext;
 3001:         }
 3002:     }
 3003:     return;
 3004: }
 3005: 
 3006: function changeInputType(oldObject,newType) {
 3007:     var newObject = document.createElement('input');
 3008:     newObject.type = newType;
 3009:     if (oldObject.size) {
 3010:         newObject.size = oldObject.size;
 3011:     }
 3012:     if (oldObject.value) {
 3013:         newObject.value = oldObject.value;
 3014:     }
 3015:     if (oldObject.name) {
 3016:         newObject.name = oldObject.name;
 3017:     }
 3018:     if (oldObject.id) {
 3019:         newObject.id = oldObject.id;
 3020:     }
 3021:     oldObject.parentNode.replaceChild(newObject,oldObject);
 3022:     return;
 3023: }
 3024: 
 3025: ENDJS
 3026: }
 3027: 
 3028: sub gradeleveldescription {
 3029:     my $gradelevel=shift;
 3030:     my %gradelevels=(0 => 'Not specified',
 3031: 		     1 => 'Grade 1',
 3032: 		     2 => 'Grade 2',
 3033: 		     3 => 'Grade 3',
 3034: 		     4 => 'Grade 4',
 3035: 		     5 => 'Grade 5',
 3036: 		     6 => 'Grade 6',
 3037: 		     7 => 'Grade 7',
 3038: 		     8 => 'Grade 8',
 3039: 		     9 => 'Grade 9',
 3040: 		     10 => 'Grade 10',
 3041: 		     11 => 'Grade 11',
 3042: 		     12 => 'Grade 12',
 3043: 		     13 => 'Grade 13',
 3044: 		     14 => '100 Level',
 3045: 		     15 => '200 Level',
 3046: 		     16 => '300 Level',
 3047: 		     17 => '400 Level',
 3048: 		     18 => 'Graduate Level');
 3049:     return &mt($gradelevels{$gradelevel});
 3050: }
 3051: 
 3052: sub select_level_form {
 3053:     my ($deflevel,$name)=@_;
 3054:     unless ($deflevel) { $deflevel=0; }
 3055:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 3056:     for (my $i=0; $i<=18; $i++) {
 3057:         $selectform.="<option value=\"$i\" ".
 3058:             ($i==$deflevel ? 'selected="selected" ' : '').
 3059:                 ">".&gradeleveldescription($i)."</option>\n";
 3060:     }
 3061:     $selectform.="</select>";
 3062:     return $selectform;
 3063: }
 3064: 
 3065: #-------------------------------------------
 3066: 
 3067: =pod
 3068: 
 3069: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
 3070: 
 3071: Returns a string containing a <select name='$name' size='1'> form to 
 3072: allow a user to select the domain to preform an operation in.  
 3073: See loncreateuser.pm for an example invocation and use.
 3074: 
 3075: If the $includeempty flag is set, it also includes an empty choice ("no domain
 3076: selected");
 3077: 
 3078: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 3079: 
 3080: 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.
 3081: 
 3082: The optional $incdoms is a reference to an array of domains which will be the only available options.
 3083: 
 3084: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
 3085: 
 3086: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
 3087: 
 3088: =cut
 3089: 
 3090: #-------------------------------------------
 3091: sub select_dom_form {
 3092:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
 3093:     if ($onchange) {
 3094:         $onchange = ' onchange="'.$onchange.'"';
 3095:     }
 3096:     if ($disabled) {
 3097:         $disabled = ' disabled="disabled"';
 3098:     }
 3099:     my (@domains,%exclude);
 3100:     if (ref($incdoms) eq 'ARRAY') {
 3101:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 3102:     } else {
 3103:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 3104:     }
 3105:     if ($includeempty) { @domains=('',@domains); }
 3106:     if (ref($excdoms) eq 'ARRAY') {
 3107:         map { $exclude{$_} = 1; } @{$excdoms}; 
 3108:     }
 3109:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 3110:     foreach my $dom (@domains) {
 3111:         next if ($exclude{$dom});
 3112:         $selectdomain.="<option value=\"$dom\" ".
 3113:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 3114:         if ($showdomdesc) {
 3115:             if ($dom ne '') {
 3116:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 3117:                 if ($domdesc ne '') {
 3118:                     $selectdomain .= ' ('.$domdesc.')';
 3119:                 }
 3120:             } 
 3121:         }
 3122:         $selectdomain .= "</option>\n";
 3123:     }
 3124:     $selectdomain.="</select>";
 3125:     return $selectdomain;
 3126: }
 3127: 
 3128: #-------------------------------------------
 3129: 
 3130: =pod
 3131: 
 3132: =item * &home_server_form_item($domain,$name,$defaultflag)
 3133: 
 3134: input: 4 arguments (two required, two optional) - 
 3135:     $domain - domain of new user
 3136:     $name - name of form element
 3137:     $default - Value of 'default' causes a default item to be first 
 3138:                             option, and selected by default. 
 3139:     $hide - Value of 'hide' causes hiding of the name of the server, 
 3140:                             if 1 server found, or default, if 0 found.
 3141: output: returns 2 items: 
 3142: (a) form element which contains either:
 3143:    (i) <select name="$name">
 3144:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 3145:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 3146:        </select>
 3147:        form item if there are multiple library servers in $domain, or
 3148:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 3149:        if there is only one library server in $domain.
 3150: 
 3151: (b) number of library servers found.
 3152: 
 3153: See loncreateuser.pm for example of use.
 3154: 
 3155: =cut
 3156: 
 3157: #-------------------------------------------
 3158: sub home_server_form_item {
 3159:     my ($domain,$name,$default,$hide) = @_;
 3160:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 3161:     my $result;
 3162:     my $numlib = keys(%servers);
 3163:     if ($numlib > 1) {
 3164:         $result .= '<select name="'.$name.'" />'."\n";
 3165:         if ($default) {
 3166:             $result .= '<option value="default" selected="selected">'.&mt('default').
 3167:                        '</option>'."\n";
 3168:         }
 3169:         foreach my $hostid (sort(keys(%servers))) {
 3170:             $result.= '<option value="'.$hostid.'">'.
 3171: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 3172:         }
 3173:         $result .= '</select>'."\n";
 3174:     } elsif ($numlib == 1) {
 3175:         my $hostid;
 3176:         foreach my $item (keys(%servers)) {
 3177:             $hostid = $item;
 3178:         }
 3179:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 3180:                    $hostid.'" />';
 3181:                    if (!$hide) {
 3182:                        $result .= $hostid.' '.$servers{$hostid};
 3183:                    }
 3184:                    $result .= "\n";
 3185:     } elsif ($default) {
 3186:         $result .= '<input type="hidden" name="'.$name.
 3187:                    '" value="default" />';
 3188:                    if (!$hide) {
 3189:                        $result .= &mt('default');
 3190:                    }
 3191:                    $result .= "\n";
 3192:     }
 3193:     return ($result,$numlib);
 3194: }
 3195: 
 3196: =pod
 3197: 
 3198: =back 
 3199: 
 3200: =cut
 3201: 
 3202: ###############################################################
 3203: ##                  Decoding User Agent                      ##
 3204: ###############################################################
 3205: 
 3206: =pod
 3207: 
 3208: =head1 Decoding the User Agent
 3209: 
 3210: =over 4
 3211: 
 3212: =item * &decode_user_agent()
 3213: 
 3214: Inputs: $r
 3215: 
 3216: Outputs:
 3217: 
 3218: =over 4
 3219: 
 3220: =item * $httpbrowser
 3221: 
 3222: =item * $clientbrowser
 3223: 
 3224: =item * $clientversion
 3225: 
 3226: =item * $clientmathml
 3227: 
 3228: =item * $clientunicode
 3229: 
 3230: =item * $clientos
 3231: 
 3232: =item * $clientmobile
 3233: 
 3234: =item * $clientinfo
 3235: 
 3236: =item * $clientosversion
 3237: 
 3238: =back
 3239: 
 3240: =back 
 3241: 
 3242: =cut
 3243: 
 3244: ###############################################################
 3245: ###############################################################
 3246: sub decode_user_agent {
 3247:     my ($r)=@_;
 3248:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 3249:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 3250:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 3251:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 3252:     my $clientbrowser='unknown';
 3253:     my $clientversion='0';
 3254:     my $clientmathml='';
 3255:     my $clientunicode='0';
 3256:     my $clientmobile=0;
 3257:     my $clientosversion='';
 3258:     for (my $i=0;$i<=$#browsertype;$i++) {
 3259:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
 3260: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 3261: 	    $clientbrowser=$bname;
 3262:             $httpbrowser=~/$vreg/i;
 3263: 	    $clientversion=$1;
 3264:             $clientmathml=($clientversion>=$minv);
 3265:             $clientunicode=($clientversion>=$univ);
 3266: 	}
 3267:     }
 3268:     my $clientos='unknown';
 3269:     my $clientinfo;
 3270:     if (($httpbrowser=~/linux/i) ||
 3271:         ($httpbrowser=~/unix/i) ||
 3272:         ($httpbrowser=~/ux/i) ||
 3273:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 3274:     if (($httpbrowser=~/vax/i) ||
 3275:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 3276:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 3277:     if (($httpbrowser=~/mac/i) ||
 3278:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 3279:     if ($httpbrowser=~/win/i) {
 3280:         $clientos='win';
 3281:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
 3282:             $clientosversion = $1;
 3283:         }
 3284:     }
 3285:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 3286:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 3287:         $clientmobile=lc($1);
 3288:     }
 3289:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 3290:         $clientinfo = 'firefox-'.$1;
 3291:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 3292:         $clientinfo = 'chromeframe-'.$1;
 3293:     }
 3294:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 3295:             $clientunicode,$clientos,$clientmobile,$clientinfo,
 3296:             $clientosversion);
 3297: }
 3298: 
 3299: ###############################################################
 3300: ##    Authentication changing form generation subroutines    ##
 3301: ###############################################################
 3302: ##
 3303: ## All of the authform_xxxxxxx subroutines take their inputs in a
 3304: ## hash, and have reasonable default values.
 3305: ##
 3306: ##    formname = the name given in the <form> tag.
 3307: #-------------------------------------------
 3308: 
 3309: =pod
 3310: 
 3311: =head1 Authentication Routines
 3312: 
 3313: =over 4
 3314: 
 3315: =item * &authform_xxxxxx()
 3316: 
 3317: The authform_xxxxxx subroutines provide javascript and html forms which 
 3318: handle some of the conveniences required for authentication forms.  
 3319: This is not an optimal method, but it works.  
 3320: 
 3321: =over 4
 3322: 
 3323: =item * authform_header
 3324: 
 3325: =item * authform_authorwarning
 3326: 
 3327: =item * authform_nochange
 3328: 
 3329: =item * authform_kerberos
 3330: 
 3331: =item * authform_internal
 3332: 
 3333: =item * authform_filesystem
 3334: 
 3335: =item * authform_lti
 3336: 
 3337: =back
 3338: 
 3339: See loncreateuser.pm for invocation and use examples.
 3340: 
 3341: =cut
 3342: 
 3343: #-------------------------------------------
 3344: sub authform_header{  
 3345:     my %in = (
 3346:         formname => 'cu',
 3347:         kerb_def_dom => '',
 3348:         @_,
 3349:     );
 3350:     $in{'formname'} = 'document.' . $in{'formname'};
 3351:     my $result='';
 3352: 
 3353: #---------------------------------------------- Code for upper case translation
 3354:     my $Javascript_toUpperCase;
 3355:     unless ($in{kerb_def_dom}) {
 3356:         $Javascript_toUpperCase =<<"END";
 3357:         switch (choice) {
 3358:            case 'krb': currentform.elements[choicearg].value =
 3359:                currentform.elements[choicearg].value.toUpperCase();
 3360:                break;
 3361:            default:
 3362:         }
 3363: END
 3364:     } else {
 3365:         $Javascript_toUpperCase = "";
 3366:     }
 3367: 
 3368:     my $radioval = "'nochange'";
 3369:     if (defined($in{'curr_authtype'})) {
 3370:         if ($in{'curr_authtype'} ne '') {
 3371:             $radioval = "'".$in{'curr_authtype'}."arg'";
 3372:         }
 3373:     }
 3374:     my $argfield = 'null';
 3375:     if (defined($in{'mode'})) {
 3376:         if ($in{'mode'} eq 'modifycourse')  {
 3377:             if (defined($in{'curr_autharg'})) {
 3378:                 if ($in{'curr_autharg'} ne '') {
 3379:                     $argfield = "'$in{'curr_autharg'}'";
 3380:                 }
 3381:             }
 3382:         }
 3383:     }
 3384: 
 3385:     $result.=<<"END";
 3386: var current = new Object();
 3387: current.radiovalue = $radioval;
 3388: current.argfield = $argfield;
 3389: 
 3390: function changed_radio(choice,currentform) {
 3391:     var choicearg = choice + 'arg';
 3392:     // If a radio button in changed, we need to change the argfield
 3393:     if (current.radiovalue != choice) {
 3394:         current.radiovalue = choice;
 3395:         if (current.argfield != null) {
 3396:             currentform.elements[current.argfield].value = '';
 3397:         }
 3398:         if (choice == 'nochange') {
 3399:             current.argfield = null;
 3400:         } else {
 3401:             current.argfield = choicearg;
 3402:             switch(choice) {
 3403:                 case 'krb': 
 3404:                     currentform.elements[current.argfield].value = 
 3405:                         "$in{'kerb_def_dom'}";
 3406:                 break;
 3407:               default:
 3408:                 break;
 3409:             }
 3410:         }
 3411:     }
 3412:     return;
 3413: }
 3414: 
 3415: function changed_text(choice,currentform) {
 3416:     var choicearg = choice + 'arg';
 3417:     if (currentform.elements[choicearg].value !='') {
 3418:         $Javascript_toUpperCase
 3419:         // clear old field
 3420:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 3421:             currentform.elements[current.argfield].value = '';
 3422:         }
 3423:         current.argfield = choicearg;
 3424:     }
 3425:     set_auth_radio_buttons(choice,currentform);
 3426:     return;
 3427: }
 3428: 
 3429: function set_auth_radio_buttons(newvalue,currentform) {
 3430:     var numauthchoices = currentform.login.length;
 3431:     if (typeof numauthchoices  == "undefined") {
 3432:         return;
 3433:     } 
 3434:     var i=0;
 3435:     while (i < numauthchoices) {
 3436:         if (currentform.login[i].value == newvalue) { break; }
 3437:         i++;
 3438:     }
 3439:     if (i == numauthchoices) {
 3440:         return;
 3441:     }
 3442:     current.radiovalue = newvalue;
 3443:     currentform.login[i].checked = true;
 3444:     return;
 3445: }
 3446: END
 3447:     return $result;
 3448: }
 3449: 
 3450: sub authform_authorwarning {
 3451:     my $result='';
 3452:     $result='<i>'.
 3453:         &mt('As a general rule, only authors or co-authors should be '.
 3454:             'filesystem authenticated '.
 3455:             '(which allows access to the server filesystem).')."</i>\n";
 3456:     return $result;
 3457: }
 3458: 
 3459: sub authform_nochange {
 3460:     my %in = (
 3461:               formname => 'document.cu',
 3462:               kerb_def_dom => 'MSU.EDU',
 3463:               @_,
 3464:           );
 3465:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3466:     my $result;
 3467:     if (!$authnum) {
 3468:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 3469:     } else {
 3470:         $result = '<label>'.&mt('[_1] Do not change login data',
 3471:                   '<input type="radio" name="login" value="nochange" '.
 3472:                   'checked="checked" onclick="'.
 3473:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 3474: 	    '</label>';
 3475:     }
 3476:     return $result;
 3477: }
 3478: 
 3479: sub authform_kerberos {
 3480:     my %in = (
 3481:               formname => 'document.cu',
 3482:               kerb_def_dom => 'MSU.EDU',
 3483:               kerb_def_auth => 'krb4',
 3484:               @_,
 3485:               );
 3486:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 3487:         $autharg,$jscall,$disabled);
 3488:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3489:     if ($in{'kerb_def_auth'} eq 'krb5') {
 3490:        $check5 = ' checked="checked"';
 3491:     } else {
 3492:        $check4 = ' checked="checked"';
 3493:     }
 3494:     if ($in{'readonly'}) {
 3495:         $disabled = ' disabled="disabled"';
 3496:     }
 3497:     $krbarg = $in{'kerb_def_dom'};
 3498:     if (defined($in{'curr_authtype'})) {
 3499:         if ($in{'curr_authtype'} eq 'krb') {
 3500:             $krbcheck = ' checked="checked"';
 3501:             if (defined($in{'mode'})) {
 3502:                 if ($in{'mode'} eq 'modifyuser') {
 3503:                     $krbcheck = '';
 3504:                 }
 3505:             }
 3506:             if (defined($in{'curr_kerb_ver'})) {
 3507:                 if ($in{'curr_krb_ver'} eq '5') {
 3508:                     $check5 = ' checked="checked"';
 3509:                     $check4 = '';
 3510:                 } else {
 3511:                     $check4 = ' checked="checked"';
 3512:                     $check5 = '';
 3513:                 }
 3514:             }
 3515:             if (defined($in{'curr_autharg'})) {
 3516:                 $krbarg = $in{'curr_autharg'};
 3517:             }
 3518:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 3519:                 if (defined($in{'curr_autharg'})) {
 3520:                     $result = 
 3521:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 3522:         $in{'curr_autharg'},$krbver);
 3523:                 } else {
 3524:                     $result =
 3525:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 3526:                 }
 3527:                 return $result; 
 3528:             }
 3529:         }
 3530:     } else {
 3531:         if ($authnum == 1) {
 3532:             $authtype = '<input type="hidden" name="login" value="krb" />';
 3533:         }
 3534:     }
 3535:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 3536:         return;
 3537:     } elsif ($authtype eq '') {
 3538:         if (defined($in{'mode'})) {
 3539:             if ($in{'mode'} eq 'modifycourse') {
 3540:                 if ($authnum == 1) {
 3541:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
 3542:                 }
 3543:             }
 3544:         }
 3545:     }
 3546:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 3547:     if ($authtype eq '') {
 3548:         $authtype = '<input type="radio" name="login" value="krb" '.
 3549:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 3550:                     $krbcheck.$disabled.' />';
 3551:     }
 3552:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 3553:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 3554:          $in{'curr_authtype'} eq 'krb5') ||
 3555:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 3556:          $in{'curr_authtype'} eq 'krb4')) {
 3557:         $result .= &mt
 3558:         ('[_1] Kerberos authenticated with domain [_2] '.
 3559:          '[_3] Version 4 [_4] Version 5 [_5]',
 3560:          '<label>'.$authtype,
 3561:          '</label><input type="text" size="10" name="krbarg" '.
 3562:              'value="'.$krbarg.'" '.
 3563:              'onchange="'.$jscall.'"'.$disabled.' />',
 3564:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
 3565:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
 3566: 	 '</label>');
 3567:     } elsif ($can_assign{'krb4'}) {
 3568:         $result .= &mt
 3569:         ('[_1] Kerberos authenticated with domain [_2] '.
 3570:          '[_3] Version 4 [_4]',
 3571:          '<label>'.$authtype,
 3572:          '</label><input type="text" size="10" name="krbarg" '.
 3573:              'value="'.$krbarg.'" '.
 3574:              'onchange="'.$jscall.'"'.$disabled.' />',
 3575:          '<label><input type="hidden" name="krbver" value="4" />',
 3576:          '</label>');
 3577:     } elsif ($can_assign{'krb5'}) {
 3578:         $result .= &mt
 3579:         ('[_1] Kerberos authenticated with domain [_2] '.
 3580:          '[_3] Version 5 [_4]',
 3581:          '<label>'.$authtype,
 3582:          '</label><input type="text" size="10" name="krbarg" '.
 3583:              'value="'.$krbarg.'" '.
 3584:              'onchange="'.$jscall.'"'.$disabled.' />',
 3585:          '<label><input type="hidden" name="krbver" value="5" />',
 3586:          '</label>');
 3587:     }
 3588:     return $result;
 3589: }
 3590: 
 3591: sub authform_internal {
 3592:     my %in = (
 3593:                 formname => 'document.cu',
 3594:                 kerb_def_dom => 'MSU.EDU',
 3595:                 @_,
 3596:                 );
 3597:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
 3598:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3599:     if ($in{'readonly'}) {
 3600:         $disabled = ' disabled="disabled"';
 3601:     }
 3602:     if (defined($in{'curr_authtype'})) {
 3603:         if ($in{'curr_authtype'} eq 'int') {
 3604:             if ($can_assign{'int'}) {
 3605:                 $intcheck = 'checked="checked" ';
 3606:                 if (defined($in{'mode'})) {
 3607:                     if ($in{'mode'} eq 'modifyuser') {
 3608:                         $intcheck = '';
 3609:                     }
 3610:                 }
 3611:                 if (defined($in{'curr_autharg'})) {
 3612:                     $intarg = $in{'curr_autharg'};
 3613:                 }
 3614:             } else {
 3615:                 $result = &mt('Currently internally authenticated.');
 3616:                 return $result;
 3617:             }
 3618:         }
 3619:     } else {
 3620:         if ($authnum == 1) {
 3621:             $authtype = '<input type="hidden" name="login" value="int" />';
 3622:         }
 3623:     }
 3624:     if (!$can_assign{'int'}) {
 3625:         return;
 3626:     } elsif ($authtype eq '') {
 3627:         if (defined($in{'mode'})) {
 3628:             if ($in{'mode'} eq 'modifycourse') {
 3629:                 if ($authnum == 1) {
 3630:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
 3631:                 }
 3632:             }
 3633:         }
 3634:     }
 3635:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 3636:     if ($authtype eq '') {
 3637:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 3638:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
 3639:     }
 3640:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 3641:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3642:     $result = &mt
 3643:         ('[_1] Internally authenticated (with initial password [_2])',
 3644:          '<label>'.$authtype,'</label>'.$autharg);
 3645:     $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>';
 3646:     return $result;
 3647: }
 3648: 
 3649: sub authform_local {
 3650:     my %in = (
 3651:               formname => 'document.cu',
 3652:               kerb_def_dom => 'MSU.EDU',
 3653:               @_,
 3654:               );
 3655:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
 3656:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3657:     if ($in{'readonly'}) {
 3658:         $disabled = ' disabled="disabled"';
 3659:     } 
 3660:     if (defined($in{'curr_authtype'})) {
 3661:         if ($in{'curr_authtype'} eq 'loc') {
 3662:             if ($can_assign{'loc'}) {
 3663:                 $loccheck = 'checked="checked" ';
 3664:                 if (defined($in{'mode'})) {
 3665:                     if ($in{'mode'} eq 'modifyuser') {
 3666:                         $loccheck = '';
 3667:                     }
 3668:                 }
 3669:                 if (defined($in{'curr_autharg'})) {
 3670:                     $locarg = $in{'curr_autharg'};
 3671:                 }
 3672:             } else {
 3673:                 $result = &mt('Currently using local (institutional) authentication.');
 3674:                 return $result;
 3675:             }
 3676:         }
 3677:     } else {
 3678:         if ($authnum == 1) {
 3679:             $authtype = '<input type="hidden" name="login" value="loc" />';
 3680:         }
 3681:     }
 3682:     if (!$can_assign{'loc'}) {
 3683:         return;
 3684:     } elsif ($authtype eq '') {
 3685:         if (defined($in{'mode'})) {
 3686:             if ($in{'mode'} eq 'modifycourse') {
 3687:                 if ($authnum == 1) {
 3688:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
 3689:                 }
 3690:             }
 3691:         }
 3692:     }
 3693:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 3694:     if ($authtype eq '') {
 3695:         $authtype = '<input type="radio" name="login" value="loc" '.
 3696:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 3697:                     $jscall.'"'.$disabled.' />';
 3698:     }
 3699:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 3700:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3701:     $result = &mt('[_1] Local Authentication with argument [_2]',
 3702:                   '<label>'.$authtype,'</label>'.$autharg);
 3703:     return $result;
 3704: }
 3705: 
 3706: sub authform_filesystem {
 3707:     my %in = (
 3708:               formname => 'document.cu',
 3709:               kerb_def_dom => 'MSU.EDU',
 3710:               @_,
 3711:               );
 3712:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
 3713:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3714:     if ($in{'readonly'}) {
 3715:         $disabled = ' disabled="disabled"';
 3716:     }
 3717:     if (defined($in{'curr_authtype'})) {
 3718:         if ($in{'curr_authtype'} eq 'fsys') {
 3719:             if ($can_assign{'fsys'}) {
 3720:                 $fsyscheck = 'checked="checked" ';
 3721:                 if (defined($in{'mode'})) {
 3722:                     if ($in{'mode'} eq 'modifyuser') {
 3723:                         $fsyscheck = '';
 3724:                     }
 3725:                 }
 3726:             } else {
 3727:                 $result = &mt('Currently Filesystem Authenticated.');
 3728:                 return $result;
 3729:             }
 3730:         }
 3731:     } else {
 3732:         if ($authnum == 1) {
 3733:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 3734:         }
 3735:     }
 3736:     if (!$can_assign{'fsys'}) {
 3737:         return;
 3738:     } elsif ($authtype eq '') {
 3739:         if (defined($in{'mode'})) {
 3740:             if ($in{'mode'} eq 'modifycourse') {
 3741:                 if ($authnum == 1) {
 3742:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
 3743:                 }
 3744:             }
 3745:         }
 3746:     }
 3747:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 3748:     if ($authtype eq '') {
 3749:         $authtype = '<input type="radio" name="login" value="fsys" '.
 3750:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 3751:                     $jscall.'"'.$disabled.' />';
 3752:     }
 3753:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
 3754:                ' onchange="'.$jscall.'"'.$disabled.' />';
 3755:     $result = &mt
 3756:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 3757:          '<label>'.$authtype,'</label>'.$autharg);
 3758:     return $result;
 3759: }
 3760: 
 3761: sub authform_lti {
 3762:     my %in = (
 3763:               formname => 'document.cu',
 3764:               kerb_def_dom => 'MSU.EDU',
 3765:               @_,
 3766:               );
 3767:     my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
 3768:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3769:     if ($in{'readonly'}) {
 3770:         $disabled = ' disabled="disabled"';
 3771:     }
 3772:     if (defined($in{'curr_authtype'})) {
 3773:         if ($in{'curr_authtype'} eq 'lti') {
 3774:             if ($can_assign{'lti'}) {
 3775:                 $lticheck = 'checked="checked" ';
 3776:                 if (defined($in{'mode'})) {
 3777:                     if ($in{'mode'} eq 'modifyuser') {
 3778:                         $lticheck = '';
 3779:                     }
 3780:                 }
 3781:             } else {
 3782:                 $result = &mt('Currently LTI Authenticated.');
 3783:                 return $result;
 3784:             }
 3785:         }
 3786:     } else {
 3787:         if ($authnum == 1) {
 3788:             $authtype = '<input type="hidden" name="login" value="lti" />';
 3789:         }
 3790:     }
 3791:     if (!$can_assign{'lti'}) {
 3792:         return;
 3793:     } elsif ($authtype eq '') {
 3794:         if (defined($in{'mode'})) {
 3795:             if ($in{'mode'} eq 'modifycourse') {
 3796:                 if ($authnum == 1) {
 3797:                     $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
 3798:                 }
 3799:             }
 3800:         }
 3801:     }
 3802:     $jscall = "javascript:changed_radio('lti',$in{'formname'});";
 3803:     if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
 3804:         $authtype = '<input type="radio" name="login" value="lti" '.
 3805:                     $lticheck.' onchange="'.$jscall.'" onclick="'.
 3806:                     $jscall.'"'.$disabled.' />';
 3807:     }
 3808:     $autharg = '<input type="hidden" name="ltiarg" value="" />';
 3809:     if ($authtype) {
 3810:         $result = &mt('[_1] LTI Authenticated',
 3811:                       '<label>'.$authtype.'</label>'.$autharg);
 3812:     } else {
 3813:         $result = '<b>'.&mt('LTI Authenticated').'</b>'.
 3814:                   $autharg;
 3815:     }
 3816:     return $result;
 3817: }
 3818: 
 3819: sub get_assignable_auth {
 3820:     my ($dom) = @_;
 3821:     if ($dom eq '') {
 3822:         $dom = $env{'request.role.domain'};
 3823:     }
 3824:     my %can_assign = (
 3825:                           krb4 => 1,
 3826:                           krb5 => 1,
 3827:                           int  => 1,
 3828:                           loc  => 1,
 3829:                           lti  => 1,
 3830:                      );
 3831:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 3832:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 3833:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 3834:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 3835:             my $context;
 3836:             if ($env{'request.role'} =~ /^au/) {
 3837:                 $context = 'author';
 3838:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
 3839:                 $context = 'domain';
 3840:             } elsif ($env{'request.course.id'}) {
 3841:                 $context = 'course';
 3842:             }
 3843:             if ($context) {
 3844:                 if (ref($authhash->{$context}) eq 'HASH') {
 3845:                    %can_assign = %{$authhash->{$context}}; 
 3846:                 }
 3847:             }
 3848:         }
 3849:     }
 3850:     my $authnum = 0;
 3851:     foreach my $key (keys(%can_assign)) {
 3852:         if ($can_assign{$key}) {
 3853:             $authnum ++;
 3854:         }
 3855:     }
 3856:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 3857:         $authnum --;
 3858:     }
 3859:     return ($authnum,%can_assign);
 3860: }
 3861: 
 3862: sub check_passwd_rules {
 3863:     my ($domain,$plainpass) = @_;
 3864:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
 3865:     my ($min,$max,@chars,@brokerule,$warning);
 3866:     $min = $Apache::lonnet::passwdmin;
 3867:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
 3868:         if ($passwdconf{'min'} =~ /^\d+$/) {
 3869:             if ($passwdconf{'min'} > $min) {
 3870:                 $min = $passwdconf{'min'};
 3871:             }
 3872:         }
 3873:         if ($passwdconf{'max'} =~ /^\d+$/) {
 3874:             $max = $passwdconf{'max'};
 3875:         }
 3876:         @chars = @{$passwdconf{'chars'}};
 3877:     }
 3878:     if (($min) && (length($plainpass) < $min)) {
 3879:         push(@brokerule,'min');
 3880:     }
 3881:     if (($max) && (length($plainpass) > $max)) {
 3882:         push(@brokerule,'max');
 3883:     }
 3884:     if (@chars) {
 3885:         my %rules;
 3886:         map { $rules{$_} = 1; } @chars;
 3887:         if ($rules{'uc'}) {
 3888:             unless ($plainpass =~ /[A-Z]/) {
 3889:                 push(@brokerule,'uc');
 3890:             }
 3891:         }
 3892:         if ($rules{'lc'}) {
 3893:             unless ($plainpass =~ /[a-z]/) {
 3894:                 push(@brokerule,'lc');
 3895:             }
 3896:         }
 3897:         if ($rules{'num'}) {
 3898:             unless ($plainpass =~ /\d/) {
 3899:                 push(@brokerule,'num');
 3900:             }
 3901:         }
 3902:         if ($rules{'spec'}) {
 3903:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
 3904:                 push(@brokerule,'spec');
 3905:             }
 3906:         }
 3907:     }
 3908:     if (@brokerule) {
 3909:         my %rulenames = &Apache::lonlocal::texthash(
 3910:             uc   => 'At least one upper case letter',
 3911:             lc   => 'At least one lower case letter',
 3912:             num  => 'At least one number',
 3913:             spec => 'At least one non-alphanumeric',
 3914:         );
 3915:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
 3916:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
 3917:         $rulenames{'num'} .= ': 0123456789';
 3918:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
 3919:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
 3920:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
 3921:         $warning = &mt('Password did not satisfy the following:').'<ul>';
 3922:         foreach my $rule ('min','max','uc','lc','num','spec') {
 3923:             if (grep(/^$rule$/,@brokerule)) {
 3924:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
 3925:             }
 3926:         }
 3927:         $warning .= '</ul>';
 3928:     }
 3929:     if (wantarray) {
 3930:         return @brokerule;
 3931:     }
 3932:     return $warning;
 3933: }
 3934: 
 3935: sub passwd_validation_js {
 3936:     my ($currpasswdval,$domain,$context,$id) = @_;
 3937:     my (%passwdconf,$alertmsg);
 3938:     if ($context eq 'linkprot') {
 3939:         my %domconfig = &Apache::lonnet::get_dom('configuration',['ltisec'],$domain);
 3940:         if (ref($domconfig{'ltisec'}) eq 'HASH') {
 3941:             if (ref($domconfig{'ltisec'}{'rules'}) eq 'HASH') {
 3942:                 %passwdconf = %{$domconfig{'ltisec'}{'rules'}};
 3943:             }
 3944:         }
 3945:         if ($id eq 'add') {
 3946:             $alertmsg = &mt('Secret for added launcher did not satisfy requirement(s):').'\n\n';
 3947:         } elsif ($id =~ /^\d+$/) {
 3948:             my $pos = $id+1;
 3949:             $alertmsg = &mt('Secret for launcher [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
 3950:         } else {
 3951:             $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
 3952:         }
 3953:     } else {
 3954:         %passwdconf = &Apache::lonnet::get_passwdconf($domain);
 3955:         $alertmsg = &mt('Initial password did not satisfy requirement(s):').'\n\n';
 3956:     }
 3957:     my ($min,$max,@chars,$numrules,$intargjs,%alert);
 3958:     $numrules = 0;
 3959:     $min = $Apache::lonnet::passwdmin;
 3960:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
 3961:         if ($passwdconf{'min'} =~ /^\d+$/) {
 3962:             if ($passwdconf{'min'} > $min) {
 3963:                 $min = $passwdconf{'min'};
 3964:             }
 3965:         }
 3966:         if ($passwdconf{'max'} =~ /^\d+$/) {
 3967:             $max = $passwdconf{'max'};
 3968:             $numrules ++;
 3969:         }
 3970:         @chars = @{$passwdconf{'chars'}};
 3971:         if (@chars) {
 3972:             $numrules ++;
 3973:         }
 3974:     }
 3975:     if ($min > 0) {
 3976:         $numrules ++;
 3977:     }
 3978:     if (($min > 0) || ($max ne '') || (@chars > 0)) {
 3979:         if ($min) {
 3980:             $alert{'min'} = &mt('minimum [quant,_1,character]',$min).'\n';
 3981:         }
 3982:         if ($max) {
 3983:             $alert{'max'} = &mt('maximum [quant,_1,character]',$max).'\n';
 3984:         }
 3985:         my (@charalerts,@charrules);
 3986:         if (@chars) {
 3987:             if (grep(/^uc$/,@chars)) {
 3988:                 push(@charalerts,&mt('contain at least one upper case letter'));
 3989:                 push(@charrules,'uc');
 3990:             }
 3991:             if (grep(/^lc$/,@chars)) {
 3992:                 push(@charalerts,&mt('contain at least one lower case letter'));
 3993:                 push(@charrules,'lc');
 3994:             }
 3995:             if (grep(/^num$/,@chars)) {
 3996:                 push(@charalerts,&mt('contain at least one number'));
 3997:                 push(@charrules,'num');
 3998:             }
 3999:             if (grep(/^spec$/,@chars)) {
 4000:                 push(@charalerts,&mt('contain at least one non-alphanumeric'));
 4001:                 push(@charrules,'spec');
 4002:             }
 4003:         }
 4004:         $intargjs = qq|            var rulesmsg = '';\n|.
 4005:                     qq|            var currpwval = $currpasswdval;\n|;
 4006:             if ($min) {
 4007:                 $intargjs .= qq|
 4008:             if (currpwval.length < $min) {
 4009:                 rulesmsg += ' - $alert{min}';
 4010:             }
 4011: |;
 4012:             }
 4013:             if ($max) {
 4014:                 $intargjs .= qq|
 4015:             if (currpwval.length > $max) {
 4016:                 rulesmsg += ' - $alert{max}';
 4017:             }
 4018: |;
 4019:             }
 4020:             if (@chars > 0) {
 4021:                 my $charrulestr = '"'.join('","',@charrules).'"';
 4022:                 my $charalertstr = '"'.join('","',@charalerts).'"';
 4023:                 $intargjs .= qq|            var brokerules = new Array();\n|.
 4024:                              qq|            var charrules = new Array($charrulestr);\n|.
 4025:                              qq|            var charalerts = new Array($charalertstr);\n|;
 4026:                 my %rules;
 4027:                 map { $rules{$_} = 1; } @chars;
 4028:                 if ($rules{'uc'}) {
 4029:                     $intargjs .= qq|
 4030:             var ucRegExp = /[A-Z]/;
 4031:             if (!ucRegExp.test(currpwval)) {
 4032:                 brokerules.push('uc');
 4033:             }
 4034: |;
 4035:                 }
 4036:                 if ($rules{'lc'}) {
 4037:                     $intargjs .= qq|
 4038:             var lcRegExp = /[a-z]/;
 4039:             if (!lcRegExp.test(currpwval)) {
 4040:                 brokerules.push('lc');
 4041:             }
 4042: |;
 4043:                 }
 4044:                 if ($rules{'num'}) {
 4045:                      $intargjs .= qq|
 4046:             var numRegExp = /[0-9]/;
 4047:             if (!numRegExp.test(currpwval)) {
 4048:                 brokerules.push('num');
 4049:             }
 4050: |;
 4051:                 }
 4052:                 if ($rules{'spec'}) {
 4053:                      $intargjs .= q|
 4054:             var specRegExp = /[!"#$%&'()*+,\-.\/:;<=>?@[\\^\]_`{\|}~]/;
 4055:             if (!specRegExp.test(currpwval)) {
 4056:                 brokerules.push('spec');
 4057:             }
 4058: |;
 4059:                 }
 4060:                 $intargjs .= qq|
 4061:             if (brokerules.length > 0) {
 4062:                 for (var i=0; i<brokerules.length; i++) {
 4063:                     for (var j=0; j<charrules.length; j++) {
 4064:                         if (brokerules[i] == charrules[j]) {
 4065:                             rulesmsg += ' - '+charalerts[j]+'\\n';
 4066:                             break;
 4067:                         }
 4068:                     }
 4069:                 }
 4070:             }
 4071: |;
 4072:             }
 4073:             $intargjs .= qq|
 4074:             if (rulesmsg != '') {
 4075:                 rulesmsg = '$alertmsg'+rulesmsg;
 4076:                 alert(rulesmsg);
 4077:                 return false;
 4078:             }
 4079: |;
 4080:     }
 4081:     return ($numrules,$intargjs);
 4082: }
 4083: 
 4084: ###############################################################
 4085: ##    Get Kerberos Defaults for Domain                 ##
 4086: ###############################################################
 4087: ##
 4088: ## Returns default kerberos version and an associated argument
 4089: ## as listed in file domain.tab. If not listed, provides
 4090: ## appropriate default domain and kerberos version.
 4091: ##
 4092: #-------------------------------------------
 4093: 
 4094: =pod
 4095: 
 4096: =item * &get_kerberos_defaults()
 4097: 
 4098: get_kerberos_defaults($target_domain) returns the default kerberos
 4099: version and domain. If not found, it defaults to version 4 and the 
 4100: domain of the server.
 4101: 
 4102: =over 4
 4103: 
 4104: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 4105: 
 4106: =back
 4107: 
 4108: =back
 4109: 
 4110: =cut
 4111: 
 4112: #-------------------------------------------
 4113: sub get_kerberos_defaults {
 4114:     my $domain=shift;
 4115:     my ($krbdef,$krbdefdom);
 4116:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 4117:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 4118:         $krbdef = $domdefaults{'auth_def'};
 4119:         $krbdefdom = $domdefaults{'auth_arg_def'};
 4120:     } else {
 4121:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 4122:         my $krbdefdom=$1;
 4123:         $krbdefdom=~tr/a-z/A-Z/;
 4124:         $krbdef = "krb4";
 4125:     }
 4126:     return ($krbdef,$krbdefdom);
 4127: }
 4128: 
 4129: 
 4130: ###############################################################
 4131: ##                Thesaurus Functions                        ##
 4132: ###############################################################
 4133: 
 4134: =pod
 4135: 
 4136: =head1 Thesaurus Functions
 4137: 
 4138: =over 4
 4139: 
 4140: =item * &initialize_keywords()
 4141: 
 4142: Initializes the package variable %Keywords if it is empty.  Uses the
 4143: package variable $thesaurus_db_file.
 4144: 
 4145: =cut
 4146: 
 4147: ###################################################
 4148: 
 4149: sub initialize_keywords {
 4150:     return 1 if (scalar keys(%Keywords));
 4151:     # If we are here, %Keywords is empty, so fill it up
 4152:     #   Make sure the file we need exists...
 4153:     if (! -e $thesaurus_db_file) {
 4154:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 4155:                                  " failed because it does not exist");
 4156:         return 0;
 4157:     }
 4158:     #   Set up the hash as a database
 4159:     my %thesaurus_db;
 4160:     if (! tie(%thesaurus_db,'GDBM_File',
 4161:               $thesaurus_db_file,&GDBM_READER(),0640)){
 4162:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 4163:                                  $thesaurus_db_file);
 4164:         return 0;
 4165:     } 
 4166:     #  Get the average number of appearances of a word.
 4167:     my $avecount = $thesaurus_db{'average.count'};
 4168:     #  Put keywords (those that appear > average) into %Keywords
 4169:     while (my ($word,$data)=each (%thesaurus_db)) {
 4170:         my ($count,undef) = split /:/,$data;
 4171:         $Keywords{$word}++ if ($count > $avecount);
 4172:     }
 4173:     untie %thesaurus_db;
 4174:     # Remove special values from %Keywords.
 4175:     foreach my $value ('total.count','average.count') {
 4176:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 4177:   }
 4178:     return 1;
 4179: }
 4180: 
 4181: ###################################################
 4182: 
 4183: =pod
 4184: 
 4185: =item * &keyword($word)
 4186: 
 4187: Returns true if $word is a keyword.  A keyword is a word that appears more 
 4188: than the average number of times in the thesaurus database.  Calls 
 4189: &initialize_keywords
 4190: 
 4191: =cut
 4192: 
 4193: ###################################################
 4194: 
 4195: sub keyword {
 4196:     return if (!&initialize_keywords());
 4197:     my $word=lc(shift());
 4198:     $word=~s/\W//g;
 4199:     return exists($Keywords{$word});
 4200: }
 4201: 
 4202: ###############################################################
 4203: 
 4204: =pod 
 4205: 
 4206: =item * &get_related_words()
 4207: 
 4208: Look up a word in the thesaurus.  Takes a scalar argument and returns
 4209: an array of words.  If the keyword is not in the thesaurus, an empty array
 4210: will be returned.  The order of the words returned is determined by the
 4211: database which holds them.
 4212: 
 4213: Uses global $thesaurus_db_file.
 4214: 
 4215: 
 4216: =cut
 4217: 
 4218: ###############################################################
 4219: sub get_related_words {
 4220:     my $keyword = shift;
 4221:     my %thesaurus_db;
 4222:     if (! -e $thesaurus_db_file) {
 4223:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 4224:                                  "failed because the file does not exist");
 4225:         return ();
 4226:     }
 4227:     if (! tie(%thesaurus_db,'GDBM_File',
 4228:               $thesaurus_db_file,&GDBM_READER(),0640)){
 4229:         return ();
 4230:     } 
 4231:     my @Words=();
 4232:     my $count=0;
 4233:     if (exists($thesaurus_db{$keyword})) {
 4234: 	# The first element is the number of times
 4235: 	# the word appears.  We do not need it now.
 4236: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 4237: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 4238: 	my $threshold=$mostfrequentcount/10;
 4239:         foreach my $possibleword (@RelatedWords) {
 4240:             my ($word,$wordcount)=split(/\,/,$possibleword);
 4241:             if ($wordcount>$threshold) {
 4242: 		push(@Words,$word);
 4243:                 $count++;
 4244:                 if ($count>10) { last; }
 4245: 	    }
 4246:         }
 4247:     }
 4248:     untie %thesaurus_db;
 4249:     return @Words;
 4250: }
 4251: ###############################################################
 4252: #
 4253: #  Spell checking
 4254: #
 4255: 
 4256: =pod
 4257: 
 4258: =back
 4259: 
 4260: =head1 Spell checking
 4261: 
 4262: =over 4
 4263: 
 4264: =item * &check_spelling($wordlist $language)
 4265: 
 4266: Takes a string containing words and feeds it to an external
 4267: spellcheck program via a pipeline. Returns a string containing
 4268: them mis-spelled words.
 4269: 
 4270: Parameters:
 4271: 
 4272: =over 4
 4273: 
 4274: =item - $wordlist
 4275: 
 4276: String that will be fed into the spellcheck program.
 4277: 
 4278: =item - $language
 4279: 
 4280: Language string that specifies the language for which the spell
 4281: check will be performed.
 4282: 
 4283: =back
 4284: 
 4285: =back
 4286: 
 4287: Note: This sub assumes that aspell is installed.
 4288: 
 4289: 
 4290: =cut
 4291: 
 4292: 
 4293: sub check_spelling {
 4294:     my ($wordlist, $language) = @_;
 4295:     my @misspellings;
 4296:     
 4297:     # Generate the speller and set the langauge.
 4298:     # if explicitly selected:
 4299: 
 4300:     my $speller = Text::Aspell->new;
 4301:     if ($language) {
 4302: 	$speller->set_option('lang', $language);
 4303:     }
 4304: 
 4305:     # Turn the word list into an array of words by splittingon whitespace
 4306: 
 4307:     my @words = split(/\s+/, $wordlist);
 4308: 
 4309:     foreach my $word (@words) {
 4310: 	if(! $speller->check($word)) {
 4311: 	    push(@misspellings, $word);
 4312: 	}
 4313:     }
 4314:     return join(' ', @misspellings);
 4315:     
 4316: }
 4317: 
 4318: # -------------------------------------------------------------- Plaintext name
 4319: =pod
 4320: 
 4321: =head1 User Name Functions
 4322: 
 4323: =over 4
 4324: 
 4325: =item * &plainname($uname,$udom,$first)
 4326: 
 4327: Takes a users logon name and returns it as a string in
 4328: "first middle last generation" form 
 4329: if $first is set to 'lastname' then it returns it as
 4330: 'lastname generation, firstname middlename' if their is a lastname
 4331: 
 4332: =cut
 4333: 
 4334: 
 4335: ###############################################################
 4336: sub plainname {
 4337:     my ($uname,$udom,$first)=@_;
 4338:     return if (!defined($uname) || !defined($udom));
 4339:     my %names=&getnames($uname,$udom);
 4340:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 4341: 					  $names{'middlename'},
 4342: 					  $names{'lastname'},
 4343: 					  $names{'generation'},$first);
 4344:     $name=~s/^\s+//;
 4345:     $name=~s/\s+$//;
 4346:     $name=~s/\s+/ /g;
 4347:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 4348:     return $name;
 4349: }
 4350: 
 4351: # -------------------------------------------------------------------- Nickname
 4352: =pod
 4353: 
 4354: =item * &nickname($uname,$udom)
 4355: 
 4356: Gets a users name and returns it as a string as
 4357: 
 4358: "&quot;nickname&quot;"
 4359: 
 4360: if the user has a nickname or
 4361: 
 4362: "first middle last generation"
 4363: 
 4364: if the user does not
 4365: 
 4366: =cut
 4367: 
 4368: sub nickname {
 4369:     my ($uname,$udom)=@_;
 4370:     return if (!defined($uname) || !defined($udom));
 4371:     my %names=&getnames($uname,$udom);
 4372:     my $name=$names{'nickname'};
 4373:     if ($name) {
 4374:        $name='&quot;'.$name.'&quot;'; 
 4375:     } else {
 4376:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 4377: 	     $names{'lastname'}.' '.$names{'generation'};
 4378:        $name=~s/\s+$//;
 4379:        $name=~s/\s+/ /g;
 4380:     }
 4381:     return $name;
 4382: }
 4383: 
 4384: sub getnames {
 4385:     my ($uname,$udom)=@_;
 4386:     return if (!defined($uname) || !defined($udom));
 4387:     if ($udom eq 'public' && $uname eq 'public') {
 4388: 	return ('lastname' => &mt('Public'));
 4389:     }
 4390:     my $id=$uname.':'.$udom;
 4391:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 4392:     if ($cached) {
 4393: 	return %{$names};
 4394:     } else {
 4395: 	my %loadnames=&Apache::lonnet::get('environment',
 4396:                     ['firstname','middlename','lastname','generation','nickname'],
 4397: 					 $udom,$uname);
 4398: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 4399: 	return %loadnames;
 4400:     }
 4401: }
 4402: 
 4403: # -------------------------------------------------------------------- getemails
 4404: 
 4405: =pod
 4406: 
 4407: =item * &getemails($uname,$udom)
 4408: 
 4409: Gets a user's email information and returns it as a hash with keys:
 4410: notification, critnotification, permanentemail
 4411: 
 4412: For notification and critnotification, values are comma-separated lists 
 4413: of e-mail addresses; for permanentemail, value is a single e-mail address.
 4414:  
 4415: 
 4416: =cut
 4417: 
 4418: 
 4419: sub getemails {
 4420:     my ($uname,$udom)=@_;
 4421:     if ($udom eq 'public' && $uname eq 'public') {
 4422: 	return;
 4423:     }
 4424:     if (!$udom) { $udom=$env{'user.domain'}; }
 4425:     if (!$uname) { $uname=$env{'user.name'}; }
 4426:     my $id=$uname.':'.$udom;
 4427:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 4428:     if ($cached) {
 4429: 	return %{$names};
 4430:     } else {
 4431: 	my %loadnames=&Apache::lonnet::get('environment',
 4432:                     			   ['notification','critnotification',
 4433: 					    'permanentemail'],
 4434: 					   $udom,$uname);
 4435: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 4436: 	return %loadnames;
 4437:     }
 4438: }
 4439: 
 4440: sub flush_email_cache {
 4441:     my ($uname,$udom)=@_;
 4442:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4443:     if (!$uname) { $uname=$env{'user.name'};   }
 4444:     return if ($udom eq 'public' && $uname eq 'public');
 4445:     my $id=$uname.':'.$udom;
 4446:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 4447: }
 4448: 
 4449: # -------------------------------------------------------------------- getlangs
 4450: 
 4451: =pod
 4452: 
 4453: =item * &getlangs($uname,$udom)
 4454: 
 4455: Gets a user's language preference and returns it as a hash with key:
 4456: language.
 4457: 
 4458: =cut
 4459: 
 4460: 
 4461: sub getlangs {
 4462:     my ($uname,$udom) = @_;
 4463:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4464:     if (!$uname) { $uname=$env{'user.name'};   }
 4465:     my $id=$uname.':'.$udom;
 4466:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 4467:     if ($cached) {
 4468:         return %{$langs};
 4469:     } else {
 4470:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 4471:                                            $udom,$uname);
 4472:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 4473:         return %loadlangs;
 4474:     }
 4475: }
 4476: 
 4477: sub flush_langs_cache {
 4478:     my ($uname,$udom)=@_;
 4479:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4480:     if (!$uname) { $uname=$env{'user.name'};   }
 4481:     return if ($udom eq 'public' && $uname eq 'public');
 4482:     my $id=$uname.':'.$udom;
 4483:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 4484: }
 4485: 
 4486: # ------------------------------------------------------------------ Screenname
 4487: 
 4488: =pod
 4489: 
 4490: =item * &screenname($uname,$udom)
 4491: 
 4492: Gets a users screenname and returns it as a string
 4493: 
 4494: =cut
 4495: 
 4496: sub screenname {
 4497:     my ($uname,$udom)=@_;
 4498:     if ($uname eq $env{'user.name'} &&
 4499: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 4500:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 4501:     return $names{'screenname'};
 4502: }
 4503: 
 4504: 
 4505: # ------------------------------------------------------------- Confirm Wrapper
 4506: =pod
 4507: 
 4508: =item * &confirmwrapper($message)
 4509: 
 4510: Wrap messages about completion of operation in box
 4511: 
 4512: =cut
 4513: 
 4514: sub confirmwrapper {
 4515:     my ($message)=@_;
 4516:     if ($message) {
 4517:         return "\n".'<div class="LC_confirm_box">'."\n"
 4518:                .$message."\n"
 4519:                .'</div>'."\n";
 4520:     } else {
 4521:         return $message;
 4522:     }
 4523: }
 4524: 
 4525: # ------------------------------------------------------------- Message Wrapper
 4526: 
 4527: sub messagewrapper {
 4528:     my ($link,$username,$domain,$subject,$text)=@_;
 4529:     return 
 4530:         '<a href="/adm/email?compose=individual&amp;'.
 4531:         'recname='.$username.'&amp;recdom='.$domain.
 4532: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 4533:         'title="'.&mt('Send message').'">'.$link.'</a>';
 4534: }
 4535: 
 4536: # --------------------------------------------------------------- Notes Wrapper
 4537: 
 4538: sub noteswrapper {
 4539:     my ($link,$un,$do)=@_;
 4540:     return 
 4541: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 4542: }
 4543: 
 4544: # ------------------------------------------------------------- Aboutme Wrapper
 4545: 
 4546: sub aboutmewrapper {
 4547:     my ($link,$username,$domain,$target,$class)=@_;
 4548:     if (!defined($username)  && !defined($domain)) {
 4549:         return;
 4550:     }
 4551:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 4552: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 4553: }
 4554: 
 4555: # ------------------------------------------------------------ Syllabus Wrapper
 4556: 
 4557: sub syllabuswrapper {
 4558:     my ($linktext,$coursedir,$domain)=@_;
 4559:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 4560: }
 4561: 
 4562: # -----------------------------------------------------------------------------
 4563: 
 4564: sub aboutme_on {
 4565:     my ($uname,$udom)=@_;
 4566:     unless ($uname) { $uname=$env{'user.name'}; }
 4567:     unless ($udom)  { $udom=$env{'user.domain'}; }
 4568:     return if ($udom eq 'public' && $uname eq 'public');
 4569:     my $hashkey=$uname.':'.$udom;
 4570:     my ($aboutme,$cached)=&Apache::lonnet::is_cached_new('aboutme',$hashkey);
 4571:     if ($cached) {
 4572:         return $aboutme;
 4573:     }
 4574:     $aboutme = &Apache::lonnet::usertools_access($uname,$udom,'aboutme');
 4575:     &Apache::lonnet::do_cache_new('aboutme',$hashkey,$aboutme,3600);
 4576:     return $aboutme;
 4577: }
 4578: 
 4579: sub devalidate_aboutme_cache {
 4580:     my ($uname,$udom)=@_;
 4581:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4582:     if (!$uname) { $uname=$env{'user.name'};   }
 4583:     return if ($udom eq 'public' && $uname eq 'public');
 4584:     my $id=$uname.':'.$udom;
 4585:     &Apache::lonnet::devalidate_cache_new('aboutme',$id);
 4586: }
 4587: 
 4588: sub track_student_link {
 4589:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 4590:     my $link ="/adm/trackstudent?";
 4591:     my $title = 'View recent activity';
 4592:     if (defined($sname) && $sname !~ /^\s*$/ &&
 4593:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 4594:         $link .= "selected_student=$sname:$sdom";
 4595:         $title .= ' of this student';
 4596:     } 
 4597:     if (defined($target) && $target !~ /^\s*$/) {
 4598:         $target = qq{target="$target"};
 4599:     } else {
 4600:         $target = '';
 4601:     }
 4602:     if ($start) { $link.='&amp;start='.$start; }
 4603:     if ($only_body) { $link .= '&amp;only_body=1'; }
 4604:     $title = &mt($title);
 4605:     $linktext = &mt($linktext);
 4606:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 4607: 	&help_open_topic('View_recent_activity');
 4608: }
 4609: 
 4610: sub slot_reservations_link {
 4611:     my ($linktext,$sname,$sdom,$target) = @_;
 4612:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 4613:     my $title = 'View slot reservation history';
 4614:     if (defined($sname) && $sname !~ /^\s*$/ &&
 4615:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 4616:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 4617:         $title .= ' of this student';
 4618:     }
 4619:     if (defined($target) && $target !~ /^\s*$/) {
 4620:         $target = qq{target="$target"};
 4621:     } else {
 4622:         $target = '';
 4623:     }
 4624:     $title = &mt($title);
 4625:     $linktext = &mt($linktext);
 4626:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 4627: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 4628: 
 4629: }
 4630: 
 4631: # ===================================================== Display a student photo
 4632: 
 4633: 
 4634: sub student_image_tag {
 4635:     my ($domain,$user)=@_;
 4636:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 4637:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 4638: 	return '<img src="'.$imgsrc.'" align="right" />';
 4639:     } else {
 4640: 	return '';
 4641:     }
 4642: }
 4643: 
 4644: =pod
 4645: 
 4646: =back
 4647: 
 4648: =head1 Access .tab File Data
 4649: 
 4650: =over 4
 4651: 
 4652: =item * &languageids() 
 4653: 
 4654: returns list of all language ids
 4655: 
 4656: =cut
 4657: 
 4658: sub languageids {
 4659:     return sort(keys(%language));
 4660: }
 4661: 
 4662: =pod
 4663: 
 4664: =item * &languagedescription() 
 4665: 
 4666: returns description of a specified language id
 4667: 
 4668: =cut
 4669: 
 4670: sub languagedescription {
 4671:     my $code=shift;
 4672:     return  ($supported_language{$code}?'* ':'').
 4673:             $language{$code}.
 4674: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 4675: }
 4676: 
 4677: =pod
 4678: 
 4679: =item * &plainlanguagedescription
 4680: 
 4681: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 4682: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 4683: 
 4684: =cut
 4685: 
 4686: sub plainlanguagedescription {
 4687:     my $code=shift;
 4688:     return $language{$code};
 4689: }
 4690: 
 4691: =pod
 4692: 
 4693: =item * &supportedlanguagecode
 4694: 
 4695: Returns the supported language code (e.g. sptutf maps to pt) given a language
 4696: code.
 4697: 
 4698: =cut
 4699: 
 4700: sub supportedlanguagecode {
 4701:     my $code=shift;
 4702:     return $supported_language{$code};
 4703: }
 4704: 
 4705: =pod
 4706: 
 4707: =item * &latexlanguage()
 4708: 
 4709: Given a language key code returns the correspondnig language to use
 4710: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 4711: is no supported hyphenation for the language code.
 4712: 
 4713: =cut
 4714: 
 4715: sub latexlanguage {
 4716:     my $code = shift;
 4717:     return $latex_language{$code};
 4718: }
 4719: 
 4720: =pod
 4721: 
 4722: =item * &latexhyphenation()
 4723: 
 4724: Same as above but what's supplied is the language as it might be stored
 4725: in the metadata.
 4726: 
 4727: =cut
 4728: 
 4729: sub latexhyphenation {
 4730:     my $key = shift;
 4731:     return $latex_language_bykey{$key};
 4732: }
 4733: 
 4734: =pod
 4735: 
 4736: =item * &copyrightids() 
 4737: 
 4738: returns list of all copyrights
 4739: 
 4740: =cut
 4741: 
 4742: sub copyrightids {
 4743:     return sort(keys(%cprtag));
 4744: }
 4745: 
 4746: =pod
 4747: 
 4748: =item * &copyrightdescription() 
 4749: 
 4750: returns description of a specified copyright id
 4751: 
 4752: =cut
 4753: 
 4754: sub copyrightdescription {
 4755:     return &mt($cprtag{shift(@_)});
 4756: }
 4757: 
 4758: =pod
 4759: 
 4760: =item * &source_copyrightids() 
 4761: 
 4762: returns list of all source copyrights
 4763: 
 4764: =cut
 4765: 
 4766: sub source_copyrightids {
 4767:     return sort(keys(%scprtag));
 4768: }
 4769: 
 4770: =pod
 4771: 
 4772: =item * &source_copyrightdescription() 
 4773: 
 4774: returns description of a specified source copyright id
 4775: 
 4776: =cut
 4777: 
 4778: sub source_copyrightdescription {
 4779:     return &mt($scprtag{shift(@_)});
 4780: }
 4781: 
 4782: =pod
 4783: 
 4784: =item * &filecategories() 
 4785: 
 4786: returns list of all file categories
 4787: 
 4788: =cut
 4789: 
 4790: sub filecategories {
 4791:     return sort(keys(%category_extensions));
 4792: }
 4793: 
 4794: =pod
 4795: 
 4796: =item * &filecategorytypes() 
 4797: 
 4798: returns list of file types belonging to a given file
 4799: category
 4800: 
 4801: =cut
 4802: 
 4803: sub filecategorytypes {
 4804:     my ($cat) = @_;
 4805:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
 4806:         return @{$category_extensions{lc($cat)}};
 4807:     } else {
 4808:         return ();
 4809:     }
 4810: }
 4811: 
 4812: =pod
 4813: 
 4814: =item * &fileembstyle() 
 4815: 
 4816: returns embedding style for a specified file type
 4817: 
 4818: =cut
 4819: 
 4820: sub fileembstyle {
 4821:     return $fe{lc(shift(@_))};
 4822: }
 4823: 
 4824: sub filemimetype {
 4825:     return $fm{lc(shift(@_))};
 4826: }
 4827: 
 4828: 
 4829: sub filecategoryselect {
 4830:     my ($name,$value)=@_;
 4831:     return &select_form($value,$name,
 4832:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 4833: }
 4834: 
 4835: =pod
 4836: 
 4837: =item * &filedescription() 
 4838: 
 4839: returns description for a specified file type
 4840: 
 4841: =cut
 4842: 
 4843: sub filedescription {
 4844:     my $file_description = $fd{lc(shift())};
 4845:     $file_description =~ s:([\[\]]):~$1:g;
 4846:     return &mt($file_description);
 4847: }
 4848: 
 4849: =pod
 4850: 
 4851: =item * &filedescriptionex() 
 4852: 
 4853: returns description for a specified file type with
 4854: extra formatting
 4855: 
 4856: =cut
 4857: 
 4858: sub filedescriptionex {
 4859:     my $ex=shift;
 4860:     my $file_description = $fd{lc($ex)};
 4861:     $file_description =~ s:([\[\]]):~$1:g;
 4862:     return '.'.$ex.' '.&mt($file_description);
 4863: }
 4864: 
 4865: # End of .tab access
 4866: =pod
 4867: 
 4868: =back
 4869: 
 4870: =cut
 4871: 
 4872: # ------------------------------------------------------------------ File Types
 4873: sub fileextensions {
 4874:     return sort(keys(%fe));
 4875: }
 4876: 
 4877: # ----------------------------------------------------------- Display Languages
 4878: # returns a hash with all desired display languages
 4879: #
 4880: 
 4881: sub display_languages {
 4882:     my %languages=();
 4883:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 4884: 	$languages{$lang}=1;
 4885:     }
 4886:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 4887:     if ($env{'form.displaylanguage'}) {
 4888: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 4889: 	    $languages{$lang}=1;
 4890:         }
 4891:     }
 4892:     return %languages;
 4893: }
 4894: 
 4895: sub languages {
 4896:     my ($possible_langs) = @_;
 4897:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 4898:     if (!ref($possible_langs)) {
 4899: 	if( wantarray ) {
 4900: 	    return @preferred_langs;
 4901: 	} else {
 4902: 	    return $preferred_langs[0];
 4903: 	}
 4904:     }
 4905:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 4906:     my @preferred_possibilities;
 4907:     foreach my $preferred_lang (@preferred_langs) {
 4908: 	if (exists($possibilities{$preferred_lang})) {
 4909: 	    push(@preferred_possibilities, $preferred_lang);
 4910: 	}
 4911:     }
 4912:     if( wantarray ) {
 4913: 	return @preferred_possibilities;
 4914:     }
 4915:     return $preferred_possibilities[0];
 4916: }
 4917: 
 4918: sub user_lang {
 4919:     my ($touname,$toudom,$fromcid) = @_;
 4920:     my @userlangs;
 4921:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 4922:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 4923:                     $env{'course.'.$fromcid.'.languages'}));
 4924:     } else {
 4925:         my %langhash = &getlangs($touname,$toudom);
 4926:         if ($langhash{'languages'} ne '') {
 4927:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 4928:         } else {
 4929:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 4930:             if ($domdefs{'lang_def'} ne '') {
 4931:                 @userlangs = ($domdefs{'lang_def'});
 4932:             }
 4933:         }
 4934:     }
 4935:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 4936:     my $user_lh = Apache::localize->get_handle(@languages);
 4937:     return $user_lh;
 4938: }
 4939: 
 4940: 
 4941: ###############################################################
 4942: ##               Student Answer Attempts                     ##
 4943: ###############################################################
 4944: 
 4945: =pod
 4946: 
 4947: =head1 Alternate Problem Views
 4948: 
 4949: =over 4
 4950: 
 4951: =item * &get_previous_attempt($symb, $username, $domain, $course,
 4952:     $getattempt, $regexp, $gradesub, $usec, $identifier)
 4953: 
 4954: Return string with previous attempt on problem. Arguments:
 4955: 
 4956: =over 4
 4957: 
 4958: =item * $symb: Problem, including path
 4959: 
 4960: =item * $username: username of the desired student
 4961: 
 4962: =item * $domain: domain of the desired student
 4963: 
 4964: =item * $course: Course ID
 4965: 
 4966: =item * $getattempt: Leave blank for all attempts, otherwise put
 4967:     something
 4968: 
 4969: =item * $regexp: if string matches this regexp, the string will be
 4970:     sent to $gradesub
 4971: 
 4972: =item * $gradesub: routine that processes the string if it matches $regexp
 4973: 
 4974: =item * $usec: section of the desired student
 4975: 
 4976: =item * $identifier: counter for student (multiple students one problem) or 
 4977:     problem (one student; whole sequence).
 4978: 
 4979: =back
 4980: 
 4981: The output string is a table containing all desired attempts, if any.
 4982: 
 4983: =cut
 4984: 
 4985: sub get_previous_attempt {
 4986:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
 4987:   my $prevattempts='';
 4988:   no strict 'refs';
 4989:   if ($symb) {
 4990:     my (%returnhash)=
 4991:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 4992:     if ($returnhash{'version'}) {
 4993:       my %lasthash=();
 4994:       my $version;
 4995:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 4996:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
 4997:             if ($key =~ /\.rawrndseed$/) {
 4998:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
 4999:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
 5000:             } else {
 5001:                 $lasthash{$key}=$returnhash{$version.':'.$key};
 5002:             }
 5003:         }
 5004:       }
 5005:       $prevattempts=&start_data_table().&start_data_table_header_row();
 5006:       $prevattempts.='<th>'.&mt('History').'</th>';
 5007:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
 5008:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 5009:       foreach my $key (sort(keys(%lasthash))) {
 5010: 	my ($ign,@parts) = split(/\./,$key);
 5011: 	if ($#parts > 0) {
 5012: 	  my $data=$parts[-1];
 5013:           next if ($data eq 'foilorder');
 5014: 	  pop(@parts);
 5015:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 5016:           if ($data eq 'type') {
 5017:               unless ($showsurv) {
 5018:                   my $id = join(',',@parts);
 5019:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 5020:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 5021:                       $lasthidden{$ign.'.'.$id} = 1;
 5022:                   }
 5023:               }
 5024:               if ($identifier ne '') {
 5025:                   my $id = join(',',@parts);
 5026:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
 5027:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
 5028:                       $hidestatus{$ign.'.'.$id} = 1;
 5029:                   }
 5030:               }
 5031:           } elsif ($data eq 'regrader') {
 5032:               if (($identifier ne '') && (@parts)) {
 5033:                   my $id = join(',',@parts);
 5034:                   $regraded{$ign.'.'.$id} = 1;
 5035:               }
 5036:           } 
 5037: 	} else {
 5038: 	  if ($#parts == 0) {
 5039: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 5040: 	  } else {
 5041: 	    $prevattempts.='<th>'.$ign.'</th>';
 5042: 	  }
 5043: 	}
 5044:       }
 5045:       $prevattempts.=&end_data_table_header_row();
 5046:       if ($getattempt eq '') {
 5047:         my (%solved,%resets,%probstatus);
 5048:         if (($identifier ne '') && (keys(%regraded) > 0)) {
 5049:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 5050:                 foreach my $id (keys(%regraded)) {
 5051:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
 5052:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
 5053:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
 5054:                         push(@{$resets{$id}},$version);
 5055:                     }
 5056:                 }
 5057:             }
 5058:         }
 5059: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 5060:             my (@hidden,@unsolved);
 5061:             if (%typeparts) {
 5062:                 foreach my $id (keys(%typeparts)) {
 5063:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
 5064:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 5065:                         push(@hidden,$id);
 5066:                     } elsif ($identifier ne '') {
 5067:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
 5068:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
 5069:                                 ($hidestatus{$id})) {
 5070:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
 5071:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
 5072:                                 push(@{$solved{$id}},$version);
 5073:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
 5074:                                      (ref($solved{$id}) eq 'ARRAY')) {
 5075:                                 my $skip;
 5076:                                 if (ref($resets{$id}) eq 'ARRAY') {
 5077:                                     foreach my $reset (@{$resets{$id}}) {
 5078:                                         if ($reset > $solved{$id}[-1]) {
 5079:                                             $skip=1;
 5080:                                             last;
 5081:                                         }
 5082:                                     }
 5083:                                 }
 5084:                                 unless ($skip) {
 5085:                                     my ($ign,$partslist) = split(/\./,$id,2);
 5086:                                     push(@unsolved,$partslist);
 5087:                                 }
 5088:                             }
 5089:                         }
 5090:                     }
 5091:                 }
 5092:             }
 5093:             $prevattempts.=&start_data_table_row().
 5094:                            '<td>'.&mt('Transaction [_1]',$version);
 5095:             if (@unsolved) {
 5096:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
 5097:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
 5098:                                  &mt('Hide').'</label></span>';
 5099:             }
 5100:             $prevattempts .= '</td>';
 5101:             if (@hidden) {
 5102:                 foreach my $key (sort(keys(%lasthash))) {
 5103:                     next if ($key =~ /\.foilorder$/);
 5104:                     my $hide;
 5105:                     foreach my $id (@hidden) {
 5106:                         if ($key =~ /^\Q$id\E/) {
 5107:                             $hide = 1;
 5108:                             last;
 5109:                         }
 5110:                     }
 5111:                     if ($hide) {
 5112:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 5113:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 5114:                             my $value = &format_previous_attempt_value($key,
 5115:                                              $returnhash{$version.':'.$key});
 5116:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 5117:                         } else {
 5118:                             $prevattempts.='<td>&nbsp;</td>';
 5119:                         }
 5120:                     } else {
 5121:                         if ($key =~ /\./) {
 5122:                             my $value = $returnhash{$version.':'.$key};
 5123:                             if ($key =~ /\.rndseed$/) {
 5124:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 5125:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 5126:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 5127:                                 }
 5128:                             }
 5129:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 5130:                                            '&nbsp;</td>';
 5131:                         } else {
 5132:                             $prevattempts.='<td>&nbsp;</td>';
 5133:                         }
 5134:                     }
 5135:                 }
 5136:             } else {
 5137: 	        foreach my $key (sort(keys(%lasthash))) {
 5138:                     next if ($key =~ /\.foilorder$/);
 5139:                     my $value = $returnhash{$version.':'.$key};
 5140:                     if ($key =~ /\.rndseed$/) {
 5141:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 5142:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 5143:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 5144:                         }
 5145:                     }
 5146:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 5147:                                    '&nbsp;</td>';
 5148: 	        }
 5149:             }
 5150: 	    $prevattempts.=&end_data_table_row();
 5151: 	 }
 5152:       }
 5153:       my @currhidden = keys(%lasthidden);
 5154:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 5155:       foreach my $key (sort(keys(%lasthash))) {
 5156:           next if ($key =~ /\.foilorder$/);
 5157:           if (%typeparts) {
 5158:               my $hidden;
 5159:               foreach my $id (@currhidden) {
 5160:                   if ($key =~ /^\Q$id\E/) {
 5161:                       $hidden = 1;
 5162:                       last;
 5163:                   }
 5164:               }
 5165:               if ($hidden) {
 5166:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 5167:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 5168:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 5169:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 5170:                           $value = &$gradesub($value);
 5171:                       }
 5172:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
 5173:                   } else {
 5174:                       $prevattempts.='<td>&nbsp;</td>';
 5175:                   }
 5176:               } else {
 5177:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 5178:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 5179:                       $value = &$gradesub($value);
 5180:                   }
 5181:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 5182:               }
 5183:           } else {
 5184: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 5185: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 5186:                   $value = &$gradesub($value);
 5187:               }
 5188: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
 5189:           }
 5190:       }
 5191:       $prevattempts.= &end_data_table_row().&end_data_table();
 5192:     } else {
 5193:       my $msg;
 5194:       if ($symb =~ /ext\.tool$/) {
 5195:           $msg = &mt('No grade passed back.');
 5196:       } else {
 5197:           $msg = &mt('Nothing submitted - no attempts.');
 5198:       }
 5199:       $prevattempts=
 5200: 	  &start_data_table().&start_data_table_row().
 5201: 	  '<td>'.$msg.'</td>'.
 5202: 	  &end_data_table_row().&end_data_table();
 5203:     }
 5204:   } else {
 5205:     $prevattempts=
 5206: 	  &start_data_table().&start_data_table_row().
 5207: 	  '<td>'.&mt('No data.').'</td>'.
 5208: 	  &end_data_table_row().&end_data_table();
 5209:   }
 5210: }
 5211: 
 5212: sub format_previous_attempt_value {
 5213:     my ($key,$value) = @_;
 5214:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 5215:         $value = &Apache::lonlocal::locallocaltime($value);
 5216:     } elsif (ref($value) eq 'ARRAY') {
 5217:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
 5218:     } elsif ($key =~ /answerstring$/) {
 5219:         my %answers = &Apache::lonnet::str2hash($value);
 5220:         my @answer = %answers;
 5221:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
 5222:         my @anskeys = sort(keys(%answers));
 5223:         if (@anskeys == 1) {
 5224:             my $answer = $answers{$anskeys[0]};
 5225:             if ($answer =~ m{\0}) {
 5226:                 $answer =~ s{\0}{,}g;
 5227:             }
 5228:             my $tag_internal_answer_name = 'INTERNAL';
 5229:             if ($anskeys[0] eq $tag_internal_answer_name) {
 5230:                 $value = $answer; 
 5231:             } else {
 5232:                 $value = $anskeys[0].'='.$answer;
 5233:             }
 5234:         } else {
 5235:             foreach my $ans (@anskeys) {
 5236:                 my $answer = $answers{$ans};
 5237:                 if ($answer =~ m{\0}) {
 5238:                     $answer =~ s{\0}{,}g;
 5239:                 }
 5240:                 $value .=  $ans.'='.$answer.'<br />';;
 5241:             } 
 5242:         }
 5243:     } else {
 5244:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
 5245:     }
 5246:     return $value;
 5247: }
 5248: 
 5249: 
 5250: sub relative_to_absolute {
 5251:     my ($url,$output)=@_;
 5252:     my $parser=HTML::TokeParser->new(\$output);
 5253:     my $token;
 5254:     my $thisdir=$url;
 5255:     my @rlinks=();
 5256:     while ($token=$parser->get_token) {
 5257: 	if ($token->[0] eq 'S') {
 5258: 	    if ($token->[1] eq 'a') {
 5259: 		if ($token->[2]->{'href'}) {
 5260: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 5261: 		}
 5262: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 5263: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 5264: 	    } elsif ($token->[1] eq 'base') {
 5265: 		$thisdir=$token->[2]->{'href'};
 5266: 	    }
 5267: 	}
 5268:     }
 5269:     $thisdir=~s-/[^/]*$--;
 5270:     foreach my $link (@rlinks) {
 5271: 	unless (($link=~/^https?\:\/\//i) ||
 5272: 		($link=~/^\//) ||
 5273: 		($link=~/^javascript:/i) ||
 5274: 		($link=~/^mailto:/i) ||
 5275: 		($link=~/^\#/)) {
 5276: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 5277: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 5278: 	}
 5279:     }
 5280: # -------------------------------------------------- Deal with Applet codebases
 5281:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 5282:     return $output;
 5283: }
 5284: 
 5285: =pod
 5286: 
 5287: =item * &get_student_view()
 5288: 
 5289: show a snapshot of what student was looking at
 5290: 
 5291: =cut
 5292: 
 5293: sub get_student_view {
 5294:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 5295:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 5296:   my (%form);
 5297:   my @elements=('symb','courseid','domain','username');
 5298:   foreach my $element (@elements) {
 5299:       $form{'grade_'.$element}=eval '$'.$element #'
 5300:   }
 5301:   if (defined($moreenv)) {
 5302:       %form=(%form,%{$moreenv});
 5303:   }
 5304:   if (defined($target)) { $form{'grade_target'} = $target; }
 5305:   $feedurl=&Apache::lonnet::clutter($feedurl);
 5306:   if (($feedurl =~ /ext\.tool$/) && ($target eq 'tex')) {
 5307:       $feedurl =~ s{^/adm/wrapper}{};
 5308:   }
 5309:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 5310:   $userview=~s/\<body[^\>]*\>//gi;
 5311:   $userview=~s/\<\/body\>//gi;
 5312:   $userview=~s/\<html\>//gi;
 5313:   $userview=~s/\<\/html\>//gi;
 5314:   $userview=~s/\<head\>//gi;
 5315:   $userview=~s/\<\/head\>//gi;
 5316:   $userview=~s/action\s*\=/would_be_action\=/gi;
 5317:   $userview=&relative_to_absolute($feedurl,$userview);
 5318:   if (wantarray) {
 5319:      return ($userview,$response);
 5320:   } else {
 5321:      return $userview;
 5322:   }
 5323: }
 5324: 
 5325: sub get_student_view_with_retries {
 5326:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 5327: 
 5328:     my $ok = 0;                 # True if we got a good response.
 5329:     my $content;
 5330:     my $response;
 5331: 
 5332:     # Try to get the student_view done. within the retries count:
 5333:     
 5334:     do {
 5335:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 5336:          $ok      = $response->is_success;
 5337:          if (!$ok) {
 5338:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 5339:          }
 5340:          $retries--;
 5341:     } while (!$ok && ($retries > 0));
 5342:     
 5343:     if (!$ok) {
 5344:        $content = '';          # On error return an empty content.
 5345:     }
 5346:     if (wantarray) {
 5347:        return ($content, $response);
 5348:     } else {
 5349:        return $content;
 5350:     }
 5351: }
 5352: 
 5353: sub css_links {
 5354:     my ($currsymb,$level) = @_;
 5355:     my ($links,@symbs,%cssrefs,%httpref);
 5356:     if ($level eq 'map') {
 5357:         my $navmap = Apache::lonnavmaps::navmap->new();
 5358:         if (ref($navmap)) {
 5359:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
 5360:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
 5361:             foreach my $res (@resources) {
 5362:                 if (ref($res) && $res->symb()) {
 5363:                     push(@symbs,$res->symb());
 5364:                 }
 5365:             }
 5366:         }
 5367:     } else {
 5368:         @symbs = ($currsymb);
 5369:     }
 5370:     foreach my $symb (@symbs) {
 5371:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
 5372:         if ($css_href =~ /\S/) {
 5373:             unless ($css_href =~ m{https?://}) {
 5374:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
 5375:                 my $proburl =  &Apache::lonnet::clutter($url);
 5376:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
 5377:                 unless ($css_href =~ m{^/}) {
 5378:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
 5379:                 }
 5380:                 if ($css_href =~ m{^/(res|uploaded)/}) {
 5381:                     unless (($httpref{'httpref.'.$css_href}) ||
 5382:                             (&Apache::lonnet::is_on_map($css_href))) {
 5383:                         my $thisurl = $proburl;
 5384:                         if ($env{'httpref.'.$proburl}) {
 5385:                             $thisurl = $env{'httpref.'.$proburl};
 5386:                         }
 5387:                         $httpref{'httpref.'.$css_href} = $thisurl;
 5388:                     }
 5389:                 }
 5390:             }
 5391:             $cssrefs{$css_href} = 1;
 5392:         }
 5393:     }
 5394:     if (keys(%httpref)) {
 5395:         &Apache::lonnet::appenv(\%httpref);
 5396:     }
 5397:     if (keys(%cssrefs)) {
 5398:         foreach my $css_href (keys(%cssrefs)) {
 5399:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
 5400:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
 5401:         }
 5402:     }
 5403:     return $links;
 5404: }
 5405: 
 5406: =pod
 5407: 
 5408: =item * &get_student_answers() 
 5409: 
 5410: show a snapshot of how student was answering problem
 5411: 
 5412: =cut
 5413: 
 5414: sub get_student_answers {
 5415:   my ($symb,$username,$domain,$courseid,%form) = @_;
 5416:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 5417:   my (%moreenv);
 5418:   my @elements=('symb','courseid','domain','username');
 5419:   foreach my $element (@elements) {
 5420:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 5421:   }
 5422:   $moreenv{'grade_target'}='answer';
 5423:   %moreenv=(%form,%moreenv);
 5424:   $feedurl = &Apache::lonnet::clutter($feedurl);
 5425:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 5426:   return $userview;
 5427: }
 5428: 
 5429: =pod
 5430: 
 5431: =item * &submlink()
 5432: 
 5433: Inputs: $text $uname $udom $symb $target
 5434: 
 5435: Returns: A link to grades.pm such as to see the SUBM view of a student
 5436: 
 5437: =cut
 5438: 
 5439: ###############################################
 5440: sub submlink {
 5441:     my ($text,$uname,$udom,$symb,$target)=@_;
 5442:     if (!($uname && $udom)) {
 5443: 	(my $cursymb, my $courseid,$udom,$uname)=
 5444: 	    &Apache::lonnet::whichuser($symb);
 5445: 	if (!$symb) { $symb=$cursymb; }
 5446:     }
 5447:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 5448:     $symb=&escape($symb);
 5449:     if ($target) { $target=" target=\"$target\""; }
 5450:     return
 5451:         '<a href="/adm/grades?command=submission'.
 5452:         '&amp;symb='.$symb.
 5453:         '&amp;student='.$uname.
 5454:         '&amp;userdom='.$udom.'"'.
 5455:         $target.'>'.$text.'</a>';
 5456: }
 5457: ##############################################
 5458: 
 5459: =pod
 5460: 
 5461: =item * &pgrdlink()
 5462: 
 5463: Inputs: $text $uname $udom $symb $target
 5464: 
 5465: Returns: A link to grades.pm such as to see the PGRD view of a student
 5466: 
 5467: =cut
 5468: 
 5469: ###############################################
 5470: sub pgrdlink {
 5471:     my $link=&submlink(@_);
 5472:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 5473:     return $link;
 5474: }
 5475: ##############################################
 5476: 
 5477: =pod
 5478: 
 5479: =item * &pprmlink()
 5480: 
 5481: Inputs: $text $uname $udom $symb $target
 5482: 
 5483: Returns: A link to parmset.pm such as to see the PPRM view of a
 5484: student and a specific resource
 5485: 
 5486: =cut
 5487: 
 5488: ###############################################
 5489: sub pprmlink {
 5490:     my ($text,$uname,$udom,$symb,$target)=@_;
 5491:     if (!($uname && $udom)) {
 5492: 	(my $cursymb, my $courseid,$udom,$uname)=
 5493: 	    &Apache::lonnet::whichuser($symb);
 5494: 	if (!$symb) { $symb=$cursymb; }
 5495:     }
 5496:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 5497:     $symb=&escape($symb);
 5498:     if ($target) { $target="target=\"$target\""; }
 5499:     return '<a href="/adm/parmset?command=set&amp;'.
 5500: 	'symb='.$symb.'&amp;uname='.$uname.
 5501: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 5502: }
 5503: ##############################################
 5504: 
 5505: =pod
 5506: 
 5507: =back
 5508: 
 5509: =cut
 5510: 
 5511: ###############################################
 5512: 
 5513: 
 5514: sub timehash {
 5515:     my ($thistime) = @_;
 5516:     my $timezone = &Apache::lonlocal::gettimezone();
 5517:     my $dt = DateTime->from_epoch(epoch => $thistime)
 5518:                      ->set_time_zone($timezone);
 5519:     my $wday = $dt->day_of_week();
 5520:     if ($wday == 7) { $wday = 0; }
 5521:     return ( 'second' => $dt->second(),
 5522:              'minute' => $dt->minute(),
 5523:              'hour'   => $dt->hour(),
 5524:              'day'     => $dt->day_of_month(),
 5525:              'month'   => $dt->month(),
 5526:              'year'    => $dt->year(),
 5527:              'weekday' => $wday,
 5528:              'dayyear' => $dt->day_of_year(),
 5529:              'dlsav'   => $dt->is_dst() );
 5530: }
 5531: 
 5532: sub utc_string {
 5533:     my ($date)=@_;
 5534:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 5535: }
 5536: 
 5537: sub maketime {
 5538:     my %th=@_;
 5539:     my ($epoch_time,$timezone,$dt);
 5540:     $timezone = &Apache::lonlocal::gettimezone();
 5541:     eval {
 5542:         $dt = DateTime->new( year   => $th{'year'},
 5543:                              month  => $th{'month'},
 5544:                              day    => $th{'day'},
 5545:                              hour   => $th{'hour'},
 5546:                              minute => $th{'minute'},
 5547:                              second => $th{'second'},
 5548:                              time_zone => $timezone,
 5549:                          );
 5550:     };
 5551:     if (!$@) {
 5552:         $epoch_time = $dt->epoch;
 5553:         if ($epoch_time) {
 5554:             return $epoch_time;
 5555:         }
 5556:     }
 5557:     return POSIX::mktime(
 5558:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 5559:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 5560: }
 5561: 
 5562: #########################################
 5563: 
 5564: sub findallcourses {
 5565:     my ($roles,$uname,$udom) = @_;
 5566:     my %roles;
 5567:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 5568:     my %courses;
 5569:     my $now=time;
 5570:     if (!defined($uname)) {
 5571:         $uname = $env{'user.name'};
 5572:     }
 5573:     if (!defined($udom)) {
 5574:         $udom = $env{'user.domain'};
 5575:     }
 5576:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 5577:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 5578:         if (!%roles) {
 5579:             %roles = (
 5580:                        cc => 1,
 5581:                        co => 1,
 5582:                        in => 1,
 5583:                        ep => 1,
 5584:                        ta => 1,
 5585:                        cr => 1,
 5586:                        st => 1,
 5587:              );
 5588:         }
 5589:         foreach my $entry (keys(%roleshash)) {
 5590:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 5591:             if ($trole =~ /^cr/) { 
 5592:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 5593:             } else {
 5594:                 next if (!exists($roles{$trole}));
 5595:             }
 5596:             if ($tend) {
 5597:                 next if ($tend < $now);
 5598:             }
 5599:             if ($tstart) {
 5600:                 next if ($tstart > $now);
 5601:             }
 5602:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 5603:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 5604:             my $value = $trole.'/'.$cdom.'/';
 5605:             if ($secpart eq '') {
 5606:                 ($cnum,$role) = split(/_/,$cnumpart); 
 5607:                 $sec = 'none';
 5608:                 $value .= $cnum.'/';
 5609:             } else {
 5610:                 $cnum = $cnumpart;
 5611:                 ($sec,$role) = split(/_/,$secpart);
 5612:                 $value .= $cnum.'/'.$sec;
 5613:             }
 5614:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 5615:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 5616:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 5617:                 }
 5618:             } else {
 5619:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 5620:             }
 5621:         }
 5622:     } else {
 5623:         foreach my $key (keys(%env)) {
 5624: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 5625:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 5626: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 5627: 	        next if ($role eq 'ca' || $role eq 'aa');
 5628: 	        next if (%roles && !exists($roles{$role}));
 5629: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 5630:                 my $active=1;
 5631:                 if ($starttime) {
 5632: 		    if ($now<$starttime) { $active=0; }
 5633:                 }
 5634:                 if ($endtime) {
 5635:                     if ($now>$endtime) { $active=0; }
 5636:                 }
 5637:                 if ($active) {
 5638:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 5639:                     if ($sec eq '') {
 5640:                         $sec = 'none';
 5641:                     } else {
 5642:                         $value .= $sec;
 5643:                     }
 5644:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 5645:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 5646:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 5647:                         }
 5648:                     } else {
 5649:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 5650:                     }
 5651:                 }
 5652:             }
 5653:         }
 5654:     }
 5655:     return %courses;
 5656: }
 5657: 
 5658: ###############################################
 5659: 
 5660: sub blockcheck {
 5661:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
 5662:     unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
 5663:         my ($has_evb,$check_ipaccess);
 5664:         my $dom = $env{'user.domain'};
 5665:         if ($env{'request.course.id'}) {
 5666:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5667:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5668:             my $checkrole = "cm./$cdom/$cnum";
 5669:             my $sec = $env{'request.course.sec'};
 5670:             if ($sec ne '') {
 5671:                 $checkrole .= "/$sec";
 5672:             }
 5673:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 5674:                 ($env{'request.role'} !~ /^st/)) {
 5675:                 $has_evb = 1;
 5676:             }
 5677:             unless ($has_evb) {
 5678:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
 5679:                     ($activity eq 'boards') || ($activity eq 'groups') || ($activity eq 'chat')) {
 5680:                     if ($udom eq $cdom) {
 5681:                         $check_ipaccess = 1;
 5682:                     }
 5683:                 }
 5684:             }
 5685:         } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
 5686:                 ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
 5687:             my $checkrole;
 5688:             if ($env{'request.role.domain'} eq '') {
 5689:                 $checkrole = "cm./$env{'user.domain'}/";
 5690:             } else {
 5691:                 $checkrole = "cm./$env{'request.role.domain'}/";
 5692:             }
 5693:             if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
 5694:                 $has_evb = 1;
 5695:             }
 5696:         }
 5697:         unless ($has_evb || $check_ipaccess) {
 5698:             my @machinedoms = &Apache::lonnet::current_machine_domains();
 5699:             if (($dom eq 'public') && ($activity eq 'port')) {
 5700:                 $dom = $udom;
 5701:             }
 5702:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
 5703:                 $check_ipaccess = 1;
 5704:             } else {
 5705:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 5706:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
 5707:                 my $prim = &Apache::lonnet::domain($dom,'primary');
 5708:                 my $intdom = &Apache::lonnet::internet_dom($prim);
 5709:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
 5710:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
 5711:                         $check_ipaccess = 1;
 5712:                     }
 5713:                 }
 5714:             }
 5715:         }
 5716:         if ($check_ipaccess) {
 5717:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
 5718:             unless (defined($cached)) {
 5719:                 my %domconfig =
 5720:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
 5721:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
 5722:             }
 5723:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
 5724:                 foreach my $id (keys(%{$ipaccessref})) {
 5725:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
 5726:                         my $range = $ipaccessref->{$id}->{'ip'};
 5727:                         if ($range) {
 5728:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
 5729:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
 5730:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
 5731:                                         return ('','','',$id,$dom);
 5732:                                         last;
 5733:                                     }
 5734:                                 }
 5735:                             }
 5736:                         }
 5737:                     }
 5738:                 }
 5739:             }
 5740:         }
 5741:         if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
 5742:             return ();
 5743:         }
 5744:     }
 5745:     if (defined($udom) && defined($uname)) {
 5746:         # If uname and udom are for a course, check for blocks in the course.
 5747:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
 5748:             my ($startblock,$endblock,$triggerblock) =
 5749:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
 5750:             return ($startblock,$endblock,$triggerblock);
 5751:         }
 5752:     } else {
 5753:         $udom = $env{'user.domain'};
 5754:         $uname = $env{'user.name'};
 5755:     }
 5756: 
 5757:     my $startblock = 0;
 5758:     my $endblock = 0;
 5759:     my $triggerblock = '';
 5760:     my %live_courses;
 5761:     unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
 5762:         %live_courses = &findallcourses(undef,$uname,$udom);
 5763:     }
 5764: 
 5765:     # If uname is for a user, and activity is course-specific, i.e.,
 5766:     # boards, chat or groups, check for blocking in current course only.
 5767: 
 5768:     if (($activity eq 'boards' || $activity eq 'chat' ||
 5769:          $activity eq 'groups' || $activity eq 'printout' ||
 5770:          $activity eq 'search' || $activity eq 'reinit' ||
 5771:          $activity eq 'alert') &&
 5772:         ($env{'request.course.id'})) {
 5773:         foreach my $key (keys(%live_courses)) {
 5774:             if ($key ne $env{'request.course.id'}) {
 5775:                 delete($live_courses{$key});
 5776:             }
 5777:         }
 5778:     }
 5779: 
 5780:     my $otheruser = 0;
 5781:     my %own_courses;
 5782:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 5783:         # Resource belongs to user other than current user.
 5784:         $otheruser = 1;
 5785:         # Gather courses for current user
 5786:         %own_courses = 
 5787:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 5788:     }
 5789: 
 5790:     # Gather active course roles - course coordinator, instructor, 
 5791:     # exam proctor, ta, student, or custom role.
 5792: 
 5793:     foreach my $course (keys(%live_courses)) {
 5794:         my ($cdom,$cnum);
 5795:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 5796:             $cdom = $env{'course.'.$course.'.domain'};
 5797:             $cnum = $env{'course.'.$course.'.num'};
 5798:         } else {
 5799:             ($cdom,$cnum) = split(/_/,$course); 
 5800:         }
 5801:         my $no_ownblock = 0;
 5802:         my $no_userblock = 0;
 5803:         if ($otheruser && $activity ne 'com') {
 5804:             # Check if current user has 'evb' priv for this
 5805:             if (defined($own_courses{$course})) {
 5806:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 5807:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5808:                     if ($sec ne 'none') {
 5809:                         $checkrole .= '/'.$sec;
 5810:                     }
 5811:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5812:                         $no_ownblock = 1;
 5813:                         last;
 5814:                     }
 5815:                 }
 5816:             }
 5817:             # if they have 'evb' priv and are currently not playing student
 5818:             next if (($no_ownblock) &&
 5819:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 5820:         }
 5821:         foreach my $sec (keys(%{$live_courses{$course}})) {
 5822:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5823:             if ($sec ne 'none') {
 5824:                 $checkrole .= '/'.$sec;
 5825:             }
 5826:             if ($otheruser) {
 5827:                 # Resource belongs to user other than current user.
 5828:                 # Assemble privs for that user, and check for 'evb' priv.
 5829:                 my (%allroles,%userroles);
 5830:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 5831:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 5832:                         my ($trole,$tdom,$tnum,$tsec);
 5833:                         if ($entry =~ /^cr/) {
 5834:                             ($trole,$tdom,$tnum,$tsec) = 
 5835:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 5836:                         } else {
 5837:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 5838:                         }
 5839:                         my ($spec,$area,$trest);
 5840:                         $area = '/'.$tdom.'/'.$tnum;
 5841:                         $trest = $tnum;
 5842:                         if ($tsec ne '') {
 5843:                             $area .= '/'.$tsec;
 5844:                             $trest .= '/'.$tsec;
 5845:                         }
 5846:                         $spec = $trole.'.'.$area;
 5847:                         if ($trole =~ /^cr/) {
 5848:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 5849:                                                               $tdom,$spec,$trest,$area);
 5850:                         } else {
 5851:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 5852:                                                                 $tdom,$spec,$trest,$area);
 5853:                         }
 5854:                     }
 5855:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 5856:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 5857:                         if ($1) {
 5858:                             $no_userblock = 1;
 5859:                             last;
 5860:                         }
 5861:                     }
 5862:                 }
 5863:             } else {
 5864:                 # Resource belongs to current user
 5865:                 # Check for 'evb' priv via lonnet::allowed().
 5866:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5867:                     $no_ownblock = 1;
 5868:                     last;
 5869:                 }
 5870:             }
 5871:         }
 5872:         # if they have the evb priv and are currently not playing student
 5873:         next if (($no_ownblock) &&
 5874:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 5875:         next if ($no_userblock);
 5876: 
 5877:         # Retrieve blocking times and identity of blocker for course
 5878:         # of specified user, unless user has 'evb' privilege.
 5879: 
 5880:         my ($start,$end,$trigger) = 
 5881:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
 5882:         if (($start != 0) && 
 5883:             (($startblock == 0) || ($startblock > $start))) {
 5884:             $startblock = $start;
 5885:             if ($trigger ne '') {
 5886:                 $triggerblock = $trigger;
 5887:             }
 5888:         }
 5889:         if (($end != 0)  &&
 5890:             (($endblock == 0) || ($endblock < $end))) {
 5891:             $endblock = $end;
 5892:             if ($trigger ne '') {
 5893:                 $triggerblock = $trigger;
 5894:             }
 5895:         }
 5896:     }
 5897:     return ($startblock,$endblock,$triggerblock);
 5898: }
 5899: 
 5900: sub get_blocks {
 5901:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
 5902:     my $startblock = 0;
 5903:     my $endblock = 0;
 5904:     my $triggerblock = '';
 5905:     my $course = $cdom.'_'.$cnum;
 5906:     $setters->{$course} = {};
 5907:     $setters->{$course}{'staff'} = [];
 5908:     $setters->{$course}{'times'} = [];
 5909:     $setters->{$course}{'triggers'} = [];
 5910:     my (@blockers,%triggered);
 5911:     my $now = time;
 5912:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 5913:     if ($activity eq 'docs') {
 5914:         my ($blocked,$nosymbcache,$noenccheck);
 5915:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
 5916:             $blocked = 1;
 5917:             $nosymbcache = 1;
 5918:             $noenccheck = 1;
 5919:         }
 5920:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
 5921:         foreach my $block (@blockers) {
 5922:             if ($block =~ /^firstaccess____(.+)$/) {
 5923:                 my $item = $1;
 5924:                 my $type = 'map';
 5925:                 my $timersymb = $item;
 5926:                 if ($item eq 'course') {
 5927:                     $type = 'course';
 5928:                 } elsif ($item =~ /___\d+___/) {
 5929:                     $type = 'resource';
 5930:                 } else {
 5931:                     $timersymb = &Apache::lonnet::symbread($item);
 5932:                 }
 5933:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5934:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 5935:                 $triggered{$block} = {
 5936:                                        start => $start,
 5937:                                        end   => $end,
 5938:                                        type  => $type,
 5939:                                      };
 5940:             }
 5941:         }
 5942:     } else {
 5943:         foreach my $block (keys(%commblocks)) {
 5944:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 5945:                 my ($start,$end) = ($1,$2);
 5946:                 if ($start <= time && $end >= time) {
 5947:                     if (ref($commblocks{$block}) eq 'HASH') {
 5948:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5949:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5950:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 5951:                                     push(@blockers,$block);
 5952:                                 }
 5953:                             }
 5954:                         }
 5955:                     }
 5956:                 }
 5957:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 5958:                 my $item = $1;
 5959:                 my $timersymb = $item; 
 5960:                 my $type = 'map';
 5961:                 if ($item eq 'course') {
 5962:                     $type = 'course';
 5963:                 } elsif ($item =~ /___\d+___/) {
 5964:                     $type = 'resource';
 5965:                 } else {
 5966:                     $timersymb = &Apache::lonnet::symbread($item);
 5967:                 }
 5968:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5969:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 5970:                 if ($start && $end) {
 5971:                     if (($start <= time) && ($end >= time)) {
 5972:                         if (ref($commblocks{$block}) eq 'HASH') {
 5973:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5974:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5975:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
 5976:                                         push(@blockers,$block);
 5977:                                         $triggered{$block} = {
 5978:                                                                start => $start,
 5979:                                                                end   => $end,
 5980:                                                                type  => $type,
 5981:                                                              };
 5982:                                     }
 5983:                                 }
 5984:                             }
 5985:                         }
 5986:                     }
 5987:                 }
 5988:             }
 5989:         }
 5990:     }
 5991:     foreach my $blocker (@blockers) {
 5992:         my ($staff_name,$staff_dom,$title,$blocks) =
 5993:             &parse_block_record($commblocks{$blocker});
 5994:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 5995:         my ($start,$end,$triggertype);
 5996:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 5997:             ($start,$end) = ($1,$2);
 5998:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 5999:             $start = $triggered{$blocker}{'start'};
 6000:             $end = $triggered{$blocker}{'end'};
 6001:             $triggertype = $triggered{$blocker}{'type'};
 6002:         }
 6003:         if ($start) {
 6004:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 6005:             if ($triggertype) {
 6006:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 6007:             } else {
 6008:                 push(@{$$setters{$course}{'triggers'}},0);
 6009:             }
 6010:             if ( ($startblock == 0) || ($startblock > $start) ) {
 6011:                 $startblock = $start;
 6012:                 if ($triggertype) {
 6013:                     $triggerblock = $blocker;
 6014:                 }
 6015:             }
 6016:             if ( ($endblock == 0) || ($endblock < $end) ) {
 6017:                $endblock = $end;
 6018:                if ($triggertype) {
 6019:                    $triggerblock = $blocker;
 6020:                }
 6021:             }
 6022:         }
 6023:     }
 6024:     return ($startblock,$endblock,$triggerblock);
 6025: }
 6026: 
 6027: sub parse_block_record {
 6028:     my ($record) = @_;
 6029:     my ($setuname,$setudom,$title,$blocks);
 6030:     if (ref($record) eq 'HASH') {
 6031:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 6032:         $title = &unescape($record->{'event'});
 6033:         $blocks = $record->{'blocks'};
 6034:     } else {
 6035:         my @data = split(/:/,$record,3);
 6036:         if (scalar(@data) eq 2) {
 6037:             $title = $data[1];
 6038:             ($setuname,$setudom) = split(/@/,$data[0]);
 6039:         } else {
 6040:             ($setuname,$setudom,$title) = @data;
 6041:         }
 6042:         $blocks = { 'com' => 'on' };
 6043:     }
 6044:     return ($setuname,$setudom,$title,$blocks);
 6045: }
 6046: 
 6047: sub blocking_status {
 6048:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
 6049:     my %setters;
 6050: 
 6051: # check for active blocking
 6052:     if ($clientip eq '') {
 6053:         $clientip = &Apache::lonnet::get_requestor_ip();
 6054:     }
 6055:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
 6056:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
 6057:     my $blocked = 0;
 6058:     if (($startblock && $endblock) || ($by_ip)) {
 6059:         $blocked = 1;
 6060:     }
 6061: 
 6062: # caller just wants to know whether a block is active
 6063:     if (!wantarray) { return $blocked; }
 6064: 
 6065: # build a link to a popup window containing the details
 6066:     my $querystring  = "?activity=$activity";
 6067: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
 6068:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
 6069:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
 6070:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
 6071:     } elsif ($activity eq 'docs') {
 6072:         my $showurl = &Apache::lonenc::check_encrypt($url);
 6073:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
 6074:         if ($symb) {
 6075:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
 6076:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
 6077:         }
 6078:     }
 6079: 
 6080:     my $output .= <<'END_MYBLOCK';
 6081: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 6082:     var options = "width=" + w + ",height=" + h + ",";
 6083:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 6084:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 6085:     var newWin = window.open(url, wdwName, options);
 6086:     newWin.focus();
 6087: }
 6088: END_MYBLOCK
 6089: 
 6090:     $output = Apache::lonhtmlcommon::scripttag($output);
 6091:   
 6092:     my $popupUrl = "/adm/blockingstatus/$querystring";
 6093:     my $text = &mt('Communication Blocked');
 6094:     my $class = 'LC_comblock';
 6095:     if ($activity eq 'docs') {
 6096:         $text = &mt('Content Access Blocked');
 6097:         $class = '';
 6098:     } elsif ($activity eq 'printout') {
 6099:         $text = &mt('Printing Blocked');
 6100:     } elsif ($activity eq 'passwd') {
 6101:         $text = &mt('Password Changing Blocked');
 6102:     } elsif ($activity eq 'grades') {
 6103:         $text = &mt('Gradebook Blocked');
 6104:     } elsif ($activity eq 'search') {
 6105:         $text = &mt('Search Blocked');
 6106:     } elsif ($activity eq 'alert') {
 6107:         $text = &mt('Checking Critical Messages Blocked');
 6108:     } elsif ($activity eq 'reinit') {
 6109:         $text = &mt('Checking Course Update Blocked');
 6110:     } elsif ($activity eq 'about') {
 6111:         $text = &mt('Access to User Information Pages Blocked');
 6112:     } elsif ($activity eq 'wishlist') {
 6113:         $text = &mt('Access to Stored Links Blocked');
 6114:     } elsif ($activity eq 'annotate') {
 6115:         $text = &mt('Access to Annotations Blocked');
 6116:     }
 6117:     $output .= <<"END_BLOCK";
 6118: <div class='$class'>
 6119:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 6120:   title='$text'>
 6121:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 6122:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 6123:   title='$text'>$text</a>
 6124: </div>
 6125: 
 6126: END_BLOCK
 6127: 
 6128:     return ($blocked, $output);
 6129: }
 6130: 
 6131: ###############################################
 6132: 
 6133: sub check_ip_acc {
 6134:     my ($acc,$clientip)=@_;
 6135:     &Apache::lonxml::debug("acc is $acc");
 6136:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 6137:         return 1;
 6138:     }
 6139:     my ($ip,$allowed);
 6140:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
 6141:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
 6142:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
 6143:     } else {
 6144:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
 6145:         $ip = $remote_ip || $env{'request.host'} || $clientip;
 6146:     }
 6147: 
 6148:     my $name;
 6149:     my %access = (
 6150:                      allowfrom => 1,
 6151:                      denyfrom  => 0,
 6152:                  );
 6153:     my @allows;
 6154:     my @denies;
 6155:     foreach my $item (split(',',$acc)) {
 6156:         $item =~ s/^\s*//;
 6157:         $item =~ s/\s*$//;
 6158:         my $pattern;
 6159:         if ($item =~ /^\!(.+)$/) {
 6160:             push(@denies,$1);
 6161:         } else {
 6162:             push(@allows,$item);
 6163:         }
 6164:    }
 6165:    my $numdenies = scalar(@denies);
 6166:    my $numallows = scalar(@allows);
 6167:    my $count = 0;
 6168:    foreach my $pattern (@denies,@allows) {
 6169:         $count ++; 
 6170:         my $acctype = 'allowfrom';
 6171:         if ($count <= $numdenies) {
 6172:             $acctype = 'denyfrom';
 6173:         }
 6174:         if ($pattern =~ /\*$/) {
 6175:             #35.8.*
 6176:             $pattern=~s/\*//;
 6177:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 6178:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 6179:             #35.8.3.[34-56]
 6180:             my $low=$2;
 6181:             my $high=$3;
 6182:             $pattern=$1;
 6183:             if ($ip =~ /^\Q$pattern\E/) {
 6184:                 my $last=(split(/\./,$ip))[3];
 6185:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
 6186:             }
 6187:         } elsif ($pattern =~ /^\*/) {
 6188:             #*.msu.edu
 6189:             $pattern=~s/\*//;
 6190:             if (!defined($name)) {
 6191:                 use Socket;
 6192:                 my $netaddr=inet_aton($ip);
 6193:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 6194:             }
 6195:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 6196:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 6197:             #127.0.0.1
 6198:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 6199:         } else {
 6200:             #some.name.com
 6201:             if (!defined($name)) {
 6202:                 use Socket;
 6203:                 my $netaddr=inet_aton($ip);
 6204:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 6205:             }
 6206:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 6207:         }
 6208:         if ($allowed =~ /^(0|1)$/) { last; }
 6209:     }
 6210:     if ($allowed eq '') {
 6211:         if ($numdenies && !$numallows) {
 6212:             $allowed = 1;
 6213:         } else {
 6214:             $allowed = 0;
 6215:         }
 6216:     }
 6217:     return $allowed;
 6218: }
 6219: 
 6220: ###############################################
 6221: 
 6222: =pod
 6223: 
 6224: =head1 Domain Template Functions
 6225: 
 6226: =over 4
 6227: 
 6228: =item * &determinedomain()
 6229: 
 6230: Inputs: $domain (usually will be undef)
 6231: 
 6232: Returns: Determines which domain should be used for designs
 6233: 
 6234: =cut
 6235: 
 6236: ###############################################
 6237: sub determinedomain {
 6238:     my $domain=shift;
 6239:     if (! $domain) {
 6240:         # Determine domain if we have not been given one
 6241:         $domain = &Apache::lonnet::default_login_domain();
 6242:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 6243:         if ($env{'request.role.domain'}) { 
 6244:             $domain=$env{'request.role.domain'}; 
 6245:         }
 6246:     }
 6247:     return $domain;
 6248: }
 6249: ###############################################
 6250: 
 6251: sub devalidate_domconfig_cache {
 6252:     my ($udom)=@_;
 6253:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 6254: }
 6255: 
 6256: # ---------------------- Get domain configuration for a domain
 6257: sub get_domainconf {
 6258:     my ($udom) = @_;
 6259:     my $cachetime=1800;
 6260:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 6261:     if (defined($cached)) { return %{$result}; }
 6262: 
 6263:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 6264: 					     ['login','rolecolors','autoenroll'],$udom);
 6265:     my (%designhash,%legacy);
 6266:     if (keys(%domconfig) > 0) {
 6267:         if (ref($domconfig{'login'}) eq 'HASH') {
 6268:             if (keys(%{$domconfig{'login'}})) {
 6269:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 6270:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 6271:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
 6272:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 6273:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
 6274:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
 6275:                                         if ($key eq 'loginvia') {
 6276:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 6277:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 6278:                                                 $designhash{$udom.'.login.loginvia'} = $server;
 6279:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 6280: 
 6281:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 6282:                                                 } else {
 6283:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 6284:                                                 }
 6285:                                             }
 6286:                                         } elsif ($key eq 'headtag') {
 6287:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
 6288:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
 6289:                                             }
 6290:                                         }
 6291:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
 6292:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
 6293:                                         }
 6294:                                     }
 6295:                                 }
 6296:                             }
 6297:                         } elsif ($key eq 'saml') {
 6298:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 6299:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
 6300:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
 6301:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
 6302:                                         foreach my $item ('text','img','alt','url','title','window','notsso') {
 6303:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
 6304:                                         }
 6305:                                     }
 6306:                                 }
 6307:                             }
 6308:                         } else {
 6309:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 6310:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 6311:                                     $domconfig{'login'}{$key}{$img};
 6312:                             }
 6313:                         }
 6314:                     } else {
 6315:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 6316:                     }
 6317:                 }
 6318:             } else {
 6319:                 $legacy{'login'} = 1;
 6320:             }
 6321:         } else {
 6322:             $legacy{'login'} = 1;
 6323:         }
 6324:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 6325:             if (keys(%{$domconfig{'rolecolors'}})) {
 6326:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 6327:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 6328:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 6329:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 6330:                         }
 6331:                     }
 6332:                 }
 6333:             } else {
 6334:                 $legacy{'rolecolors'} = 1;
 6335:             }
 6336:         } else {
 6337:             $legacy{'rolecolors'} = 1;
 6338:         }
 6339:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 6340:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 6341:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 6342:             }
 6343:         }
 6344:         if (keys(%legacy) > 0) {
 6345:             my %legacyhash = &get_legacy_domconf($udom);
 6346:             foreach my $item (keys(%legacyhash)) {
 6347:                 if ($item =~ /^\Q$udom\E\.login/) {
 6348:                     if ($legacy{'login'}) { 
 6349:                         $designhash{$item} = $legacyhash{$item};
 6350:                     }
 6351:                 } else {
 6352:                     if ($legacy{'rolecolors'}) {
 6353:                         $designhash{$item} = $legacyhash{$item};
 6354:                     }
 6355:                 }
 6356:             }
 6357:         }
 6358:     } else {
 6359:         %designhash = &get_legacy_domconf($udom); 
 6360:     }
 6361:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 6362: 				  $cachetime);
 6363:     return %designhash;
 6364: }
 6365: 
 6366: sub get_legacy_domconf {
 6367:     my ($udom) = @_;
 6368:     my %legacyhash;
 6369:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 6370:     my $designfile =  $designdir.'/'.$udom.'.tab';
 6371:     if (-e $designfile) {
 6372:         if ( open (my $fh,'<',$designfile) ) {
 6373:             while (my $line = <$fh>) {
 6374:                 next if ($line =~ /^\#/);
 6375:                 chomp($line);
 6376:                 my ($key,$val)=(split(/\=/,$line));
 6377:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 6378:             }
 6379:             close($fh);
 6380:         }
 6381:     }
 6382:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 6383:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 6384:     }
 6385:     return %legacyhash;
 6386: }
 6387: 
 6388: =pod
 6389: 
 6390: =item * &domainlogo()
 6391: 
 6392: Inputs: $domain (usually will be undef)
 6393: 
 6394: Returns: A link to a domain logo, if the domain logo exists.
 6395: If the domain logo does not exist, a description of the domain.
 6396: 
 6397: =cut
 6398: 
 6399: ###############################################
 6400: sub domainlogo {
 6401:     my $domain = &determinedomain(shift);
 6402:     my %designhash = &get_domainconf($domain);    
 6403:     # See if there is a logo
 6404:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 6405:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 6406:         if ($imgsrc =~ m{^/(adm|res)/}) {
 6407: 	    if ($imgsrc =~ m{^/res/}) {
 6408: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 6409: 		&Apache::lonnet::repcopy($local_name);
 6410: 	    }
 6411: 	   $imgsrc = &lonhttpdurl($imgsrc);
 6412:         }
 6413:         my $alttext = $domain;
 6414:         if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
 6415:             $alttext = $designhash{$domain.'.login.alttext_domlogo'};
 6416:         }
 6417:         return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
 6418:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 6419:         return &Apache::lonnet::domain($domain,'description');
 6420:     } else {
 6421:         return '';
 6422:     }
 6423: }
 6424: ##############################################
 6425: 
 6426: =pod
 6427: 
 6428: =item * &designparm()
 6429: 
 6430: Inputs: $which parameter; $domain (usually will be undef)
 6431: 
 6432: Returns: value of designparamter $which
 6433: 
 6434: =cut
 6435: 
 6436: 
 6437: ##############################################
 6438: sub designparm {
 6439:     my ($which,$domain)=@_;
 6440:     if (exists($env{'environment.color.'.$which})) {
 6441:         return $env{'environment.color.'.$which};
 6442:     }
 6443:     $domain=&determinedomain($domain);
 6444:     my %domdesign;
 6445:     unless ($domain eq 'public') {
 6446:         %domdesign = &get_domainconf($domain);
 6447:     }
 6448:     my $output;
 6449:     if ($domdesign{$domain.'.'.$which} ne '') {
 6450:         $output = $domdesign{$domain.'.'.$which};
 6451:     } else {
 6452:         $output = $defaultdesign{$which};
 6453:     }
 6454:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 6455:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 6456:         if ($output =~ m{^/(adm|res)/}) {
 6457:             if ($output =~ m{^/res/}) {
 6458:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 6459:                 &Apache::lonnet::repcopy($local_name);
 6460:             }
 6461:             $output = &lonhttpdurl($output);
 6462:         }
 6463:     }
 6464:     return $output;
 6465: }
 6466: 
 6467: ##############################################
 6468: =pod
 6469: 
 6470: =item * &authorspace()
 6471: 
 6472: Inputs: $url (usually will be undef).
 6473: 
 6474: Returns: Path to Authoring Space containing the resource or 
 6475:          directory being viewed (or for which action is being taken). 
 6476:          If $url is provided, and begins /priv/<domain>/<uname>
 6477:          the path will be that portion of the $context argument.
 6478:          Otherwise the path will be for the author space of the current
 6479:          user when the current role is author, or for that of the 
 6480:          co-author/assistant co-author space when the current role 
 6481:          is co-author or assistant co-author.
 6482: 
 6483: =cut
 6484: 
 6485: sub authorspace {
 6486:     my ($url) = @_;
 6487:     if ($url ne '') {
 6488:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 6489:            return $1;
 6490:         }
 6491:     }
 6492:     my $caname = '';
 6493:     my $cadom = '';
 6494:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 6495:         ($cadom,$caname) =
 6496:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 6497:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 6498:         $caname = $env{'user.name'};
 6499:         $cadom = $env{'user.domain'};
 6500:     }
 6501:     if (($caname ne '') && ($cadom ne '')) {
 6502:         return "/priv/$cadom/$caname/";
 6503:     }
 6504:     return;
 6505: }
 6506: 
 6507: ##############################################
 6508: =pod
 6509: 
 6510: =item * &head_subbox()
 6511: 
 6512: Inputs: $content (contains HTML code with page functions, etc.)
 6513: 
 6514: Returns: HTML div with $content
 6515:          To be included in page header
 6516: 
 6517: =cut
 6518: 
 6519: sub head_subbox {
 6520:     my ($content)=@_;
 6521:     my $output =
 6522:         '<div class="LC_head_subbox">'
 6523:        .$content
 6524:        .'</div>'
 6525: }
 6526: 
 6527: ##############################################
 6528: =pod
 6529: 
 6530: =item * &CSTR_pageheader()
 6531: 
 6532: Input: (optional) filename from which breadcrumb trail is built.
 6533:        In most cases no input as needed, as $env{'request.filename'}
 6534:        is appropriate for use in building the breadcrumb trail.
 6535:        frameset flag
 6536:        If page header is being requested for use in a frameset, then
 6537:        the second (option) argument -- frameset will be true, and
 6538:        the target attribute set for links should be target="_parent".
 6539:        If $title is supplied as the thitd arg, that will be used to 
 6540:        the left of the breadcrumbs tail for the current path.
 6541: 
 6542: Returns: HTML div with CSTR path and recent box
 6543:          To be included on Authoring Space pages
 6544: 
 6545: =cut
 6546: 
 6547: sub CSTR_pageheader {
 6548:     my ($trailfile,$frameset,$title) = @_;
 6549:     if ($trailfile eq '') {
 6550:         $trailfile = $env{'request.filename'};
 6551:     }
 6552: 
 6553: # this is for resources; directories have customtitle, and crumbs
 6554: # and select recent are created in lonpubdir.pm
 6555: 
 6556:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 6557:     my ($udom,$uname,$thisdisfn)=
 6558:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 6559:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 6560:     $formaction =~ s{/+}{/}g;
 6561: 
 6562:     my $parentpath = '';
 6563:     my $lastitem = '';
 6564:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 6565:         $parentpath = $1;
 6566:         $lastitem = $2;
 6567:     } else {
 6568:         $lastitem = $thisdisfn;
 6569:     }
 6570: 
 6571:     my $crsauthor;
 6572:     if (($env{'request.course.id'}) &&
 6573:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
 6574:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
 6575:         $crsauthor = 1;
 6576:         if ($title eq '') {
 6577:             $title = &mt('Course Authoring Space');
 6578:         }
 6579:     } elsif ($title eq '') {
 6580:         $title = &mt('Authoring Space');
 6581:     }
 6582: 
 6583:     my ($target,$crumbtarget) = (' target="_top"','_top');
 6584:     if ($frameset) {
 6585:         $target = ' target="_parent"';
 6586:         $crumbtarget = '_parent';
 6587:     } elsif (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
 6588:         $target = '';
 6589:         $crumbtarget = '';
 6590:     } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
 6591:         $target = ' target="'.$env{'request.deeplink.target'}.'"';
 6592:         $crumbtarget = $env{'request.deeplink.target'};
 6593:     }
 6594: 
 6595:     my $output =
 6596:          '<div>'
 6597:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 6598:         .'<b>'.$title.'</b> '
 6599:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
 6600:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
 6601: 
 6602:     if ($lastitem) {
 6603:         $output .=
 6604:              '<span class="LC_filename">'
 6605:             .$lastitem
 6606:             .'</span>';
 6607:     }
 6608: 
 6609:     if ($crsauthor) {
 6610:         $output .= '</form>'.&Apache::lonmenu::constspaceform($frameset);
 6611:     } else {
 6612:         $output .=
 6613:              '<br />'
 6614:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
 6615:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 6616:             .'</form>'
 6617:             .&Apache::lonmenu::constspaceform($frameset);
 6618:     }
 6619:     $output .= '</div>';
 6620: 
 6621:     return $output;
 6622: }
 6623: 
 6624: ##############################################
 6625: =pod
 6626: 
 6627: =item * &nocodemirror()
 6628: 
 6629: Input: None
 6630: 
 6631: Returns: 1 if CodeMirror is deactivated based on
 6632:          user's preference, or domain default,
 6633:          if user indicated use of default.
 6634: 
 6635: =cut
 6636: 
 6637: sub nocodemirror {
 6638:     my $nocodem = $env{'environment.nocodemirror'};
 6639:     unless ($nocodem) {
 6640:         my %domdefs = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
 6641:         if ($domdefs{'nocodemirror'}) {
 6642:             $nocodem = 'yes';
 6643:         }
 6644:     }
 6645:     if ($nocodem eq 'yes') {
 6646:         return 1;
 6647:     }
 6648:     return;
 6649: }
 6650: 
 6651: ##############################################
 6652: =pod
 6653: 
 6654: =item * &permitted_editors()
 6655: 
 6656: Input: $uri (optional)
 6657: 
 6658: Returns: %editors hash in which keys are editors
 6659:          permitted in current Authoring Space,
 6660:          or in current course for web pages
 6661:          created in a course.
 6662: 
 6663:          Value for each key is 1. Possible keys
 6664:          are: edit, xml, and daxe.
 6665: 
 6666:          For a regular Authoring Space, if no specific
 6667:          set of editors has been set for the Author
 6668:          who owns the Authoring Space, then the
 6669:          domain default will be used.  If no domain
 6670:          default has been set, then the keys will be
 6671:          edit and xml.
 6672: 
 6673:          For a course author, or for web pages created
 6674:          in a course, if no specific set of editors has
 6675:          been set for the course, then the domain
 6676:          course default will be used. If no domain
 6677:          course default has been set, then the keys
 6678:          will be edit and xml.
 6679: 
 6680: =cut
 6681: 
 6682: sub permitted_editors {
 6683:     my ($uri) = @_;
 6684:     my ($is_author,$is_coauthor,$is_course,$auname,$audom,%editors);
 6685:     if ($env{'request.role'} =~ m{^au\./}) {
 6686:         $is_author = 1;
 6687:     } elsif ($env{'request.role'} =~ m{^(?:ca|aa)\./($match_domain)/($match_username)}) {
 6688:         ($audom,$auname) = ($1,$2);
 6689:         if (($audom ne '') && ($auname ne '')) {
 6690:             if (($env{'user.domain'} eq $audom) &&
 6691:                 ($env{'user.name'} eq $auname)) {
 6692:                 $is_author = 1;
 6693:             } else {
 6694:                 $is_coauthor = 1;
 6695:             }
 6696:         }
 6697:     } elsif ($env{'request.course.id'}) {
 6698:         my ($cdom,$cnum);
 6699:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6700:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6701:         if (($env{'request.editurl'} =~ m{^/priv/\Q$cdom/$cnum\E/}) ||
 6702:             ($env{'request.editurl'} =~ m{^/uploaded/\Q$cdom/$cnum\E/(docs|supplemental)/})) {
 6703:             $is_course = 1;
 6704:         } elsif ($env{'request.editurl'} =~ m{^/priv/($match_domain)/($match_username)/}) {
 6705:             ($audom,$auname) = ($1,$2);
 6706:         } elsif ($env{'request.uri'} =~ m{^/priv/($match_domain)/($match_username)/}) {
 6707:             ($audom,$auname) = ($1,$2);
 6708:         } elsif (($uri eq '/daxesave') &&
 6709:                  (($env{'form.path'} =~ m{^/daxeopen/priv/\Q$cdom/$cnum\E/}) ||
 6710:                   ($env{'form.path'} =~ m{^/daxeopen/uploaded/\Q$cdom/$cnum\E/(docs|supplemental)/}))) {
 6711:             $is_course = 1;
 6712:         } elsif (($uri eq '/daxesave') &&
 6713:                  ($env{'form.path'} =~ m{^/daxeopen/priv/($match_domain)/($match_username)/})) {
 6714:             ($audom,$auname) = ($1,$2);
 6715:         }
 6716:         unless ($is_course) {
 6717:             if (($audom ne '') && ($auname ne '')) {
 6718:                 if (($env{'user.domain'} eq $audom) &&
 6719:                     ($env{'user.name'} eq $auname)) {
 6720:                     $is_author = 1;
 6721:                 } else {
 6722:                     $is_coauthor = 1;
 6723:                 }
 6724:             }
 6725:         }
 6726:     }
 6727:     if ($is_author) {
 6728:         if (exists($env{'environment.editors'})) {
 6729:             map { $editors{$_} = 1; } split(/,/,$env{'environment.editors'});
 6730:         } else {
 6731:             %editors = ( edit => 1,
 6732:                          xml => 1,
 6733:                        );
 6734:         }
 6735:     } elsif ($is_coauthor) {
 6736:         if (exists($env{"environment.internal.editors./$audom/$auname"})) {
 6737:             map { $editors{$_} = 1; } split(/,/,$env{"environment.internal.editors./$audom/$auname"});
 6738:         } else {
 6739:             %editors = ( edit => 1,
 6740:                          xml => 1,
 6741:                        );
 6742:         }
 6743:     } elsif ($is_course) {
 6744:         if (exists($env{'course.'.$env{'request.course.id'}.'.internal.crseditors'})) {
 6745:             map { $editors{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.internal.crseditors'});
 6746:         } else {
 6747:             my %domdefaults = &Apache::lonnet::get_domain_defaults($env{'course.'.$env{'request.course.id'}.'.domain'});
 6748:             if (exists($domdefaults{'crseditors'})) {
 6749:                 map { $editors{$_} = 1; } split(/,/,$domdefaults{'crseditors'});
 6750:             } else {
 6751:                 %editors = ( edit => 1,
 6752:                              xml => 1,
 6753:                            );
 6754:             }
 6755:         }
 6756:     } else {
 6757:         %editors = ( edit => 1,
 6758:                      xml => 1,
 6759:                    );
 6760:     }
 6761:     return %editors;
 6762: }
 6763: 
 6764: ###############################################
 6765: ###############################################
 6766: 
 6767: =pod
 6768: 
 6769: =back
 6770: 
 6771: =head1 HTML Helpers
 6772: 
 6773: =over 4
 6774: 
 6775: =item * &bodytag()
 6776: 
 6777: Returns a uniform header for LON-CAPA web pages.
 6778: 
 6779: Inputs: 
 6780: 
 6781: =over 4
 6782: 
 6783: =item * $title, A title to be displayed on the page.
 6784: 
 6785: =item * $function, the current role (can be undef).
 6786: 
 6787: =item * $addentries, extra parameters for the <body> tag.
 6788: 
 6789: =item * $bodyonly, if defined, only return the <body> tag.
 6790: 
 6791: =item * $domain, if defined, force a given domain.
 6792: 
 6793: =item * $forcereg, if page should register as content page (relevant for 
 6794:             text interface only)
 6795: 
 6796: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 6797:                      navigational links
 6798: 
 6799: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 6800: 
 6801: =item * $args, optional argument valid values are
 6802:             no_auto_mt_title -> prevents &mt()ing the title arg
 6803:             use_absolute     -> for external resource or syllabus, this will
 6804:                                 contain https://<hostname> if server uses
 6805:                                 https (as per hosts.tab), but request is for http
 6806:             hostname         -> hostname, from $r->hostname().
 6807: 
 6808: =item * $advtoolsref, optional argument, ref to an array containing
 6809:             inlineremote items to be added in "Functions" menu below
 6810:             breadcrumbs.
 6811: 
 6812: =item * $ltiscope, optional argument, will be one of: resource, map or
 6813:             course, if LON-CAPA is in LTI Provider context. Value is
 6814:             the scope of use, i.e., launch was for access to a single, a map
 6815:             or the entire course.
 6816: 
 6817: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
 6818:             context, this will contain the URL for the landing item in
 6819:             the course, after launch from an LTI Consumer
 6820: 
 6821: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
 6822:             context, this will contain a reference to hash of items
 6823:             to be included in the page header and/or inline menu.
 6824: 
 6825: =item * $menucoll, optional argument, if specific menu collection is in
 6826:             effect, either set as the default for the course, or set for
 6827:             the deeplink paramater for $env{'request.deeplink.login'}
 6828:             then $menucoll will be the number of that collection. 
 6829: 
 6830: =item * $menuref, optional argument, reference to a hash, containing the
 6831:             menu options included for the menu in effect, based on the
 6832:             configuration for the numbered menu collection in use.  
 6833: 
 6834: =item * $showncrumbsref, reference to a scalar. Calls to lonmenu::innerregister
 6835:             within &bodytag() can result in calls to lonhtmlcommon::breadcrumbs(),
 6836:             if so, $showncrumbsref is set there to 1, and will propagate back
 6837:             via &bodytag() to &start_page(), to prevent lonhtmlcommon::breadcrumbs()
 6838:             being called a second time.
 6839: 
 6840: =back
 6841: 
 6842: Returns: A uniform header for LON-CAPA web pages.  
 6843: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 6844: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 6845: other decorations will be returned.
 6846: 
 6847: =cut
 6848: 
 6849: sub bodytag {
 6850:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 6851:         $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri,
 6852:         $ltimenu,$menucoll,$menuref,$showncrumbsref)=@_;
 6853: 
 6854:     my $public;
 6855:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 6856:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 6857:         $public = 1;
 6858:     }
 6859:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 6860:     my $httphost = $args->{'use_absolute'};
 6861:     my $hostname = $args->{'hostname'};
 6862: 
 6863:     $function = &get_users_function() if (!$function);
 6864:     my $img =    &designparm($function.'.img',$domain);
 6865:     my $font =   &designparm($function.'.font',$domain);
 6866:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 6867: 
 6868:     my %design = ( 'style'   => 'margin-top: 0',
 6869: 		   'bgcolor' => $pgbg,
 6870: 		   'text'    => $font,
 6871:                    'alink'   => &designparm($function.'.alink',$domain),
 6872: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 6873: 		   'link'    => &designparm($function.'.link',$domain),);
 6874:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 6875: 
 6876:  # role and realm
 6877:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
 6878:     if ($realm) {
 6879:         $realm = '/'.$realm;
 6880:     }
 6881:     if ($role eq 'ca') {
 6882:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 6883:         $realm = &plainname($rname,$rdom);
 6884:     } 
 6885: # realm
 6886:     my ($cid,$sec);
 6887:     if ($env{'request.course.id'}) {
 6888:         $cid = $env{'request.course.id'};
 6889:         if ($env{'request.course.sec'}) {
 6890:             $sec = $env{'request.course.sec'};
 6891:         }
 6892:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
 6893:         if (&Apache::lonnet::is_course($1,$2)) {
 6894:             $cid = $1.'_'.$2;
 6895:             $sec = $3;
 6896:         }
 6897:     }
 6898:     if ($cid) {
 6899:         if ($env{'request.role'} !~ /^cr/) {
 6900:             $role = &Apache::lonnet::plaintext($role,&course_type());
 6901:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
 6902:             if ($env{'request.role.desc'}) {
 6903:                 $role = $env{'request.role.desc'};
 6904:             } else {
 6905:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
 6906:             }
 6907:         } else {
 6908:             $role = (split(/\//,$role,4))[-1]; 
 6909:         }
 6910:         if ($sec) {
 6911:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
 6912:         }   
 6913: 	$realm = $env{'course.'.$cid.'.description'};
 6914:     } else {
 6915:         $role = &Apache::lonnet::plaintext($role);
 6916:     }
 6917: 
 6918:     if (!$realm) { $realm='&nbsp;'; }
 6919: 
 6920:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 6921: 
 6922: # construct main body tag
 6923:     my $bodytag = "<body $extra_body_attr>".
 6924: 	&Apache::lontexconvert::init_math_support();
 6925: 
 6926:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 6927: 
 6928:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 6929:         return $bodytag;
 6930:     }
 6931: 
 6932:     if ($public) {
 6933: 	undef($role);
 6934:     }
 6935: 
 6936:     my $showcrstitle = 1;
 6937:     if (($cid) && ($env{'request.lti.login'})) {
 6938:         if (ref($ltimenu) eq 'HASH') {
 6939:             unless ($ltimenu->{'role'}) {
 6940:                 undef($role);
 6941:             }
 6942:             unless ($ltimenu->{'coursetitle'}) {
 6943:                 $realm='&nbsp;';
 6944:                 $showcrstitle = 0;
 6945:             }
 6946:         }
 6947:     } elsif (($cid) && ($menucoll)) {
 6948:         if (ref($menuref) eq 'HASH') {
 6949:             unless ($menuref->{'role'}) {
 6950:                 undef($role);
 6951:             }
 6952:             unless ($menuref->{'crs'}) {
 6953:                 $realm='&nbsp;';
 6954:                 $showcrstitle = 0;
 6955:             }
 6956:         }
 6957:     }
 6958: 
 6959:     my $titleinfo = '<h1>'.$title.'</h1>';
 6960:     #
 6961:     # Extra info if you are the DC
 6962:     my $dc_info = '';
 6963:     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
 6964:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
 6965:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 6966:         $dc_info =~ s/\s+$//;
 6967:     }
 6968: 
 6969:     my $crstype;
 6970:     if ($cid) {
 6971:         $crstype = $env{'course.'.$cid.'.type'};
 6972:     } elsif ($args->{'crstype'}) {
 6973:         $crstype = $args->{'crstype'};
 6974:     }
 6975:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
 6976:         undef($role);
 6977:     } else {
 6978:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
 6979:     }
 6980: 
 6981:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 6982: 
 6983:         #    if ($env{'request.state'} eq 'construct') {
 6984:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 6985:         #    }
 6986: 
 6987:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 6988:             Apache::lonmenu::utilityfunctions($httphost), 'start');
 6989: 
 6990:         my $collapsible;
 6991:         if ($args->{'collapsible_header'} ne '') {
 6992:             $collapsible = 1;
 6993:             my ($menustate,$tiptext,$divclass);
 6994:             if ($args->{'start_collapsed'}) {
 6995:                 $menustate = 'collapsed';
 6996:                 $tiptext = 'display';
 6997:                 $divclass = 'hidden';
 6998:             } else {
 6999:                 $menustate = 'expanded';
 7000:                 $tiptext = 'hide';
 7001:                 $divclass = 'shown';
 7002:             }
 7003:             my $alttext = &mt('menu state: '.$menustate);
 7004:             my $tooltip = &mt($tiptext.' standard menus');
 7005:             $bodytag .= <<"END";
 7006: <div id="LC_expandingContainer" style="display:inline;">
 7007: <div id="LC_collapsible" class="LC_collapse_trigger" style="position: absolute;top: -5px;left: 0px; z-index:101; display:inline;">
 7008: <a href="#" style="text-decoration:none;"><img class="LC_collapsible_indicator" alt="$alttext" title="$tooltip" src="/res/adm/pages/$menustate.png" style="border:0;margin:0;padding:0;max-width:100%;height:auto" /></a></div>
 7009: <div class="LC_menus_content $divclass">
 7010: END
 7011:         }
 7012:         unless ($args->{'no_primary_menu'}) {
 7013:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
 7014:                                                               $args->{'links_disabled'},
 7015:                                                               $args->{'links_target'},
 7016:                                                               $collapsible);
 7017: 
 7018:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 7019:                 if ($dc_info) {
 7020:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 7021:                 }
 7022:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 7023:                                <em>$realm</em> $dc_info</div>|;
 7024:                 return $bodytag;
 7025:             }
 7026: 
 7027:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 7028:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 7029:             }
 7030: 
 7031:             $bodytag .= $right;
 7032: 
 7033:             if ($dc_info) {
 7034:                 $dc_info = &dc_courseid_toggle($dc_info);
 7035:             }
 7036:             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 7037:         }
 7038: 
 7039:         #if directed to not display the secondary menu, don't.  
 7040:         if ($args->{'no_secondary_menu'}) {
 7041:             return $bodytag;
 7042:         }
 7043:         #don't show menus for public users
 7044:         if (!$public){
 7045:             unless ($args->{'no_inline_menu'}) {
 7046:                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
 7047:                                                             $args->{'no_primary_menu'},
 7048:                                                             $menucoll,$menuref,
 7049:                                                             $args->{'links_disabled'},
 7050:                                                             $args->{'links_target'});
 7051:             }
 7052:             $bodytag .= Apache::lonmenu::serverform();
 7053:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 7054:             if ($env{'request.state'} eq 'construct') {
 7055:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 7056:                                 $args->{'bread_crumbs'},'','',$hostname,
 7057:                                 $ltiscope,$ltiuri,$showncrumbsref);
 7058:             } elsif ($forcereg) {
 7059:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 7060:                                 $args->{'group'},$args->{'hide_buttons'},
 7061:                                 $hostname,$ltiscope,$ltiuri,$showncrumbsref);
 7062:             } else {
 7063:                 $bodytag .= 
 7064:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 7065:                                                         $forcereg,$args->{'group'},
 7066:                                                         $args->{'bread_crumbs'},
 7067:                                                         $advtoolsref,'',$hostname);
 7068:             }
 7069:         }else{
 7070:             # this is to seperate menu from content when there's no secondary
 7071:             # menu. Especially needed for public accessible ressources.
 7072:             $bodytag .= '<hr style="clear:both" />';
 7073:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 7074:         }
 7075:         if ($args->{'collapsible_header'} ne '') {
 7076:             $bodytag .= $args->{'collapsible_header'}.
 7077:                         '<div id="LC_collapsible_separator"></div>'.
 7078:                         '</div></div>';
 7079:         }
 7080:         return $bodytag;
 7081: }
 7082: 
 7083: sub dc_courseid_toggle {
 7084:     my ($dc_info) = @_;
 7085:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 7086:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 7087:            &mt('(More ...)').'</a></span>'.
 7088:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 7089: }
 7090: 
 7091: sub make_attr_string {
 7092:     my ($register,$attr_ref) = @_;
 7093: 
 7094:     if ($attr_ref && !ref($attr_ref)) {
 7095: 	die("addentries Must be a hash ref ".
 7096: 	    join(':',caller(1))." ".
 7097: 	    join(':',caller(0))." ");
 7098:     }
 7099: 
 7100:     if ($register) {
 7101: 	my ($on_load,$on_unload);
 7102: 	foreach my $key (keys(%{$attr_ref})) {
 7103: 	    if      (lc($key) eq 'onload') {
 7104: 		$on_load.=$attr_ref->{$key}.';';
 7105: 		delete($attr_ref->{$key});
 7106: 
 7107: 	    } elsif (lc($key) eq 'onunload') {
 7108: 		$on_unload.=$attr_ref->{$key}.';';
 7109: 		delete($attr_ref->{$key});
 7110: 	    }
 7111: 	}
 7112: 	$attr_ref->{'onload'}  = $on_load;
 7113: 	$attr_ref->{'onunload'}= $on_unload;
 7114:     }
 7115: 
 7116:     my $attr_string;
 7117:     foreach my $attr (sort(keys(%$attr_ref))) {
 7118: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 7119:     }
 7120:     return $attr_string;
 7121: }
 7122: 
 7123: 
 7124: ###############################################
 7125: ###############################################
 7126: 
 7127: =pod
 7128: 
 7129: =item * &endbodytag()
 7130: 
 7131: Returns a uniform footer for LON-CAPA web pages.
 7132: 
 7133: Inputs: 1 - optional reference to an args hash
 7134: If in the hash, key for noredirectlink has a value which evaluates to true,
 7135: a 'Continue' link is not displayed if the page contains an
 7136: internal redirect in the <head></head> section,
 7137: i.e., $env{'internal.head.redirect'} exists   
 7138: 
 7139: =cut
 7140: 
 7141: sub endbodytag {
 7142:     my ($args) = @_;
 7143:     my $endbodytag;
 7144:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 7145:         $endbodytag='</body>';
 7146:     }
 7147:     if ( exists( $env{'internal.head.redirect'} ) ) {
 7148:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 7149:             my ($endbodyjs,$idattr);
 7150:             if ($env{'internal.head.to_opener'}) {
 7151:                 my $linkid = 'LC_continue_link';
 7152:                 $idattr = ' id="'.$linkid.'"';
 7153:                 my $redirect_for_js = &js_escape($env{'internal.head.redirect'});
 7154:                 $endbodyjs=<<ENDJS;
 7155: <script type="text/javascript">
 7156: // <![CDATA[
 7157: function ebFunction(evt) {
 7158:     evt.preventDefault();
 7159:     var dest = '$redirect_for_js';
 7160:     if (window.opener != null && !window.opener.closed) {
 7161:         window.opener.location.href=dest;
 7162:         window.close();
 7163:     } else {
 7164:         window.location.href=dest;
 7165:     }
 7166:     return false;
 7167: }
 7168: 
 7169: \$(document).ready(function () {
 7170:   if (document.getElementById('$linkid')) {
 7171:     var clickelem = document.getElementById('$linkid');
 7172:     clickelem.addEventListener('click',ebFunction,false);
 7173:   }
 7174: });
 7175: // ]]>
 7176: </script>
 7177: ENDJS
 7178:             }
 7179: 	    $endbodytag=
 7180: 	        "$endbodyjs<br /><a href=\"$env{'internal.head.redirect'}\"$idattr>".
 7181: 	        &mt('Continue').'</a>'.
 7182: 	        $endbodytag;
 7183:         }
 7184:     }
 7185:     if ((ref($args) eq 'HASH') && ($args->{'dashjs'})) {
 7186:         $endbodytag = &Apache::lonhtmlcommon::dash_to_minus_js().$endbodytag;
 7187:     }
 7188:     return $endbodytag;
 7189: }
 7190: 
 7191: =pod
 7192: 
 7193: =item * &standard_css()
 7194: 
 7195: Returns a style sheet
 7196: 
 7197: Inputs: (all optional)
 7198:             domain         -> force to color decorate a page for a specific
 7199:                                domain
 7200:             function       -> force usage of a specific rolish color scheme
 7201:             bgcolor        -> override the default page bgcolor
 7202: 
 7203: =cut
 7204: 
 7205: sub standard_css {
 7206:     my ($function,$domain,$bgcolor) = @_;
 7207:     $function  = &get_users_function() if (!$function);
 7208:     my $img    = &designparm($function.'.img',   $domain);
 7209:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 7210:     my $font   = &designparm($function.'.font',  $domain);
 7211:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 7212: #second colour for later usage
 7213:     my $sidebg = &designparm($function.'.sidebg',$domain);
 7214:     my $pgbg_or_bgcolor =
 7215: 	         $bgcolor ||
 7216: 	         &designparm($function.'.pgbg',  $domain);
 7217:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 7218:     my $alink  = &designparm($function.'.alink', $domain);
 7219:     my $vlink  = &designparm($function.'.vlink', $domain);
 7220:     my $link   = &designparm($function.'.link',  $domain);
 7221: 
 7222:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 7223:     my $mono                 = 'monospace';
 7224:     my $data_table_head      = $sidebg;
 7225:     my $data_table_light     = '#FAFAFA';
 7226:     my $data_table_dark      = '#E0E0E0';
 7227:     my $data_table_darker    = '#CCCCCC';
 7228:     my $data_table_highlight = '#FFFF00';
 7229:     my $mail_new             = '#FFBB77';
 7230:     my $mail_new_hover       = '#DD9955';
 7231:     my $mail_read            = '#BBBB77';
 7232:     my $mail_read_hover      = '#999944';
 7233:     my $mail_replied         = '#AAAA88';
 7234:     my $mail_replied_hover   = '#888855';
 7235:     my $mail_other           = '#99BBBB';
 7236:     my $mail_other_hover     = '#669999';
 7237:     my $table_header         = '#DDDDDD';
 7238:     my $feedback_link_bg     = '#BBBBBB';
 7239:     my $lg_border_color      = '#C8C8C8';
 7240:     my $button_hover         = '#BF2317';
 7241: 
 7242:     my $border = ($env{'browser.type'} eq 'explorer' ||
 7243:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 7244:                                              : '0 3px 0 4px';
 7245: 
 7246: 
 7247:     return <<END;
 7248: 
 7249: /* needed for iframe to allow 100% height in FF */
 7250: body, html { 
 7251:     margin: 0;
 7252:     padding: 0 0.5%;
 7253:     height: 99%; /* to avoid scrollbars */
 7254: }
 7255: 
 7256: body {
 7257:   font-family: $sans;
 7258:   line-height:130%;
 7259:   font-size:0.83em;
 7260:   color:$font;
 7261: }
 7262: 
 7263: a:focus,
 7264: a:focus img {
 7265:   color: red;
 7266: }
 7267: 
 7268: form, .inline {
 7269:   display: inline;
 7270: }
 7271: 
 7272: .LC_menus_content.shown{
 7273:   display: block;
 7274: }
 7275: 
 7276: .LC_menus_content.hidden {
 7277:   display: none;
 7278: }
 7279: 
 7280: .LC_right {
 7281:   text-align:right;
 7282: }
 7283: 
 7284: .LC_middle {
 7285:   vertical-align:middle;
 7286: }
 7287: 
 7288: .LC_floatleft {
 7289:   float: left;
 7290: }
 7291: 
 7292: .LC_floatright {
 7293:   float: right;
 7294: }
 7295: 
 7296: .LC_400Box {
 7297:   width:400px;
 7298: }
 7299: 
 7300: #LC_collapsible_separator {
 7301:     border: 1px solid black;
 7302:     width: 99.9%;
 7303:     height: 0px;
 7304: }
 7305: 
 7306: .LC_iframecontainer {
 7307:     width: 98%;
 7308:     margin: 0;
 7309:     position: fixed;
 7310:     top: 8.5em;
 7311:     bottom: 0;
 7312: }
 7313: 
 7314: .LC_iframecontainer iframe{
 7315:     border: none;
 7316:     width: 100%;
 7317:     height: 100%;
 7318: }
 7319: 
 7320: .LC_filename {
 7321:   font-family: $mono;
 7322:   white-space:pre;
 7323:   font-size: 120%;
 7324: }
 7325: 
 7326: .LC_fileicon {
 7327:   border: none;
 7328:   height: 1.3em;
 7329:   vertical-align: text-bottom;
 7330:   margin-right: 0.3em;
 7331:   text-decoration:none;
 7332: }
 7333: 
 7334: .LC_setting {
 7335:   text-decoration:underline;
 7336: }
 7337: 
 7338: .LC_error {
 7339:   color: red;
 7340: }
 7341: 
 7342: .LC_warning {
 7343:   color: darkorange;
 7344: }
 7345: 
 7346: .LC_diff_removed {
 7347:   color: red;
 7348: }
 7349: 
 7350: .LC_info,
 7351: .LC_success,
 7352: .LC_diff_added {
 7353:   color: green;
 7354: }
 7355: 
 7356: div.LC_confirm_box {
 7357:   background-color: #FAFAFA;
 7358:   border: 1px solid $lg_border_color;
 7359:   margin-right: 0;
 7360:   padding: 5px;
 7361: }
 7362: 
 7363: div.LC_confirm_box .LC_error img,
 7364: div.LC_confirm_box .LC_success img {
 7365:   vertical-align: middle;
 7366: }
 7367: 
 7368: .LC_maxwidth {
 7369:   max-width: 100%;
 7370:   height: auto;
 7371: }
 7372: 
 7373: .LC_textsize_mobile {
 7374:   \@media only screen and (max-device-width: 480px) {
 7375:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
 7376:   }
 7377: }
 7378: 
 7379: .LC_icon {
 7380:   border: none;
 7381:   vertical-align: middle;
 7382: }
 7383: 
 7384: .LC_docs_spacer {
 7385:   width: 25px;
 7386:   height: 1px;
 7387:   border: none;
 7388: }
 7389: 
 7390: .LC_internal_info {
 7391:   color: #999999;
 7392: }
 7393: 
 7394: .LC_discussion {
 7395:   background: $data_table_dark;
 7396:   border: 1px solid black;
 7397:   margin: 2px;
 7398: }
 7399: 
 7400: .LC_disc_action_left {
 7401:   background: $sidebg;
 7402:   text-align: left;
 7403:   padding: 4px;
 7404:   margin: 2px;
 7405: }
 7406: 
 7407: .LC_disc_action_right {
 7408:   background: $sidebg;
 7409:   text-align: right;
 7410:   padding: 4px;
 7411:   margin: 2px;
 7412: }
 7413: 
 7414: .LC_disc_new_item {
 7415:   background: white;
 7416:   border: 2px solid red;
 7417:   margin: 4px;
 7418:   padding: 4px;
 7419: }
 7420: 
 7421: .LC_disc_old_item {
 7422:   background: white;
 7423:   margin: 4px;
 7424:   padding: 4px;
 7425: }
 7426: 
 7427: table.LC_pastsubmission {
 7428:   border: 1px solid black;
 7429:   margin: 2px;
 7430: }
 7431: 
 7432: table#LC_menubuttons {
 7433:   width: 100%;
 7434:   background: $pgbg;
 7435:   border: 2px;
 7436:   border-collapse: separate;
 7437:   padding: 0;
 7438: }
 7439: 
 7440: table#LC_title_bar a {
 7441:   color: $fontmenu;
 7442: }
 7443: 
 7444: table#LC_title_bar {
 7445:   clear: both;
 7446:   display: none;
 7447: }
 7448: 
 7449: table#LC_title_bar,
 7450: table.LC_breadcrumbs, /* obsolete? */
 7451: table#LC_title_bar.LC_with_remote {
 7452:   width: 100%;
 7453:   border-color: $pgbg;
 7454:   border-style: solid;
 7455:   border-width: $border;
 7456:   background: $pgbg;
 7457:   color: $fontmenu;
 7458:   border-collapse: collapse;
 7459:   padding: 0;
 7460:   margin: 0;
 7461: }
 7462: 
 7463: ul.LC_breadcrumb_tools_outerlist {
 7464:     margin: 0;
 7465:     padding: 0;
 7466:     position: relative;
 7467:     list-style: none;
 7468: }
 7469: ul.LC_breadcrumb_tools_outerlist li {
 7470:     display: inline;
 7471: }
 7472: 
 7473: .LC_breadcrumb_tools_navigation {
 7474:     padding: 0;
 7475:     margin: 0;
 7476:     float: left;
 7477: }
 7478: .LC_breadcrumb_tools_tools {
 7479:     padding: 0;
 7480:     margin: 0;
 7481:     float: right;
 7482: }
 7483: 
 7484: .LC_placement_prog {
 7485:     padding-right: 20px;
 7486:     font-weight: bold;
 7487:     font-size: 90%;
 7488: }
 7489: 
 7490: table#LC_title_bar td {
 7491:   background: $tabbg;
 7492: }
 7493: 
 7494: table#LC_menubuttons img {
 7495:   border: none;
 7496: }
 7497: 
 7498: .LC_breadcrumbs_component {
 7499:   float: right;
 7500:   margin: 0 1em;
 7501: }
 7502: .LC_breadcrumbs_component img {
 7503:   vertical-align: middle;
 7504: }
 7505: 
 7506: .LC_breadcrumbs_hoverable {
 7507:   background: $sidebg;
 7508: }
 7509: 
 7510: td.LC_table_cell_checkbox {
 7511:   text-align: center;
 7512: }
 7513: 
 7514: .LC_fontsize_small {
 7515:   font-size: 70%;
 7516: }
 7517: 
 7518: #LC_breadcrumbs {
 7519:   clear:both;
 7520:   background: $sidebg;
 7521:   border-bottom: 1px solid $lg_border_color;
 7522:   line-height: 2.5em;
 7523:   overflow: hidden;
 7524:   margin: 0;
 7525:   padding: 0;
 7526:   text-align: left;
 7527: }
 7528: 
 7529: .LC_head_subbox, .LC_actionbox {
 7530:   clear:both;
 7531:   background: #F8F8F8; /* $sidebg; */
 7532:   border: 1px solid $sidebg;
 7533:   margin: 0 0 10px 0;
 7534:   padding: 3px;
 7535:   text-align: left;
 7536: }
 7537: 
 7538: .LC_fontsize_medium {
 7539:   font-size: 85%;
 7540: }
 7541: 
 7542: .LC_fontsize_large {
 7543:   font-size: 120%;
 7544: }
 7545: 
 7546: .LC_menubuttons_inline_text {
 7547:   color: $font;
 7548:   font-size: 90%;
 7549:   padding-left:3px;
 7550: }
 7551: 
 7552: .LC_menubuttons_inline_text img{
 7553:   vertical-align: middle;
 7554: }
 7555: 
 7556: li.LC_menubuttons_inline_text img {
 7557:   cursor:pointer;
 7558:   text-decoration: none;
 7559: }
 7560: 
 7561: .LC_menubuttons_link {
 7562:   text-decoration: none;
 7563: }
 7564: 
 7565: .LC_menubuttons_category {
 7566:   color: $font;
 7567:   background: $pgbg;
 7568:   font-size: larger;
 7569:   font-weight: bold;
 7570: }
 7571: 
 7572: td.LC_menubuttons_text {
 7573:   color: $font;
 7574: }
 7575: 
 7576: .LC_current_location {
 7577:   background: $tabbg;
 7578: }
 7579: 
 7580: td.LC_zero_height {
 7581:   line-height: 0; 
 7582:   cellpadding: 0;
 7583: }
 7584: 
 7585: table.LC_data_table {
 7586:   border: 1px solid #000000;
 7587:   border-collapse: separate;
 7588:   border-spacing: 1px;
 7589:   background: $pgbg;
 7590: }
 7591: 
 7592: .LC_data_table_dense {
 7593:   font-size: small;
 7594: }
 7595: 
 7596: table.LC_nested_outer {
 7597:   border: 1px solid #000000;
 7598:   border-collapse: collapse;
 7599:   border-spacing: 0;
 7600:   width: 100%;
 7601: }
 7602: 
 7603: table.LC_innerpickbox,
 7604: table.LC_nested {
 7605:   border: none;
 7606:   border-collapse: collapse;
 7607:   border-spacing: 0;
 7608:   width: 100%;
 7609: }
 7610: 
 7611: table.LC_data_table tr th,
 7612: table.LC_calendar tr th,
 7613: table.LC_prior_tries tr th,
 7614: table.LC_innerpickbox tr th {
 7615:   font-weight: bold;
 7616:   background-color: $data_table_head;
 7617:   color:$fontmenu;
 7618:   font-size:90%;
 7619: }
 7620: 
 7621: table.LC_innerpickbox tr th,
 7622: table.LC_innerpickbox tr td {
 7623:   vertical-align: top;
 7624: }
 7625: 
 7626: table.LC_data_table tr.LC_info_row > td {
 7627:   background-color: #CCCCCC;
 7628:   font-weight: bold;
 7629:   text-align: left;
 7630: }
 7631: 
 7632: table.LC_data_table tr.LC_odd_row > td {
 7633:   background-color: $data_table_light;
 7634:   padding: 2px;
 7635:   vertical-align: top;
 7636: }
 7637: 
 7638: table.LC_pick_box tr > td.LC_odd_row {
 7639:   background-color: $data_table_light;
 7640:   vertical-align: top;
 7641: }
 7642: 
 7643: table.LC_data_table tr.LC_even_row > td {
 7644:   background-color: $data_table_dark;
 7645:   padding: 2px;
 7646:   vertical-align: top;
 7647: }
 7648: 
 7649: table.LC_pick_box tr > td.LC_even_row {
 7650:   background-color: $data_table_dark;
 7651:   vertical-align: top;
 7652: }
 7653: 
 7654: table.LC_data_table tr.LC_data_table_highlight td {
 7655:   background-color: $data_table_darker;
 7656: }
 7657: 
 7658: table.LC_data_table tr td.LC_leftcol_header {
 7659:   background-color: $data_table_head;
 7660:   font-weight: bold;
 7661: }
 7662: 
 7663: table.LC_data_table tr.LC_empty_row td,
 7664: table.LC_nested tr.LC_empty_row td {
 7665:   font-weight: bold;
 7666:   font-style: italic;
 7667:   text-align: center;
 7668:   padding: 8px;
 7669: }
 7670: 
 7671: table.LC_data_table tr.LC_empty_row td,
 7672: table.LC_data_table tr.LC_footer_row td {
 7673:   background-color: $sidebg;
 7674: }
 7675: 
 7676: table.LC_nested tr.LC_empty_row td {
 7677:   background-color: #FFFFFF;
 7678: }
 7679: 
 7680: table.LC_caption {
 7681: }
 7682: 
 7683: table.LC_nested tr.LC_empty_row td {
 7684:   padding: 4ex
 7685: }
 7686: 
 7687: table.LC_nested_outer tr th {
 7688:   font-weight: bold;
 7689:   color:$fontmenu;
 7690:   background-color: $data_table_head;
 7691:   font-size: small;
 7692:   border-bottom: 1px solid #000000;
 7693: }
 7694: 
 7695: table.LC_nested_outer tr td.LC_subheader {
 7696:   background-color: $data_table_head;
 7697:   font-weight: bold;
 7698:   font-size: small;
 7699:   border-bottom: 1px solid #000000;
 7700:   text-align: right;
 7701: }
 7702: 
 7703: table.LC_nested tr.LC_info_row td {
 7704:   background-color: #CCCCCC;
 7705:   font-weight: bold;
 7706:   font-size: small;
 7707:   text-align: center;
 7708: }
 7709: 
 7710: table.LC_nested tr.LC_info_row td.LC_left_item,
 7711: table.LC_nested_outer tr th.LC_left_item {
 7712:   text-align: left;
 7713: }
 7714: 
 7715: table.LC_nested td {
 7716:   background-color: #FFFFFF;
 7717:   font-size: small;
 7718: }
 7719: 
 7720: table.LC_nested_outer tr th.LC_right_item,
 7721: table.LC_nested tr.LC_info_row td.LC_right_item,
 7722: table.LC_nested tr.LC_odd_row td.LC_right_item,
 7723: table.LC_nested tr td.LC_right_item {
 7724:   text-align: right;
 7725: }
 7726: 
 7727: table.LC_nested tr.LC_odd_row td {
 7728:   background-color: #EEEEEE;
 7729: }
 7730: 
 7731: table.LC_createuser {
 7732: }
 7733: 
 7734: table.LC_createuser tr.LC_section_row td {
 7735:   font-size: small;
 7736: }
 7737: 
 7738: table.LC_createuser tr.LC_info_row td  {
 7739:   background-color: #CCCCCC;
 7740:   font-weight: bold;
 7741:   text-align: center;
 7742: }
 7743: 
 7744: table.LC_calendar {
 7745:   border: 1px solid #000000;
 7746:   border-collapse: collapse;
 7747:   width: 98%;
 7748: }
 7749: 
 7750: table.LC_calendar_pickdate {
 7751:   font-size: xx-small;
 7752: }
 7753: 
 7754: table.LC_calendar tr td {
 7755:   border: 1px solid #000000;
 7756:   vertical-align: top;
 7757:   width: 14%;
 7758: }
 7759: 
 7760: table.LC_calendar tr td.LC_calendar_day_empty {
 7761:   background-color: $data_table_dark;
 7762: }
 7763: 
 7764: table.LC_calendar tr td.LC_calendar_day_current {
 7765:   background-color: $data_table_highlight;
 7766: }
 7767: 
 7768: table.LC_data_table tr td.LC_mail_new {
 7769:   background-color: $mail_new;
 7770: }
 7771: 
 7772: table.LC_data_table tr.LC_mail_new:hover {
 7773:   background-color: $mail_new_hover;
 7774: }
 7775: 
 7776: table.LC_data_table tr td.LC_mail_read {
 7777:   background-color: $mail_read;
 7778: }
 7779: 
 7780: /*
 7781: table.LC_data_table tr.LC_mail_read:hover {
 7782:   background-color: $mail_read_hover;
 7783: }
 7784: */
 7785: 
 7786: table.LC_data_table tr td.LC_mail_replied {
 7787:   background-color: $mail_replied;
 7788: }
 7789: 
 7790: /*
 7791: table.LC_data_table tr.LC_mail_replied:hover {
 7792:   background-color: $mail_replied_hover;
 7793: }
 7794: */
 7795: 
 7796: table.LC_data_table tr td.LC_mail_other {
 7797:   background-color: $mail_other;
 7798: }
 7799: 
 7800: /*
 7801: table.LC_data_table tr.LC_mail_other:hover {
 7802:   background-color: $mail_other_hover;
 7803: }
 7804: */
 7805: 
 7806: table.LC_data_table tr > td.LC_browser_file,
 7807: table.LC_data_table tr > td.LC_browser_file_published {
 7808:   background: #AAEE77;
 7809: }
 7810: 
 7811: table.LC_data_table tr > td.LC_browser_file_locked,
 7812: table.LC_data_table tr > td.LC_browser_file_unpublished {
 7813:   background: #FFAA99;
 7814: }
 7815: 
 7816: table.LC_data_table tr > td.LC_browser_file_obsolete {
 7817:   background: #888888;
 7818: }
 7819: 
 7820: table.LC_data_table tr > td.LC_browser_file_modified,
 7821: table.LC_data_table tr > td.LC_browser_file_metamodified {
 7822:   background: #F8F866;
 7823: }
 7824: 
 7825: table.LC_data_table tr.LC_browser_folder > td {
 7826:   background: #E0E8FF;
 7827: }
 7828: 
 7829: table.LC_data_table tr > td.LC_roles_is {
 7830:   /* background: #77FF77; */
 7831: }
 7832: 
 7833: table.LC_data_table tr > td.LC_roles_future {
 7834:   border-right: 8px solid #FFFF77;
 7835: }
 7836: 
 7837: table.LC_data_table tr > td.LC_roles_will {
 7838:   border-right: 8px solid #FFAA77;
 7839: }
 7840: 
 7841: table.LC_data_table tr > td.LC_roles_expired {
 7842:   border-right: 8px solid #FF7777;
 7843: }
 7844: 
 7845: table.LC_data_table tr > td.LC_roles_will_not {
 7846:   border-right: 8px solid #AAFF77;
 7847: }
 7848: 
 7849: table.LC_data_table tr > td.LC_roles_selected {
 7850:   border-right: 8px solid #11CC55;
 7851: }
 7852: 
 7853: span.LC_current_location {
 7854:   font-size:larger;
 7855:   background: $pgbg;
 7856: }
 7857: 
 7858: span.LC_current_nav_location {
 7859:   font-weight:bold;
 7860:   background: $sidebg;
 7861: }
 7862: 
 7863: span.LC_parm_menu_item {
 7864:   font-size: larger;
 7865: }
 7866: 
 7867: span.LC_parm_scope_all {
 7868:   color: red;
 7869: }
 7870: 
 7871: span.LC_parm_scope_folder {
 7872:   color: green;
 7873: }
 7874: 
 7875: span.LC_parm_scope_resource {
 7876:   color: orange;
 7877: }
 7878: 
 7879: span.LC_parm_part {
 7880:   color: blue;
 7881: }
 7882: 
 7883: span.LC_parm_folder,
 7884: span.LC_parm_symb {
 7885:   font-size: x-small;
 7886:   font-family: $mono;
 7887:   color: #AAAAAA;
 7888: }
 7889: 
 7890: ul.LC_parm_parmlist li {
 7891:   display: inline-block;
 7892:   padding: 0.3em 0.8em;
 7893:   vertical-align: top;
 7894:   width: 150px;
 7895:   border-top:1px solid $lg_border_color;
 7896: }
 7897: 
 7898: td.LC_parm_overview_level_menu,
 7899: td.LC_parm_overview_map_menu,
 7900: td.LC_parm_overview_parm_selectors,
 7901: td.LC_parm_overview_restrictions  {
 7902:   border: 1px solid black;
 7903:   border-collapse: collapse;
 7904: }
 7905: 
 7906: span.LC_parm_recursive,
 7907: td.LC_parm_recursive {
 7908:   font-weight: bold;
 7909:   font-size: smaller;
 7910: }
 7911: 
 7912: table.LC_parm_overview_restrictions td {
 7913:   border-width: 1px 4px 1px 4px;
 7914:   border-style: solid;
 7915:   border-color: $pgbg;
 7916:   text-align: center;
 7917: }
 7918: 
 7919: table.LC_parm_overview_restrictions th {
 7920:   background: $tabbg;
 7921:   border-width: 1px 4px 1px 4px;
 7922:   border-style: solid;
 7923:   border-color: $pgbg;
 7924: }
 7925: 
 7926: table#LC_helpmenu {
 7927:   border: none;
 7928:   height: 55px;
 7929:   border-spacing: 0;
 7930: }
 7931: 
 7932: table#LC_helpmenu fieldset legend {
 7933:   font-size: larger;
 7934: }
 7935: 
 7936: table#LC_helpmenu_links {
 7937:   width: 100%;
 7938:   border: 1px solid black;
 7939:   background: $pgbg;
 7940:   padding: 0;
 7941:   border-spacing: 1px;
 7942: }
 7943: 
 7944: table#LC_helpmenu_links tr td {
 7945:   padding: 1px;
 7946:   background: $tabbg;
 7947:   text-align: center;
 7948:   font-weight: bold;
 7949: }
 7950: 
 7951: table#LC_helpmenu_links a:link,
 7952: table#LC_helpmenu_links a:visited,
 7953: table#LC_helpmenu_links a:active {
 7954:   text-decoration: none;
 7955:   color: $font;
 7956: }
 7957: 
 7958: table#LC_helpmenu_links a:hover {
 7959:   text-decoration: underline;
 7960:   color: $vlink;
 7961: }
 7962: 
 7963: .LC_chrt_popup_exists {
 7964:   border: 1px solid #339933;
 7965:   margin: -1px;
 7966: }
 7967: 
 7968: .LC_chrt_popup_up {
 7969:   border: 1px solid yellow;
 7970:   margin: -1px;
 7971: }
 7972: 
 7973: .LC_chrt_popup {
 7974:   border: 1px solid #8888FF;
 7975:   background: #CCCCFF;
 7976: }
 7977: 
 7978: table.LC_pick_box {
 7979:   border-collapse: separate;
 7980:   background: white;
 7981:   border: 1px solid black;
 7982:   border-spacing: 1px;
 7983: }
 7984: 
 7985: table.LC_pick_box td.LC_pick_box_title {
 7986:   background: $sidebg;
 7987:   font-weight: bold;
 7988:   text-align: left;
 7989:   vertical-align: top;
 7990:   width: 184px;
 7991:   padding: 8px;
 7992: }
 7993: 
 7994: table.LC_pick_box td.LC_pick_box_value {
 7995:   text-align: left;
 7996:   padding: 8px;
 7997: }
 7998: 
 7999: table.LC_pick_box td.LC_pick_box_select {
 8000:   text-align: left;
 8001:   padding: 8px;
 8002: }
 8003: 
 8004: table.LC_pick_box td.LC_pick_box_separator {
 8005:   padding: 0;
 8006:   height: 1px;
 8007:   background: black;
 8008: }
 8009: 
 8010: table.LC_pick_box td.LC_pick_box_submit {
 8011:   text-align: right;
 8012: }
 8013: 
 8014: table.LC_pick_box td.LC_evenrow_value {
 8015:   text-align: left;
 8016:   padding: 8px;
 8017:   background-color: $data_table_light;
 8018: }
 8019: 
 8020: table.LC_pick_box td.LC_oddrow_value {
 8021:   text-align: left;
 8022:   padding: 8px;
 8023:   background-color: $data_table_light;
 8024: }
 8025: 
 8026: span.LC_helpform_receipt_cat {
 8027:   font-weight: bold;
 8028: }
 8029: 
 8030: table.LC_group_priv_box {
 8031:   background: white;
 8032:   border: 1px solid black;
 8033:   border-spacing: 1px;
 8034: }
 8035: 
 8036: table.LC_group_priv_box td.LC_pick_box_title {
 8037:   background: $tabbg;
 8038:   font-weight: bold;
 8039:   text-align: right;
 8040:   width: 184px;
 8041: }
 8042: 
 8043: table.LC_group_priv_box td.LC_groups_fixed {
 8044:   background: $data_table_light;
 8045:   text-align: center;
 8046: }
 8047: 
 8048: table.LC_group_priv_box td.LC_groups_optional {
 8049:   background: $data_table_dark;
 8050:   text-align: center;
 8051: }
 8052: 
 8053: table.LC_group_priv_box td.LC_groups_functionality {
 8054:   background: $data_table_darker;
 8055:   text-align: center;
 8056:   font-weight: bold;
 8057: }
 8058: 
 8059: table.LC_group_priv td {
 8060:   text-align: left;
 8061:   padding: 0;
 8062: }
 8063: 
 8064: .LC_navbuttons {
 8065:   margin: 2ex 0ex 2ex 0ex;
 8066: }
 8067: 
 8068: .LC_topic_bar {
 8069:   font-weight: bold;
 8070:   background: $tabbg;
 8071:   margin: 1em 0em 1em 2em;
 8072:   padding: 3px;
 8073:   font-size: 1.2em;
 8074: }
 8075: 
 8076: .LC_topic_bar span {
 8077:   left: 0.5em;
 8078:   position: absolute;
 8079:   vertical-align: middle;
 8080:   font-size: 1.2em;
 8081: }
 8082: 
 8083: table.LC_course_group_status {
 8084:   margin: 20px;
 8085: }
 8086: 
 8087: table.LC_status_selector td {
 8088:   vertical-align: top;
 8089:   text-align: center;
 8090:   padding: 4px;
 8091: }
 8092: 
 8093: div.LC_feedback_link {
 8094:   clear: both;
 8095:   background: $sidebg;
 8096:   width: 100%;
 8097:   padding-bottom: 10px;
 8098:   border: 1px $tabbg solid;
 8099:   height: 22px;
 8100:   line-height: 22px;
 8101:   padding-top: 5px;
 8102: }
 8103: 
 8104: div.LC_feedback_link img {
 8105:   height: 22px;
 8106:   vertical-align:middle;
 8107: }
 8108: 
 8109: div.LC_feedback_link a {
 8110:   text-decoration: none;
 8111: }
 8112: 
 8113: div.LC_comblock {
 8114:   display:inline;
 8115:   color:$font;
 8116:   font-size:90%;
 8117: }
 8118: 
 8119: div.LC_feedback_link div.LC_comblock {
 8120:   padding-left:5px;
 8121: }
 8122: 
 8123: div.LC_feedback_link div.LC_comblock a {
 8124:   color:$font;
 8125: }
 8126: 
 8127: span.LC_feedback_link {
 8128:   /* background: $feedback_link_bg; */
 8129:   font-size: larger;
 8130: }
 8131: 
 8132: span.LC_message_link {
 8133:   /* background: $feedback_link_bg; */
 8134:   font-size: larger;
 8135:   position: absolute;
 8136:   right: 1em;
 8137: }
 8138: 
 8139: table.LC_prior_tries {
 8140:   border: 1px solid #000000;
 8141:   border-collapse: separate;
 8142:   border-spacing: 1px;
 8143: }
 8144: 
 8145: table.LC_prior_tries td {
 8146:   padding: 2px;
 8147: }
 8148: 
 8149: .LC_answer_correct {
 8150:   background: lightgreen;
 8151:   color: darkgreen;
 8152:   padding: 6px;
 8153: }
 8154: 
 8155: .LC_answer_charged_try {
 8156:   background: #FFAAAA;
 8157:   color: darkred;
 8158:   padding: 6px;
 8159: }
 8160: 
 8161: .LC_answer_not_charged_try,
 8162: .LC_answer_no_grade,
 8163: .LC_answer_late {
 8164:   background: lightyellow;
 8165:   color: black;
 8166:   padding: 6px;
 8167: }
 8168: 
 8169: .LC_answer_previous {
 8170:   background: lightblue;
 8171:   color: darkblue;
 8172:   padding: 6px;
 8173: }
 8174: 
 8175: .LC_answer_no_message {
 8176:   background: #FFFFFF;
 8177:   color: black;
 8178:   padding: 6px;
 8179: }
 8180: 
 8181: .LC_answer_unknown,
 8182: .LC_answer_warning {
 8183:   background: orange;
 8184:   color: black;
 8185:   padding: 6px;
 8186: }
 8187: 
 8188: span.LC_prior_numerical,
 8189: span.LC_prior_string,
 8190: span.LC_prior_custom,
 8191: span.LC_prior_reaction,
 8192: span.LC_prior_math {
 8193:   font-family: $mono;
 8194:   white-space: pre;
 8195: }
 8196: 
 8197: span.LC_prior_string {
 8198:   font-family: $mono;
 8199:   white-space: pre;
 8200: }
 8201: 
 8202: table.LC_prior_option {
 8203:   width: 100%;
 8204:   border-collapse: collapse;
 8205: }
 8206: 
 8207: table.LC_prior_rank,
 8208: table.LC_prior_match {
 8209:   border-collapse: collapse;
 8210: }
 8211: 
 8212: table.LC_prior_option tr td,
 8213: table.LC_prior_rank tr td,
 8214: table.LC_prior_match tr td {
 8215:   border: 1px solid #000000;
 8216: }
 8217: 
 8218: .LC_nobreak {
 8219:   white-space: nowrap;
 8220: }
 8221: 
 8222: span.LC_cusr_emph {
 8223:   font-style: italic;
 8224: }
 8225: 
 8226: span.LC_cusr_subheading {
 8227:   font-weight: normal;
 8228:   font-size: 85%;
 8229: }
 8230: 
 8231: div.LC_docs_entry_move {
 8232:   border: 1px solid #BBBBBB;
 8233:   background: #DDDDDD;
 8234:   width: 22px;
 8235:   padding: 1px;
 8236:   margin: 0;
 8237: }
 8238: 
 8239: table.LC_data_table tr > td.LC_docs_entry_commands,
 8240: table.LC_data_table tr > td.LC_docs_entry_parameter {
 8241:   font-size: x-small;
 8242: }
 8243: 
 8244: .LC_docs_entry_parameter {
 8245:   white-space: nowrap;
 8246: }
 8247: 
 8248: .LC_docs_copy {
 8249:   color: #000099;
 8250: }
 8251: 
 8252: .LC_docs_cut {
 8253:   color: #550044;
 8254: }
 8255: 
 8256: .LC_docs_rename {
 8257:   color: #009900;
 8258: }
 8259: 
 8260: .LC_docs_remove {
 8261:   color: #990000;
 8262: }
 8263: 
 8264: .LC_docs_alias {
 8265:   color: #440055;  
 8266: }
 8267: 
 8268: .LC_domprefs_email,
 8269: .LC_docs_alias_name,
 8270: .LC_docs_reinit_warn,
 8271: .LC_docs_ext_edit {
 8272:   font-size: x-small;
 8273: }
 8274: 
 8275: table.LC_docs_adddocs td,
 8276: table.LC_docs_adddocs th {
 8277:   border: 1px solid #BBBBBB;
 8278:   padding: 4px;
 8279:   background: #DDDDDD;
 8280: }
 8281: 
 8282: table.LC_sty_begin {
 8283:   background: #BBFFBB;
 8284: }
 8285: 
 8286: table.LC_sty_end {
 8287:   background: #FFBBBB;
 8288: }
 8289: 
 8290: table.LC_double_column {
 8291:   border-width: 0;
 8292:   border-collapse: collapse;
 8293:   width: 100%;
 8294:   padding: 2px;
 8295: }
 8296: 
 8297: table.LC_double_column tr td.LC_left_col {
 8298:   top: 2px;
 8299:   left: 2px;
 8300:   width: 47%;
 8301:   vertical-align: top;
 8302: }
 8303: 
 8304: table.LC_double_column tr td.LC_right_col {
 8305:   top: 2px;
 8306:   right: 2px;
 8307:   width: 47%;
 8308:   vertical-align: top;
 8309: }
 8310: 
 8311: div.LC_left_float {
 8312:   float: left;
 8313:   padding-right: 5%;
 8314:   padding-bottom: 4px;
 8315: }
 8316: 
 8317: div.LC_clear_float_header {
 8318:   padding-bottom: 2px;
 8319: }
 8320: 
 8321: div.LC_clear_float_footer {
 8322:   padding-top: 10px;
 8323:   clear: both;
 8324: }
 8325: 
 8326: div.LC_grade_show_user {
 8327: /*  border-left: 5px solid $sidebg; */
 8328:   border-top: 5px solid #000000;
 8329:   margin: 50px 0 0 0;
 8330:   padding: 15px 0 5px 10px;
 8331: }
 8332: 
 8333: div.LC_grade_show_user_odd_row {
 8334: /*  border-left: 5px solid #000000; */
 8335: }
 8336: 
 8337: div.LC_grade_show_user div.LC_Box {
 8338:   margin-right: 50px;
 8339: }
 8340: 
 8341: div.LC_grade_submissions,
 8342: div.LC_grade_message_center,
 8343: div.LC_grade_info_links {
 8344:   margin: 5px;
 8345:   width: 99%;
 8346:   background: #FFFFFF;
 8347: }
 8348: 
 8349: div.LC_grade_submissions_header,
 8350: div.LC_grade_message_center_header {
 8351:   font-weight: bold;
 8352:   font-size: large;
 8353: }
 8354: 
 8355: div.LC_grade_submissions_body,
 8356: div.LC_grade_message_center_body {
 8357:   border: 1px solid black;
 8358:   width: 99%;
 8359:   background: #FFFFFF;
 8360: }
 8361: 
 8362: table.LC_scantron_action {
 8363:   width: 100%;
 8364: }
 8365: 
 8366: table.LC_scantron_action tr th {
 8367:   font-weight:bold;
 8368:   font-style:normal;
 8369: }
 8370: 
 8371: .LC_edit_problem_header,
 8372: div.LC_edit_problem_footer {
 8373:   font-weight: normal;
 8374:   font-size:  medium;
 8375:   margin: 2px;
 8376:   background-color: $sidebg;
 8377: }
 8378: 
 8379: div.LC_edit_problem_header,
 8380: div.LC_edit_problem_header div,
 8381: div.LC_edit_problem_footer,
 8382: div.LC_edit_problem_footer div,
 8383: div.LC_edit_problem_editxml_header,
 8384: div.LC_edit_problem_editxml_header div {
 8385:   z-index: 100;
 8386: }
 8387: 
 8388: div.LC_edit_problem_header_title {
 8389:   font-weight: bold;
 8390:   font-size: larger;
 8391:   background: $tabbg;
 8392:   padding: 3px;
 8393:   margin: 0 0 5px 0;
 8394: }
 8395: 
 8396: table.LC_edit_problem_header_title {
 8397:   width: 100%;
 8398:   background: $tabbg;
 8399: }
 8400: 
 8401: div.LC_edit_actionbar {
 8402:     background-color: $sidebg;
 8403:     margin: 0;
 8404:     padding: 0;
 8405:     line-height: 200%;
 8406: }
 8407: 
 8408: div.LC_edit_actionbar div{
 8409:     padding: 0;
 8410:     margin: 0;
 8411:     display: inline-block;
 8412: }
 8413: 
 8414: .LC_edit_opt {
 8415:   padding-left: 1em;
 8416:   white-space: nowrap;
 8417: }
 8418: 
 8419: .LC_edit_problem_latexhelper{
 8420:     text-align: right;
 8421: }
 8422: 
 8423: #LC_edit_problem_colorful div{
 8424:     margin-left: 40px;
 8425: }
 8426: 
 8427: #LC_edit_problem_codemirror div{
 8428:     margin-left: 0px;
 8429: }
 8430: 
 8431: img.stift {
 8432:   border-width: 0;
 8433:   vertical-align: middle;
 8434: }
 8435: 
 8436: table td.LC_mainmenu_col_fieldset {
 8437:   vertical-align: top;
 8438: }
 8439: 
 8440: div.LC_createcourse {
 8441:   margin: 10px 10px 10px 10px;
 8442: }
 8443: 
 8444: .LC_dccid {
 8445:   float: right;
 8446:   margin: 0.2em 0 0 0;
 8447:   padding: 0;
 8448:   font-size: 90%;
 8449:   display:none;
 8450: }
 8451: 
 8452: ol.LC_primary_menu a:hover,
 8453: ol#LC_MenuBreadcrumbs a:hover,
 8454: ol#LC_PathBreadcrumbs a:hover,
 8455: ul#LC_secondary_menu a:hover,
 8456: .LC_FormSectionClearButton input:hover
 8457: ul.LC_TabContent   li:hover a {
 8458:   color:$button_hover;
 8459:   text-decoration:none;
 8460: }
 8461: 
 8462: h1 {
 8463:   padding: 0;
 8464:   line-height:130%;
 8465: }
 8466: 
 8467: h2,
 8468: h3,
 8469: h4,
 8470: h5,
 8471: h6 {
 8472:   margin: 5px 0 5px 0;
 8473:   padding: 0;
 8474:   line-height:130%;
 8475: }
 8476: 
 8477: .LC_hcell {
 8478:   padding:3px 15px 3px 15px;
 8479:   margin: 0;
 8480:   background-color:$tabbg;
 8481:   color:$fontmenu;
 8482:   border-bottom:solid 1px $lg_border_color;
 8483: }
 8484: 
 8485: .LC_Box > .LC_hcell {
 8486:   margin: 0 -10px 10px -10px;
 8487: }
 8488: 
 8489: .LC_noBorder {
 8490:   border: 0;
 8491: }
 8492: 
 8493: .LC_FormSectionClearButton input {
 8494:   background-color:transparent;
 8495:   border: none;
 8496:   cursor:pointer;
 8497:   text-decoration:underline;
 8498: }
 8499: 
 8500: .LC_help_open_topic {
 8501:   color: #FFFFFF;
 8502:   background-color: #EEEEFF;
 8503:   margin: 1px;
 8504:   padding: 4px;
 8505:   border: 1px solid #000033;
 8506:   white-space: nowrap;
 8507:   /* vertical-align: middle; */
 8508: }
 8509: 
 8510: dl,
 8511: ul,
 8512: div,
 8513: fieldset {
 8514:   margin: 10px 10px 10px 0;
 8515:   /* overflow: hidden; */
 8516: }
 8517: 
 8518: fieldset#LC_selectuser {
 8519:     margin: 0;
 8520:     padding: 0;
 8521: }
 8522: 
 8523: article.geogebraweb div {
 8524:     margin: 0;
 8525: }
 8526: 
 8527: fieldset > legend {
 8528:   font-weight: bold;
 8529:   padding: 0 5px 0 5px;
 8530: }
 8531: 
 8532: #LC_nav_bar {
 8533:   float: left;
 8534:   background-color: $pgbg_or_bgcolor;
 8535:   margin: 0 0 2px 0;
 8536: }
 8537: 
 8538: #LC_realm {
 8539:   margin: 0.2em 0 0 0;
 8540:   padding: 0;
 8541:   font-weight: bold;
 8542:   text-align: center;
 8543:   background-color: $pgbg_or_bgcolor;
 8544: }
 8545: 
 8546: #LC_nav_bar em {
 8547:   font-weight: bold;
 8548:   font-style: normal;
 8549: }
 8550: 
 8551: ol.LC_primary_menu {
 8552:   margin: 0;
 8553:   padding: 0;
 8554: }
 8555: 
 8556: ol#LC_PathBreadcrumbs {
 8557:   margin: 0;
 8558: }
 8559: 
 8560: ol.LC_primary_menu li {
 8561:   color: RGB(80, 80, 80);
 8562:   vertical-align: middle;
 8563:   text-align: left;
 8564:   list-style: none;
 8565:   position: relative;
 8566:   float: left;
 8567:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
 8568:   line-height: 1.5em;
 8569: }
 8570: 
 8571: ol.LC_primary_menu li a,
 8572: ol.LC_primary_menu li p {
 8573:   display: block;
 8574:   margin: 0;
 8575:   padding: 0 5px 0 10px;
 8576:   text-decoration: none;
 8577: }
 8578: 
 8579: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
 8580:   display: inline-block;
 8581:   width: 95%;
 8582:   text-align: left;
 8583: }
 8584: 
 8585: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
 8586:   display: inline-block;	
 8587:   width: 5%;
 8588:   float: right;
 8589:   text-align: right;
 8590:   font-size: 70%;
 8591: }
 8592: 
 8593: ol.LC_primary_menu ul {
 8594:   display: none;
 8595:   width: 15em;
 8596:   background-color: $data_table_light;
 8597:   position: absolute;
 8598:   top: 100%;
 8599: }
 8600: 
 8601: ol.LC_primary_menu ul ul {
 8602:   left: 100%;
 8603:   top: 0;
 8604: }
 8605: 
 8606: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
 8607:   display: block;
 8608:   position: absolute;
 8609:   margin: 0;
 8610:   padding: 0;
 8611:   z-index: 2;
 8612: }
 8613: 
 8614: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 8615: /* First Submenu -> size should be smaller than the menu title of the whole menu */
 8616:   font-size: 90%;
 8617:   vertical-align: top;
 8618:   float: none;
 8619:   border-left: 1px solid black;
 8620:   border-right: 1px solid black;
 8621: /* A dark bottom border to visualize different menu options; 
 8622: overwritten in the create_submenu routine for the last border-bottom of the menu */
 8623:   border-bottom: 1px solid $data_table_dark; 
 8624: }
 8625: 
 8626: ol.LC_primary_menu li li p:hover {
 8627:   color:$button_hover;
 8628:   text-decoration:none;
 8629:   background-color:$data_table_dark;
 8630: }
 8631: 
 8632: ol.LC_primary_menu li li a:hover {
 8633:    color:$button_hover;
 8634:    background-color:$data_table_dark;
 8635: }
 8636: 
 8637: /* Font-size equal to the size of the predecessors*/
 8638: ol.LC_primary_menu li:hover li li {
 8639:   font-size: 100%;
 8640: }
 8641: 
 8642: ol.LC_primary_menu li img {
 8643:   vertical-align: bottom;
 8644:   height: 1.1em;
 8645:   margin: 0.2em 0 0 0;
 8646: }
 8647: 
 8648: ol.LC_primary_menu a {
 8649:   color: RGB(80, 80, 80);
 8650:   text-decoration: none;
 8651: }
 8652: 
 8653: ol.LC_primary_menu a.LC_new_message {
 8654:   font-weight:bold;
 8655:   color: darkred;
 8656: }
 8657: 
 8658: ol.LC_docs_parameters {
 8659:   margin-left: 0;
 8660:   padding: 0;
 8661:   list-style: none;
 8662: }
 8663: 
 8664: ol.LC_docs_parameters li {
 8665:   margin: 0;
 8666:   padding-right: 20px;
 8667:   display: inline;
 8668: }
 8669: 
 8670: ol.LC_docs_parameters li:before {
 8671:   content: "\\002022 \\0020";
 8672: }
 8673: 
 8674: li.LC_docs_parameters_title {
 8675:   font-weight: bold;
 8676: }
 8677: 
 8678: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 8679:   content: "";
 8680: }
 8681: 
 8682: ul#LC_secondary_menu {
 8683:   clear: right;
 8684:   color: $fontmenu;
 8685:   background: $tabbg;
 8686:   list-style: none;
 8687:   padding: 0;
 8688:   margin: 0;
 8689:   width: 100%;
 8690:   text-align: left;
 8691:   float: left;
 8692: }
 8693: 
 8694: ul#LC_secondary_menu li {
 8695:   font-weight: bold;
 8696:   line-height: 1.8em;
 8697:   border-right: 1px solid black;
 8698:   float: left;
 8699: }
 8700: 
 8701: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 8702:   background-color: $data_table_light;
 8703: }
 8704: 
 8705: ul#LC_secondary_menu li a {
 8706:   padding: 0 0.8em;
 8707: }
 8708: 
 8709: ul#LC_secondary_menu li ul {
 8710:   display: none;
 8711: }
 8712: 
 8713: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 8714:   display: block;
 8715:   position: absolute;
 8716:   margin: 0;
 8717:   padding: 0;
 8718:   list-style:none;
 8719:   float: none;
 8720:   background-color: $data_table_light;
 8721:   z-index: 2;
 8722:   margin-left: -1px;
 8723: }
 8724: 
 8725: ul#LC_secondary_menu li ul li {
 8726:   font-size: 90%;
 8727:   vertical-align: top;
 8728:   border-left: 1px solid black;
 8729:   border-right: 1px solid black;
 8730:   background-color: $data_table_light;
 8731:   list-style:none;
 8732:   float: none;
 8733: }
 8734: 
 8735: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 8736:   background-color: $data_table_dark;
 8737: }
 8738: 
 8739: ul.LC_TabContent {
 8740:   display:block;
 8741:   background: $sidebg;
 8742:   border-bottom: solid 1px $lg_border_color;
 8743:   list-style:none;
 8744:   margin: -1px -10px 0 -10px;
 8745:   padding: 0;
 8746: }
 8747: 
 8748: ul.LC_TabContent li,
 8749: ul.LC_TabContentBigger li {
 8750:   float:left;
 8751: }
 8752: 
 8753: ul#LC_secondary_menu li a {
 8754:   color: $fontmenu;
 8755:   text-decoration: none;
 8756: }
 8757: 
 8758: ul.LC_TabContent {
 8759:   min-height:20px;
 8760: }
 8761: 
 8762: ul.LC_TabContent li {
 8763:   vertical-align:middle;
 8764:   padding: 0 16px 0 10px;
 8765:   background-color:$tabbg;
 8766:   border-bottom:solid 1px $lg_border_color;
 8767:   border-left: solid 1px $font;
 8768: }
 8769: 
 8770: ul.LC_TabContent .right {
 8771:   float:right;
 8772: }
 8773: 
 8774: ul.LC_TabContent li a,
 8775: ul.LC_TabContent li {
 8776:   color:rgb(47,47,47);
 8777:   text-decoration:none;
 8778:   font-size:95%;
 8779:   font-weight:bold;
 8780:   min-height:20px;
 8781: }
 8782: 
 8783: ul.LC_TabContent li a:hover,
 8784: ul.LC_TabContent li a:focus {
 8785:   color: $button_hover;
 8786:   background:none;
 8787:   outline:none;
 8788: }
 8789: 
 8790: ul.LC_TabContent li:hover {
 8791:   color: $button_hover;
 8792:   cursor:pointer;
 8793: }
 8794: 
 8795: ul.LC_TabContent li.active {
 8796:   color: $font;
 8797:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 8798:   border-bottom:solid 1px #FFFFFF;
 8799:   cursor: default;
 8800: }
 8801: 
 8802: ul.LC_TabContent li.active a {
 8803:   color:$font;
 8804:   background:#FFFFFF;
 8805:   outline: none;
 8806: }
 8807: 
 8808: ul.LC_TabContent li.goback {
 8809:   float: left;
 8810:   border-left: none;
 8811: }
 8812: 
 8813: #maincoursedoc {
 8814:   clear:both;
 8815: }
 8816: 
 8817: ul.LC_TabContentBigger {
 8818:   display:block;
 8819:   list-style:none;
 8820:   padding: 0;
 8821: }
 8822: 
 8823: ul.LC_TabContentBigger li {
 8824:   vertical-align:bottom;
 8825:   height: 30px;
 8826:   font-size:110%;
 8827:   font-weight:bold;
 8828:   color: #737373;
 8829: }
 8830: 
 8831: ul.LC_TabContentBigger li.active {
 8832:   position: relative;
 8833:   top: 1px;
 8834: }
 8835: 
 8836: ul.LC_TabContentBigger li a {
 8837:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 8838:   height: 30px;
 8839:   line-height: 30px;
 8840:   text-align: center;
 8841:   display: block;
 8842:   text-decoration: none;
 8843:   outline: none;  
 8844: }
 8845: 
 8846: ul.LC_TabContentBigger li.active a {
 8847:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 8848:   color:$font;
 8849: }
 8850: 
 8851: ul.LC_TabContentBigger li b {
 8852:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 8853:   display: block;
 8854:   float: left;
 8855:   padding: 0 30px;
 8856:   border-bottom: 1px solid $lg_border_color;
 8857: }
 8858: 
 8859: ul.LC_TabContentBigger li:hover b {
 8860:   color:$button_hover;
 8861: }
 8862: 
 8863: ul.LC_TabContentBigger li.active b {
 8864:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 8865:   color:$font;
 8866:   border: 0;
 8867: }
 8868: 
 8869: 
 8870: ul.LC_CourseBreadcrumbs {
 8871:   background: $sidebg;
 8872:   height: 2em;
 8873:   padding-left: 10px;
 8874:   margin: 0;
 8875:   list-style-position: inside;
 8876: }
 8877: 
 8878: ol#LC_MenuBreadcrumbs,
 8879: ol#LC_PathBreadcrumbs {
 8880:   padding-left: 10px;
 8881:   margin: 0;
 8882:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 8883: }
 8884: 
 8885: ol#LC_MenuBreadcrumbs li,
 8886: ol#LC_PathBreadcrumbs li,
 8887: ul.LC_CourseBreadcrumbs li {
 8888:   display: inline;
 8889:   white-space: normal;  
 8890: }
 8891: 
 8892: ol#LC_MenuBreadcrumbs li a,
 8893: ul.LC_CourseBreadcrumbs li a {
 8894:   text-decoration: none;
 8895:   font-size:90%;
 8896: }
 8897: 
 8898: ol#LC_MenuBreadcrumbs h1 {
 8899:   display: inline;
 8900:   font-size: 90%;
 8901:   line-height: 2.5em;
 8902:   margin: 0;
 8903:   padding: 0;
 8904: }
 8905: 
 8906: ol#LC_PathBreadcrumbs li a {
 8907:   text-decoration:none;
 8908:   font-size:100%;
 8909:   font-weight:bold;
 8910: }
 8911: 
 8912: .LC_Box {
 8913:   border: solid 1px $lg_border_color;
 8914:   padding: 0 10px 10px 10px;
 8915: }
 8916: 
 8917: .LC_DocsBox {
 8918:   border: solid 1px $lg_border_color;
 8919:   padding: 0 0 10px 10px;
 8920: }
 8921: 
 8922: .LC_AboutMe_Image {
 8923:   float:left;
 8924:   margin-right:10px;
 8925: }
 8926: 
 8927: .LC_Clear_AboutMe_Image {
 8928:   clear:left;
 8929: }
 8930: 
 8931: dl.LC_ListStyleClean dt {
 8932:   padding-right: 5px;
 8933:   display: table-header-group;
 8934: }
 8935: 
 8936: dl.LC_ListStyleClean dd {
 8937:   display: table-row;
 8938: }
 8939: 
 8940: .LC_ListStyleClean,
 8941: .LC_ListStyleSimple,
 8942: .LC_ListStyleNormal,
 8943: .LC_ListStyleSpecial {
 8944:   /* display:block; */
 8945:   list-style-position: inside;
 8946:   list-style-type: none;
 8947:   overflow: hidden;
 8948:   padding: 0;
 8949: }
 8950: 
 8951: .LC_ListStyleSimple li,
 8952: .LC_ListStyleSimple dd,
 8953: .LC_ListStyleNormal li,
 8954: .LC_ListStyleNormal dd,
 8955: .LC_ListStyleSpecial li,
 8956: .LC_ListStyleSpecial dd {
 8957:   margin: 0;
 8958:   padding: 5px 5px 5px 10px;
 8959:   clear: both;
 8960: }
 8961: 
 8962: .LC_ListStyleClean li,
 8963: .LC_ListStyleClean dd {
 8964:   padding-top: 0;
 8965:   padding-bottom: 0;
 8966: }
 8967: 
 8968: .LC_ListStyleSimple dd,
 8969: .LC_ListStyleSimple li {
 8970:   border-bottom: solid 1px $lg_border_color;
 8971: }
 8972: 
 8973: .LC_ListStyleSpecial li,
 8974: .LC_ListStyleSpecial dd {
 8975:   list-style-type: none;
 8976:   background-color: RGB(220, 220, 220);
 8977:   margin-bottom: 4px;
 8978: }
 8979: 
 8980: table.LC_SimpleTable {
 8981:   margin:5px;
 8982:   border:solid 1px $lg_border_color;
 8983: }
 8984: 
 8985: table.LC_SimpleTable tr {
 8986:   padding: 0;
 8987:   border:solid 1px $lg_border_color;
 8988: }
 8989: 
 8990: table.LC_SimpleTable thead {
 8991:   background:rgb(220,220,220);
 8992: }
 8993: 
 8994: div.LC_columnSection {
 8995:   display: block;
 8996:   clear: both;
 8997:   overflow: hidden;
 8998:   margin: 0;
 8999: }
 9000: 
 9001: div.LC_columnSection>* {
 9002:   float: left;
 9003:   margin: 10px 20px 10px 0;
 9004:   overflow:hidden;
 9005: }
 9006: 
 9007: table em {
 9008:   font-weight: bold;
 9009:   font-style: normal;
 9010: }
 9011: 
 9012: table.LC_tableBrowseRes,
 9013: table.LC_tableOfContent {
 9014:   border:none;
 9015:   border-spacing: 1px;
 9016:   padding: 3px;
 9017:   background-color: #FFFFFF;
 9018:   font-size: 90%;
 9019: }
 9020: 
 9021: table.LC_tableOfContent {
 9022:   border-collapse: collapse;
 9023: }
 9024: 
 9025: table.LC_tableBrowseRes a,
 9026: table.LC_tableOfContent a {
 9027:   background-color: transparent;
 9028:   text-decoration: none;
 9029: }
 9030: 
 9031: table.LC_tableOfContent img {
 9032:   border: none;
 9033:   height: 1.3em;
 9034:   vertical-align: text-bottom;
 9035:   margin-right: 0.3em;
 9036: }
 9037: 
 9038: a#LC_content_toolbar_firsthomework {
 9039:   background-image:url(/res/adm/pages/open-first-problem.gif);
 9040: }
 9041: 
 9042: a#LC_content_toolbar_everything {
 9043:   background-image:url(/res/adm/pages/show-all.gif);
 9044: }
 9045: 
 9046: a#LC_content_toolbar_uncompleted {
 9047:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 9048: }
 9049: 
 9050: #LC_content_toolbar_clearbubbles {
 9051:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 9052: }
 9053: 
 9054: a#LC_content_toolbar_changefolder {
 9055:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 9056: }
 9057: 
 9058: a#LC_content_toolbar_changefolder_toggled {
 9059:   background-image:url(/res/adm/pages/open-all-folders.gif);
 9060: }
 9061: 
 9062: a#LC_content_toolbar_edittoplevel {
 9063:   background-image:url(/res/adm/pages/edittoplevel.gif);
 9064: }
 9065: 
 9066: a#LC_content_toolbar_printout {
 9067:   background-image:url(/res/adm/pages/printout.gif);
 9068: }
 9069: 
 9070: ul#LC_toolbar li a:hover {
 9071:   background-position: bottom center;
 9072: }
 9073: 
 9074: ul#LC_toolbar {
 9075:   padding: 0;
 9076:   margin: 2px;
 9077:   list-style:none;
 9078:   position:relative;
 9079:   background-color:white;
 9080:   overflow: auto;
 9081: }
 9082: 
 9083: ul#LC_toolbar li {
 9084:   border:1px solid white;
 9085:   padding: 0;
 9086:   margin: 0;
 9087:   float: left;
 9088:   display:inline;
 9089:   vertical-align:middle;
 9090:   white-space: nowrap;
 9091: }
 9092: 
 9093: 
 9094: a.LC_toolbarItem {
 9095:   display:block;
 9096:   padding: 0;
 9097:   margin: 0;
 9098:   height: 32px;
 9099:   width: 32px;
 9100:   color:white;
 9101:   border: none;
 9102:   background-repeat:no-repeat;
 9103:   background-color:transparent;
 9104: }
 9105: 
 9106: ul.LC_funclist {
 9107:     margin: 0;
 9108:     padding: 0.5em 1em 0.5em 0;
 9109: }
 9110: 
 9111: ul.LC_funclist > li:first-child {
 9112:     font-weight:bold; 
 9113:     margin-left:0.8em;
 9114: }
 9115: 
 9116: ul.LC_funclist + ul.LC_funclist {
 9117:     /* 
 9118:        left border as a seperator if we have more than
 9119:        one list 
 9120:     */
 9121:     border-left: 1px solid $sidebg;
 9122:     /* 
 9123:        this hides the left border behind the border of the 
 9124:        outer box if element is wrapped to the next 'line' 
 9125:     */
 9126:     margin-left: -1px;
 9127: }
 9128: 
 9129: ul.LC_funclist li {
 9130:   display: inline;
 9131:   white-space: nowrap;
 9132:   margin: 0 0 0 25px;
 9133:   line-height: 150%;
 9134: }
 9135: 
 9136: .LC_hidden {
 9137:   display: none;
 9138: }
 9139: 
 9140: .LCmodal-overlay {
 9141: 		position:fixed;
 9142: 		top:0;
 9143: 		right:0;
 9144: 		bottom:0;
 9145: 		left:0;
 9146: 		height:100%;
 9147: 		width:100%;
 9148: 		margin:0;
 9149: 		padding:0;
 9150: 		background:#999;
 9151: 		opacity:.75;
 9152: 		filter: alpha(opacity=75);
 9153: 		-moz-opacity: 0.75;
 9154: 		z-index:101;
 9155: }
 9156: 
 9157: * html .LCmodal-overlay {   
 9158: 		position: absolute;
 9159: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 9160: }
 9161: 
 9162: .LCmodal-window {
 9163: 		position:fixed;
 9164: 		top:50%;
 9165: 		left:50%;
 9166: 		margin:0;
 9167: 		padding:0;
 9168: 		z-index:102;
 9169: 	}
 9170: 
 9171: * html .LCmodal-window {
 9172: 		position:absolute;
 9173: }
 9174: 
 9175: .LCclose-window {
 9176: 		position:absolute;
 9177: 		width:32px;
 9178: 		height:32px;
 9179: 		right:8px;
 9180: 		top:8px;
 9181: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 9182: 		text-indent:-99999px;
 9183: 		overflow:hidden;
 9184: 		cursor:pointer;
 9185: }
 9186: 
 9187: .LCisDisabled {
 9188:   cursor: not-allowed;
 9189:   opacity: 0.5;
 9190: }
 9191: 
 9192: a[aria-disabled="true"] {
 9193:   color: currentColor;
 9194:   display: inline-block;  /* For IE11/ MS Edge bug */
 9195:   pointer-events: none;
 9196:   text-decoration: none;
 9197: }
 9198: 
 9199: pre.LC_wordwrap {
 9200:   white-space: pre-wrap;
 9201:   white-space: -moz-pre-wrap;
 9202:   white-space: -pre-wrap;
 9203:   white-space: -o-pre-wrap;
 9204:   word-wrap: break-word;
 9205: }
 9206: 
 9207: /*
 9208:   styles used for response display
 9209: */
 9210: div.LC_radiofoil, div.LC_rankfoil {
 9211:   margin: .5em 0em .5em 0em;
 9212: }
 9213: table.LC_itemgroup {
 9214:   margin-top: 1em;
 9215: }
 9216: 
 9217: /*
 9218:   styles used by TTH when "Default set of options to pass to tth/m
 9219:   when converting TeX" in course settings has been set
 9220: 
 9221:   option passed: -t
 9222: 
 9223: */
 9224: 
 9225: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 9226: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 9227: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 9228: td div.norm {line-height:normal;}
 9229: 
 9230: /*
 9231:   option passed -y3
 9232: */
 9233: 
 9234: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 9235: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 9236: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 9237: 
 9238: /*
 9239:   sections with roles, for content only
 9240: */
 9241: section[class^="role-"] {
 9242:   padding-left: 10px;
 9243:   padding-right: 5px;
 9244:   margin-top: 8px;
 9245:   margin-bottom: 8px;
 9246:   border: 1px solid #2A4;
 9247:   border-radius: 5px;
 9248:   box-shadow: 0px 1px 1px #BBB;
 9249: }
 9250: section[class^="role-"]>h1 {
 9251:   position: relative;
 9252:   margin: 0px;
 9253:   padding-top: 10px;
 9254:   padding-left: 40px;
 9255: }
 9256: section[class^="role-"]>h1:before {
 9257:   position: absolute;
 9258:   left: -5px;
 9259:   top: 5px;
 9260: }
 9261: section.role-activity>h1:before {
 9262:   content:url('/adm/daxe/images/section_icons/activity.png');
 9263: }
 9264: section.role-advice>h1:before {
 9265:   content:url('/adm/daxe/images/section_icons/advice.png');
 9266: }
 9267: section.role-bibliography>h1:before {
 9268:   content:url('/adm/daxe/images/section_icons/bibliography.png');
 9269: }
 9270: section.role-citation>h1:before {
 9271:   content:url('/adm/daxe/images/section_icons/citation.png');
 9272: }
 9273: section.role-conclusion>h1:before {
 9274:   content:url('/adm/daxe/images/section_icons/conclusion.png');
 9275: }
 9276: section.role-definition>h1:before {
 9277:   content:url('/adm/daxe/images/section_icons/definition.png');
 9278: }
 9279: section.role-demonstration>h1:before {
 9280:   content:url('/adm/daxe/images/section_icons/demonstration.png');
 9281: }
 9282: section.role-example>h1:before {
 9283:   content:url('/adm/daxe/images/section_icons/example.png');
 9284: }
 9285: section.role-explanation>h1:before {
 9286:   content:url('/adm/daxe/images/section_icons/explanation.png');
 9287: }
 9288: section.role-introduction>h1:before {
 9289:   content:url('/adm/daxe/images/section_icons/introduction.png');
 9290: }
 9291: section.role-method>h1:before {
 9292:   content:url('/adm/daxe/images/section_icons/method.png');
 9293: }
 9294: section.role-more_information>h1:before {
 9295:   content:url('/adm/daxe/images/section_icons/more_information.png');
 9296: }
 9297: section.role-objectives>h1:before {
 9298:   content:url('/adm/daxe/images/section_icons/objectives.png');
 9299: }
 9300: section.role-prerequisites>h1:before {
 9301:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
 9302: }
 9303: section.role-remark>h1:before {
 9304:   content:url('/adm/daxe/images/section_icons/remark.png');
 9305: }
 9306: section.role-reminder>h1:before {
 9307:   content:url('/adm/daxe/images/section_icons/reminder.png');
 9308: }
 9309: section.role-summary>h1:before {
 9310:   content:url('/adm/daxe/images/section_icons/summary.png');
 9311: }
 9312: section.role-syntax>h1:before {
 9313:   content:url('/adm/daxe/images/section_icons/syntax.png');
 9314: }
 9315: section.role-warning>h1:before {
 9316:   content:url('/adm/daxe/images/section_icons/warning.png');
 9317: }
 9318: 
 9319: #LC_minitab_header {
 9320:   float:left;
 9321:   width:100%;
 9322:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
 9323:   font-size:93%;
 9324:   line-height:normal;
 9325:   margin: 0.5em 0 0.5em 0;
 9326: }
 9327: #LC_minitab_header ul {
 9328:   margin:0;
 9329:   padding:10px 10px 0;
 9330:   list-style:none;
 9331: }
 9332: #LC_minitab_header li {
 9333:   float:left;
 9334:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
 9335:   margin:0;
 9336:   padding:0 0 0 9px;
 9337: }
 9338: #LC_minitab_header a {
 9339:   display:block;
 9340:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
 9341:   padding:5px 15px 4px 6px;
 9342: }
 9343: #LC_minitab_header #LC_current_minitab {
 9344:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
 9345: }
 9346: #LC_minitab_header #LC_current_minitab a {
 9347:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
 9348:   padding-bottom:5px;
 9349: }
 9350: 
 9351: 
 9352: END
 9353: }
 9354: 
 9355: =pod
 9356: 
 9357: =item * &headtag()
 9358: 
 9359: Returns a uniform footer for LON-CAPA web pages.
 9360: 
 9361: Inputs: $title - optional title for the head
 9362:         $head_extra - optional extra HTML to put inside the <head>
 9363:         $args - optional arguments
 9364:             force_register - if is true call registerurl so the remote is 
 9365:                              informed
 9366:             redirect       -> array ref of
 9367:                                    1- seconds before redirect occurs
 9368:                                    2- url to redirect to
 9369:                                    3- whether the side effect should occur
 9370:                            (side effect of setting 
 9371:                                $env{'internal.head.redirect'} to the url 
 9372:                                redirected to)
 9373:                                    4- whether the redirect target should be
 9374:                                       the opener of the current (pop-up)
 9375:                                       window (side effect of setting
 9376:                                       $env{'internal.head.to_opener'} to
 9377:                                       1, if true.
 9378:                                    5- whether encrypt check should be skipped
 9379:             domain         -> force to color decorate a page for a specific
 9380:                                domain
 9381:             function       -> force usage of a specific rolish color scheme
 9382:             bgcolor        -> override the default page bgcolor
 9383:             no_auto_mt_title
 9384:                            -> prevent &mt()ing the title arg
 9385: 
 9386: =cut
 9387: 
 9388: sub headtag {
 9389:     my ($title,$head_extra,$args) = @_;
 9390:     
 9391:     my $function = $args->{'function'} || &get_users_function();
 9392:     my $domain   = $args->{'domain'}   || &determinedomain();
 9393:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 9394:     my $httphost = $args->{'use_absolute'};
 9395:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 9396: 		   $Apache::lonnet::perlvar{'lonVersion'},
 9397: 		   #time(),
 9398: 		   $env{'environment.color.timestamp'},
 9399: 		   $function,$domain,$bgcolor);
 9400: 
 9401:     $url = '/adm/css/'.&escape($url).'.css';
 9402: 
 9403:     my $result =
 9404: 	'<head>'.
 9405: 	&font_settings($args);
 9406: 
 9407:     my $inhibitprint;
 9408:     if ($args->{'print_suppress'}) {
 9409:         $inhibitprint = &print_suppression();
 9410:     }
 9411: 
 9412:     if (!$args->{'frameset'}) {
 9413: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 9414:     }
 9415:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
 9416:         $result .= Apache::lonxml::display_title();
 9417:     }
 9418:     if (!$args->{'no_nav_bar'} 
 9419: 	&& !$args->{'only_body'}
 9420: 	&& !$args->{'frameset'}) {
 9421: 	$result .= &help_menu_js($httphost);
 9422:         $result.=&modal_window();
 9423:         $result.=&togglebox_script();
 9424:         $result.=&wishlist_window();
 9425:         $result.=&LCprogressbarUpdate_script();
 9426:     } else {
 9427:         if ($args->{'add_modal'}) {
 9428:            $result.=&modal_window();
 9429:         }
 9430:         if ($args->{'add_wishlist'}) {
 9431:            $result.=&wishlist_window();
 9432:         }
 9433:         if ($args->{'add_togglebox'}) {
 9434:            $result.=&togglebox_script();
 9435:         }
 9436:         if ($args->{'add_progressbar'}) {
 9437:            $result.=&LCprogressbarUpdate_script();
 9438:         }
 9439:     }
 9440:     if (ref($args->{'redirect'})) {
 9441: 	my ($time,$url,$inhibit_continue,$to_opener,$skip_enc_check) = @{$args->{'redirect'}};
 9442:         if (!$skip_enc_check) {
 9443:             $url = &Apache::lonenc::check_encrypt($url);
 9444:         }
 9445: 	if (!$inhibit_continue) {
 9446: 	    $env{'internal.head.redirect'} = $url;
 9447: 	}
 9448: 	$result.=<<"ADDMETA";
 9449: <meta http-equiv="pragma" content="no-cache" />
 9450: ADDMETA
 9451:         if ($to_opener) {
 9452:             $env{'internal.head.to_opener'} = 1;
 9453:             my $dest = &js_escape($url);
 9454:             my $timeout = int($time * 1000);
 9455:             $result .=<<"ENDJS";
 9456: <script type="text/javascript">
 9457: // <![CDATA[
 9458: function LC_To_Opener() {
 9459:     var dest = '$dest';
 9460:     if (dest != '') {
 9461:         if (window.opener != null && !window.opener.closed) {
 9462:             window.opener.location.href=dest;
 9463:             window.close();
 9464:         } else {
 9465:             window.location.href=dest;
 9466:         }
 9467:     }
 9468: }
 9469: \$(document).ready(function () {
 9470:     setTimeout('LC_To_Opener()',$timeout);
 9471: });
 9472: // ]]>
 9473: </script>
 9474: ENDJS
 9475:         } else {
 9476:             $result.=<<"ADDMETA";
 9477: <meta http-equiv="Refresh" content="$time; url=$url" />
 9478: ADDMETA
 9479:         }
 9480:     } else {
 9481:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
 9482:             my $requrl = $env{'request.uri'};
 9483:             if ($requrl eq '') {
 9484:                 $requrl = $ENV{'REQUEST_URI'};
 9485:                 $requrl =~ s/\?.+$//;
 9486:             }
 9487:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
 9488:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
 9489:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
 9490:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
 9491:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
 9492:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
 9493:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 9494:                     my ($offload,$offloadoth);
 9495:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
 9496:                         if ($domdefs{'offloadnow'}{$lonhost}) {
 9497:                             $offload = 1;
 9498:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
 9499:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
 9500:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
 9501:                                     $offloadoth = 1;
 9502:                                     $dom_in_use = $env{'user.domain'};
 9503:                                 }
 9504:                             }
 9505:                         }
 9506:                     }
 9507:                     unless ($offload) {
 9508:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
 9509:                             if ($domdefs{'offloadoth'}{$lonhost}) {
 9510:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
 9511:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
 9512:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
 9513:                                         $offload = 1;
 9514:                                         $offloadoth = 1;
 9515:                                         $dom_in_use = $env{'user.domain'};
 9516:                                     }
 9517:                                 }
 9518:                             }
 9519:                         }
 9520:                     }
 9521:                     if ($offload) {
 9522:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
 9523:                         if (($newserver eq '') && ($offloadoth)) {
 9524:                             my @domains = &Apache::lonnet::current_machine_domains();
 9525:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) { 
 9526:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
 9527:                             }
 9528:                         }
 9529:                         if (($newserver) && ($newserver ne $lonhost)) {
 9530:                             my $numsec = 5;
 9531:                             my $timeout = $numsec * 1000;
 9532:                             my ($newurl,$locknum,%locks,$msg);
 9533:                             if ($env{'request.role.adv'}) {
 9534:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
 9535:                             }
 9536:                             my $disable_submit = 0;
 9537:                             if ($requrl =~ /$LONCAPA::assess_re/) {
 9538:                                 $disable_submit = 1;
 9539:                             }
 9540:                             if ($locknum) {
 9541:                                 my @lockinfo = sort(values(%locks));
 9542:                                 $msg = &mt('Once the following tasks are complete:')." \n".
 9543:                                        join(", ",sort(values(%locks)))."\n";
 9544:                                 if (&show_course()) {
 9545:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
 9546:                                 } else {
 9547:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
 9548:                                 }
 9549:                             } else {
 9550:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
 9551:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
 9552:                                 }
 9553:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
 9554:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
 9555:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
 9556:                                     $newurl .= '&role='.$env{'request.role'};
 9557:                                 }
 9558:                                 if ($env{'request.symb'}) {
 9559:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
 9560:                                     if ($shownsymb =~ m{^/enc/}) {
 9561:                                         my $reqdmajor = 2;
 9562:                                         my $reqdminor = 11;
 9563:                                         my $reqdsubminor = 3;
 9564:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
 9565:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
 9566:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
 9567:                                         if (($major eq '' && $minor eq '') ||
 9568:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
 9569:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
 9570:                                              ($reqdsubminor > $subminor))))) {
 9571:                                             undef($shownsymb);
 9572:                                         }
 9573:                                     }
 9574:                                     if ($shownsymb) {
 9575:                                         &js_escape(\$shownsymb);
 9576:                                         $newurl .= '&symb='.$shownsymb;
 9577:                                     }
 9578:                                 } else {
 9579:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
 9580:                                     &js_escape(\$shownurl);
 9581:                                     $newurl .= '&origurl='.$shownurl;
 9582:                                 }
 9583:                             }
 9584:                             &js_escape(\$msg);
 9585:                             $result.=<<OFFLOAD
 9586: <meta http-equiv="pragma" content="no-cache" />
 9587: <script type="text/javascript">
 9588: // <![CDATA[
 9589: function LC_Offload_Now() {
 9590:     var dest = "$newurl";
 9591:     if (dest != '') {
 9592:         window.location.href="$newurl";
 9593:     }
 9594: }
 9595: \$(document).ready(function () {
 9596:     window.alert('$msg');
 9597:     if ($disable_submit) {
 9598:         \$(".LC_hwk_submit").prop("disabled", true);
 9599:         \$( ".LC_textline" ).prop( "readonly", "readonly");
 9600:     }
 9601:     setTimeout('LC_Offload_Now()', $timeout);
 9602: });
 9603: // ]]>
 9604: </script>
 9605: OFFLOAD
 9606:                         }
 9607:                     }
 9608:                 }
 9609:             }
 9610:         }
 9611:     }
 9612:     if (!defined($title)) {
 9613: 	$title = 'The LearningOnline Network with CAPA';
 9614:     }
 9615:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 9616:     $result .= '<title> LON-CAPA '.$title.'</title>'
 9617: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
 9618:     if (!$args->{'frameset'}) {
 9619:         $result .= ' /';
 9620:     }
 9621:     $result .= '>' 
 9622:         .$inhibitprint
 9623: 	.$head_extra;
 9624:     my $clientmobile;
 9625:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 9626:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
 9627:     } else {
 9628:         $clientmobile = $env{'browser.mobile'};
 9629:     }
 9630:     if ($clientmobile) {
 9631:         $result .= '
 9632: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 9633: <meta name="apple-mobile-web-app-capable" content="yes" />';
 9634:     }
 9635:     $result .= '<meta name="google" content="notranslate" />'."\n";
 9636:     return $result.'</head>';
 9637: }
 9638: 
 9639: =pod
 9640: 
 9641: =item * &font_settings()
 9642: 
 9643: Returns neccessary <meta> to set the proper encoding
 9644: 
 9645: Inputs: optional reference to HASH -- $args passed to &headtag()
 9646: 
 9647: =cut
 9648: 
 9649: sub font_settings {
 9650:     my ($args) = @_;
 9651:     my $headerstring='';
 9652:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
 9653:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
 9654:         $headerstring.=
 9655:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
 9656:         if (!$args->{'frameset'}) {
 9657: 	    $headerstring.= ' /';
 9658:         }
 9659: 	$headerstring .= '>'."\n";
 9660:     }
 9661:     return $headerstring;
 9662: }
 9663: 
 9664: =pod
 9665: 
 9666: =item * &print_suppression()
 9667: 
 9668: In course context returns css which causes the body to be blank when media="print",
 9669: if printout generation is unavailable for the current resource.
 9670: 
 9671: This could be because:
 9672: 
 9673: (a) printstartdate is in the future
 9674: 
 9675: (b) printenddate is in the past
 9676: 
 9677: (c) there is an active exam block with "printout"
 9678: functionality blocked
 9679: 
 9680: Users with pav, pfo or evb privileges are exempt.
 9681: 
 9682: Inputs: none
 9683: 
 9684: =cut
 9685: 
 9686: 
 9687: sub print_suppression {
 9688:     my $noprint;
 9689:     if ($env{'request.course.id'}) {
 9690:         my $scope = $env{'request.course.id'};
 9691:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 9692:             (&Apache::lonnet::allowed('pfo',$scope))) {
 9693:             return;
 9694:         }
 9695:         if ($env{'request.course.sec'} ne '') {
 9696:             $scope .= "/$env{'request.course.sec'}";
 9697:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 9698:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 9699:                 return;
 9700:             }
 9701:         }
 9702:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9703:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9704:         my $clientip = &Apache::lonnet::get_requestor_ip();
 9705:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
 9706:         if ($blocked) {
 9707:             my $checkrole = "cm./$cdom/$cnum";
 9708:             if ($env{'request.course.sec'} ne '') {
 9709:                 $checkrole .= "/$env{'request.course.sec'}";
 9710:             }
 9711:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 9712:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 9713:                 $noprint = 1;
 9714:             }
 9715:         }
 9716:         unless ($noprint) {
 9717:             my $symb = &Apache::lonnet::symbread();
 9718:             if ($symb ne '') {
 9719:                 my $navmap = Apache::lonnavmaps::navmap->new();
 9720:                 if (ref($navmap)) {
 9721:                     my $res = $navmap->getBySymb($symb);
 9722:                     if (ref($res)) {
 9723:                         if (!$res->resprintable()) {
 9724:                             $noprint = 1;
 9725:                         }
 9726:                     }
 9727:                 }
 9728:             }
 9729:         }
 9730:         if ($noprint) {
 9731:             return <<"ENDSTYLE";
 9732: <style type="text/css" media="print">
 9733:     body { display:none }
 9734: </style>
 9735: ENDSTYLE
 9736:         }
 9737:     }
 9738:     return;
 9739: }
 9740: 
 9741: =pod
 9742: 
 9743: =item * &xml_begin()
 9744: 
 9745: Returns the needed doctype and <html>
 9746: 
 9747: Inputs: none
 9748: 
 9749: =cut
 9750: 
 9751: sub xml_begin {
 9752:     my ($is_frameset) = @_;
 9753:     my $output='';
 9754: 
 9755:     if ($env{'browser.mathml'}) {
 9756: 	$output='<?xml version="1.0"?>'
 9757:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 9758: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 9759:             
 9760: #	    .'<!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">] >'
 9761: 	    .'<!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">'
 9762:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 9763: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 9764:     } elsif ($is_frameset) {
 9765:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
 9766:                 '<html>'."\n";
 9767:     } else {
 9768: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
 9769:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
 9770:     }
 9771:     return $output;
 9772: }
 9773: 
 9774: =pod
 9775: 
 9776: =item * &start_page()
 9777: 
 9778: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 9779: 
 9780: Inputs:
 9781: 
 9782: =over 4
 9783: 
 9784: $title - optional title for the page
 9785: 
 9786: $head_extra - optional extra HTML to incude inside the <head>
 9787: 
 9788: $args - additional optional args supported are:
 9789: 
 9790: =over 8
 9791: 
 9792:              only_body      -> is true will set &bodytag() onlybodytag
 9793:                                     arg on
 9794:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 9795:              add_entries    -> additional attributes to add to the  <body>
 9796:              domain         -> force to color decorate a page for a 
 9797:                                     specific domain
 9798:              function       -> force usage of a specific rolish color
 9799:                                     scheme
 9800:              redirect       -> see &headtag()
 9801:              bgcolor        -> override the default page bg color
 9802:              js_ready       -> return a string ready for being used in 
 9803:                                     a javascript writeln
 9804:              html_encode    -> return a string ready for being used in 
 9805:                                     a html attribute
 9806:              force_register -> if is true will turn on the &bodytag()
 9807:                                     $forcereg arg
 9808:              frameset       -> if true will start with a <frameset>
 9809:                                     rather than <body>
 9810:              skip_phases    -> hash ref of 
 9811:                                     head -> skip the <html><head> generation
 9812:                                     body -> skip all <body> generation
 9813:              no_auto_mt_title -> prevent &mt()ing the title arg
 9814:              bread_crumbs ->             Array containing breadcrumbs
 9815:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 9816:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
 9817:                                     to lonhtmlcommon::breadcrumbs
 9818:              group          -> includes the current group, if page is for a 
 9819:                                specific group
 9820:              use_absolute   -> for request for external resource or syllabus, this
 9821:                                will contain https://<hostname> if server uses
 9822:                                https (as per hosts.tab), but request is for http
 9823:              hostname       -> hostname, originally from $r->hostname(), (optional).
 9824:              links_disabled -> Links in primary and secondary menus are disabled
 9825:                                (Can enable them once page has loaded - see lonroles.pm
 9826:                                for an example).
 9827:              links_target   -> Target for links, e.g., _parent (optional).
 9828: 
 9829: =back
 9830: 
 9831: =back
 9832: 
 9833: =cut
 9834: 
 9835: sub start_page {
 9836:     my ($title,$head_extra,$args) = @_;
 9837:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 9838: 
 9839:     $env{'internal.start_page'}++;
 9840:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
 9841: 
 9842:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 9843:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
 9844:     }
 9845: 
 9846:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
 9847:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
 9848:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
 9849:                 $args->{'no_primary_menu'} = 1;
 9850:             }
 9851:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
 9852:                 $args->{'no_inline_menu'} = 1;
 9853:             }
 9854:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
 9855:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
 9856:             }
 9857:         } else {
 9858:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9859:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
 9860:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
 9861:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
 9862:                     $args->{'no_primary_menu'} = 1;
 9863:                 }
 9864:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
 9865:                     $args->{'no_inline_menu'} = 1;
 9866:                 }
 9867:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
 9868:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
 9869:                 }
 9870:             }
 9871:         }
 9872:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
 9873:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
 9874:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
 9875:     } elsif ($env{'request.course.id'}) {
 9876:         my $expiretime=600;
 9877:         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
 9878:             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
 9879:         }
 9880:         my ($deeplinkmenu,$menuref);
 9881:         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
 9882:         if ($menucoll) {
 9883:             if (ref($menuref) eq 'HASH') {
 9884:                 %menu = %{$menuref};
 9885:             }
 9886:             if ($menu{'top'} eq 'n') {
 9887:                 $args->{'no_primary_menu'} = 1;
 9888:             }
 9889:             if ($menu{'inline'} eq 'n') {
 9890:                 unless (&Apache::lonnet::allowed('opa')) {
 9891:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9892:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9893:                     my $crstype = &course_type();
 9894:                     my $now = time;
 9895:                     my $ccrole;
 9896:                     if ($crstype eq 'Community') {
 9897:                         $ccrole = 'co';
 9898:                     } else {
 9899:                         $ccrole = 'cc';
 9900:                     }
 9901:                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
 9902:                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
 9903:                         if ((($start) && ($start<0)) ||
 9904:                             (($end) && ($end<$now))  ||
 9905:                             (($start) && ($now<$start))) {
 9906:                             $args->{'no_inline_menu'} = 1;
 9907:                         }
 9908:                     } else {
 9909:                         $args->{'no_inline_menu'} = 1;
 9910:                     }
 9911:                 }
 9912:             }
 9913:         }
 9914:     }
 9915: 
 9916:     my $showncrumbs;
 9917:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 9918: 	if ($args->{'frameset'}) {
 9919: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 9920: 						$args->{'add_entries'});
 9921: 	    $result .= "\n<frameset $attr_string>\n";
 9922:         } else {
 9923:             $result .=
 9924:                 &bodytag($title, 
 9925:                          $args->{'function'},       $args->{'add_entries'},
 9926:                          $args->{'only_body'},      $args->{'domain'},
 9927:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 9928:                          $args->{'bgcolor'},        $args,
 9929:                          \@advtools,$ltiscope,$ltiuri,\%ltimenu,$menucoll,
 9930:                          \%menu,\$showncrumbs);
 9931:         }
 9932:     }
 9933: 
 9934:     if ($args->{'js_ready'}) {
 9935: 		$result = &js_ready($result);
 9936:     }
 9937:     if ($args->{'html_encode'}) {
 9938: 		$result = &html_encode($result);
 9939:     }
 9940: 
 9941:     # Preparation for new and consistent functionlist at top of screen
 9942:     # if ($args->{'functionlist'}) {
 9943:     #            $result .= &build_functionlist();
 9944:     #}
 9945: 
 9946:     # Don't add anything more if only_body wanted or in const space
 9947:     return $result if    $args->{'only_body'} 
 9948:                       || $env{'request.state'} eq 'construct';
 9949: 
 9950:     #Breadcrumbs
 9951:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 9952:         unless ($showncrumbs) {
 9953: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 9954: 		#if any br links exists, add them to the breadcrumbs
 9955: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 9956: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 9957: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 9958: 			}
 9959: 		}
 9960:                 # if @advtools array contains items add then to the breadcrumbs
 9961:                 if (@advtools > 0) {
 9962:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 9963:                 }
 9964:                 my $menulink;
 9965:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
 9966:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
 9967:                      ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
 9968:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
 9969:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
 9970:                      (!$env{'request.role.adv'}))) {
 9971:                     $menulink = 0;
 9972:                 } else {
 9973:                     undef($menulink);
 9974:                 }
 9975:                 my $linkprotout;
 9976:                 if ($env{'request.deeplink.login'}) {
 9977:                     my $linkprotout = &Apache::lonmenu::linkprot_exit();
 9978:                     if ($linkprotout) {
 9979:                         &Apache::lonhtmlcommon::add_breadcrumb_tool('tools',$linkprotout);
 9980:                     }
 9981:                 }
 9982: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 9983: 		if(exists($args->{'bread_crumbs_component'})){
 9984: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
 9985:                 } else {
 9986: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
 9987: 		}
 9988:         }
 9989:     }
 9990:     return $result;
 9991: }
 9992: 
 9993: sub end_page {
 9994:     my ($args) = @_;
 9995:     $env{'internal.end_page'}++;
 9996:     my $result;
 9997:     if ($args->{'discussion'}) {
 9998: 	my ($target,$parser);
 9999: 	if (ref($args->{'discussion'})) {
10000: 	    ($target,$parser) =($args->{'discussion'}{'target'},
10001: 				$args->{'discussion'}{'parser'});
10002: 	}
10003: 	$result .= &Apache::lonxml::xmlend($target,$parser);
10004:     }
10005:     if ($args->{'frameset'}) {
10006: 	$result .= '</frameset>';
10007:     } else {
10008: 	$result .= &endbodytag($args);
10009:     }
10010:     unless ($args->{'notbody'}) {
10011:         $result .= "\n</html>";
10012:     }
10013: 
10014:     if ($args->{'js_ready'}) {
10015: 	$result = &js_ready($result);
10016:     }
10017: 
10018:     if ($args->{'html_encode'}) {
10019: 	$result = &html_encode($result);
10020:     }
10021: 
10022:     return $result;
10023: }
10024: 
10025: sub menucoll_in_effect {
10026:     my ($menucoll,$deeplinkmenu,%menu);
10027:     if ($env{'request.course.id'}) {
10028:         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
10029:         if ($env{'request.deeplink.login'}) {
10030:             my ($deeplink_symb,$deeplink,$check_login_symb);
10031:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10032:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10033:             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
10034:                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
10035:                     my $navmap = Apache::lonnavmaps::navmap->new();
10036:                     if (ref($navmap)) {
10037:                         $deeplink = $navmap->get_mapparam(undef,
10038:                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
10039:                                                           '0.deeplink');
10040:                     } else {
10041:                         $check_login_symb = 1;
10042:                     }
10043:                 } else {
10044:                     my $symb = &Apache::lonnet::symbread();
10045:                     if ($symb) {
10046:                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
10047:                     } else {
10048:                         $check_login_symb = 1;
10049:                     }
10050:                 }
10051:             } else {
10052:                 $check_login_symb = 1;
10053:             }
10054:             if ($check_login_symb) {
10055:                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
10056:                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
10057:                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
10058:                     my $navmap = Apache::lonnavmaps::navmap->new();
10059:                     if (ref($navmap)) {
10060:                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
10061:                     }
10062:                 } else {
10063:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
10064:                 }
10065:             }
10066:             if ($deeplink ne '') {
10067:                 my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
10068:                 if ($display =~ /^\d+$/) {
10069:                     $deeplinkmenu = 1;
10070:                     $menucoll = $display;
10071:                 }
10072:             }
10073:         }
10074:         if ($menucoll) {
10075:             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
10076:         }
10077:     }
10078:     return ($menucoll,$deeplinkmenu,\%menu);
10079: }
10080: 
10081: sub deeplink_login_symb {
10082:     my ($cnum,$cdom) = @_;
10083:     my $login_symb;
10084:     if ($env{'request.deeplink.login'}) {
10085:         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
10086:     }
10087:     return $login_symb;
10088: }
10089: 
10090: sub symb_from_tinyurl {
10091:     my ($url,$cnum,$cdom) = @_;
10092:     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
10093:         my $key = $1;
10094:         my ($tinyurl,$login);
10095:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
10096:         if (defined($cached)) {
10097:             $tinyurl = $result;
10098:         } else {
10099:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
10100:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
10101:             if ($currtiny{$key} ne '') {
10102:                 $tinyurl = $currtiny{$key};
10103:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
10104:             }
10105:         }
10106:         if ($tinyurl ne '') {
10107:             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
10108:             if (wantarray) {
10109:                 return ($cnumreq,$symb);
10110:             } elsif ($cnumreq eq $cnum) {
10111:                 return $symb;
10112:             }
10113:         }
10114:     }
10115:     if (wantarray) {
10116:         return ();
10117:     } else {
10118:         return;
10119:     }
10120: }
10121: 
10122: sub usable_exttools {
10123:     my %tooltypes;
10124:     if ($env{'request.course.id'}) {
10125:         if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'}) {
10126:            if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'both') {
10127:                %tooltypes = (
10128:                              crs => 1,
10129:                              dom => 1,
10130:                             );
10131:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'crs') {
10132:                $tooltypes{'crs'} = 1;
10133:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'dom') {
10134:                $tooltypes{'dom'} = 1;
10135:            }
10136:         } else {
10137:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10138:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10139:             my $crstype = lc($env{'course.'.$env{'request.course.id'}.'.type'});
10140:             if ($crstype eq '') {
10141:                 $crstype = 'course';
10142:             }
10143:             if ($crstype eq 'course') {
10144:                 if ($env{'course.'.$env{'request.course.id'}.'internal.coursecode'}) {
10145:                     $crstype = 'official';
10146:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.textbook'}) {
10147:                     $crstype = 'textbook';
10148:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.lti'}) {
10149:                     $crstype = 'lti';
10150:                 } else {
10151:                     $crstype = 'unofficial';
10152:                 }
10153:             }
10154:             my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
10155:             if ($domdefaults{$crstype.'domexttool'}) {
10156:                 $tooltypes{'dom'} = 1;
10157:             }
10158:             if ($domdefaults{$crstype.'exttool'}) {
10159:                 $tooltypes{'crs'} = 1;
10160:             }
10161:         }
10162:     }
10163:     return %tooltypes;
10164: }
10165: 
10166: sub wishlist_window {
10167:     return(<<'ENDWISHLIST');
10168: <script type="text/javascript">
10169: // <![CDATA[
10170: // <!-- BEGIN LON-CAPA Internal
10171: function set_wishlistlink(title, path) {
10172:     if (!title) {
10173:         title = document.title;
10174:         title = title.replace(/^LON-CAPA /,'');
10175:     }
10176:     title = encodeURIComponent(title);
10177:     title = title.replace("'","\\\'");
10178:     if (!path) {
10179:         path = location.pathname;
10180:     }
10181:     path = encodeURIComponent(path);
10182:     path = path.replace("'","\\\'");
10183:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
10184:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
10185: }
10186: // END LON-CAPA Internal -->
10187: // ]]>
10188: </script>
10189: ENDWISHLIST
10190: }
10191: 
10192: sub modal_window {
10193:     return(<<'ENDMODAL');
10194: <script type="text/javascript">
10195: // <![CDATA[
10196: // <!-- BEGIN LON-CAPA Internal
10197: var modalWindow = {
10198: 	parent:"body",
10199: 	windowId:null,
10200: 	content:null,
10201: 	width:null,
10202: 	height:null,
10203: 	close:function()
10204: 	{
10205: 	        $(".LCmodal-window").remove();
10206: 	        $(".LCmodal-overlay").remove();
10207: 	},
10208: 	open:function()
10209: 	{
10210: 		var modal = "";
10211: 		modal += "<div class=\"LCmodal-overlay\"></div>";
10212: 		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;\">";
10213: 		modal += this.content;
10214: 		modal += "</div>";	
10215: 
10216: 		$(this.parent).append(modal);
10217: 
10218: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
10219: 		$(".LCclose-window").click(function(){modalWindow.close();});
10220: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
10221: 	}
10222: };
10223: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
10224: 	{
10225:                 source = source.replace(/'/g,"&#39;");
10226: 		modalWindow.windowId = "myModal";
10227: 		modalWindow.width = width;
10228: 		modalWindow.height = height;
10229: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
10230: 		modalWindow.open();
10231: 	};
10232: // END LON-CAPA Internal -->
10233: // ]]>
10234: </script>
10235: ENDMODAL
10236: }
10237: 
10238: sub modal_link {
10239:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
10240:     unless ($width) { $width=480; }
10241:     unless ($height) { $height=400; }
10242:     unless ($scrolling) { $scrolling='yes'; }
10243:     unless ($transparency) { $transparency='true'; }
10244: 
10245:     my $target_attr;
10246:     if (defined($target)) {
10247:         $target_attr = 'target="'.$target.'"';
10248:     }
10249:     return <<"ENDLINK";
10250: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
10251: ENDLINK
10252: }
10253: 
10254: sub modal_adhoc_script {
10255:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
10256:     my $mathjax;
10257:     if ($possmathjax) {
10258:         $mathjax = <<'ENDJAX';
10259:                if (typeof MathJax == 'object') {
10260:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
10261:                }
10262: ENDJAX
10263:     }
10264:     return (<<ENDADHOC);
10265: <script type="text/javascript">
10266: // <![CDATA[
10267:         var $funcname = function()
10268:         {
10269:                 modalWindow.windowId = "myModal";
10270:                 modalWindow.width = $width;
10271:                 modalWindow.height = $height;
10272:                 modalWindow.content = '$content';
10273:                 modalWindow.open();
10274:                 $mathjax
10275:         };  
10276: // ]]>
10277: </script>
10278: ENDADHOC
10279: }
10280: 
10281: sub modal_adhoc_inner {
10282:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
10283:     my $innerwidth=$width-20;
10284:     $content=&js_ready(
10285:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
10286:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
10287:                  $content.
10288:                  &end_scrollbox().
10289:                  &end_page()
10290:              );
10291:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
10292: }
10293: 
10294: sub modal_adhoc_window {
10295:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
10296:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
10297:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
10298: }
10299: 
10300: sub modal_adhoc_launch {
10301:     my ($funcname,$width,$height,$content)=@_;
10302:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
10303: <script type="text/javascript">
10304: // <![CDATA[
10305: $funcname();
10306: // ]]>
10307: </script>
10308: ENDLAUNCH
10309: }
10310: 
10311: sub modal_adhoc_close {
10312:     return (<<ENDCLOSE);
10313: <script type="text/javascript">
10314: // <![CDATA[
10315: modalWindow.close();
10316: // ]]>
10317: </script>
10318: ENDCLOSE
10319: }
10320: 
10321: sub togglebox_script {
10322:    return(<<ENDTOGGLE);
10323: <script type="text/javascript"> 
10324: // <![CDATA[
10325: function LCtoggleDisplay(id,hidetext,showtext) {
10326:    link = document.getElementById(id + "link").childNodes[0];
10327:    with (document.getElementById(id).style) {
10328:       if (display == "none" ) {
10329:           display = "inline";
10330:           link.nodeValue = hidetext;
10331:         } else {
10332:           display = "none";
10333:           link.nodeValue = showtext;
10334:        }
10335:    }
10336: }
10337: // ]]>
10338: </script>
10339: ENDTOGGLE
10340: }
10341: 
10342: sub start_togglebox {
10343:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
10344:     unless ($heading) { $heading=''; } else { $heading.=' '; }
10345:     unless ($showtext) { $showtext=&mt('show'); }
10346:     unless ($hidetext) { $hidetext=&mt('hide'); }
10347:     unless ($headerbg) { $headerbg='#FFFFFF'; }
10348:     return &start_data_table().
10349:            &start_data_table_header_row().
10350:            '<td bgcolor="'.$headerbg.'">'.$heading.
10351:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
10352:            $showtext.'\')">'.$showtext.'</a>]</td>'.
10353:            &end_data_table_header_row().
10354:            '<tr id="'.$id.'" style="display:none""><td>';
10355: }
10356: 
10357: sub end_togglebox {
10358:     return '</td></tr>'.&end_data_table();
10359: }
10360: 
10361: sub LCprogressbar_script {
10362:    my ($id,$number_to_do)=@_;
10363:    if ($number_to_do) {
10364:        return(<<ENDPROGRESS);
10365: <script type="text/javascript">
10366: // <![CDATA[
10367: \$('#progressbar$id').progressbar({
10368:   value: 0,
10369:   change: function(event, ui) {
10370:     var newVal = \$(this).progressbar('option', 'value');
10371:     \$('.pblabel', this).text(LCprogressTxt);
10372:   }
10373: });
10374: // ]]>
10375: </script>
10376: ENDPROGRESS
10377:    } else {
10378:        return(<<ENDPROGRESS);
10379: <script type="text/javascript">
10380: // <![CDATA[
10381: \$('#progressbar$id').progressbar({
10382:   value: false,
10383:   create: function(event, ui) {
10384:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
10385:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
10386:   }
10387: });
10388: // ]]>
10389: </script>
10390: ENDPROGRESS
10391:    }
10392: }
10393: 
10394: sub LCprogressbarUpdate_script {
10395:    return(<<ENDPROGRESSUPDATE);
10396: <style type="text/css">
10397: .ui-progressbar { position:relative; }
10398: .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%; }
10399: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
10400: </style>
10401: <script type="text/javascript">
10402: // <![CDATA[
10403: var LCprogressTxt='---';
10404: 
10405: function LCupdateProgress(percent,progresstext,id,maxnum) {
10406:    LCprogressTxt=progresstext;
10407:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
10408:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
10409:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
10410:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
10411:    } else {
10412:        \$('#progressbar'+id).progressbar('value',percent);
10413:    }
10414: }
10415: // ]]>
10416: </script>
10417: ENDPROGRESSUPDATE
10418: }
10419: 
10420: my $LClastpercent;
10421: my $LCidcnt;
10422: my $LCcurrentid;
10423: 
10424: sub LCprogressbar {
10425:     my ($r,$number_to_do,$preamble)=@_;
10426:     $LClastpercent=0;
10427:     $LCidcnt++;
10428:     $LCcurrentid=$$.'_'.$LCidcnt;
10429:     my ($starting,$content);
10430:     if ($number_to_do) {
10431:         $starting=&mt('Starting');
10432:         $content=(<<ENDPROGBAR);
10433: $preamble
10434:   <div id="progressbar$LCcurrentid">
10435:     <span class="pblabel">$starting</span>
10436:   </div>
10437: ENDPROGBAR
10438:     } else {
10439:         $starting=&mt('Loading...');
10440:         $LClastpercent='false';
10441:         $content=(<<ENDPROGBAR);
10442: $preamble
10443:   <div id="progressbar$LCcurrentid">
10444:       <div class="progress-label">$starting</div>
10445:   </div>
10446: ENDPROGBAR
10447:     }
10448:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
10449: }
10450: 
10451: sub LCprogressbarUpdate {
10452:     my ($r,$val,$text,$number_to_do)=@_;
10453:     if ($number_to_do) {
10454:         unless ($val) { 
10455:             if ($LClastpercent) {
10456:                 $val=$LClastpercent;
10457:             } else {
10458:                 $val=0;
10459:             }
10460:         }
10461:         if ($val<0) { $val=0; }
10462:         if ($val>100) { $val=0; }
10463:         $LClastpercent=$val;
10464:         unless ($text) { $text=$val.'%'; }
10465:     } else {
10466:         $val = 'false';
10467:     }
10468:     $text=&js_ready($text);
10469:     &r_print($r,<<ENDUPDATE);
10470: <script type="text/javascript">
10471: // <![CDATA[
10472: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
10473: // ]]>
10474: </script>
10475: ENDUPDATE
10476: }
10477: 
10478: sub LCprogressbarClose {
10479:     my ($r)=@_;
10480:     $LClastpercent=0;
10481:     &r_print($r,<<ENDCLOSE);
10482: <script type="text/javascript">
10483: // <![CDATA[
10484: \$("#progressbar$LCcurrentid").hide('slow'); 
10485: // ]]>
10486: </script>
10487: ENDCLOSE
10488: }
10489: 
10490: sub r_print {
10491:     my ($r,$to_print)=@_;
10492:     if ($r) {
10493:       $r->print($to_print);
10494:       $r->rflush();
10495:     } else {
10496:       print($to_print);
10497:     }
10498: }
10499: 
10500: sub html_encode {
10501:     my ($result) = @_;
10502: 
10503:     $result = &HTML::Entities::encode($result,'<>&"');
10504:     
10505:     return $result;
10506: }
10507: 
10508: sub js_ready {
10509:     my ($result) = @_;
10510: 
10511:     $result =~ s/[\n\r]/ /xmsg;
10512:     $result =~ s/\\/\\\\/xmsg;
10513:     $result =~ s/'/\\'/xmsg;
10514:     $result =~ s{</}{<\\/}xmsg;
10515:     
10516:     return $result;
10517: }
10518: 
10519: sub validate_page {
10520:     if (  exists($env{'internal.start_page'})
10521: 	  &&     $env{'internal.start_page'} > 1) {
10522: 	&Apache::lonnet::logthis('start_page called multiple times '.
10523: 				 $env{'internal.start_page'}.' '.
10524: 				 $ENV{'request.filename'});
10525:     }
10526:     if (  exists($env{'internal.end_page'})
10527: 	  &&     $env{'internal.end_page'} > 1) {
10528: 	&Apache::lonnet::logthis('end_page called multiple times '.
10529: 				 $env{'internal.end_page'}.' '.
10530: 				 $env{'request.filename'});
10531:     }
10532:     if (     exists($env{'internal.start_page'})
10533: 	&& ! exists($env{'internal.end_page'})) {
10534: 	&Apache::lonnet::logthis('start_page called without end_page '.
10535: 				 $env{'request.filename'});
10536:     }
10537:     if (   ! exists($env{'internal.start_page'})
10538: 	&&   exists($env{'internal.end_page'})) {
10539: 	&Apache::lonnet::logthis('end_page called without start_page'.
10540: 				 $env{'request.filename'});
10541:     }
10542: }
10543: 
10544: 
10545: sub start_scrollbox {
10546:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
10547:     unless ($outerwidth) { $outerwidth='520px'; }
10548:     unless ($width) { $width='500px'; }
10549:     unless ($height) { $height='200px'; }
10550:     my ($table_id,$div_id,$tdcol);
10551:     if ($id ne '') {
10552:         $table_id = ' id="table_'.$id.'"';
10553:         $div_id = ' id="div_'.$id.'"';
10554:     }
10555:     if ($bgcolor ne '') {
10556:         $tdcol = "background-color: $bgcolor;";
10557:     }
10558:     my $nicescroll_js;
10559:     if ($env{'browser.mobile'}) {
10560:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
10561:     }
10562:     return <<"END";
10563: $nicescroll_js
10564: 
10565: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
10566: <div style="overflow:auto; width:$width; height:$height;"$div_id>
10567: END
10568: }
10569: 
10570: sub end_scrollbox {
10571:     return '</div></td></tr></table>';
10572: }
10573: 
10574: sub nicescroll_javascript {
10575:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
10576:     my %options;
10577:     if (ref($cursor) eq 'HASH') {
10578:         %options = %{$cursor};
10579:     }
10580:     unless ($options{'railalign'} =~ /^left|right$/) {
10581:         $options{'railalign'} = 'left';
10582:     }
10583:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
10584:         my $function  = &get_users_function();
10585:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
10586:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
10587:             $options{'cursorcolor'} = '#00F';
10588:         }
10589:     }
10590:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
10591:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
10592:             $options{'cursoropacity'}='1.0';
10593:         }
10594:     } else {
10595:         $options{'cursoropacity'}='1.0';
10596:     }
10597:     if ($options{'cursorfixedheight'} eq 'none') {
10598:         delete($options{'cursorfixedheight'});
10599:     } else {
10600:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
10601:     }
10602:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
10603:         delete($options{'railoffset'});
10604:     }
10605:     my @niceoptions;
10606:     while (my($key,$value) = each(%options)) {
10607:         if ($value =~ /^\{.+\}$/) {
10608:             push(@niceoptions,$key.':'.$value);
10609:         } else {
10610:             push(@niceoptions,$key.':"'.$value.'"');
10611:         }
10612:     }
10613:     my $nicescroll_js = '
10614: $(document).ready(
10615:       function() {
10616:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
10617:       }
10618: );
10619: ';
10620:     if ($framecheck) {
10621:         $nicescroll_js .= '
10622: function expand_div(caller) {
10623:     if (top === self) {
10624:         document.getElementById("'.$id.'").style.width = "auto";
10625:         document.getElementById("'.$id.'").style.height = "auto";
10626:     } else {
10627:         try {
10628:             if (parent.frames) {
10629:                 if (parent.frames.length > 1) {
10630:                     var framesrc = parent.frames[1].location.href;
10631:                     var currsrc = framesrc.replace(/\#.*$/,"");
10632:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
10633:                         document.getElementById("'.$id.'").style.width = "auto";
10634:                         document.getElementById("'.$id.'").style.height = "auto";
10635:                     }
10636:                 }
10637:             }
10638:         } catch (e) {
10639:             return;
10640:         }
10641:     }
10642:     return;
10643: }
10644: ';
10645:     }
10646:     if ($needjsready) {
10647:         $nicescroll_js = '
10648: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
10649:     } else {
10650:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
10651:     }
10652:     return $nicescroll_js;
10653: }
10654: 
10655: sub simple_error_page {
10656:     my ($r,$title,$msg,$args) = @_;
10657:     my %displayargs;
10658:     if (ref($args) eq 'HASH') {
10659:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
10660:         if ($args->{'only_body'}) {
10661:             $displayargs{'only_body'} = 1;
10662:         }
10663:         if ($args->{'no_nav_bar'}) {
10664:             $displayargs{'no_nav_bar'} = 1;
10665:         }
10666:     } else {
10667:         $msg = &mt($msg);
10668:     }
10669: 
10670:     my $page =
10671: 	&Apache::loncommon::start_page($title,'',\%displayargs).
10672: 	'<p class="LC_error">'.$msg.'</p>'.
10673: 	&Apache::loncommon::end_page();
10674:     if (ref($r)) {
10675: 	$r->print($page);
10676: 	return;
10677:     }
10678:     return $page;
10679: }
10680: 
10681: {
10682:     my @row_count;
10683: 
10684:     sub start_data_table_count {
10685:         unshift(@row_count, 0);
10686:         return;
10687:     }
10688: 
10689:     sub end_data_table_count {
10690:         shift(@row_count);
10691:         return;
10692:     }
10693: 
10694:     sub start_data_table {
10695: 	my ($add_class,$id) = @_;
10696: 	my $css_class = (join(' ','LC_data_table',$add_class));
10697:         my $table_id;
10698:         if (defined($id)) {
10699:             $table_id = ' id="'.$id.'"';
10700:         }
10701: 	&start_data_table_count();
10702: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
10703:     }
10704: 
10705:     sub end_data_table {
10706: 	&end_data_table_count();
10707: 	return '</table>'."\n";;
10708:     }
10709: 
10710:     sub start_data_table_row {
10711: 	my ($add_class, $id) = @_;
10712: 	$row_count[0]++;
10713: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
10714: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
10715:         $id = (' id="'.$id.'"') unless ($id eq '');
10716:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
10717:     }
10718:     
10719:     sub continue_data_table_row {
10720: 	my ($add_class, $id) = @_;
10721: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
10722: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
10723:         $id = (' id="'.$id.'"') unless ($id eq '');
10724:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
10725:     }
10726: 
10727:     sub end_data_table_row {
10728: 	return '</tr>'."\n";;
10729:     }
10730: 
10731:     sub start_data_table_empty_row {
10732: #	$row_count[0]++;
10733: 	return  '<tr class="LC_empty_row" >'."\n";;
10734:     }
10735: 
10736:     sub end_data_table_empty_row {
10737: 	return '</tr>'."\n";;
10738:     }
10739: 
10740:     sub start_data_table_header_row {
10741: 	return  '<tr class="LC_header_row">'."\n";;
10742:     }
10743: 
10744:     sub end_data_table_header_row {
10745: 	return '</tr>'."\n";;
10746:     }
10747: 
10748:     sub data_table_caption {
10749:         my $caption = shift;
10750:         return "<caption class=\"LC_caption\">$caption</caption>";
10751:     }
10752: }
10753: 
10754: =pod
10755: 
10756: =item * &inhibit_menu_check($arg)
10757: 
10758: Checks for a inhibitmenu state and generates output to preserve it
10759: 
10760: Inputs:         $arg - can be any of
10761:                      - undef - in which case the return value is a string 
10762:                                to add  into arguments list of a uri
10763:                      - 'input' - in which case the return value is a HTML
10764:                                  <form> <input> field of type hidden to
10765:                                  preserve the value
10766:                      - a url - in which case the return value is the url with
10767:                                the neccesary cgi args added to preserve the
10768:                                inhibitmenu state
10769:                      - a ref to a url - no return value, but the string is
10770:                                         updated to include the neccessary cgi
10771:                                         args to preserve the inhibitmenu state
10772: 
10773: =cut
10774: 
10775: sub inhibit_menu_check {
10776:     my ($arg) = @_;
10777:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
10778:     if ($arg eq 'input') {
10779: 	if ($env{'form.inhibitmenu'}) {
10780: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
10781: 	} else {
10782: 	    return
10783: 	}
10784:     }
10785:     if ($env{'form.inhibitmenu'}) {
10786: 	if (ref($arg)) {
10787: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
10788: 	} elsif ($arg eq '') {
10789: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
10790: 	} else {
10791: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
10792: 	}
10793:     }
10794:     if (!ref($arg)) {
10795: 	return $arg;
10796:     }
10797: }
10798: 
10799: ###############################################
10800: 
10801: =pod
10802: 
10803: =back
10804: 
10805: =head1 User Information Routines
10806: 
10807: =over 4
10808: 
10809: =item * &get_users_function()
10810: 
10811: Used by &bodytag to determine the current users primary role.
10812: Returns either 'student','coordinator','admin', or 'author'.
10813: 
10814: =cut
10815: 
10816: ###############################################
10817: sub get_users_function {
10818:     my $function = 'norole';
10819:     if ($env{'request.role'}=~/^(st)/) {
10820:         $function='student';
10821:     }
10822:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
10823:         $function='coordinator';
10824:     }
10825:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
10826:         $function='admin';
10827:     }
10828:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
10829:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
10830:         $function='author';
10831:     }
10832:     return $function;
10833: }
10834: 
10835: ###############################################
10836: 
10837: =pod
10838: 
10839: =item * &show_course()
10840: 
10841: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
10842: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
10843: 
10844: Inputs:
10845: None
10846: 
10847: Outputs:
10848: Scalar: 1 if 'Course' to be used, 0 otherwise.
10849: 
10850: =cut
10851: 
10852: ###############################################
10853: sub show_course {
10854:     my ($udom,$uname) = @_;
10855:     if (($udom ne '') && ($uname ne '')) {
10856:         if (($udom ne $env{'user.domain'}) || ($uname ne $env{'user.name'})) {
10857:             if (&Apache::lonnet::is_advanced_user($udom,$uname)) {
10858:                 return 0;
10859:             } else {
10860:                 return 1;
10861:             }
10862:         }
10863:     }
10864:     my $course = !$env{'user.adv'};
10865:     if (!$env{'user.adv'}) {
10866:         foreach my $env (keys(%env)) {
10867:             next if ($env !~ m/^user\.priv\./);
10868:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
10869:                 $course = 0;
10870:                 last;
10871:             }
10872:         }
10873:     }
10874:     return $course;
10875: }
10876: 
10877: ###############################################
10878: 
10879: =pod
10880: 
10881: =item * &check_user_status()
10882: 
10883: Determines current status of supplied role for a
10884: specific user. Roles can be active, previous or future.
10885: 
10886: Inputs: 
10887: user's domain, user's username, course's domain,
10888: course's number, optional section ID.
10889: 
10890: Outputs:
10891: role status: active, previous or future. 
10892: 
10893: =cut
10894: 
10895: sub check_user_status {
10896:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
10897:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
10898:     my @uroles = keys(%userinfo);
10899:     my $srchstr;
10900:     my $active_chk = 'none';
10901:     my $now = time;
10902:     if (@uroles > 0) {
10903:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
10904:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
10905:         } else {
10906:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
10907:         }
10908:         if (grep/^\Q$srchstr\E$/,@uroles) {
10909:             my $role_end = 0;
10910:             my $role_start = 0;
10911:             $active_chk = 'active';
10912:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
10913:                 $role_end = $1;
10914:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
10915:                     $role_start = $1;
10916:                 }
10917:             }
10918:             if ($role_start > 0) {
10919:                 if ($now < $role_start) {
10920:                     $active_chk = 'future';
10921:                 }
10922:             }
10923:             if ($role_end > 0) {
10924:                 if ($now > $role_end) {
10925:                     $active_chk = 'previous';
10926:                 }
10927:             }
10928:         }
10929:     }
10930:     return $active_chk;
10931: }
10932: 
10933: ###############################################
10934: 
10935: =pod
10936: 
10937: =item * &get_sections()
10938: 
10939: Determines all the sections for a course including
10940: sections with students and sections containing other roles.
10941: Incoming parameters: 
10942: 
10943: 1. domain
10944: 2. course number 
10945: 3. reference to array containing roles for which sections should 
10946: be gathered (optional).
10947: 4. reference to array containing status types for which sections 
10948: should be gathered (optional).
10949: 
10950: If the third argument is undefined, sections are gathered for any role. 
10951: If the fourth argument is undefined, sections are gathered for any status.
10952: Permissible values are 'active' or 'future' or 'previous'.
10953:  
10954: Returns section hash (keys are section IDs, values are
10955: number of users in each section), subject to the
10956: optional roles filter, optional status filter 
10957: 
10958: =cut
10959: 
10960: ###############################################
10961: sub get_sections {
10962:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
10963:     if (!defined($cdom) || !defined($cnum)) {
10964:         my $cid =  $env{'request.course.id'};
10965: 
10966: 	return if (!defined($cid));
10967: 
10968:         $cdom = $env{'course.'.$cid.'.domain'};
10969:         $cnum = $env{'course.'.$cid.'.num'};
10970:     }
10971: 
10972:     my %sectioncount;
10973:     my $now = time;
10974: 
10975:     my $check_students = 1;
10976:     my $only_students = 0;
10977:     if (ref($possible_roles) eq 'ARRAY') {
10978:         if (grep(/^st$/,@{$possible_roles})) {
10979:             if (@{$possible_roles} == 1) {
10980:                 $only_students = 1;
10981:             }
10982:         } else {
10983:             $check_students = 0;
10984:         }
10985:     }
10986: 
10987:     if ($check_students) { 
10988: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
10989: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
10990: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
10991:         my $start_index = &Apache::loncoursedata::CL_START();
10992:         my $end_index = &Apache::loncoursedata::CL_END();
10993:         my $status;
10994: 	while (my ($student,$data) = each(%$classlist)) {
10995: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
10996: 				                     $data->[$status_index],
10997:                                                      $data->[$start_index],
10998:                                                      $data->[$end_index]);
10999:             if ($stu_status eq 'Active') {
11000:                 $status = 'active';
11001:             } elsif ($end < $now) {
11002:                 $status = 'previous';
11003:             } elsif ($start > $now) {
11004:                 $status = 'future';
11005:             } 
11006: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
11007:                 if ((!defined($possible_status)) || (($status ne '') && 
11008:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
11009: 		    $sectioncount{$section}++;
11010:                 }
11011: 	    }
11012: 	}
11013:     }
11014:     if ($only_students) {
11015:         return %sectioncount;
11016:     }
11017:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
11018:     foreach my $user (sort(keys(%courseroles))) {
11019: 	if ($user !~ /^(\w{2})/) { next; }
11020: 	my ($role) = ($user =~ /^(\w{2})/);
11021: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
11022: 	my ($section,$status);
11023: 	if ($role eq 'cr' &&
11024: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
11025: 	    $section=$1;
11026: 	}
11027: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
11028: 	if (!defined($section) || $section eq '-1') { next; }
11029:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
11030:         if ($end == -1 && $start == -1) {
11031:             next; #deleted role
11032:         }
11033:         if (!defined($possible_status)) { 
11034:             $sectioncount{$section}++;
11035:         } else {
11036:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
11037:                 $status = 'active';
11038:             } elsif ($end < $now) {
11039:                 $status = 'future';
11040:             } elsif ($start > $now) {
11041:                 $status = 'previous';
11042:             }
11043:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
11044:                 $sectioncount{$section}++;
11045:             }
11046:         }
11047:     }
11048:     return %sectioncount;
11049: }
11050: 
11051: ###############################################
11052: 
11053: =pod
11054: 
11055: =item * &get_course_users()
11056: 
11057: Retrieves usernames:domains for users in the specified course
11058: with specific role(s), and access status. 
11059: 
11060: Incoming parameters:
11061: 1. course domain
11062: 2. course number
11063: 3. access status: users must have - either active, 
11064: previous, future, or all.
11065: 4. reference to array of permissible roles
11066: 5. reference to array of section restrictions (optional)
11067: 6. reference to results object (hash of hashes).
11068: 7. reference to optional userdata hash
11069: 8. reference to optional statushash
11070: 9. flag if privileged users (except those set to unhide in
11071:    course settings) should be excluded    
11072: Keys of top level results hash are roles.
11073: Keys of inner hashes are username:domain, with 
11074: values set to access type.
11075: Optional userdata hash returns an array with arguments in the 
11076: same order as loncoursedata::get_classlist() for student data.
11077: 
11078: Optional statushash returns
11079: 
11080: Entries for end, start, section and status are blank because
11081: of the possibility of multiple values for non-student roles.
11082: 
11083: =cut
11084: 
11085: ###############################################
11086: 
11087: sub get_course_users {
11088:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
11089:     my %idx = ();
11090:     my %seclists;
11091: 
11092:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
11093:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
11094:     $idx{end} = &Apache::loncoursedata::CL_END();
11095:     $idx{start} = &Apache::loncoursedata::CL_START();
11096:     $idx{id} = &Apache::loncoursedata::CL_ID();
11097:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
11098:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
11099:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
11100: 
11101:     if (grep(/^st$/,@{$roles})) {
11102:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
11103:         my $now = time;
11104:         foreach my $student (keys(%{$classlist})) {
11105:             my $match = 0;
11106:             my $secmatch = 0;
11107:             my $section = $$classlist{$student}[$idx{section}];
11108:             my $status = $$classlist{$student}[$idx{status}];
11109:             if ($section eq '') {
11110:                 $section = 'none';
11111:             }
11112:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
11113:                 if (grep(/^all$/,@{$sections})) {
11114:                     $secmatch = 1;
11115:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
11116:                     if (grep(/^none$/,@{$sections})) {
11117:                         $secmatch = 1;
11118:                     }
11119:                 } else {  
11120: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
11121: 		        $secmatch = 1;
11122:                     }
11123: 		}
11124:                 if (!$secmatch) {
11125:                     next;
11126:                 }
11127:             }
11128:             if (defined($$types{'active'})) {
11129:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
11130:                     push(@{$$users{st}{$student}},'active');
11131:                     $match = 1;
11132:                 }
11133:             }
11134:             if (defined($$types{'previous'})) {
11135:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
11136:                     push(@{$$users{st}{$student}},'previous');
11137:                     $match = 1;
11138:                 }
11139:             }
11140:             if (defined($$types{'future'})) {
11141:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
11142:                     push(@{$$users{st}{$student}},'future');
11143:                     $match = 1;
11144:                 }
11145:             }
11146:             if ($match) {
11147:                 push(@{$seclists{$student}},$section);
11148:                 if (ref($userdata) eq 'HASH') {
11149:                     $$userdata{$student} = $$classlist{$student};
11150:                 }
11151:                 if (ref($statushash) eq 'HASH') {
11152:                     $statushash->{$student}{'st'}{$section} = $status;
11153:                 }
11154:             }
11155:         }
11156:     }
11157:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
11158:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
11159:         my $now = time;
11160:         my %displaystatus = ( previous => 'Expired',
11161:                               active   => 'Active',
11162:                               future   => 'Future',
11163:                             );
11164:         my (%nothide,@possdoms);
11165:         if ($hidepriv) {
11166:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
11167:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
11168:                 if ($user !~ /:/) {
11169:                     $nothide{join(':',split(/[\@]/,$user))}=1;
11170:                 } else {
11171:                     $nothide{$user} = 1;
11172:                 }
11173:             }
11174:             my @possdoms = ($cdom);
11175:             if ($coursehash{'checkforpriv'}) {
11176:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
11177:             }
11178:         }
11179:         foreach my $person (sort(keys(%coursepersonnel))) {
11180:             my $match = 0;
11181:             my $secmatch = 0;
11182:             my $status;
11183:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
11184:             $user =~ s/:$//;
11185:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
11186:             if ($end == -1 || $start == -1) {
11187:                 next;
11188:             }
11189:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
11190:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
11191:                 my ($uname,$udom) = split(/:/,$user);
11192:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
11193:                     if (grep(/^all$/,@{$sections})) {
11194:                         $secmatch = 1;
11195:                     } elsif ($usec eq '') {
11196:                         if (grep(/^none$/,@{$sections})) {
11197:                             $secmatch = 1;
11198:                         }
11199:                     } else {
11200:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
11201:                             $secmatch = 1;
11202:                         }
11203:                     }
11204:                     if (!$secmatch) {
11205:                         next;
11206:                     }
11207:                 }
11208:                 if ($usec eq '') {
11209:                     $usec = 'none';
11210:                 }
11211:                 if ($uname ne '' && $udom ne '') {
11212:                     if ($hidepriv) {
11213:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
11214:                             (!$nothide{$uname.':'.$udom})) {
11215:                             next;
11216:                         }
11217:                     }
11218:                     if ($end > 0 && $end < $now) {
11219:                         $status = 'previous';
11220:                     } elsif ($start > $now) {
11221:                         $status = 'future';
11222:                     } else {
11223:                         $status = 'active';
11224:                     }
11225:                     foreach my $type (keys(%{$types})) { 
11226:                         if ($status eq $type) {
11227:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
11228:                                 push(@{$$users{$role}{$user}},$type);
11229:                             }
11230:                             $match = 1;
11231:                         }
11232:                     }
11233:                     if (($match) && (ref($userdata) eq 'HASH')) {
11234:                         if (!exists($$userdata{$uname.':'.$udom})) {
11235: 			    &get_user_info($udom,$uname,\%idx,$userdata);
11236:                         }
11237:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
11238:                             push(@{$seclists{$uname.':'.$udom}},$usec);
11239:                         }
11240:                         if (ref($statushash) eq 'HASH') {
11241:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
11242:                         }
11243:                     }
11244:                 }
11245:             }
11246:         }
11247:         if (grep(/^ow$/,@{$roles})) {
11248:             if ((defined($cdom)) && (defined($cnum))) {
11249:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
11250:                 if ( defined($csettings{'internal.courseowner'}) ) {
11251:                     my $owner = $csettings{'internal.courseowner'};
11252:                     next if ($owner eq '');
11253:                     my ($ownername,$ownerdom);
11254:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
11255:                         $ownername = $1;
11256:                         $ownerdom = $2;
11257:                     } else {
11258:                         $ownername = $owner;
11259:                         $ownerdom = $cdom;
11260:                         $owner = $ownername.':'.$ownerdom;
11261:                     }
11262:                     @{$$users{'ow'}{$owner}} = 'any';
11263:                     if (defined($userdata) && 
11264: 			!exists($$userdata{$owner})) {
11265: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
11266:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
11267:                             push(@{$seclists{$owner}},'none');
11268:                         }
11269:                         if (ref($statushash) eq 'HASH') {
11270:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
11271:                         }
11272: 		    }
11273:                 }
11274:             }
11275:         }
11276:         foreach my $user (keys(%seclists)) {
11277:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
11278:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
11279:         }
11280:     }
11281:     return;
11282: }
11283: 
11284: sub get_user_info {
11285:     my ($udom,$uname,$idx,$userdata) = @_;
11286:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
11287: 	&plainname($uname,$udom,'lastname');
11288:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
11289:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
11290:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
11291:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
11292:     return;
11293: }
11294: 
11295: ###############################################
11296: 
11297: =pod
11298: 
11299: =item * &get_user_quota()
11300: 
11301: Retrieves quota assigned for storage of user files.
11302: Default is to report quota for portfolio files.
11303: 
11304: Incoming parameters:
11305: 1. user's username
11306: 2. user's domain
11307: 3. quota name - portfolio, author, or course
11308:    (if no quota name provided, defaults to portfolio).
11309: 4. crstype - official, unofficial, textbook, placement or community, 
11310:    if quota name is course
11311: 
11312: Returns:
11313: 1. Disk quota (in MB) assigned to student.
11314: 2. (Optional) Type of setting: custom or default
11315:    (individually assigned or default for user's 
11316:    institutional status).
11317: 3. (Optional) - User's institutional status (e.g., faculty, staff
11318:    or student - types as defined in localenroll::inst_usertypes 
11319:    for user's domain, which determines default quota for user.
11320: 4. (Optional) - Default quota which would apply to the user.
11321: 
11322: If a value has been stored in the user's environment, 
11323: it will return that, otherwise it returns the maximal default
11324: defined for the user's institutional status(es) in the domain.
11325: 
11326: =cut
11327: 
11328: ###############################################
11329: 
11330: 
11331: sub get_user_quota {
11332:     my ($uname,$udom,$quotaname,$crstype) = @_;
11333:     my ($quota,$quotatype,$settingstatus,$defquota);
11334:     if (!defined($udom)) {
11335:         $udom = $env{'user.domain'};
11336:     }
11337:     if (!defined($uname)) {
11338:         $uname = $env{'user.name'};
11339:     }
11340:     if (($udom eq '' || $uname eq '') ||
11341:         ($udom eq 'public') && ($uname eq 'public')) {
11342:         $quota = 0;
11343:         $quotatype = 'default';
11344:         $defquota = 0; 
11345:     } else {
11346:         my $inststatus;
11347:         if ($quotaname eq 'course') {
11348:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
11349:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
11350:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
11351:             } else {
11352:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
11353:                 $quota = $cenv{'internal.uploadquota'};
11354:             }
11355:         } else {
11356:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
11357:                 if ($quotaname eq 'author') {
11358:                     $quota = $env{'environment.authorquota'};
11359:                 } else {
11360:                     $quota = $env{'environment.portfolioquota'};
11361:                 }
11362:                 $inststatus = $env{'environment.inststatus'};
11363:             } else {
11364:                 my %userenv = 
11365:                     &Apache::lonnet::get('environment',['portfolioquota',
11366:                                          'authorquota','inststatus'],$udom,$uname);
11367:                 my ($tmp) = keys(%userenv);
11368:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11369:                     if ($quotaname eq 'author') {
11370:                         $quota = $userenv{'authorquota'};
11371:                     } else {
11372:                         $quota = $userenv{'portfolioquota'};
11373:                     }
11374:                     $inststatus = $userenv{'inststatus'};
11375:                 } else {
11376:                     undef(%userenv);
11377:                 }
11378:             }
11379:         }
11380:         if ($quota eq '' || wantarray) {
11381:             if ($quotaname eq 'course') {
11382:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
11383:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
11384:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
11385:                     ($crstype eq 'placement')) { 
11386:                     $defquota = $domdefs{$crstype.'quota'};
11387:                 }
11388:                 if ($defquota eq '') {
11389:                     $defquota = 500;
11390:                 }
11391:             } else {
11392:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
11393:             }
11394:             if ($quota eq '') {
11395:                 $quota = $defquota;
11396:                 $quotatype = 'default';
11397:             } else {
11398:                 $quotatype = 'custom';
11399:             }
11400:         }
11401:     }
11402:     if (wantarray) {
11403:         return ($quota,$quotatype,$settingstatus,$defquota);
11404:     } else {
11405:         return $quota;
11406:     }
11407: }
11408: 
11409: ###############################################
11410: 
11411: =pod
11412: 
11413: =item * &default_quota()
11414: 
11415: Retrieves default quota assigned for storage of user portfolio files,
11416: given an (optional) user's institutional status.
11417: 
11418: Incoming parameters:
11419: 
11420: 1. domain
11421: 2. (Optional) institutional status(es).  This is a : separated list of 
11422:    status types (e.g., faculty, staff, student etc.)
11423:    which apply to the user for whom the default is being retrieved.
11424:    If the institutional status string in undefined, the domain
11425:    default quota will be returned.
11426: 3.  quota name - portfolio, author, or course
11427:    (if no quota name provided, defaults to portfolio).
11428: 
11429: Returns:
11430: 
11431: 1. Default disk quota (in MB) for user portfolios in the domain.
11432: 2. (Optional) institutional type which determined the value of the
11433:    default quota.
11434: 
11435: If a value has been stored in the domain's configuration db,
11436: it will return that, otherwise it returns 20 (for backwards 
11437: compatibility with domains which have not set up a configuration
11438: db file; the original statically defined portfolio quota was 20 MB). 
11439: 
11440: If the user's status includes multiple types (e.g., staff and student),
11441: the largest default quota which applies to the user determines the
11442: default quota returned.
11443: 
11444: =cut
11445: 
11446: ###############################################
11447: 
11448: 
11449: sub default_quota {
11450:     my ($udom,$inststatus,$quotaname) = @_;
11451:     my ($defquota,$settingstatus);
11452:     my %quotahash = &Apache::lonnet::get_dom('configuration',
11453:                                             ['quotas'],$udom);
11454:     my $key = 'defaultquota';
11455:     if ($quotaname eq 'author') {
11456:         $key = 'authorquota';
11457:     }
11458:     if (ref($quotahash{'quotas'}) eq 'HASH') {
11459:         if ($inststatus ne '') {
11460:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
11461:             foreach my $item (@statuses) {
11462:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
11463:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
11464:                         if ($defquota eq '') {
11465:                             $defquota = $quotahash{'quotas'}{$key}{$item};
11466:                             $settingstatus = $item;
11467:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
11468:                             $defquota = $quotahash{'quotas'}{$key}{$item};
11469:                             $settingstatus = $item;
11470:                         }
11471:                     }
11472:                 } elsif ($key eq 'defaultquota') {
11473:                     if ($quotahash{'quotas'}{$item} ne '') {
11474:                         if ($defquota eq '') {
11475:                             $defquota = $quotahash{'quotas'}{$item};
11476:                             $settingstatus = $item;
11477:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
11478:                             $defquota = $quotahash{'quotas'}{$item};
11479:                             $settingstatus = $item;
11480:                         }
11481:                     }
11482:                 }
11483:             }
11484:         }
11485:         if ($defquota eq '') {
11486:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
11487:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
11488:             } elsif ($key eq 'defaultquota') {
11489:                 $defquota = $quotahash{'quotas'}{'default'};
11490:             }
11491:             $settingstatus = 'default';
11492:             if ($defquota eq '') {
11493:                 if ($quotaname eq 'author') {
11494:                     $defquota = 500;
11495:                 }
11496:             }
11497:         }
11498:     } else {
11499:         $settingstatus = 'default';
11500:         if ($quotaname eq 'author') {
11501:             $defquota = 500;
11502:         } else {
11503:             $defquota = 20;
11504:         }
11505:     }
11506:     if (wantarray) {
11507:         return ($defquota,$settingstatus);
11508:     } else {
11509:         return $defquota;
11510:     }
11511: }
11512: 
11513: ###############################################
11514: 
11515: =pod
11516: 
11517: =item * &excess_filesize_warning()
11518: 
11519: Returns warning message if upload of file to authoring space, or copying
11520: of existing file within authoring space will cause quota for the authoring
11521: space to be exceeded.
11522: 
11523: Same, if upload of a file directly to a course/community via Course Editor
11524: will cause quota for uploaded content for the course to be exceeded.
11525: 
11526: Inputs: 7 
11527: 1. username or coursenum
11528: 2. domain
11529: 3. context ('author' or 'course')
11530: 4. filename of file for which action is being requested
11531: 5. filesize (kB) of file
11532: 6. action being taken: copy or upload.
11533: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
11534: 
11535: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
11536:          otherwise return null.
11537: 
11538: =back
11539: 
11540: =cut
11541: 
11542: sub excess_filesize_warning {
11543:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
11544:     my $current_disk_usage = 0;
11545:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
11546:     if ($context eq 'author') {
11547:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
11548:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
11549:     } else {
11550:         foreach my $subdir ('docs','supplemental') {
11551:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
11552:         }
11553:     }
11554:     $disk_quota = int($disk_quota * 1000);
11555:     if (($current_disk_usage + $filesize) > $disk_quota) {
11556:         return '<p class="LC_warning">'.
11557:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
11558:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
11559:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
11560:                             $disk_quota,$current_disk_usage).
11561:                '</p>';
11562:     }
11563:     return;
11564: }
11565: 
11566: ###############################################
11567: 
11568: 
11569: 
11570: 
11571: sub get_secgrprole_info {
11572:     my ($cdom,$cnum,$needroles,$type)  = @_;
11573:     my %sections_count = &get_sections($cdom,$cnum);
11574:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
11575:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
11576:     my @groups = sort(keys(%curr_groups));
11577:     my $allroles = [];
11578:     my $rolehash;
11579:     my $accesshash = {
11580:                      active => 'Currently has access',
11581:                      future => 'Will have future access',
11582:                      previous => 'Previously had access',
11583:                   };
11584:     if ($needroles) {
11585:         $rolehash = {'all' => 'all'};
11586:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
11587: 	if (&Apache::lonnet::error(%user_roles)) {
11588: 	    undef(%user_roles);
11589: 	}
11590:         foreach my $item (keys(%user_roles)) {
11591:             my ($role)=split(/\:/,$item,2);
11592:             if ($role eq 'cr') { next; }
11593:             if ($role =~ /^cr/) {
11594:                 $$rolehash{$role} = (split('/',$role))[3];
11595:             } else {
11596:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
11597:             }
11598:         }
11599:         foreach my $key (sort(keys(%{$rolehash}))) {
11600:             push(@{$allroles},$key);
11601:         }
11602:         push (@{$allroles},'st');
11603:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
11604:     }
11605:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
11606: }
11607: 
11608: sub user_picker {
11609:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
11610:     my $currdom = $dom;
11611:     my @alldoms = &Apache::lonnet::all_domains();
11612:     if (@alldoms == 1) {
11613:         my %domsrch = &Apache::lonnet::get_dom('configuration',
11614:                                                ['directorysrch'],$alldoms[0]);
11615:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
11616:         my $showdom = $domdesc;
11617:         if ($showdom eq '') {
11618:             $showdom = $dom;
11619:         }
11620:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
11621:             if ((!$domsrch{'directorysrch'}{'available'}) &&
11622:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
11623:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
11624:             }
11625:         }
11626:     }
11627:     my %curr_selected = (
11628:                         srchin => 'dom',
11629:                         srchby => 'lastname',
11630:                       );
11631:     my $srchterm;
11632:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
11633:         if ($srch->{'srchby'} ne '') {
11634:             $curr_selected{'srchby'} = $srch->{'srchby'};
11635:         }
11636:         if ($srch->{'srchin'} ne '') {
11637:             $curr_selected{'srchin'} = $srch->{'srchin'};
11638:         }
11639:         if ($srch->{'srchtype'} ne '') {
11640:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
11641:         }
11642:         if ($srch->{'srchdomain'} ne '') {
11643:             $currdom = $srch->{'srchdomain'};
11644:         }
11645:         $srchterm = $srch->{'srchterm'};
11646:     }
11647:     my %html_lt=&Apache::lonlocal::texthash(
11648:                     'usr'       => 'Search criteria',
11649:                     'doma'      => 'Domain/institution to search',
11650:                     'uname'     => 'username',
11651:                     'lastname'  => 'last name',
11652:                     'lastfirst' => 'last name, first name',
11653:                     'crs'       => 'in this course',
11654:                     'dom'       => 'in selected LON-CAPA domain', 
11655:                     'alc'       => 'all LON-CAPA',
11656:                     'instd'     => 'in institutional directory for selected domain',
11657:                     'exact'     => 'is',
11658:                     'contains'  => 'contains',
11659:                     'begins'    => 'begins with',
11660:                                        );
11661:     my %js_lt=&Apache::lonlocal::texthash(
11662:                     'youm'      => "You must include some text to search for.",
11663:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
11664:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
11665:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
11666:                     'ymcd'      => "You must choose a domain when using a domain search.",
11667:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
11668:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
11669:                      'thfo'     => "The following need to be corrected before the search can be run:",
11670:                                        );
11671:     &html_escape(\%html_lt);
11672:     &js_escape(\%js_lt);
11673:     my $domform;
11674:     my $allow_blank = 1;
11675:     if ($fixeddom) {
11676:         $allow_blank = 0;
11677:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
11678:     } else {
11679:         my $defdom = $env{'request.role.domain'};
11680:         my ($trusted,$untrusted);
11681:         if (($context eq 'requestcrs') || ($context eq 'course')) {
11682:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
11683:         } elsif ($context eq 'author') {
11684:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
11685:         } elsif ($context eq 'domain') {
11686:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
11687:         }
11688:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
11689:     }
11690:     my $srchinsel = ' <select name="srchin">';
11691: 
11692:     my @srchins = ('crs','dom','alc','instd');
11693: 
11694:     foreach my $option (@srchins) {
11695:         # FIXME 'alc' option unavailable until 
11696:         #       loncreateuser::print_user_query_page()
11697:         #       has been completed.
11698:         next if ($option eq 'alc');
11699:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
11700:         next if ($option eq 'crs' && !$env{'request.course.id'});
11701:         next if (($option eq 'instd') && ($noinstd));
11702:         if ($curr_selected{'srchin'} eq $option) {
11703:             $srchinsel .= ' 
11704:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
11705:         } else {
11706:             $srchinsel .= '
11707:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
11708:         }
11709:     }
11710:     $srchinsel .= "\n  </select>\n";
11711: 
11712:     my $srchbysel =  ' <select name="srchby">';
11713:     foreach my $option ('lastname','lastfirst','uname') {
11714:         if ($curr_selected{'srchby'} eq $option) {
11715:             $srchbysel .= '
11716:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
11717:         } else {
11718:             $srchbysel .= '
11719:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
11720:          }
11721:     }
11722:     $srchbysel .= "\n  </select>\n";
11723: 
11724:     my $srchtypesel = ' <select name="srchtype">';
11725:     foreach my $option ('begins','contains','exact') {
11726:         if ($curr_selected{'srchtype'} eq $option) {
11727:             $srchtypesel .= '
11728:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
11729:         } else {
11730:             $srchtypesel .= '
11731:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
11732:         }
11733:     }
11734:     $srchtypesel .= "\n  </select>\n";
11735: 
11736:     my ($newuserscript,$new_user_create);
11737:     my $context_dom = $env{'request.role.domain'};
11738:     if ($context eq 'requestcrs') {
11739:         if ($env{'form.coursedom'} ne '') { 
11740:             $context_dom = $env{'form.coursedom'};
11741:         }
11742:     }
11743:     if ($forcenewuser) {
11744:         if (ref($srch) eq 'HASH') {
11745:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
11746:                 if ($cancreate) {
11747:                     $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>';
11748:                 } else {
11749:                     my $helplink = 'javascript:helpMenu('."'display'".')';
11750:                     my %usertypetext = (
11751:                         official   => 'institutional',
11752:                         unofficial => 'non-institutional',
11753:                     );
11754:                     $new_user_create = '<p class="LC_warning">'
11755:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
11756:                                       .' '
11757:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
11758:                                           ,'<a href="'.$helplink.'">','</a>')
11759:                                       .'</p><br />';
11760:                 }
11761:             }
11762:         }
11763: 
11764:         $newuserscript = <<"ENDSCRIPT";
11765: 
11766: function setSearch(createnew,callingForm) {
11767:     if (createnew == 1) {
11768:         for (var i=0; i<callingForm.srchby.length; i++) {
11769:             if (callingForm.srchby.options[i].value == 'uname') {
11770:                 callingForm.srchby.selectedIndex = i;
11771:             }
11772:         }
11773:         for (var i=0; i<callingForm.srchin.length; i++) {
11774:             if ( callingForm.srchin.options[i].value == 'dom') {
11775: 		callingForm.srchin.selectedIndex = i;
11776:             }
11777:         }
11778:         for (var i=0; i<callingForm.srchtype.length; i++) {
11779:             if (callingForm.srchtype.options[i].value == 'exact') {
11780:                 callingForm.srchtype.selectedIndex = i;
11781:             }
11782:         }
11783:         for (var i=0; i<callingForm.srchdomain.length; i++) {
11784:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
11785:                 callingForm.srchdomain.selectedIndex = i;
11786:             }
11787:         }
11788:     }
11789: }
11790: ENDSCRIPT
11791: 
11792:     }
11793: 
11794:     my $output = <<"END_BLOCK";
11795: <script type="text/javascript">
11796: // <![CDATA[
11797: function validateEntry(callingForm) {
11798: 
11799:     var checkok = 1;
11800:     var srchin;
11801:     for (var i=0; i<callingForm.srchin.length; i++) {
11802: 	if ( callingForm.srchin[i].checked ) {
11803: 	    srchin = callingForm.srchin[i].value;
11804: 	}
11805:     }
11806: 
11807:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
11808:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
11809:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
11810:     var srchterm =  callingForm.srchterm.value;
11811:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
11812:     var msg = "";
11813: 
11814:     if (srchterm == "") {
11815:         checkok = 0;
11816:         msg += "$js_lt{'youm'}\\n";
11817:     }
11818: 
11819:     if (srchtype== 'begins') {
11820:         if (srchterm.length < 2) {
11821:             checkok = 0;
11822:             msg += "$js_lt{'thte'}\\n";
11823:         }
11824:     }
11825: 
11826:     if (srchtype== 'contains') {
11827:         if (srchterm.length < 3) {
11828:             checkok = 0;
11829:             msg += "$js_lt{'thet'}\\n";
11830:         }
11831:     }
11832:     if (srchin == 'instd') {
11833:         if (srchdomain == '') {
11834:             checkok = 0;
11835:             msg += "$js_lt{'yomc'}\\n";
11836:         }
11837:     }
11838:     if (srchin == 'dom') {
11839:         if (srchdomain == '') {
11840:             checkok = 0;
11841:             msg += "$js_lt{'ymcd'}\\n";
11842:         }
11843:     }
11844:     if (srchby == 'lastfirst') {
11845:         if (srchterm.indexOf(",") == -1) {
11846:             checkok = 0;
11847:             msg += "$js_lt{'whus'}\\n";
11848:         }
11849:         if (srchterm.indexOf(",") == srchterm.length -1) {
11850:             checkok = 0;
11851:             msg += "$js_lt{'whse'}\\n";
11852:         }
11853:     }
11854:     if (checkok == 0) {
11855:         alert("$js_lt{'thfo'}\\n"+msg);
11856:         return;
11857:     }
11858:     if (checkok == 1) {
11859:         callingForm.submit();
11860:     }
11861: }
11862: 
11863: $newuserscript
11864: 
11865: // ]]>
11866: </script>
11867: 
11868: $new_user_create
11869: 
11870: END_BLOCK
11871: 
11872:     $output .= &Apache::lonhtmlcommon::start_pick_box().
11873:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
11874:                $domform.
11875:                &Apache::lonhtmlcommon::row_closure().
11876:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
11877:                $srchbysel.
11878:                $srchtypesel. 
11879:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
11880:                $srchinsel.
11881:                &Apache::lonhtmlcommon::row_closure(1). 
11882:                &Apache::lonhtmlcommon::end_pick_box().
11883:                '<br />';
11884:     return ($output,1);
11885: }
11886: 
11887: sub user_rule_check {
11888:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
11889:     my ($response,%inst_response);
11890:     if (ref($usershash) eq 'HASH') {
11891:         if (keys(%{$usershash}) > 1) {
11892:             my (%by_username,%by_id,%userdoms);
11893:             my $checkid; 
11894:             if (ref($checks) eq 'HASH') {
11895:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
11896:                     $checkid = 1;
11897:                 }
11898:             }
11899:             foreach my $user (keys(%{$usershash})) {
11900:                 my ($uname,$udom) = split(/:/,$user);
11901:                 if ($checkid) {
11902:                     if (ref($usershash->{$user}) eq 'HASH') {
11903:                         if ($usershash->{$user}->{'id'} ne '') {
11904:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
11905:                             $userdoms{$udom} = 1;
11906:                             if (ref($inst_results) eq 'HASH') {
11907:                                 $inst_results->{$uname.':'.$udom} = {};
11908:                             }
11909:                         }
11910:                     }
11911:                 } else {
11912:                     $by_username{$udom}{$uname} = 1;
11913:                     $userdoms{$udom} = 1;
11914:                     if (ref($inst_results) eq 'HASH') {
11915:                         $inst_results->{$uname.':'.$udom} = {};
11916:                     }
11917:                 }
11918:             }
11919:             foreach my $udom (keys(%userdoms)) {
11920:                 if (!$got_rules->{$udom}) {
11921:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
11922:                                                              ['usercreation'],$udom);
11923:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
11924:                         foreach my $item ('username','id') {
11925:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
11926:                                 $$curr_rules{$udom}{$item} =
11927:                                     $domconfig{'usercreation'}{$item.'_rule'};
11928:                             }
11929:                         }
11930:                     }
11931:                     $got_rules->{$udom} = 1;
11932:                 }
11933:             }
11934:             if ($checkid) {
11935:                 foreach my $udom (keys(%by_id)) {
11936:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
11937:                     if ($outcome eq 'ok') {
11938:                         foreach my $id (keys(%{$by_id{$udom}})) {
11939:                             my $uname = $by_id{$udom}{$id};
11940:                             $inst_response{$uname.':'.$udom} = $outcome;
11941:                         }
11942:                         if (ref($results) eq 'HASH') {
11943:                             foreach my $uname (keys(%{$results})) {
11944:                                 if (exists($inst_response{$uname.':'.$udom})) {
11945:                                     $inst_response{$uname.':'.$udom} = $outcome;
11946:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
11947:                                 }
11948:                             }
11949:                         }
11950:                     }
11951:                 }
11952:             } else {
11953:                 foreach my $udom (keys(%by_username)) {
11954:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
11955:                     if ($outcome eq 'ok') {
11956:                         foreach my $uname (keys(%{$by_username{$udom}})) {
11957:                             $inst_response{$uname.':'.$udom} = $outcome;
11958:                         }
11959:                         if (ref($results) eq 'HASH') {
11960:                             foreach my $uname (keys(%{$results})) {
11961:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
11962:                             }
11963:                         }
11964:                     }
11965:                 }
11966:             }
11967:         } elsif (keys(%{$usershash}) == 1) {
11968:             my $user = (keys(%{$usershash}))[0];
11969:             my ($uname,$udom) = split(/:/,$user);
11970:             if (($udom ne '') && ($uname ne '')) {
11971:                 if (ref($usershash->{$user}) eq 'HASH') {
11972:                     if (ref($checks) eq 'HASH') {
11973:                         if (defined($checks->{'username'})) {
11974:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
11975:                                 &Apache::lonnet::get_instuser($udom,$uname);
11976:                         } elsif (defined($checks->{'id'})) {
11977:                             if ($usershash->{$user}->{'id'} ne '') {
11978:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
11979:                                     &Apache::lonnet::get_instuser($udom,undef,
11980:                                                                   $usershash->{$user}->{'id'});
11981:                             } else {
11982:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
11983:                                     &Apache::lonnet::get_instuser($udom,$uname);
11984:                             }
11985:                         }
11986:                     } else {
11987:                        ($inst_response{$user},%{$inst_results->{$user}}) =
11988:                             &Apache::lonnet::get_instuser($udom,$uname);
11989:                        return;
11990:                     }
11991:                     if (!$got_rules->{$udom}) {
11992:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
11993:                                                                  ['usercreation'],$udom);
11994:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
11995:                             foreach my $item ('username','id') {
11996:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
11997:                                    $$curr_rules{$udom}{$item} = 
11998:                                        $domconfig{'usercreation'}{$item.'_rule'};
11999:                                 }
12000:                             }
12001:                         }
12002:                         $got_rules->{$udom} = 1;
12003:                     }
12004:                 }
12005:             } else {
12006:                 return;
12007:             }
12008:         } else {
12009:             return;
12010:         }
12011:         foreach my $user (keys(%{$usershash})) {
12012:             my ($uname,$udom) = split(/:/,$user);
12013:             next if (($udom eq '') || ($uname eq ''));
12014:             my $id;
12015:             if (ref($inst_results) eq 'HASH') {
12016:                 if (ref($inst_results->{$user}) eq 'HASH') {
12017:                     $id = $inst_results->{$user}->{'id'};
12018:                 }
12019:             }
12020:             if ($id eq '') { 
12021:                 if (ref($usershash->{$user})) {
12022:                     $id = $usershash->{$user}->{'id'};
12023:                 }
12024:             }
12025:             foreach my $item (keys(%{$checks})) {
12026:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
12027:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
12028:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
12029:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
12030:                                                                              $$curr_rules{$udom}{$item});
12031:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
12032:                                 if ($rule_check{$rule}) {
12033:                                     $$rulematch{$user}{$item} = $rule;
12034:                                     if ($inst_response{$user} eq 'ok') {
12035:                                         if (ref($inst_results) eq 'HASH') {
12036:                                             if (ref($inst_results->{$user}) eq 'HASH') {
12037:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
12038:                                                     $$alerts{$item}{$udom}{$uname} = 1;
12039:                                                 } elsif ($item eq 'id') {
12040:                                                     if ($inst_results->{$user}->{'id'} eq '') {
12041:                                                         $$alerts{$item}{$udom}{$uname} = 1;
12042:                                                     }
12043:                                                 }
12044:                                             }
12045:                                         }
12046:                                     }
12047:                                     last;
12048:                                 }
12049:                             }
12050:                         }
12051:                     }
12052:                 }
12053:             }
12054:         }
12055:     }
12056:     return;
12057: }
12058: 
12059: sub user_rule_formats {
12060:     my ($domain,$domdesc,$curr_rules,$check) = @_;
12061:     my %text = ( 
12062:                  'username' => 'Usernames',
12063:                  'id'       => 'IDs',
12064:                );
12065:     my $output;
12066:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
12067:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
12068:         if (@{$ruleorder} > 0) {
12069:             $output = '<br />'.
12070:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
12071:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
12072:                       ' <ul>';
12073:             foreach my $rule (@{$ruleorder}) {
12074:                 if (ref($curr_rules) eq 'ARRAY') {
12075:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
12076:                         if (ref($rules->{$rule}) eq 'HASH') {
12077:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
12078:                                         $rules->{$rule}{'desc'}.'</li>';
12079:                         }
12080:                     }
12081:                 }
12082:             }
12083:             $output .= '</ul>';
12084:         }
12085:     }
12086:     return $output;
12087: }
12088: 
12089: sub instrule_disallow_msg {
12090:     my ($checkitem,$domdesc,$count,$mode) = @_;
12091:     my $response;
12092:     my %text = (
12093:                   item   => 'username',
12094:                   items  => 'usernames',
12095:                   match  => 'matches',
12096:                   do     => 'does',
12097:                   action => 'a username',
12098:                   one    => 'one',
12099:                );
12100:     if ($count > 1) {
12101:         $text{'item'} = 'usernames';
12102:         $text{'match'} ='match';
12103:         $text{'do'} = 'do';
12104:         $text{'action'} = 'usernames',
12105:         $text{'one'} = 'ones';
12106:     }
12107:     if ($checkitem eq 'id') {
12108:         $text{'items'} = 'IDs';
12109:         $text{'item'} = 'ID';
12110:         $text{'action'} = 'an ID';
12111:         if ($count > 1) {
12112:             $text{'item'} = 'IDs';
12113:             $text{'action'} = 'IDs';
12114:         }
12115:     }
12116:     $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 />';
12117:     if ($mode eq 'upload') {
12118:         if ($checkitem eq 'username') {
12119:             $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'}.");
12120:         } elsif ($checkitem eq 'id') {
12121:             $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.");
12122:         }
12123:     } elsif ($mode eq 'selfcreate') {
12124:         if ($checkitem eq 'id') {
12125:             $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.");
12126:         }
12127:     } else {
12128:         if ($checkitem eq 'username') {
12129:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
12130:         } elsif ($checkitem eq 'id') {
12131:             $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.");
12132:         }
12133:     }
12134:     return $response;
12135: }
12136: 
12137: sub personal_data_fieldtitles {
12138:     my %fieldtitles = &Apache::lonlocal::texthash (
12139:                         id => 'Student/Employee ID',
12140:                         permanentemail => 'E-mail address',
12141:                         lastname => 'Last Name',
12142:                         firstname => 'First Name',
12143:                         middlename => 'Middle Name',
12144:                         generation => 'Generation',
12145:                         gen => 'Generation',
12146:                         inststatus => 'Affiliation',
12147:                    );
12148:     return %fieldtitles;
12149: }
12150: 
12151: sub sorted_inst_types {
12152:     my ($dom) = @_;
12153:     my ($usertypes,$order);
12154:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
12155:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
12156:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
12157:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
12158:     } else {
12159:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
12160:     }
12161:     my $othertitle = &mt('All users');
12162:     if ($env{'request.course.id'}) {
12163:         $othertitle  = &mt('Any users');
12164:     }
12165:     my @types;
12166:     if (ref($order) eq 'ARRAY') {
12167:         @types = @{$order};
12168:     }
12169:     if (@types == 0) {
12170:         if (ref($usertypes) eq 'HASH') {
12171:             @types = sort(keys(%{$usertypes}));
12172:         }
12173:     }
12174:     if (keys(%{$usertypes}) > 0) {
12175:         $othertitle = &mt('Other users');
12176:     }
12177:     return ($othertitle,$usertypes,\@types);
12178: }
12179: 
12180: sub get_institutional_codes {
12181:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
12182: # Get complete list of course sections to update
12183:     my @currsections = ();
12184:     my @currxlists = ();
12185:     my (%unclutteredsec,%unclutteredlcsec);
12186:     my $coursecode = $$settings{'internal.coursecode'};
12187:     my $crskey = $crs.':'.$coursecode;
12188:     @{$unclutteredsec{$crskey}} = ();
12189:     @{$unclutteredlcsec{$crskey}} = ();
12190: 
12191:     if ($$settings{'internal.sectionnums'} ne '') {
12192:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
12193:     }
12194: 
12195:     if ($$settings{'internal.crosslistings'} ne '') {
12196:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
12197:     }
12198: 
12199:     if (@currxlists > 0) {
12200:         foreach my $xl (@currxlists) {
12201:             if ($xl =~ /^([^:]+):(\w*)$/) {
12202:                 unless (grep/^$1$/,@{$allcourses}) {
12203:                     push(@{$allcourses},$1);
12204:                     $$LC_code{$1} = $2;
12205:                 }
12206:             }
12207:         }
12208:     }
12209: 
12210:     if (@currsections > 0) {
12211:         foreach my $sec (@currsections) {
12212:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
12213:                 my $instsec = $1;
12214:                 my $lc_sec = $2;
12215:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
12216:                     push(@{$unclutteredsec{$crskey}},$instsec);
12217:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
12218:                 }
12219:             }
12220:         }
12221:     }
12222: 
12223:     if (@{$unclutteredsec{$crskey}} > 0) {
12224:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
12225:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
12226:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
12227:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
12228:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
12229:                     push(@{$allcourses},$sec);
12230:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
12231:                 }
12232:             }
12233:         }
12234:     }
12235:     return;
12236: }
12237: 
12238: sub get_standard_codeitems {
12239:     return ('Year','Semester','Department','Number','Section');
12240: }
12241: 
12242: =pod
12243: 
12244: =head1 Slot Helpers
12245: 
12246: =over 4
12247: 
12248: =item * sorted_slots()
12249: 
12250: Sorts an array of slot names in order of an optional sort key,
12251: default sort is by slot start time (earliest first). 
12252: 
12253: Inputs:
12254: 
12255: =over 4
12256: 
12257: slotsarr  - Reference to array of unsorted slot names.
12258: 
12259: slots     - Reference to hash of hash, where outer hash keys are slot names.
12260: 
12261: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
12262: 
12263: =back
12264: 
12265: Returns:
12266: 
12267: =over 4
12268: 
12269: sorted   - An array of slot names sorted by a specified sort key 
12270:            (default sort key is start time of the slot).
12271: 
12272: =back
12273: 
12274: =cut
12275: 
12276: 
12277: sub sorted_slots {
12278:     my ($slotsarr,$slots,$sortkey) = @_;
12279:     if ($sortkey eq '') {
12280:         $sortkey = 'starttime';
12281:     }
12282:     my @sorted;
12283:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
12284:         @sorted =
12285:             sort {
12286:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
12287:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
12288:                      }
12289:                      if (ref($slots->{$a})) { return -1;}
12290:                      if (ref($slots->{$b})) { return 1;}
12291:                      return 0;
12292:                  } @{$slotsarr};
12293:     }
12294:     return @sorted;
12295: }
12296: 
12297: =pod
12298: 
12299: =item * get_future_slots()
12300: 
12301: Inputs:
12302: 
12303: =over 4
12304: 
12305: cnum - course number
12306: 
12307: cdom - course domain
12308: 
12309: now - current UNIX time
12310: 
12311: symb - optional symb
12312: 
12313: =back
12314: 
12315: Returns:
12316: 
12317: =over 4
12318: 
12319: sorted_reservable - ref to array of student_schedulable slots currently 
12320:                     reservable, ordered by end date of reservation period.
12321: 
12322: reservable_now - ref to hash of student_schedulable slots currently
12323:                  reservable.
12324: 
12325:     Keys in inner hash are:
12326:     (a) symb: either blank or symb to which slot use is restricted.
12327:     (b) endreserve: end date of reservation period.
12328:     (c) uniqueperiod: start,end dates when slot is to be uniquely
12329:         selected.
12330: 
12331: sorted_future - ref to array of student_schedulable slots reservable in
12332:                 the future, ordered by start date of reservation period.
12333: 
12334: future_reservable - ref to hash of student_schedulable slots reservable
12335:                     in the future.
12336: 
12337:     Keys in inner hash are:
12338:     (a) symb: either blank or symb to which slot use is restricted.
12339:     (b) startreserve: start date of reservation period.
12340:     (c) uniqueperiod: start,end dates when slot is to be uniquely
12341:         selected.
12342: 
12343: =back
12344: 
12345: =cut
12346: 
12347: sub get_future_slots {
12348:     my ($cnum,$cdom,$now,$symb) = @_;
12349:     my $map;
12350:     if ($symb) {
12351:         ($map) = &Apache::lonnet::decode_symb($symb);
12352:     }
12353:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
12354:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
12355:     foreach my $slot (keys(%slots)) {
12356:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
12357:         if ($symb) {
12358:             if ($slots{$slot}->{'symb'} ne '') {
12359:                 my $canuse;
12360:                 my %oksymbs;
12361:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
12362:                 map { $oksymbs{$_} = 1; } @slotsymbs;
12363:                 if ($oksymbs{$symb}) {
12364:                     $canuse = 1;
12365:                 } else {
12366:                     foreach my $item (@slotsymbs) {
12367:                         if ($item =~ /\.(page|sequence)$/) {
12368:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
12369:                             if (($map ne '') && ($map eq $sloturl)) {
12370:                                 $canuse = 1;
12371:                                 last;
12372:                             }
12373:                         }
12374:                     }
12375:                 }
12376:                 next unless ($canuse);
12377:             }
12378:         }
12379:         if (($slots{$slot}->{'starttime'} > $now) &&
12380:             ($slots{$slot}->{'endtime'} > $now)) {
12381:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
12382:                 my $userallowed = 0;
12383:                 if ($slots{$slot}->{'allowedsections'}) {
12384:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
12385:                     if (!defined($env{'request.role.sec'})
12386:                         && grep(/^No section assigned$/,@allowed_sec)) {
12387:                         $userallowed=1;
12388:                     } else {
12389:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
12390:                             $userallowed=1;
12391:                         }
12392:                     }
12393:                     unless ($userallowed) {
12394:                         if (defined($env{'request.course.groups'})) {
12395:                             my @groups = split(/:/,$env{'request.course.groups'});
12396:                             foreach my $group (@groups) {
12397:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
12398:                                     $userallowed=1;
12399:                                     last;
12400:                                 }
12401:                             }
12402:                         }
12403:                     }
12404:                 }
12405:                 if ($slots{$slot}->{'allowedusers'}) {
12406:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
12407:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
12408:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
12409:                         $userallowed = 1;
12410:                     }
12411:                 }
12412:                 next unless($userallowed);
12413:             }
12414:             my $startreserve = $slots{$slot}->{'startreserve'};
12415:             my $endreserve = $slots{$slot}->{'endreserve'};
12416:             my $symb = $slots{$slot}->{'symb'};
12417:             my $uniqueperiod;
12418:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
12419:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
12420:             }
12421:             if (($startreserve < $now) &&
12422:                 (!$endreserve || $endreserve > $now)) {
12423:                 my $lastres = $endreserve;
12424:                 if (!$lastres) {
12425:                     $lastres = $slots{$slot}->{'starttime'};
12426:                 }
12427:                 $reservable_now{$slot} = {
12428:                                            symb       => $symb,
12429:                                            endreserve => $lastres,
12430:                                            uniqueperiod => $uniqueperiod,
12431:                                          };
12432:             } elsif (($startreserve > $now) &&
12433:                      (!$endreserve || $endreserve > $startreserve)) {
12434:                 $future_reservable{$slot} = {
12435:                                               symb         => $symb,
12436:                                               startreserve => $startreserve,
12437:                                               uniqueperiod => $uniqueperiod,
12438:                                             };
12439:             }
12440:         }
12441:     }
12442:     my @unsorted_reservable = keys(%reservable_now);
12443:     if (@unsorted_reservable > 0) {
12444:         @sorted_reservable = 
12445:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
12446:     }
12447:     my @unsorted_future = keys(%future_reservable);
12448:     if (@unsorted_future > 0) {
12449:         @sorted_future =
12450:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
12451:     }
12452:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
12453: }
12454: 
12455: =pod
12456: 
12457: =back
12458: 
12459: =head1 HTTP Helpers
12460: 
12461: =over 4
12462: 
12463: =item * &get_unprocessed_cgi($query,$possible_names)
12464: 
12465: Modify the %env hash to contain unprocessed CGI form parameters held in
12466: $query.  The parameters listed in $possible_names (an array reference),
12467: will be set in $env{'form.name'} if they do not already exist.
12468: 
12469: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
12470: $possible_names is an ref to an array of form element names.  As an example:
12471: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
12472: will result in $env{'form.uname'} and $env{'form.udom'} being set.
12473: 
12474: =cut
12475: 
12476: sub get_unprocessed_cgi {
12477:   my ($query,$possible_names)= @_;
12478:   # $Apache::lonxml::debug=1;
12479:   foreach my $pair (split(/&/,$query)) {
12480:     my ($name, $value) = split(/=/,$pair);
12481:     $name = &unescape($name);
12482:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
12483:       $value =~ tr/+/ /;
12484:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
12485:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
12486:     }
12487:   }
12488: }
12489: 
12490: =pod
12491: 
12492: =item * &cacheheader() 
12493: 
12494: returns cache-controlling header code
12495: 
12496: =cut
12497: 
12498: sub cacheheader {
12499:     unless ($env{'request.method'} eq 'GET') { return ''; }
12500:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
12501:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
12502:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
12503:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
12504:     return $output;
12505: }
12506: 
12507: =pod
12508: 
12509: =item * &no_cache($r) 
12510: 
12511: specifies header code to not have cache
12512: 
12513: =cut
12514: 
12515: sub no_cache {
12516:     my ($r) = @_;
12517:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
12518: 	$env{'request.method'} ne 'GET') { return ''; }
12519:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
12520:     $r->no_cache(1);
12521:     $r->header_out("Expires" => $date);
12522:     $r->header_out("Pragma" => "no-cache");
12523: }
12524: 
12525: sub content_type {
12526:     my ($r,$type,$charset) = @_;
12527:     if ($r) {
12528: 	#  Note that printout.pl calls this with undef for $r.
12529: 	&no_cache($r);
12530:     }
12531:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
12532:     unless ($charset) {
12533: 	$charset=&Apache::lonlocal::current_encoding;
12534:     }
12535:     if ($charset) { $type.='; charset='.$charset; }
12536:     if ($r) {
12537: 	$r->content_type($type);
12538:     } else {
12539: 	print("Content-type: $type\n\n");
12540:     }
12541: }
12542: 
12543: =pod
12544: 
12545: =item * &add_to_env($name,$value) 
12546: 
12547: adds $name to the %env hash with value
12548: $value, if $name already exists, the entry is converted to an array
12549: reference and $value is added to the array.
12550: 
12551: =cut
12552: 
12553: sub add_to_env {
12554:   my ($name,$value)=@_;
12555:   if (defined($env{$name})) {
12556:     if (ref($env{$name})) {
12557:       #already have multiple values
12558:       push(@{ $env{$name} },$value);
12559:     } else {
12560:       #first time seeing multiple values, convert hash entry to an arrayref
12561:       my $first=$env{$name};
12562:       undef($env{$name});
12563:       push(@{ $env{$name} },$first,$value);
12564:     }
12565:   } else {
12566:     $env{$name}=$value;
12567:   }
12568: }
12569: 
12570: =pod
12571: 
12572: =item * &get_env_multiple($name) 
12573: 
12574: gets $name from the %env hash, it seemlessly handles the cases where multiple
12575: values may be defined and end up as an array ref.
12576: 
12577: returns an array of values
12578: 
12579: =cut
12580: 
12581: sub get_env_multiple {
12582:     my ($name) = @_;
12583:     my @values;
12584:     if (defined($env{$name})) {
12585:         # exists is it an array
12586:         if (ref($env{$name})) {
12587:             @values=@{ $env{$name} };
12588:         } else {
12589:             $values[0]=$env{$name};
12590:         }
12591:     }
12592:     return(@values);
12593: }
12594: 
12595: # Looks at given dependencies, and returns something depending on the context.
12596: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
12597: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
12598: # For all other contexts, returns ($output, $counter, $numpathchg).
12599: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
12600: # $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.
12601: # $numpathchg: integer with the number of cleaned up dependency paths.
12602: # \%existing: hash reference clean path -> 1 only for existing dependencies.
12603: # \%mapping: hash reference clean path -> original path for all dependencies.
12604: # @param {string} actionurl - The path to the handler, indicative of the context.
12605: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
12606: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
12607: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
12608: # @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)
12609: # @return {Array} - array depending on the context (not a reference)
12610: sub ask_for_embedded_content {
12611:     # NOTE: documentation was added afterwards, it could be wrong
12612:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
12613:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
12614:         %currsubfile,%unused,$rem);
12615:     my $counter = 0;
12616:     my $numnew = 0;
12617:     my $numremref = 0;
12618:     my $numinvalid = 0;
12619:     my $numpathchg = 0;
12620:     my $numexisting = 0;
12621:     my $numunused = 0;
12622:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
12623:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
12624:     my $heading = &mt('Upload embedded files');
12625:     my $buttontext = &mt('Upload');
12626: 
12627:     # fills these variables based on the context:
12628:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
12629:     # $path, $fileloc, $title, $rem, $filename
12630:     if ($env{'request.course.id'}) {
12631:         if ($actionurl eq '/adm/dependencies') {
12632:             $navmap = Apache::lonnavmaps::navmap->new();
12633:         }
12634:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12635:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12636:     }
12637:     if (($actionurl eq '/adm/portfolio') || 
12638:         ($actionurl eq '/adm/coursegrp_portfolio')) {
12639:         my $current_path='/';
12640:         if ($env{'form.currentpath'}) {
12641:             $current_path = $env{'form.currentpath'};
12642:         }
12643:         if ($actionurl eq '/adm/coursegrp_portfolio') {
12644:             $udom = $cdom;
12645:             $uname = $cnum;
12646:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
12647:         } else {
12648:             $udom = $env{'user.domain'};
12649:             $uname = $env{'user.name'};
12650:             $url = '/userfiles/portfolio';
12651:         }
12652:         $toplevel = $url.'/';
12653:         $url .= $current_path;
12654:         $getpropath = 1;
12655:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
12656:              ($actionurl eq '/adm/imsimport')) { 
12657:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
12658:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
12659:         $toplevel = $url;
12660:         if ($rest ne '') {
12661:             $url .= $rest;
12662:         }
12663:     } elsif ($actionurl eq '/adm/coursedocs') {
12664:         if (ref($args) eq 'HASH') {
12665:             $url = $args->{'docs_url'};
12666:             $toplevel = $url;
12667:             if ($args->{'context'} eq 'paste') {
12668:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
12669:                 ($path) = 
12670:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
12671:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
12672:                 $fileloc =~ s{^/}{};
12673:             }
12674:         }
12675:     } elsif ($actionurl eq '/adm/dependencies')  {
12676:         if ($env{'request.course.id'} ne '') {
12677:             if (ref($args) eq 'HASH') {
12678:                 $url = $args->{'docs_url'};
12679:                 $title = $args->{'docs_title'};
12680:                 $toplevel = $url; 
12681:                 unless ($toplevel =~ m{^/}) {
12682:                     $toplevel = "/$url";
12683:                 }
12684:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
12685:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
12686:                     $path = $1;
12687:                 } else {
12688:                     ($path) =
12689:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
12690:                 }
12691:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
12692:                     $fileloc = $toplevel;
12693:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
12694:                     my ($udom,$uname,$fname) =
12695:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
12696:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
12697:                 } else {
12698:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
12699:                 }
12700:                 $fileloc =~ s{^/}{};
12701:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
12702:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
12703:             }
12704:         }
12705:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
12706:         $udom = $cdom;
12707:         $uname = $cnum;
12708:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
12709:         $toplevel = $url;
12710:         $path = $url;
12711:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
12712:         $fileloc =~ s{^/}{};
12713:     }
12714:     
12715:     # parses the dependency paths to get some info
12716:     # fills $newfiles, $mapping, $subdependencies, $dependencies
12717:     # $newfiles: hash URL -> 1 for new files or external URLs
12718:     # (will be completed later)
12719:     # $mapping:
12720:     #   for external URLs: external URL -> external URL
12721:     #   for relative paths: clean path -> original path
12722:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
12723:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
12724:     foreach my $file (keys(%{$allfiles})) {
12725:         my $embed_file;
12726:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
12727:             $embed_file = $1;
12728:         } else {
12729:             $embed_file = $file;
12730:         }
12731:         my ($absolutepath,$cleaned_file);
12732:         if ($embed_file =~ m{^\w+://}) {
12733:             $cleaned_file = $embed_file;
12734:             $newfiles{$cleaned_file} = 1;
12735:             $mapping{$cleaned_file} = $embed_file;
12736:         } else {
12737:             $cleaned_file = &clean_path($embed_file);
12738:             if ($embed_file =~ m{^/}) {
12739:                 $absolutepath = $embed_file;
12740:             }
12741:             if ($cleaned_file =~ m{/}) {
12742:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
12743:                 $path = &check_for_traversal($path,$url,$toplevel);
12744:                 my $item = $fname;
12745:                 if ($path ne '') {
12746:                     $item = $path.'/'.$fname;
12747:                     $subdependencies{$path}{$fname} = 1;
12748:                 } else {
12749:                     $dependencies{$item} = 1;
12750:                 }
12751:                 if ($absolutepath) {
12752:                     $mapping{$item} = $absolutepath;
12753:                 } else {
12754:                     $mapping{$item} = $embed_file;
12755:                 }
12756:             } else {
12757:                 $dependencies{$embed_file} = 1;
12758:                 if ($absolutepath) {
12759:                     $mapping{$cleaned_file} = $absolutepath;
12760:                 } else {
12761:                     $mapping{$cleaned_file} = $embed_file;
12762:                 }
12763:             }
12764:         }
12765:     }
12766:     
12767:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
12768:     # and lists
12769:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
12770:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
12771:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
12772:     #                                    the path had to be cleaned up
12773:     # $existing: hash clean path -> 1 if the file exists
12774:     # $numexisting: number of keys in $existing
12775:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
12776:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
12777:     #                                      dependency subdirectories that are
12778:     #                                      not listed as dependencies, with some exceptions using $rem
12779:     my $dirptr = 16384;
12780:     foreach my $path (keys(%subdependencies)) {
12781:         $currsubfile{$path} = {};
12782:         if (($actionurl eq '/adm/portfolio') || 
12783:             ($actionurl eq '/adm/coursegrp_portfolio')) {
12784:             my ($sublistref,$listerror) =
12785:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
12786:             if (ref($sublistref) eq 'ARRAY') {
12787:                 foreach my $line (@{$sublistref}) {
12788:                     my ($file_name,$rest) = split(/\&/,$line,2);
12789:                     $currsubfile{$path}{$file_name} = 1;
12790:                 }
12791:             }
12792:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12793:             if (opendir(my $dir,$url.'/'.$path)) {
12794:                 my @subdir_list = grep(!/^\./,readdir($dir));
12795:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
12796:             }
12797:         } elsif (($actionurl eq '/adm/dependencies') ||
12798:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
12799:                   ($args->{'context'} eq 'paste')) ||
12800:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
12801:             if ($env{'request.course.id'} ne '') {
12802:                 my $dir;
12803:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
12804:                     $dir = $fileloc;
12805:                 } else {
12806:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
12807:                 }
12808:                 if ($dir ne '') {
12809:                     my ($sublistref,$listerror) =
12810:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
12811:                     if (ref($sublistref) eq 'ARRAY') {
12812:                         foreach my $line (@{$sublistref}) {
12813:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
12814:                                 undef,$mtime)=split(/\&/,$line,12);
12815:                             unless (($testdir&$dirptr) ||
12816:                                     ($file_name =~ /^\.\.?$/)) {
12817:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
12818:                             }
12819:                         }
12820:                     }
12821:                 }
12822:             }
12823:         }
12824:         foreach my $file (keys(%{$subdependencies{$path}})) {
12825:             if (exists($currsubfile{$path}{$file})) {
12826:                 my $item = $path.'/'.$file;
12827:                 unless ($mapping{$item} eq $item) {
12828:                     $pathchanges{$item} = 1;
12829:                 }
12830:                 $existing{$item} = 1;
12831:                 $numexisting ++;
12832:             } else {
12833:                 $newfiles{$path.'/'.$file} = 1;
12834:             }
12835:         }
12836:         if ($actionurl eq '/adm/dependencies') {
12837:             foreach my $path (keys(%currsubfile)) {
12838:                 if (ref($currsubfile{$path}) eq 'HASH') {
12839:                     foreach my $file (keys(%{$currsubfile{$path}})) {
12840:                          unless ($subdependencies{$path}{$file}) {
12841:                              next if (($rem ne '') &&
12842:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
12843:                                        (ref($navmap) &&
12844:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
12845:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
12846:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
12847:                              $unused{$path.'/'.$file} = 1; 
12848:                          }
12849:                     }
12850:                 }
12851:             }
12852:         }
12853:     }
12854:     
12855:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
12856:     # for files in $url or $fileloc (target directory) in some contexts
12857:     my %currfile;
12858:     if (($actionurl eq '/adm/portfolio') ||
12859:         ($actionurl eq '/adm/coursegrp_portfolio')) {
12860:         my ($dirlistref,$listerror) =
12861:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
12862:         if (ref($dirlistref) eq 'ARRAY') {
12863:             foreach my $line (@{$dirlistref}) {
12864:                 my ($file_name,$rest) = split(/\&/,$line,2);
12865:                 $currfile{$file_name} = 1;
12866:             }
12867:         }
12868:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12869:         if (opendir(my $dir,$url)) {
12870:             my @dir_list = grep(!/^\./,readdir($dir));
12871:             map {$currfile{$_} = 1;} @dir_list;
12872:         }
12873:     } elsif (($actionurl eq '/adm/dependencies') ||
12874:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
12875:               ($args->{'context'} eq 'paste')) ||
12876:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
12877:         if ($env{'request.course.id'} ne '') {
12878:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
12879:             if ($dir ne '') {
12880:                 my ($dirlistref,$listerror) =
12881:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
12882:                 if (ref($dirlistref) eq 'ARRAY') {
12883:                     foreach my $line (@{$dirlistref}) {
12884:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
12885:                             $size,undef,$mtime)=split(/\&/,$line,12);
12886:                         unless (($testdir&$dirptr) ||
12887:                                 ($file_name =~ /^\.\.?$/)) {
12888:                             $currfile{$file_name} = [$size,$mtime];
12889:                         }
12890:                     }
12891:                 }
12892:             }
12893:         }
12894:     }
12895:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
12896:     # are not in subdirectories, using $currfile
12897:     foreach my $file (keys(%dependencies)) {
12898:         if (exists($currfile{$file})) {
12899:             unless ($mapping{$file} eq $file) {
12900:                 $pathchanges{$file} = 1;
12901:             }
12902:             $existing{$file} = 1;
12903:             $numexisting ++;
12904:         } else {
12905:             $newfiles{$file} = 1;
12906:         }
12907:     }
12908:     foreach my $file (keys(%currfile)) {
12909:         unless (($file eq $filename) ||
12910:                 ($file eq $filename.'.bak') ||
12911:                 ($dependencies{$file})) {
12912:             if ($actionurl eq '/adm/dependencies') {
12913:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
12914:                     next if (($rem ne '') &&
12915:                              (($env{"httpref.$rem".$file} ne '') ||
12916:                               (ref($navmap) &&
12917:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
12918:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
12919:                                 ($navmap->getResourceByUrl($rem.$1)))))));
12920:                 }
12921:             }
12922:             $unused{$file} = 1;
12923:         }
12924:     }
12925:     
12926:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
12927:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
12928:         ($args->{'context'} eq 'paste')) {
12929:         $counter = scalar(keys(%existing));
12930:         $numpathchg = scalar(keys(%pathchanges));
12931:         return ($output,$counter,$numpathchg,\%existing);
12932:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
12933:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
12934:         $counter = scalar(keys(%existing));
12935:         $numpathchg = scalar(keys(%pathchanges));
12936:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
12937:     }
12938:     
12939:     # returns HTML otherwise, with dependency results and to ask for more uploads
12940:     
12941:     # $upload_output: missing dependencies (with upload form)
12942:     # $modify_output: uploaded dependencies (in use)
12943:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
12944:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
12945:         if ($actionurl eq '/adm/dependencies') {
12946:             next if ($embed_file =~ m{^\w+://});
12947:         }
12948:         $upload_output .= &start_data_table_row().
12949:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
12950:                           '<span class="LC_filename">'.$embed_file.'</span>';
12951:         unless ($mapping{$embed_file} eq $embed_file) {
12952:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
12953:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
12954:         }
12955:         $upload_output .= '</td>';
12956:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
12957:             $upload_output.='<td align="right">'.
12958:                             '<span class="LC_info LC_fontsize_medium">'.
12959:                             &mt("URL points to web address").'</span>';
12960:             $numremref++;
12961:         } elsif ($args->{'error_on_invalid_names'}
12962:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
12963:             $upload_output.='<td align="right"><span class="LC_warning">'.
12964:                             &mt('Invalid characters').'</span>';
12965:             $numinvalid++;
12966:         } else {
12967:             $upload_output .= '<td>'.
12968:                               &embedded_file_element('upload_embedded',$counter,
12969:                                                      $embed_file,\%mapping,
12970:                                                      $allfiles,$codebase,'upload');
12971:             $counter ++;
12972:             $numnew ++;
12973:         }
12974:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
12975:     }
12976:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
12977:         if ($actionurl eq '/adm/dependencies') {
12978:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
12979:             $modify_output .= &start_data_table_row().
12980:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
12981:                               '<img src="'.&icon($embed_file).'" border="0" />'.
12982:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
12983:                               '<td>'.$size.'</td>'.
12984:                               '<td>'.$mtime.'</td>'.
12985:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
12986:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
12987:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
12988:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
12989:                               &embedded_file_element('upload_embedded',$counter,
12990:                                                      $embed_file,\%mapping,
12991:                                                      $allfiles,$codebase,'modify').
12992:                               '</div></td>'.
12993:                               &end_data_table_row()."\n";
12994:             $counter ++;
12995:         } else {
12996:             $upload_output .= &start_data_table_row().
12997:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
12998:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
12999:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
13000:                               &Apache::loncommon::end_data_table_row()."\n";
13001:         }
13002:     }
13003:     my $delidx = $counter;
13004:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
13005:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
13006:         $delete_output .= &start_data_table_row().
13007:                           '<td><img src="'.&icon($oldfile).'" />'.
13008:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
13009:                           '<td>'.$size.'</td>'.
13010:                           '<td>'.$mtime.'</td>'.
13011:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
13012:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
13013:                           &embedded_file_element('upload_embedded',$delidx,
13014:                                                  $oldfile,\%mapping,$allfiles,
13015:                                                  $codebase,'delete').'</td>'.
13016:                           &end_data_table_row()."\n"; 
13017:         $numunused ++;
13018:         $delidx ++;
13019:     }
13020:     if ($upload_output) {
13021:         $upload_output = &start_data_table().
13022:                          $upload_output.
13023:                          &end_data_table()."\n";
13024:     }
13025:     if ($modify_output) {
13026:         $modify_output = &start_data_table().
13027:                          &start_data_table_header_row().
13028:                          '<th>'.&mt('File').'</th>'.
13029:                          '<th>'.&mt('Size (KB)').'</th>'.
13030:                          '<th>'.&mt('Modified').'</th>'.
13031:                          '<th>'.&mt('Upload replacement?').'</th>'.
13032:                          &end_data_table_header_row().
13033:                          $modify_output.
13034:                          &end_data_table()."\n";
13035:     }
13036:     if ($delete_output) {
13037:         $delete_output = &start_data_table().
13038:                          &start_data_table_header_row().
13039:                          '<th>'.&mt('File').'</th>'.
13040:                          '<th>'.&mt('Size (KB)').'</th>'.
13041:                          '<th>'.&mt('Modified').'</th>'.
13042:                          '<th>'.&mt('Delete?').'</th>'.
13043:                          &end_data_table_header_row().
13044:                          $delete_output.
13045:                          &end_data_table()."\n";
13046:     }
13047:     my $applies = 0;
13048:     if ($numremref) {
13049:         $applies ++;
13050:     }
13051:     if ($numinvalid) {
13052:         $applies ++;
13053:     }
13054:     if ($numexisting) {
13055:         $applies ++;
13056:     }
13057:     if ($counter || $numunused) {
13058:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
13059:                   ' method="post" enctype="multipart/form-data">'."\n".
13060:                   $state.'<h3>'.$heading.'</h3>'; 
13061:         if ($actionurl eq '/adm/dependencies') {
13062:             if ($numnew) {
13063:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
13064:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
13065:                            $upload_output.'<br />'."\n";
13066:             }
13067:             if ($numexisting) {
13068:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
13069:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
13070:                            $modify_output.'<br />'."\n";
13071:                            $buttontext = &mt('Save changes');
13072:             }
13073:             if ($numunused) {
13074:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
13075:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
13076:                            $delete_output.'<br />'."\n";
13077:                            $buttontext = &mt('Save changes');
13078:             }
13079:         } else {
13080:             $output .= $upload_output.'<br />'."\n";
13081:         }
13082:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
13083:                    $counter.'" />'."\n";
13084:         if ($actionurl eq '/adm/dependencies') { 
13085:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
13086:                        $numnew.'" />'."\n";
13087:         } elsif ($actionurl eq '') {
13088:             $output .=  '<input type="hidden" name="phase" value="three" />';
13089:         }
13090:     } elsif ($applies) {
13091:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
13092:         if ($applies > 1) {
13093:             $output .=  
13094:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
13095:             if ($numremref) {
13096:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
13097:             }
13098:             if ($numinvalid) {
13099:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
13100:             }
13101:             if ($numexisting) {
13102:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
13103:             }
13104:             $output .= '</ul><br />';
13105:         } elsif ($numremref) {
13106:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
13107:         } elsif ($numinvalid) {
13108:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
13109:         } elsif ($numexisting) {
13110:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
13111:         }
13112:         $output .= $upload_output.'<br />';
13113:     }
13114:     my ($pathchange_output,$chgcount);
13115:     $chgcount = $counter;
13116:     if (keys(%pathchanges) > 0) {
13117:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
13118:             if ($counter) {
13119:                 $output .= &embedded_file_element('pathchange',$chgcount,
13120:                                                   $embed_file,\%mapping,
13121:                                                   $allfiles,$codebase,'change');
13122:             } else {
13123:                 $pathchange_output .= 
13124:                     &start_data_table_row().
13125:                     '<td><input type ="checkbox" name="namechange" value="'.
13126:                     $chgcount.'" checked="checked" /></td>'.
13127:                     '<td>'.$mapping{$embed_file}.'</td>'.
13128:                     '<td>'.$embed_file.
13129:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
13130:                                            \%mapping,$allfiles,$codebase,'change').
13131:                     '</td>'.&end_data_table_row();
13132:             }
13133:             $numpathchg ++;
13134:             $chgcount ++;
13135:         }
13136:     }
13137:     if (($counter) || ($numunused)) {
13138:         if ($numpathchg) {
13139:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
13140:                        $numpathchg.'" />'."\n";
13141:         }
13142:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
13143:             ($actionurl eq '/adm/imsimport')) {
13144:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
13145:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
13146:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
13147:         } elsif ($actionurl eq '/adm/dependencies') {
13148:             $output .= '<input type="hidden" name="action" value="process_changes" />';
13149:         }
13150:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
13151:     } elsif ($numpathchg) {
13152:         my %pathchange = ();
13153:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
13154:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
13155:             $output .= '<p>'.&mt('or').'</p>'; 
13156:         }
13157:     }
13158:     return ($output,$counter,$numpathchg);
13159: }
13160: 
13161: =pod
13162: 
13163: =item * clean_path($name)
13164: 
13165: Performs clean-up of directories, subdirectories and filename in an
13166: embedded object, referenced in an HTML file which is being uploaded
13167: to a course or portfolio, where 
13168: "Upload embedded images/multimedia files if HTML file" checkbox was
13169: checked.
13170: 
13171: Clean-up is similar to replacements in lonnet::clean_filename()
13172: except each / between sub-directory and next level is preserved.
13173: 
13174: =cut
13175: 
13176: sub clean_path {
13177:     my ($embed_file) = @_;
13178:     $embed_file =~s{^/+}{};
13179:     my @contents;
13180:     if ($embed_file =~ m{/}) {
13181:         @contents = split(/\//,$embed_file);
13182:     } else {
13183:         @contents = ($embed_file);
13184:     }
13185:     my $lastidx = scalar(@contents)-1;
13186:     for (my $i=0; $i<=$lastidx; $i++) { 
13187:         $contents[$i]=~s{\\}{/}g;
13188:         $contents[$i]=~s/\s+/\_/g;
13189:         $contents[$i]=~s{[^/\w\.\-]}{}g;
13190:         if ($i == $lastidx) {
13191:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
13192:         }
13193:     }
13194:     if ($lastidx > 0) {
13195:         return join('/',@contents);
13196:     } else {
13197:         return $contents[0];
13198:     }
13199: }
13200: 
13201: sub embedded_file_element {
13202:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
13203:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
13204:                    (ref($codebase) eq 'HASH'));
13205:     my $output;
13206:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
13207:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
13208:     }
13209:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
13210:                &escape($embed_file).'" />';
13211:     unless (($context eq 'upload_embedded') && 
13212:             ($mapping->{$embed_file} eq $embed_file)) {
13213:         $output .='
13214:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
13215:     }
13216:     my $attrib;
13217:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
13218:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
13219:     }
13220:     $output .=
13221:         "\n\t\t".
13222:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
13223:         $attrib.'" />';
13224:     if (exists($codebase->{$mapping->{$embed_file}})) {
13225:         $output .=
13226:             "\n\t\t".
13227:             '<input name="codebase_'.$num.'" type="hidden" value="'.
13228:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
13229:     }
13230:     return $output;
13231: }
13232: 
13233: sub get_dependency_details {
13234:     my ($currfile,$currsubfile,$embed_file) = @_;
13235:     my ($size,$mtime,$showsize,$showmtime);
13236:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
13237:         if ($embed_file =~ m{/}) {
13238:             my ($path,$fname) = split(/\//,$embed_file);
13239:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
13240:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
13241:             }
13242:         } else {
13243:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
13244:                 ($size,$mtime) = @{$currfile->{$embed_file}};
13245:             }
13246:         }
13247:         $showsize = $size/1024.0;
13248:         $showsize = sprintf("%.1f",$showsize);
13249:         if ($mtime > 0) {
13250:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
13251:         }
13252:     }
13253:     return ($showsize,$showmtime);
13254: }
13255: 
13256: sub ask_embedded_js {
13257:     return <<"END";
13258: <script type="text/javascript"">
13259: // <![CDATA[
13260: function toggleBrowse(counter) {
13261:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
13262:     var fileid = document.getElementById('embedded_item_'+counter);
13263:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
13264:     if (chkboxid.checked == true) {
13265:         uploaddivid.style.display='block';
13266:     } else {
13267:         uploaddivid.style.display='none';
13268:         fileid.value = '';
13269:     }
13270: }
13271: // ]]>
13272: </script>
13273: 
13274: END
13275: }
13276: 
13277: sub upload_embedded {
13278:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
13279:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
13280:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
13281:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
13282:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
13283:         my $orig_uploaded_filename =
13284:             $env{'form.embedded_item_'.$i.'.filename'};
13285:         foreach my $type ('orig','ref','attrib','codebase') {
13286:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
13287:                 $env{'form.embedded_'.$type.'_'.$i} =
13288:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
13289:             }
13290:         }
13291:         my ($path,$fname) =
13292:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
13293:         # no path, whole string is fname
13294:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
13295:         $fname = &Apache::lonnet::clean_filename($fname);
13296:         # See if there is anything left
13297:         next if ($fname eq '');
13298: 
13299:         # Check if file already exists as a file or directory.
13300:         my ($state,$msg);
13301:         if ($context eq 'portfolio') {
13302:             my $port_path = $dirpath;
13303:             if ($group ne '') {
13304:                 $port_path = "groups/$group/$port_path";
13305:             }
13306:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
13307:                                               $fname,$group,'embedded_item_'.$i,
13308:                                               $dir_root,$port_path,$disk_quota,
13309:                                               $current_disk_usage,$uname,$udom);
13310:             if ($state eq 'will_exceed_quota'
13311:                 || $state eq 'file_locked') {
13312:                 $output .= $msg;
13313:                 next;
13314:             }
13315:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
13316:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
13317:             if ($state eq 'exists') {
13318:                 $output .= $msg;
13319:                 next;
13320:             }
13321:         }
13322:         # Check if extension is valid
13323:         if (($fname =~ /\.(\w+)$/) &&
13324:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
13325:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
13326:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
13327:             next;
13328:         } elsif (($fname =~ /\.(\w+)$/) &&
13329:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
13330:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
13331:             next;
13332:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
13333:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
13334:             next;
13335:         }
13336:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
13337:         my $subdir = $path;
13338:         $subdir =~ s{/+$}{};
13339:         if ($context eq 'portfolio') {
13340:             my $result;
13341:             if ($state eq 'existingfile') {
13342:                 $result=
13343:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
13344:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
13345:             } else {
13346:                 $result=
13347:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
13348:                                                     $dirpath.
13349:                                                     $env{'form.currentpath'}.$subdir);
13350:                 if ($result !~ m|^/uploaded/|) {
13351:                     $output .= '<span class="LC_error">'
13352:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
13353:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
13354:                                .'</span><br />';
13355:                     next;
13356:                 } else {
13357:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
13358:                                $path.$fname.'</span>').'<br />';     
13359:                 }
13360:             }
13361:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
13362:             my $extendedsubdir = $dirpath.'/'.$subdir;
13363:             $extendedsubdir =~ s{/+$}{};
13364:             my $result =
13365:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
13366:             if ($result !~ m|^/uploaded/|) {
13367:                 $output .= '<span class="LC_error">'
13368:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
13369:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
13370:                            .'</span><br />';
13371:                     next;
13372:             } else {
13373:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
13374:                            $path.$fname.'</span>').'<br />';
13375:                 if ($context eq 'syllabus') {
13376:                     &Apache::lonnet::make_public_indefinitely($result);
13377:                 }
13378:             }
13379:         } else {
13380: # Save the file
13381:             my $target = $env{'form.embedded_item_'.$i};
13382:             my $fullpath = $dir_root.$dirpath.'/'.$path;
13383:             my $dest = $fullpath.$fname;
13384:             my $url = $url_root.$dirpath.'/'.$path.$fname;
13385:             my @parts=split(/\//,"$dirpath/$path");
13386:             my $count;
13387:             my $filepath = $dir_root;
13388:             foreach my $subdir (@parts) {
13389:                 $filepath .= "/$subdir";
13390:                 if (!-e $filepath) {
13391:                     mkdir($filepath,0770);
13392:                 }
13393:             }
13394:             my $fh;
13395:             if (!open($fh,'>'.$dest)) {
13396:                 &Apache::lonnet::logthis('Failed to create '.$dest);
13397:                 $output .= '<span class="LC_error">'.
13398:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
13399:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
13400:                            '</span><br />';
13401:             } else {
13402:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
13403:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
13404:                     $output .= '<span class="LC_error">'.
13405:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
13406:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
13407:                               '</span><br />';
13408:                 } else {
13409:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
13410:                                $url.'</span>').'<br />';
13411:                     unless ($context eq 'testbank') {
13412:                         $footer .= &mt('View embedded file: [_1]',
13413:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
13414:                     }
13415:                 }
13416:                 close($fh);
13417:             }
13418:         }
13419:         if ($env{'form.embedded_ref_'.$i}) {
13420:             $pathchange{$i} = 1;
13421:         }
13422:     }
13423:     if ($output) {
13424:         $output = '<p>'.$output.'</p>';
13425:     }
13426:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
13427:     $returnflag = 'ok';
13428:     my $numpathchgs = scalar(keys(%pathchange));
13429:     if ($numpathchgs > 0) {
13430:         if ($context eq 'portfolio') {
13431:             $output .= '<p>'.&mt('or').'</p>';
13432:         } elsif ($context eq 'testbank') {
13433:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
13434:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
13435:             $returnflag = 'modify_orightml';
13436:         }
13437:     }
13438:     return ($output.$footer,$returnflag,$numpathchgs);
13439: }
13440: 
13441: sub modify_html_form {
13442:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
13443:     my $end = 0;
13444:     my $modifyform;
13445:     if ($context eq 'upload_embedded') {
13446:         return unless (ref($pathchange) eq 'HASH');
13447:         if ($env{'form.number_embedded_items'}) {
13448:             $end += $env{'form.number_embedded_items'};
13449:         }
13450:         if ($env{'form.number_pathchange_items'}) {
13451:             $end += $env{'form.number_pathchange_items'};
13452:         }
13453:         if ($end) {
13454:             for (my $i=0; $i<$end; $i++) {
13455:                 if ($i < $env{'form.number_embedded_items'}) {
13456:                     next unless($pathchange->{$i});
13457:                 }
13458:                 $modifyform .=
13459:                     &start_data_table_row().
13460:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
13461:                     'checked="checked" /></td>'.
13462:                     '<td>'.$env{'form.embedded_ref_'.$i}.
13463:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
13464:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
13465:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
13466:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
13467:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
13468:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
13469:                     '<td>'.$env{'form.embedded_orig_'.$i}.
13470:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
13471:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
13472:                     &end_data_table_row();
13473:             }
13474:         }
13475:     } else {
13476:         $modifyform = $pathchgtable;
13477:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
13478:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
13479:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
13480:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
13481:         }
13482:     }
13483:     if ($modifyform) {
13484:         if ($actionurl eq '/adm/dependencies') {
13485:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
13486:         }
13487:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
13488:                '<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".
13489:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
13490:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
13491:                '</ol></p>'."\n".'<p>'.
13492:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
13493:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
13494:                &start_data_table()."\n".
13495:                &start_data_table_header_row().
13496:                '<th>'.&mt('Change?').'</th>'.
13497:                '<th>'.&mt('Current reference').'</th>'.
13498:                '<th>'.&mt('Required reference').'</th>'.
13499:                &end_data_table_header_row()."\n".
13500:                $modifyform.
13501:                &end_data_table().'<br />'."\n".$hiddenstate.
13502:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
13503:                '</form>'."\n";
13504:     }
13505:     return;
13506: }
13507: 
13508: sub modify_html_refs {
13509:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
13510:     my $container;
13511:     if ($context eq 'portfolio') {
13512:         $container = $env{'form.container'};
13513:     } elsif ($context eq 'coursedoc') {
13514:         $container = $env{'form.primaryurl'};
13515:     } elsif ($context eq 'manage_dependencies') {
13516:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
13517:         $container = "/$container";
13518:     } elsif ($context eq 'syllabus') {
13519:         $container = $url;
13520:     } else {
13521:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
13522:     }
13523:     my (%allfiles,%codebase,$output,$content);
13524:     my @changes = &get_env_multiple('form.namechange');
13525:     unless ((@changes > 0) || ($context eq 'syllabus')) {
13526:         if (wantarray) {
13527:             return ('',0,0); 
13528:         } else {
13529:             return;
13530:         }
13531:     }
13532:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
13533:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
13534:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
13535:             if (wantarray) {
13536:                 return ('',0,0);
13537:             } else {
13538:                 return;
13539:             }
13540:         } 
13541:         $content = &Apache::lonnet::getfile($container);
13542:         if ($content eq '-1') {
13543:             if (wantarray) {
13544:                 return ('',0,0);
13545:             } else {
13546:                 return;
13547:             }
13548:         }
13549:     } else {
13550:         unless ($container =~ /^\Q$dir_root\E/) {
13551:             if (wantarray) {
13552:                 return ('',0,0);
13553:             } else {
13554:                 return;
13555:             }
13556:         } 
13557:         if (open(my $fh,'<',$container)) {
13558:             $content = join('', <$fh>);
13559:             close($fh);
13560:         } else {
13561:             if (wantarray) {
13562:                 return ('',0,0);
13563:             } else {
13564:                 return;
13565:             }
13566:         }
13567:     }
13568:     my ($count,$codebasecount) = (0,0);
13569:     my $mm = new File::MMagic;
13570:     my $mime_type = $mm->checktype_contents($content);
13571:     if ($mime_type eq 'text/html') {
13572:         my $parse_result = 
13573:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
13574:                                                     \%codebase,\$content);
13575:         if ($parse_result eq 'ok') {
13576:             foreach my $i (@changes) {
13577:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
13578:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
13579:                 if ($allfiles{$ref}) {
13580:                     my $newname =  $orig;
13581:                     my ($attrib_regexp,$codebase);
13582:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
13583:                     if ($attrib_regexp =~ /:/) {
13584:                         $attrib_regexp =~ s/\:/|/g;
13585:                     }
13586:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
13587:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
13588:                         $count += $numchg;
13589:                         $allfiles{$newname} = $allfiles{$ref};
13590:                         delete($allfiles{$ref});
13591:                     }
13592:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
13593:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
13594:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
13595:                         $codebasecount ++;
13596:                     }
13597:                 }
13598:             }
13599:             my $skiprewrites;
13600:             if ($count || $codebasecount) {
13601:                 my $saveresult;
13602:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
13603:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
13604:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
13605:                     if ($url eq $container) {
13606:                         my ($fname) = ($container =~ m{/([^/]+)$});
13607:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
13608:                                             $count,'<span class="LC_filename">'.
13609:                                             $fname.'</span>').'</p>';
13610:                     } else {
13611:                          $output = '<p class="LC_error">'.
13612:                                    &mt('Error: update failed for: [_1].',
13613:                                    '<span class="LC_filename">'.
13614:                                    $container.'</span>').'</p>';
13615:                     }
13616:                     if ($context eq 'syllabus') {
13617:                         unless ($saveresult eq 'ok') {
13618:                             $skiprewrites = 1;
13619:                         }
13620:                     }
13621:                 } else {
13622:                     if (open(my $fh,'>',$container)) {
13623:                         print $fh $content;
13624:                         close($fh);
13625:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
13626:                                   $count,'<span class="LC_filename">'.
13627:                                   $container.'</span>').'</p>';
13628:                     } else {
13629:                          $output = '<p class="LC_error">'.
13630:                                    &mt('Error: could not update [_1].',
13631:                                    '<span class="LC_filename">'.
13632:                                    $container.'</span>').'</p>';
13633:                     }
13634:                 }
13635:             }
13636:             if (($context eq 'syllabus') && (!$skiprewrites)) {
13637:                 my ($actionurl,$state);
13638:                 $actionurl = "/public/$udom/$uname/syllabus";
13639:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
13640:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
13641:                                               \%codebase,
13642:                                               {'context' => 'rewrites',
13643:                                                'ignore_remote_references' => 1,});
13644:                 if (ref($mapping) eq 'HASH') {
13645:                     my $rewrites = 0;
13646:                     foreach my $key (keys(%{$mapping})) {
13647:                         next if ($key =~ m{^https?://});
13648:                         my $ref = $mapping->{$key};
13649:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
13650:                         my $attrib;
13651:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
13652:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
13653:                         }
13654:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
13655:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
13656:                             $rewrites += $numchg;
13657:                         }
13658:                     }
13659:                     if ($rewrites) {
13660:                         my $saveresult; 
13661:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
13662:                         if ($url eq $container) {
13663:                             my ($fname) = ($container =~ m{/([^/]+)$});
13664:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
13665:                                             $count,'<span class="LC_filename">'.
13666:                                             $fname.'</span>').'</p>';
13667:                         } else {
13668:                             $output .= '<p class="LC_error">'.
13669:                                        &mt('Error: could not update links in [_1].',
13670:                                        '<span class="LC_filename">'.
13671:                                        $container.'</span>').'</p>';
13672: 
13673:                         }
13674:                     }
13675:                 }
13676:             }
13677:         } else {
13678:             &logthis('Failed to parse '.$container.
13679:                      ' to modify references: '.$parse_result);
13680:         }
13681:     }
13682:     if (wantarray) {
13683:         return ($output,$count,$codebasecount);
13684:     } else {
13685:         return $output;
13686:     }
13687: }
13688: 
13689: sub check_for_existing {
13690:     my ($path,$fname,$element) = @_;
13691:     my ($state,$msg);
13692:     if (-d $path.'/'.$fname) {
13693:         $state = 'exists';
13694:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
13695:     } elsif (-e $path.'/'.$fname) {
13696:         $state = 'exists';
13697:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
13698:     }
13699:     if ($state eq 'exists') {
13700:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
13701:     }
13702:     return ($state,$msg);
13703: }
13704: 
13705: sub check_for_upload {
13706:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
13707:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
13708:     my $filesize = length($env{'form.'.$element});
13709:     if (!$filesize) {
13710:         my $msg = '<span class="LC_error">'.
13711:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
13712:                       '<span class="LC_filename">'.$fname.'</span>',
13713:                       $filesize).'<br />'.
13714:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
13715:                   '</span>';
13716:         return ('zero_bytes',$msg);
13717:     }
13718:     $filesize =  $filesize/1000; #express in k (1024?)
13719:     my $getpropath = 1;
13720:     my ($dirlistref,$listerror) =
13721:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
13722:     my $found_file = 0;
13723:     my $locked_file = 0;
13724:     my @lockers;
13725:     my $navmap;
13726:     if ($env{'request.course.id'}) {
13727:         $navmap = Apache::lonnavmaps::navmap->new();
13728:     }
13729:     if (ref($dirlistref) eq 'ARRAY') {
13730:         foreach my $line (@{$dirlistref}) {
13731:             my ($file_name,$rest)=split(/\&/,$line,2);
13732:             if ($file_name eq $fname){
13733:                 $file_name = $path.$file_name;
13734:                 if ($group ne '') {
13735:                     $file_name = $group.$file_name;
13736:                 }
13737:                 $found_file = 1;
13738:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
13739:                     foreach my $lock (@lockers) {
13740:                         if (ref($lock) eq 'ARRAY') {
13741:                             my ($symb,$crsid) = @{$lock};
13742:                             if ($crsid eq $env{'request.course.id'}) {
13743:                                 if (ref($navmap)) {
13744:                                     my $res = $navmap->getBySymb($symb);
13745:                                     foreach my $part (@{$res->parts()}) { 
13746:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
13747:                                         unless (($slot_status == $res->RESERVED) ||
13748:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
13749:                                             $locked_file = 1;
13750:                                         }
13751:                                     }
13752:                                 } else {
13753:                                     $locked_file = 1;
13754:                                 }
13755:                             } else {
13756:                                 $locked_file = 1;
13757:                             }
13758:                         }
13759:                    }
13760:                 } else {
13761:                     my @info = split(/\&/,$rest);
13762:                     my $currsize = $info[6]/1000;
13763:                     if ($currsize < $filesize) {
13764:                         my $extra = $filesize - $currsize;
13765:                         if (($current_disk_usage + $extra) > $disk_quota) {
13766:                             my $msg = '<p class="LC_warning">'.
13767:                                       &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.',
13768:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
13769:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
13770:                                                    $disk_quota,$current_disk_usage).'</p>';
13771:                             return ('will_exceed_quota',$msg);
13772:                         }
13773:                     }
13774:                 }
13775:             }
13776:         }
13777:     }
13778:     if (($current_disk_usage + $filesize) > $disk_quota){
13779:         my $msg = '<p class="LC_warning">'.
13780:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
13781:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
13782:         return ('will_exceed_quota',$msg);
13783:     } elsif ($found_file) {
13784:         if ($locked_file) {
13785:             my $msg = '<p class="LC_warning">';
13786:             $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>');
13787:             $msg .= '</p>';
13788:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
13789:             return ('file_locked',$msg);
13790:         } else {
13791:             my $msg = '<p class="LC_error">';
13792:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
13793:             $msg .= '</p>';
13794:             return ('existingfile',$msg);
13795:         }
13796:     }
13797: }
13798: 
13799: sub check_for_traversal {
13800:     my ($path,$url,$toplevel) = @_;
13801:     my @parts=split(/\//,$path);
13802:     my $cleanpath;
13803:     my $fullpath = $url;
13804:     for (my $i=0;$i<@parts;$i++) {
13805:         next if ($parts[$i] eq '.');
13806:         if ($parts[$i] eq '..') {
13807:             $fullpath =~ s{([^/]+/)$}{};
13808:         } else {
13809:             $fullpath .= $parts[$i].'/';
13810:         }
13811:     }
13812:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
13813:         $cleanpath = $1;
13814:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
13815:         my $curr_toprel = $1;
13816:         my @parts = split(/\//,$curr_toprel);
13817:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
13818:         my @urlparts = split(/\//,$url_toprel);
13819:         my $doubledots;
13820:         my $startdiff = -1;
13821:         for (my $i=0; $i<@urlparts; $i++) {
13822:             if ($startdiff == -1) {
13823:                 unless ($urlparts[$i] eq $parts[$i]) {
13824:                     $startdiff = $i;
13825:                     $doubledots .= '../';
13826:                 }
13827:             } else {
13828:                 $doubledots .= '../';
13829:             }
13830:         }
13831:         if ($startdiff > -1) {
13832:             $cleanpath = $doubledots;
13833:             for (my $i=$startdiff; $i<@parts; $i++) {
13834:                 $cleanpath .= $parts[$i].'/';
13835:             }
13836:         }
13837:     }
13838:     $cleanpath =~ s{(/)$}{};
13839:     return $cleanpath;
13840: }
13841: 
13842: sub is_archive_file {
13843:     my ($mimetype) = @_;
13844:     if (($mimetype eq 'application/octet-stream') ||
13845:         ($mimetype eq 'application/x-stuffit') ||
13846:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
13847:         return 1;
13848:     }
13849:     return;
13850: }
13851: 
13852: sub decompress_form {
13853:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
13854:     my %lt = &Apache::lonlocal::texthash (
13855:         this => 'This file is an archive file.',
13856:         camt => 'This file is a Camtasia archive file.',
13857:         itsc => 'Its contents are as follows:',
13858:         youm => 'You may wish to extract its contents.',
13859:         extr => 'Extract contents',
13860:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
13861:         proa => 'Process automatically?',
13862:         yes  => 'Yes',
13863:         no   => 'No',
13864:         fold => 'Title for folder containing movie',
13865:         movi => 'Title for page containing embedded movie', 
13866:     );
13867:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
13868:     my ($is_camtasia,$topdir,%toplevel,@paths);
13869:     my $info = &list_archive_contents($fileloc,\@paths);
13870:     if (@paths) {
13871:         foreach my $path (@paths) {
13872:             $path =~ s{^/}{};
13873:             if ($path =~ m{^([^/]+)/$}) {
13874:                 $topdir = $1;
13875:             }
13876:             if ($path =~ m{^([^/]+)/}) {
13877:                 $toplevel{$1} = $path;
13878:             } else {
13879:                 $toplevel{$path} = $path;
13880:             }
13881:         }
13882:     }
13883:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
13884:         my @camtasia6 = ("$topdir/","$topdir/index.html",
13885:                         "$topdir/media/",
13886:                         "$topdir/media/$topdir.mp4",
13887:                         "$topdir/media/FirstFrame.png",
13888:                         "$topdir/media/player.swf",
13889:                         "$topdir/media/swfobject.js",
13890:                         "$topdir/media/expressInstall.swf");
13891:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
13892:                          "$topdir/$topdir.mp4",
13893:                          "$topdir/$topdir\_config.xml",
13894:                          "$topdir/$topdir\_controller.swf",
13895:                          "$topdir/$topdir\_embed.css",
13896:                          "$topdir/$topdir\_First_Frame.png",
13897:                          "$topdir/$topdir\_player.html",
13898:                          "$topdir/$topdir\_Thumbnails.png",
13899:                          "$topdir/playerProductInstall.swf",
13900:                          "$topdir/scripts/",
13901:                          "$topdir/scripts/config_xml.js",
13902:                          "$topdir/scripts/handlebars.js",
13903:                          "$topdir/scripts/jquery-1.7.1.min.js",
13904:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
13905:                          "$topdir/scripts/modernizr.js",
13906:                          "$topdir/scripts/player-min.js",
13907:                          "$topdir/scripts/swfobject.js",
13908:                          "$topdir/skins/",
13909:                          "$topdir/skins/configuration_express.xml",
13910:                          "$topdir/skins/express_show/",
13911:                          "$topdir/skins/express_show/player-min.css",
13912:                          "$topdir/skins/express_show/spritesheet.png");
13913:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
13914:                          "$topdir/$topdir.mp4",
13915:                          "$topdir/$topdir\_config.xml",
13916:                          "$topdir/$topdir\_controller.swf",
13917:                          "$topdir/$topdir\_embed.css",
13918:                          "$topdir/$topdir\_First_Frame.png",
13919:                          "$topdir/$topdir\_player.html",
13920:                          "$topdir/$topdir\_Thumbnails.png",
13921:                          "$topdir/playerProductInstall.swf",
13922:                          "$topdir/scripts/",
13923:                          "$topdir/scripts/config_xml.js",
13924:                          "$topdir/scripts/techsmith-smart-player.min.js",
13925:                          "$topdir/skins/",
13926:                          "$topdir/skins/configuration_express.xml",
13927:                          "$topdir/skins/express_show/",
13928:                          "$topdir/skins/express_show/spritesheet.min.css",
13929:                          "$topdir/skins/express_show/spritesheet.png",
13930:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
13931:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
13932:         if (@diffs == 0) {
13933:             $is_camtasia = 6;
13934:         } else {
13935:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
13936:             if (@diffs == 0) {
13937:                 $is_camtasia = 8;
13938:             } else {
13939:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
13940:                 if (@diffs == 0) {
13941:                     $is_camtasia = 8;
13942:                 }
13943:             }
13944:         }
13945:     }
13946:     my $output;
13947:     if ($is_camtasia) {
13948:         $output = <<"ENDCAM";
13949: <script type="text/javascript" language="Javascript">
13950: // <![CDATA[
13951: 
13952: function camtasiaToggle() {
13953:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
13954:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
13955:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
13956:                 document.getElementById('camtasia_titles').style.display='block';
13957:             } else {
13958:                 document.getElementById('camtasia_titles').style.display='none';
13959:             }
13960:         }
13961:     }
13962:     return;
13963: }
13964: 
13965: // ]]>
13966: </script>
13967: <p>$lt{'camt'}</p>
13968: ENDCAM
13969:     } else {
13970:         $output = '<p>'.$lt{'this'};
13971:         if ($info eq '') {
13972:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
13973:         } else {
13974:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
13975:                        '<div><pre>'.$info.'</pre></div>';
13976:         }
13977:     }
13978:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
13979:     my $duplicates;
13980:     my $num = 0;
13981:     if (ref($dirlist) eq 'ARRAY') {
13982:         foreach my $item (@{$dirlist}) {
13983:             if (ref($item) eq 'ARRAY') {
13984:                 if (exists($toplevel{$item->[0]})) {
13985:                     $duplicates .= 
13986:                         &start_data_table_row().
13987:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
13988:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
13989:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
13990:                         'value="1" />'.&mt('Yes').'</label>'.
13991:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
13992:                         '<td>'.$item->[0].'</td>';
13993:                     if ($item->[2]) {
13994:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
13995:                     } else {
13996:                         $duplicates .= '<td>'.&mt('File').'</td>';
13997:                     }
13998:                     $duplicates .= '<td>'.$item->[3].'</td>'.
13999:                                    '<td>'.
14000:                                    &Apache::lonlocal::locallocaltime($item->[4]).
14001:                                    '</td>'.
14002:                                    &end_data_table_row();
14003:                     $num ++;
14004:                 }
14005:             }
14006:         }
14007:     }
14008:     my $itemcount;
14009:     if (@paths > 0) {
14010:         $itemcount = scalar(@paths);
14011:     } else {
14012:         $itemcount = 1;
14013:     }
14014:     if ($is_camtasia) {
14015:         $output .= $lt{'auto'}.'<br />'.
14016:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
14017:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
14018:                    $lt{'yes'}.'</label>&nbsp;<label>'.
14019:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
14020:                    $lt{'no'}.'</label></span><br />'.
14021:                    '<div id="camtasia_titles" style="display:block">'.
14022:                    &Apache::lonhtmlcommon::start_pick_box().
14023:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
14024:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
14025:                    &Apache::lonhtmlcommon::row_closure().
14026:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
14027:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
14028:                    &Apache::lonhtmlcommon::row_closure(1).
14029:                    &Apache::lonhtmlcommon::end_pick_box().
14030:                    '</div>';
14031:     }
14032:     $output .= 
14033:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
14034:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
14035:         "\n";
14036:     if ($duplicates ne '') {
14037:         $output .= '<p><span class="LC_warning">'.
14038:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
14039:                    &start_data_table().
14040:                    &start_data_table_header_row().
14041:                    '<th>'.&mt('Overwrite?').'</th>'.
14042:                    '<th>'.&mt('Name').'</th>'.
14043:                    '<th>'.&mt('Type').'</th>'.
14044:                    '<th>'.&mt('Size').'</th>'.
14045:                    '<th>'.&mt('Last modified').'</th>'.
14046:                    &end_data_table_header_row().
14047:                    $duplicates.
14048:                    &end_data_table().
14049:                    '</p>';
14050:     }
14051:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
14052:     if (ref($hiddenelements) eq 'HASH') {
14053:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
14054:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
14055:         }
14056:     }
14057:     $output .= <<"END";
14058: <br />
14059: <input type="submit" name="decompress" value="$lt{'extr'}" />
14060: </form>
14061: $noextract
14062: END
14063:     return $output;
14064: }
14065: 
14066: sub decompression_utility {
14067:     my ($program) = @_;
14068:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
14069:     my $location;
14070:     if (grep(/^\Q$program\E$/,@utilities)) { 
14071:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
14072:                          '/usr/sbin/') {
14073:             if (-x $dir.$program) {
14074:                 $location = $dir.$program;
14075:                 last;
14076:             }
14077:         }
14078:     }
14079:     return $location;
14080: }
14081: 
14082: sub list_archive_contents {
14083:     my ($file,$pathsref) = @_;
14084:     my (@cmd,$output);
14085:     my $needsregexp;
14086:     if ($file =~ /\.zip$/) {
14087:         @cmd = (&decompression_utility('unzip'),"-l");
14088:         $needsregexp = 1;
14089:     } elsif (($file =~ m/\.tar\.gz$/) ||
14090:              ($file =~ /\.tgz$/)) {
14091:         @cmd = (&decompression_utility('tar'),"-ztf");
14092:     } elsif ($file =~ /\.tar\.bz2$/) {
14093:         @cmd = (&decompression_utility('tar'),"-jtf");
14094:     } elsif ($file =~ m|\.tar$|) {
14095:         @cmd = (&decompression_utility('tar'),"-tf");
14096:     }
14097:     if (@cmd) {
14098:         undef($!);
14099:         undef($@);
14100:         if (open(my $fh,"-|", @cmd, $file)) {
14101:             while (my $line = <$fh>) {
14102:                 $output .= $line;
14103:                 chomp($line);
14104:                 my $item;
14105:                 if ($needsregexp) {
14106:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
14107:                 } else {
14108:                     $item = $line;
14109:                 }
14110:                 if ($item ne '') {
14111:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
14112:                         push(@{$pathsref},$item);
14113:                     } 
14114:                 }
14115:             }
14116:             close($fh);
14117:         }
14118:     }
14119:     return $output;
14120: }
14121: 
14122: sub decompress_uploaded_file {
14123:     my ($file,$dir) = @_;
14124:     &Apache::lonnet::appenv({'cgi.file' => $file});
14125:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
14126:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
14127:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
14128:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
14129:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
14130:     my $decompressed = $env{'cgi.decompressed'};
14131:     &Apache::lonnet::delenv('cgi.file');
14132:     &Apache::lonnet::delenv('cgi.dir');
14133:     &Apache::lonnet::delenv('cgi.decompressed');
14134:     return ($decompressed,$result);
14135: }
14136: 
14137: sub process_decompression {
14138:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
14139:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
14140:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
14141:                &mt('Unexpected file path.').'</p>'."\n";
14142:     }
14143:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
14144:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
14145:                &mt('Unexpected course context.').'</p>'."\n";
14146:     }
14147:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
14148:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
14149:                &mt('Filename contained unexpected characters.').'</p>'."\n";
14150:     }
14151:     my ($dir,$error,$warning,$output);
14152:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
14153:         $error = &mt('Filename not a supported archive file type.').
14154:                  '<br />'.&mt('Filename should end with one of: [_1].',
14155:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
14156:     } else {
14157:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
14158:         if ($docuhome eq 'no_host') {
14159:             $error = &mt('Could not determine home server for course.');
14160:         } else {
14161:             my @ids=&Apache::lonnet::current_machine_ids();
14162:             my $currdir = "$dir_root/$destination";
14163:             if (grep(/^\Q$docuhome\E$/,@ids)) {
14164:                 $dir = &LONCAPA::propath($docudom,$docuname).
14165:                        "$dir_root/$destination";
14166:             } else {
14167:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
14168:                        "$dir_root/$docudom/$docuname/$destination";
14169:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
14170:                     $error = &mt('Archive file not found.');
14171:                 }
14172:             }
14173:             my (@to_overwrite,@to_skip);
14174:             if ($env{'form.archive_overwrite_total'} > 0) {
14175:                 my $total = $env{'form.archive_overwrite_total'};
14176:                 for (my $i=0; $i<$total; $i++) {
14177:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
14178:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
14179:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
14180:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
14181:                     }
14182:                 }
14183:             }
14184:             my $numskip = scalar(@to_skip);
14185:             my $numoverwrite = scalar(@to_overwrite);
14186:             if (($numskip) && (!$numoverwrite)) { 
14187:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
14188:             } elsif ($dir eq '') {
14189:                 $error = &mt('Directory containing archive file unavailable.');
14190:             } elsif (!$error) {
14191:                 my ($decompressed,$display);
14192:                 if (($numskip) || ($numoverwrite)) {
14193:                     my $tempdir = time.'_'.$$.int(rand(10000));
14194:                     mkdir("$dir/$tempdir",0755);
14195:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
14196:                         ($decompressed,$display) = 
14197:                             &decompress_uploaded_file($file,"$dir/$tempdir");
14198:                         foreach my $item (@to_skip) {
14199:                             if (($item ne '') && ($item !~ /\.\./)) {
14200:                                 if (-f "$dir/$tempdir/$item") { 
14201:                                     unlink("$dir/$tempdir/$item");
14202:                                 } elsif (-d "$dir/$tempdir/$item") {
14203:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
14204:                                 }
14205:                             }
14206:                         }
14207:                         foreach my $item (@to_overwrite) {
14208:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
14209:                                 if (($item ne '') && ($item !~ /\.\./)) {
14210:                                     if (-f "$dir/$item") {
14211:                                         unlink("$dir/$item");
14212:                                     } elsif (-d "$dir/$item") {
14213:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
14214:                                     }
14215:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
14216:                                 }
14217:                             }
14218:                         }
14219:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
14220:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
14221:                         }
14222:                     }
14223:                 } else {
14224:                     ($decompressed,$display) = 
14225:                         &decompress_uploaded_file($file,$dir);
14226:                 }
14227:                 if ($decompressed eq 'ok') {
14228:                     $output = '<p class="LC_info">'.
14229:                               &mt('Files extracted successfully from archive.').
14230:                               '</p>'."\n";
14231:                     my ($warning,$result,@contents);
14232:                     my ($newdirlistref,$newlisterror) =
14233:                         &Apache::lonnet::dirlist($currdir,$docudom,
14234:                                                  $docuname,1);
14235:                     my (%is_dir,%changes,@newitems);
14236:                     my $dirptr = 16384;
14237:                     if (ref($newdirlistref) eq 'ARRAY') {
14238:                         foreach my $dir_line (@{$newdirlistref}) {
14239:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
14240:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
14241:                                 push(@newitems,$item);
14242:                                 if ($dirptr&$testdir) {
14243:                                     $is_dir{$item} = 1;
14244:                                 }
14245:                                 $changes{$item} = 1;
14246:                             }
14247:                         }
14248:                     }
14249:                     if (keys(%changes) > 0) {
14250:                         foreach my $item (sort(@newitems)) {
14251:                             if ($changes{$item}) {
14252:                                 push(@contents,$item);
14253:                             }
14254:                         }
14255:                     }
14256:                     if (@contents > 0) {
14257:                         my $wantform;
14258:                         unless ($env{'form.autoextract_camtasia'}) {
14259:                             $wantform = 1;
14260:                         }
14261:                         my (%children,%parent,%dirorder,%titles);
14262:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
14263:                                                                 $currdir,\%is_dir,
14264:                                                                 \%children,\%parent,
14265:                                                                 \@contents,\%dirorder,
14266:                                                                 \%titles,$wantform);
14267:                         if ($datatable ne '') {
14268:                             $output .= &archive_options_form('decompressed',$datatable,
14269:                                                              $count,$hiddenelem);
14270:                             my $startcount = 6;
14271:                             $output .= &archive_javascript($startcount,$count,
14272:                                                            \%titles,\%children);
14273:                         }
14274:                         if ($env{'form.autoextract_camtasia'}) {
14275:                             my $version = $env{'form.autoextract_camtasia'};
14276:                             my %displayed;
14277:                             my $total = 1;
14278:                             $env{'form.archive_directory'} = [];
14279:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
14280:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
14281:                                 $path =~ s{/$}{};
14282:                                 my $item;
14283:                                 if ($path ne '') {
14284:                                     $item = "$path/$titles{$i}";
14285:                                 } else {
14286:                                     $item = $titles{$i};
14287:                                 }
14288:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
14289:                                 if ($item eq $contents[0]) {
14290:                                     push(@{$env{'form.archive_directory'}},$i);
14291:                                     $env{'form.archive_'.$i} = 'display';
14292:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
14293:                                     $displayed{'folder'} = $i;
14294:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
14295:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
14296:                                     $env{'form.archive_'.$i} = 'display';
14297:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
14298:                                     $displayed{'web'} = $i;
14299:                                 } else {
14300:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
14301:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
14302:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
14303:                                         push(@{$env{'form.archive_directory'}},$i);
14304:                                     }
14305:                                     $env{'form.archive_'.$i} = 'dependency';
14306:                                 }
14307:                                 $total ++;
14308:                             }
14309:                             for (my $i=1; $i<$total; $i++) {
14310:                                 next if ($i == $displayed{'web'});
14311:                                 next if ($i == $displayed{'folder'});
14312:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
14313:                             }
14314:                             $env{'form.phase'} = 'decompress_cleanup';
14315:                             $env{'form.archivedelete'} = 1;
14316:                             $env{'form.archive_count'} = $total-1;
14317:                             $output .=
14318:                                 &process_extracted_files('coursedocs',$docudom,
14319:                                                          $docuname,$destination,
14320:                                                          $dir_root,$hiddenelem);
14321:                         }
14322:                     } else {
14323:                         $warning = &mt('No new items extracted from archive file.');
14324:                     }
14325:                 } else {
14326:                     $output = $display;
14327:                     $error = &mt('An error occurred during extraction from the archive file.');
14328:                 }
14329:             }
14330:         }
14331:     }
14332:     if ($error) {
14333:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
14334:                    $error.'</p>'."\n";
14335:     }
14336:     if ($warning) {
14337:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
14338:     }
14339:     return $output;
14340: }
14341: 
14342: sub get_extracted {
14343:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
14344:         $titles,$wantform) = @_;
14345:     my $count = 0;
14346:     my $depth = 0;
14347:     my $datatable;
14348:     my @hierarchy;
14349:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
14350:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
14351:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
14352:     foreach my $item (@{$contents}) {
14353:         $count ++;
14354:         @{$dirorder->{$count}} = @hierarchy;
14355:         $titles->{$count} = $item;
14356:         &archive_hierarchy($depth,$count,$parent,$children);
14357:         if ($wantform) {
14358:             $datatable .= &archive_row($is_dir->{$item},$item,
14359:                                        $currdir,$depth,$count);
14360:         }
14361:         if ($is_dir->{$item}) {
14362:             $depth ++;
14363:             push(@hierarchy,$count);
14364:             $parent->{$depth} = $count;
14365:             $datatable .=
14366:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
14367:                                            \$depth,\$count,\@hierarchy,$dirorder,
14368:                                            $children,$parent,$titles,$wantform);
14369:             $depth --;
14370:             pop(@hierarchy);
14371:         }
14372:     }
14373:     return ($count,$datatable);
14374: }
14375: 
14376: sub recurse_extracted_archive {
14377:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
14378:         $children,$parent,$titles,$wantform) = @_;
14379:     my $result='';
14380:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
14381:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
14382:             (ref($dirorder) eq 'HASH')) {
14383:         return $result;
14384:     }
14385:     my $dirptr = 16384;
14386:     my ($newdirlistref,$newlisterror) =
14387:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
14388:     if (ref($newdirlistref) eq 'ARRAY') {
14389:         foreach my $dir_line (@{$newdirlistref}) {
14390:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
14391:             unless ($item =~ /^\.+$/) {
14392:                 $$count ++;
14393:                 @{$dirorder->{$$count}} = @{$hierarchy};
14394:                 $titles->{$$count} = $item;
14395:                 &archive_hierarchy($$depth,$$count,$parent,$children);
14396: 
14397:                 my $is_dir;
14398:                 if ($dirptr&$testdir) {
14399:                     $is_dir = 1;
14400:                 }
14401:                 if ($wantform) {
14402:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
14403:                 }
14404:                 if ($is_dir) {
14405:                     $$depth ++;
14406:                     push(@{$hierarchy},$$count);
14407:                     $parent->{$$depth} = $$count;
14408:                     $result .=
14409:                         &recurse_extracted_archive("$currdir/$item",$docudom,
14410:                                                    $docuname,$depth,$count,
14411:                                                    $hierarchy,$dirorder,$children,
14412:                                                    $parent,$titles,$wantform);
14413:                     $$depth --;
14414:                     pop(@{$hierarchy});
14415:                 }
14416:             }
14417:         }
14418:     }
14419:     return $result;
14420: }
14421: 
14422: sub archive_hierarchy {
14423:     my ($depth,$count,$parent,$children) =@_;
14424:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
14425:         if (exists($parent->{$depth})) {
14426:              $children->{$parent->{$depth}} .= $count.':';
14427:         }
14428:     }
14429:     return;
14430: }
14431: 
14432: sub archive_row {
14433:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
14434:     my ($name) = ($item =~ m{([^/]+)$});
14435:     my %choices = &Apache::lonlocal::texthash (
14436:                                        'display'    => 'Add as file',
14437:                                        'dependency' => 'Include as dependency',
14438:                                        'discard'    => 'Discard',
14439:                                       );
14440:     if ($is_dir) {
14441:         $choices{'display'} = &mt('Add as folder'); 
14442:     }
14443:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
14444:     my $offset = 0;
14445:     foreach my $action ('display','dependency','discard') {
14446:         $offset ++;
14447:         if ($action ne 'display') {
14448:             $offset ++;
14449:         }  
14450:         $output .= '<td><span class="LC_nobreak">'.
14451:                    '<label><input type="radio" name="archive_'.$count.
14452:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
14453:         my $text = $choices{$action};
14454:         if ($is_dir) {
14455:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
14456:             if ($action eq 'display') {
14457:                 $text = &mt('Add as folder');
14458:             }
14459:         } else {
14460:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
14461: 
14462:         }
14463:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
14464:         if ($action eq 'dependency') {
14465:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
14466:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
14467:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
14468:                        '<option value=""></option>'."\n".
14469:                        '</select>'."\n".
14470:                        '</div>';
14471:         } elsif ($action eq 'display') {
14472:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
14473:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
14474:                        '</div>';
14475:         }
14476:         $output .= '</td>';
14477:     }
14478:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
14479:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
14480:     for (my $i=0; $i<$depth; $i++) {
14481:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
14482:     }
14483:     if ($is_dir) {
14484:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
14485:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
14486:     } else {
14487:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
14488:     }
14489:     $output .= '&nbsp;'.$name.'</td>'."\n".
14490:                &end_data_table_row();
14491:     return $output;
14492: }
14493: 
14494: sub archive_options_form {
14495:     my ($form,$display,$count,$hiddenelem) = @_;
14496:     my %lt = &Apache::lonlocal::texthash(
14497:                perm => 'Permanently remove archive file?',
14498:                hows => 'How should each extracted item be incorporated in the course?',
14499:                cont => 'Content actions for all',
14500:                addf => 'Add as folder/file',
14501:                incd => 'Include as dependency for a displayed file',
14502:                disc => 'Discard',
14503:                no   => 'No',
14504:                yes  => 'Yes',
14505:                save => 'Save',
14506:     );
14507:     my $output = <<"END";
14508: <form name="$form" method="post" action="">
14509: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
14510: <label>
14511:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
14512: </label>
14513: &nbsp;
14514: <label>
14515:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
14516: </span>
14517: </p>
14518: <input type="hidden" name="phase" value="decompress_cleanup" />
14519: <br />$lt{'hows'}
14520: <div class="LC_columnSection">
14521:   <fieldset>
14522:     <legend>$lt{'cont'}</legend>
14523:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
14524:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
14525:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
14526:   </fieldset>
14527: </div>
14528: END
14529:     return $output.
14530:            &start_data_table()."\n".
14531:            $display."\n".
14532:            &end_data_table()."\n".
14533:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
14534:            $hiddenelem.
14535:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
14536:            '</form>';
14537: }
14538: 
14539: sub archive_javascript {
14540:     my ($startcount,$numitems,$titles,$children) = @_;
14541:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
14542:     my $maintitle = $env{'form.comment'};
14543:     my $scripttag = <<START;
14544: <script type="text/javascript">
14545: // <![CDATA[
14546: 
14547: function checkAll(form,prefix) {
14548:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
14549:     for (var i=0; i < form.elements.length; i++) {
14550:         var id = form.elements[i].id;
14551:         if ((id != '') && (id != undefined)) {
14552:             if (idstr.test(id)) {
14553:                 if (form.elements[i].type == 'radio') {
14554:                     form.elements[i].checked = true;
14555:                     var nostart = i-$startcount;
14556:                     var offset = nostart%7;
14557:                     var count = (nostart-offset)/7;    
14558:                     dependencyCheck(form,count,offset);
14559:                 }
14560:             }
14561:         }
14562:     }
14563: }
14564: 
14565: function propagateCheck(form,count) {
14566:     if (count > 0) {
14567:         var startelement = $startcount + ((count-1) * 7);
14568:         for (var j=1; j<6; j++) {
14569:             if ((j != 2) && (j != 4)) {
14570:                 var item = startelement + j; 
14571:                 if (form.elements[item].type == 'radio') {
14572:                     if (form.elements[item].checked) {
14573:                         containerCheck(form,count,j);
14574:                         break;
14575:                     }
14576:                 }
14577:             }
14578:         }
14579:     }
14580: }
14581: 
14582: numitems = $numitems
14583: var titles = new Array(numitems);
14584: var parents = new Array(numitems);
14585: for (var i=0; i<numitems; i++) {
14586:     parents[i] = new Array;
14587: }
14588: var maintitle = '$maintitle';
14589: 
14590: START
14591: 
14592:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
14593:         my @contents = split(/:/,$children->{$container});
14594:         for (my $i=0; $i<@contents; $i ++) {
14595:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
14596:         }
14597:     }
14598: 
14599:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
14600:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
14601:     }
14602: 
14603:     $scripttag .= <<END;
14604: 
14605: function containerCheck(form,count,offset) {
14606:     if (count > 0) {
14607:         dependencyCheck(form,count,offset);
14608:         var item = (offset+$startcount)+7*(count-1);
14609:         form.elements[item].checked = true;
14610:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
14611:             if (parents[count].length > 0) {
14612:                 for (var j=0; j<parents[count].length; j++) {
14613:                     containerCheck(form,parents[count][j],offset);
14614:                 }
14615:             }
14616:         }
14617:     }
14618: }
14619: 
14620: function dependencyCheck(form,count,offset) {
14621:     if (count > 0) {
14622:         var chosen = (offset+$startcount)+7*(count-1);
14623:         var depitem = $startcount + ((count-1) * 7) + 4;
14624:         var currtype = form.elements[depitem].type;
14625:         if (form.elements[chosen].value == 'dependency') {
14626:             document.getElementById('arc_depon_'+count).style.display='block'; 
14627:             form.elements[depitem].options.length = 0;
14628:             form.elements[depitem].options[0] = new Option('Select','',true,true);
14629:             for (var i=1; i<=numitems; i++) {
14630:                 if (i == count) {
14631:                     continue;
14632:                 }
14633:                 var startelement = $startcount + (i-1) * 7;
14634:                 for (var j=1; j<6; j++) {
14635:                     if ((j != 2) && (j!= 4)) {
14636:                         var item = startelement + j;
14637:                         if (form.elements[item].type == 'radio') {
14638:                             if (form.elements[item].checked) {
14639:                                 if (form.elements[item].value == 'display') {
14640:                                     var n = form.elements[depitem].options.length;
14641:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
14642:                                 }
14643:                             }
14644:                         }
14645:                     }
14646:                 }
14647:             }
14648:         } else {
14649:             document.getElementById('arc_depon_'+count).style.display='none';
14650:             form.elements[depitem].options.length = 0;
14651:             form.elements[depitem].options[0] = new Option('Select','',true,true);
14652:         }
14653:         titleCheck(form,count,offset);
14654:     }
14655: }
14656: 
14657: function propagateSelect(form,count,offset) {
14658:     if (count > 0) {
14659:         var item = (1+offset+$startcount)+7*(count-1);
14660:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
14661:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
14662:             if (parents[count].length > 0) {
14663:                 for (var j=0; j<parents[count].length; j++) {
14664:                     containerSelect(form,parents[count][j],offset,picked);
14665:                 }
14666:             }
14667:         }
14668:     }
14669: }
14670: 
14671: function containerSelect(form,count,offset,picked) {
14672:     if (count > 0) {
14673:         var item = (offset+$startcount)+7*(count-1);
14674:         if (form.elements[item].type == 'radio') {
14675:             if (form.elements[item].value == 'dependency') {
14676:                 if (form.elements[item+1].type == 'select-one') {
14677:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
14678:                         if (form.elements[item+1].options[i].value == picked) {
14679:                             form.elements[item+1].selectedIndex = i;
14680:                             break;
14681:                         }
14682:                     }
14683:                 }
14684:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
14685:                     if (parents[count].length > 0) {
14686:                         for (var j=0; j<parents[count].length; j++) {
14687:                             containerSelect(form,parents[count][j],offset,picked);
14688:                         }
14689:                     }
14690:                 }
14691:             }
14692:         }
14693:     }
14694: }
14695: 
14696: function titleCheck(form,count,offset) {
14697:     if (count > 0) {
14698:         var chosen = (offset+$startcount)+7*(count-1);
14699:         var depitem = $startcount + ((count-1) * 7) + 2;
14700:         var currtype = form.elements[depitem].type;
14701:         if (form.elements[chosen].value == 'display') {
14702:             document.getElementById('arc_title_'+count).style.display='block';
14703:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
14704:                 document.getElementById('archive_title_'+count).value=maintitle;
14705:             }
14706:         } else {
14707:             document.getElementById('arc_title_'+count).style.display='none';
14708:             if (currtype == 'text') { 
14709:                 document.getElementById('archive_title_'+count).value='';
14710:             }
14711:         }
14712:     }
14713:     return;
14714: }
14715: 
14716: // ]]>
14717: </script>
14718: END
14719:     return $scripttag;
14720: }
14721: 
14722: sub process_extracted_files {
14723:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
14724:     my $numitems = $env{'form.archive_count'};
14725:     return if ((!$numitems) || ($numitems =~ /\D/));
14726:     my @ids=&Apache::lonnet::current_machine_ids();
14727:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
14728:         %folders,%containers,%mapinner,%prompttofetch);
14729:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
14730:     if (grep(/^\Q$docuhome\E$/,@ids)) {
14731:         $prefix = &LONCAPA::propath($docudom,$docuname);
14732:         $pathtocheck = "$dir_root/$destination";
14733:         $dir = $dir_root;
14734:         $ishome = 1;
14735:     } else {
14736:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
14737:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
14738:         $dir = "$dir_root/$docudom/$docuname";
14739:     }
14740:     my $currdir = "$dir_root/$destination";
14741:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
14742:     if ($env{'form.folderpath'}) {
14743:         my @items = split('&',$env{'form.folderpath'});
14744:         $folders{'0'} = $items[-2];
14745:         if ($env{'form.folderpath'} =~ /\:1$/) {
14746:             $containers{'0'}='page';
14747:         } else {  
14748:             $containers{'0'}='sequence';
14749:         }
14750:     }
14751:     my @archdirs = &get_env_multiple('form.archive_directory');
14752:     if ($numitems) {
14753:         for (my $i=1; $i<=$numitems; $i++) {
14754:             my $path = $env{'form.archive_content_'.$i};
14755:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
14756:                 my $item = $1;
14757:                 $toplevelitems{$item} = $i;
14758:                 if (grep(/^\Q$i\E$/,@archdirs)) {
14759:                     $is_dir{$item} = 1;
14760:                 }
14761:             }
14762:         }
14763:     }
14764:     my ($output,%children,%parent,%titles,%dirorder,$result);
14765:     if (keys(%toplevelitems) > 0) {
14766:         my @contents = sort(keys(%toplevelitems));
14767:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
14768:                                            \%parent,\@contents,\%dirorder,\%titles);
14769:     }
14770:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
14771:     if ($numitems) {
14772:         for (my $i=1; $i<=$numitems; $i++) {
14773:             next if ($env{'form.archive_'.$i} eq 'dependency');
14774:             my $path = $env{'form.archive_content_'.$i};
14775:             if ($path =~ /^\Q$pathtocheck\E/) {
14776:                 if ($env{'form.archive_'.$i} eq 'discard') {
14777:                     if ($prefix ne '' && $path ne '') {
14778:                         if (-e $prefix.$path) {
14779:                             if ((@archdirs > 0) && 
14780:                                 (grep(/^\Q$i\E$/,@archdirs))) {
14781:                                 $todeletedir{$prefix.$path} = 1;
14782:                             } else {
14783:                                 $todelete{$prefix.$path} = 1;
14784:                             }
14785:                         }
14786:                     }
14787:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
14788:                     my ($docstitle,$title,$url,$outer);
14789:                     ($title) = ($path =~ m{/([^/]+)$});
14790:                     $docstitle = $env{'form.archive_title_'.$i};
14791:                     if ($docstitle eq '') {
14792:                         $docstitle = $title;
14793:                     }
14794:                     $outer = 0;
14795:                     if (ref($dirorder{$i}) eq 'ARRAY') {
14796:                         if (@{$dirorder{$i}} > 0) {
14797:                             foreach my $item (reverse(@{$dirorder{$i}})) {
14798:                                 if ($env{'form.archive_'.$item} eq 'display') {
14799:                                     $outer = $item;
14800:                                     last;
14801:                                 }
14802:                             }
14803:                         }
14804:                     }
14805:                     my ($errtext,$fatal) = 
14806:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
14807:                                                '/'.$folders{$outer}.'.'.
14808:                                                $containers{$outer});
14809:                     next if ($fatal);
14810:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
14811:                         if ($context eq 'coursedocs') {
14812:                             $mapinner{$i} = time;
14813:                             $folders{$i} = 'default_'.$mapinner{$i};
14814:                             $containers{$i} = 'sequence';
14815:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
14816:                                       $folders{$i}.'.'.$containers{$i};
14817:                             my $newidx = &LONCAPA::map::getresidx();
14818:                             $LONCAPA::map::resources[$newidx]=
14819:                                 $docstitle.':'.$url.':false:normal:res';
14820:                             push(@LONCAPA::map::order,$newidx);
14821:                             my ($outtext,$errtext) =
14822:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
14823:                                                         $docuname.'/'.$folders{$outer}.
14824:                                                         '.'.$containers{$outer},1,1);
14825:                             $newseqid{$i} = $newidx;
14826:                             unless ($errtext) {
14827:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
14828:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
14829:                                             '</li>'."\n";
14830:                             }
14831:                         }
14832:                     } else {
14833:                         if ($context eq 'coursedocs') {
14834:                             my $newidx=&LONCAPA::map::getresidx();
14835:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
14836:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
14837:                                       $title;
14838:                             if (($outer !~ /\D/) &&
14839:                                 (($mapinner{$outer} eq 'default') || ($mapinner{$outer} !~ /\D/)) &&
14840:                                 ($newidx !~ /\D/)) {
14841:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
14842:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
14843:                                 }
14844:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
14845:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
14846:                                 }
14847:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
14848:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
14849:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
14850:                                         unless ($ishome) {
14851:                                             my $fetch = "$newdest{$i}/$title";
14852:                                             $fetch =~ s/^\Q$prefix$dir\E//;
14853:                                             $prompttofetch{$fetch} = 1;
14854:                                         }
14855:                                     }
14856:                                 }
14857:                                 $LONCAPA::map::resources[$newidx]=
14858:                                     $docstitle.':'.$url.':false:normal:res';
14859:                                 push(@LONCAPA::map::order, $newidx);
14860:                                 my ($outtext,$errtext)=
14861:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
14862:                                                             $docuname.'/'.$folders{$outer}.
14863:                                                             '.'.$containers{$outer},1,1);
14864:                                 unless ($errtext) {
14865:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
14866:                                         $result .= '<li>'.&mt('File: [_1] added to course',
14867:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
14868:                                                    '</li>'."\n";
14869:                                     }
14870:                                 }
14871:                             } else {
14872:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
14873:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
14874:                             }
14875:                         }
14876:                     }
14877:                 }
14878:             } else {
14879:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
14880:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
14881:             }
14882:         }
14883:         for (my $i=1; $i<=$numitems; $i++) {
14884:             next unless ($env{'form.archive_'.$i} eq 'dependency');
14885:             my $path = $env{'form.archive_content_'.$i};
14886:             if ($path =~ /^\Q$pathtocheck\E/) {
14887:                 my ($title) = ($path =~ m{/([^/]+)$});
14888:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
14889:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
14890:                     if (ref($dirorder{$i}) eq 'ARRAY') {
14891:                         my ($itemidx,$fullpath,$relpath);
14892:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
14893:                             my $container = $dirorder{$referrer{$i}}->[-1];
14894:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
14895:                                 if ($dirorder{$i}->[$j] eq $container) {
14896:                                     $itemidx = $j;
14897:                                 }
14898:                             }
14899:                         }
14900:                         if ($itemidx eq '') {
14901:                             $itemidx =  0;
14902:                         } 
14903:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
14904:                             if ($mapinner{$referrer{$i}}) {
14905:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
14906:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
14907:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
14908:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
14909:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
14910:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
14911:                                             if (!-e $fullpath) {
14912:                                                 mkdir($fullpath,0755);
14913:                                             }
14914:                                         }
14915:                                     } else {
14916:                                         last;
14917:                                     }
14918:                                 }
14919:                             }
14920:                         } elsif ($newdest{$referrer{$i}}) {
14921:                             $fullpath = $newdest{$referrer{$i}};
14922:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
14923:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
14924:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
14925:                                     last;
14926:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
14927:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
14928:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
14929:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
14930:                                         if (!-e $fullpath) {
14931:                                             mkdir($fullpath,0755);
14932:                                         }
14933:                                     }
14934:                                 } else {
14935:                                     last;
14936:                                 }
14937:                             }
14938:                         }
14939:                         if ($fullpath ne '') {
14940:                             if (-e "$prefix$path") {
14941:                                 unless (rename("$prefix$path","$fullpath/$title")) {
14942:                                      $warning .= &mt('Failed to rename dependency').'<br />';
14943:                                 }
14944:                             }
14945:                             if (-e "$fullpath/$title") {
14946:                                 my $showpath;
14947:                                 if ($relpath ne '') {
14948:                                     $showpath = "$relpath/$title";
14949:                                 } else {
14950:                                     $showpath = "/$title";
14951:                                 } 
14952:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
14953:                                                       &HTML::Entities::encode($showpath,'<>&"')).
14954:                                            '</li>'."\n";
14955:                                 unless ($ishome) {
14956:                                     my $fetch = "$fullpath/$title";
14957:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
14958:                                     $prompttofetch{$fetch} = 1;
14959:                                 }
14960:                             }
14961:                         }
14962:                     }
14963:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
14964:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
14965:                                     &HTML::Entities::encode($path,'<>&"'),
14966:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
14967:                                 '<br />';
14968:                 }
14969:             } else {
14970:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
14971:                                 &HTML::Entities::encode($path)).'<br />';
14972:             }
14973:         }
14974:         if (keys(%todelete)) {
14975:             foreach my $key (keys(%todelete)) {
14976:                 unlink($key);
14977:             }
14978:         }
14979:         if (keys(%todeletedir)) {
14980:             foreach my $key (keys(%todeletedir)) {
14981:                 rmdir($key);
14982:             }
14983:         }
14984:         foreach my $dir (sort(keys(%is_dir))) {
14985:             if (($pathtocheck ne '') && ($dir ne ''))  {
14986:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
14987:             }
14988:         }
14989:         if ($result ne '') {
14990:             $output .= '<ul>'."\n".
14991:                        $result."\n".
14992:                        '</ul>';
14993:         }
14994:         unless ($ishome) {
14995:             my $replicationfail;
14996:             foreach my $item (keys(%prompttofetch)) {
14997:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
14998:                 unless ($fetchresult eq 'ok') {
14999:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
15000:                 }
15001:             }
15002:             if ($replicationfail) {
15003:                 $output .= '<p class="LC_error">'.
15004:                            &mt('Course home server failed to retrieve:').'<ul>'.
15005:                            $replicationfail.
15006:                            '</ul></p>';
15007:             }
15008:         }
15009:     } else {
15010:         $warning = &mt('No items found in archive.');
15011:     }
15012:     if ($error) {
15013:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
15014:                    $error.'</p>'."\n";
15015:     }
15016:     if ($warning) {
15017:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
15018:     }
15019:     return $output;
15020: }
15021: 
15022: sub cleanup_empty_dirs {
15023:     my ($path) = @_;
15024:     if (($path ne '') && (-d $path)) {
15025:         if (opendir(my $dirh,$path)) {
15026:             my @dircontents = grep(!/^\./,readdir($dirh));
15027:             my $numitems = 0;
15028:             foreach my $item (@dircontents) {
15029:                 if (-d "$path/$item") {
15030:                     &cleanup_empty_dirs("$path/$item");
15031:                     if (-e "$path/$item") {
15032:                         $numitems ++;
15033:                     }
15034:                 } else {
15035:                     $numitems ++;
15036:                 }
15037:             }
15038:             if ($numitems == 0) {
15039:                 rmdir($path);
15040:             }
15041:             closedir($dirh);
15042:         }
15043:     }
15044:     return;
15045: }
15046: 
15047: =pod
15048: 
15049: =item * &get_folder_hierarchy()
15050: 
15051: Provides hierarchy of names of folders/sub-folders containing the current
15052: item,
15053: 
15054: Inputs: 3
15055:      - $navmap - navmaps object
15056: 
15057:      - $map - url for map (either the trigger itself, or map containing
15058:                            the resource, which is the trigger).
15059: 
15060:      - $showitem - 1 => show title for map itself; 0 => do not show.
15061: 
15062: Outputs: 1 @pathitems - array of folder/subfolder names.
15063: 
15064: =cut
15065: 
15066: sub get_folder_hierarchy {
15067:     my ($navmap,$map,$showitem) = @_;
15068:     my @pathitems;
15069:     if (ref($navmap)) {
15070:         my $mapres = $navmap->getResourceByUrl($map);
15071:         if (ref($mapres)) {
15072:             my $pcslist = $mapres->map_hierarchy();
15073:             if ($pcslist ne '') {
15074:                 my @pcs = split(/,/,$pcslist);
15075:                 foreach my $pc (@pcs) {
15076:                     if ($pc == 1) {
15077:                         push(@pathitems,&mt('Main Content'));
15078:                     } else {
15079:                         my $res = $navmap->getByMapPc($pc);
15080:                         if (ref($res)) {
15081:                             my $title = $res->compTitle();
15082:                             $title =~ s/\W+/_/g;
15083:                             if ($title ne '') {
15084:                                 push(@pathitems,$title);
15085:                             }
15086:                         }
15087:                     }
15088:                 }
15089:             }
15090:             if ($showitem) {
15091:                 if ($mapres->{ID} eq '0.0') {
15092:                     push(@pathitems,&mt('Main Content'));
15093:                 } else {
15094:                     my $maptitle = $mapres->compTitle();
15095:                     $maptitle =~ s/\W+/_/g;
15096:                     if ($maptitle ne '') {
15097:                         push(@pathitems,$maptitle);
15098:                     }
15099:                 }
15100:             }
15101:         }
15102:     }
15103:     return @pathitems;
15104: }
15105: 
15106: =pod
15107: 
15108: =item * &get_turnedin_filepath()
15109: 
15110: Determines path in a user's portfolio file for storage of files uploaded
15111: to a specific essayresponse or dropbox item.
15112: 
15113: Inputs: 3 required + 1 optional.
15114: $symb is symb for resource, $uname and $udom are for current user (required).
15115: $caller is optional (can be "submission", if routine is called when storing
15116: an upoaded file when "Submit Answer" button was pressed).
15117: 
15118: Returns array containing $path and $multiresp. 
15119: $path is path in portfolio.  $multiresp is 1 if this resource contains more
15120: than one file upload item.  Callers of routine should append partid as a 
15121: subdirectory to $path in cases where $multiresp is 1.
15122: 
15123: Called by: homework/essayresponse.pm and homework/structuretags.pm
15124: 
15125: =cut
15126: 
15127: sub get_turnedin_filepath {
15128:     my ($symb,$uname,$udom,$caller) = @_;
15129:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
15130:     my $turnindir;
15131:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
15132:     $turnindir = $userhash{'turnindir'};
15133:     my ($path,$multiresp);
15134:     if ($turnindir eq '') {
15135:         if ($caller eq 'submission') {
15136:             $turnindir = &mt('turned in');
15137:             $turnindir =~ s/\W+/_/g;
15138:             my %newhash = (
15139:                             'turnindir' => $turnindir,
15140:                           );
15141:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
15142:         }
15143:     }
15144:     if ($turnindir ne '') {
15145:         $path = '/'.$turnindir.'/';
15146:         my ($multipart,$turnin,@pathitems);
15147:         my $navmap = Apache::lonnavmaps::navmap->new();
15148:         if (defined($navmap)) {
15149:             my $mapres = $navmap->getResourceByUrl($map);
15150:             if (ref($mapres)) {
15151:                 my $pcslist = $mapres->map_hierarchy();
15152:                 if ($pcslist ne '') {
15153:                     foreach my $pc (split(/,/,$pcslist)) {
15154:                         my $res = $navmap->getByMapPc($pc);
15155:                         if (ref($res)) {
15156:                             my $title = $res->compTitle();
15157:                             $title =~ s/\W+/_/g;
15158:                             if ($title ne '') {
15159:                                 if (($pc > 1) && (length($title) > 12)) {
15160:                                     $title = substr($title,0,12);
15161:                                 }
15162:                                 push(@pathitems,$title);
15163:                             }
15164:                         }
15165:                     }
15166:                 }
15167:                 my $maptitle = $mapres->compTitle();
15168:                 $maptitle =~ s/\W+/_/g;
15169:                 if ($maptitle ne '') {
15170:                     if (length($maptitle) > 12) {
15171:                         $maptitle = substr($maptitle,0,12);
15172:                     }
15173:                     push(@pathitems,$maptitle);
15174:                 }
15175:                 unless ($env{'request.state'} eq 'construct') {
15176:                     my $res = $navmap->getBySymb($symb);
15177:                     if (ref($res)) {
15178:                         my $partlist = $res->parts();
15179:                         my $totaluploads = 0;
15180:                         if (ref($partlist) eq 'ARRAY') {
15181:                             foreach my $part (@{$partlist}) {
15182:                                 my @types = $res->responseType($part);
15183:                                 my @ids = $res->responseIds($part);
15184:                                 for (my $i=0; $i < scalar(@ids); $i++) {
15185:                                     if ($types[$i] eq 'essay') {
15186:                                         my $partid = $part.'_'.$ids[$i];
15187:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
15188:                                             $totaluploads ++;
15189:                                         }
15190:                                     }
15191:                                 }
15192:                             }
15193:                             if ($totaluploads > 1) {
15194:                                 $multiresp = 1;
15195:                             }
15196:                         }
15197:                     }
15198:                 }
15199:             } else {
15200:                 return;
15201:             }
15202:         } else {
15203:             return;
15204:         }
15205:         my $restitle=&Apache::lonnet::gettitle($symb);
15206:         $restitle =~ s/\W+/_/g;
15207:         if ($restitle eq '') {
15208:             $restitle = ($resurl =~ m{/[^/]+$});
15209:             if ($restitle eq '') {
15210:                 $restitle = time;
15211:             }
15212:         }
15213:         if (length($restitle) > 12) {
15214:             $restitle = substr($restitle,0,12);
15215:         }
15216:         push(@pathitems,$restitle);
15217:         $path .= join('/',@pathitems);
15218:     }
15219:     return ($path,$multiresp);
15220: }
15221: 
15222: =pod
15223: 
15224: =back
15225: 
15226: =head1 CSV Upload/Handling functions
15227: 
15228: =over 4
15229: 
15230: =item * &upfile_store($r)
15231: 
15232: Store uploaded file, $r should be the HTTP Request object,
15233: needs $env{'form.upfile'}
15234: returns $datatoken to be put into hidden field
15235: 
15236: =cut
15237: 
15238: sub upfile_store {
15239:     my $r=shift;
15240:     $env{'form.upfile'}=~s/\r/\n/gs;
15241:     $env{'form.upfile'}=~s/\f/\n/gs;
15242:     $env{'form.upfile'}=~s/\n+/\n/gs;
15243:     $env{'form.upfile'}=~s/\n+$//gs;
15244: 
15245:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
15246:                                      '_enroll_'.$env{'request.course.id'}.'_'.
15247:                                      time.'_'.$$);
15248:     return if ($datatoken eq '');
15249: 
15250:     {
15251:         my $datafile = $r->dir_config('lonDaemons').
15252:                            '/tmp/'.$datatoken.'.tmp';
15253:         if ( open(my $fh,'>',$datafile) ) {
15254:             print $fh $env{'form.upfile'};
15255:             close($fh);
15256:         }
15257:     }
15258:     return $datatoken;
15259: }
15260: 
15261: =pod
15262: 
15263: =item * &load_tmp_file($r,$datatoken)
15264: 
15265: Load uploaded file from tmp, $r should be the HTTP Request object,
15266: $datatoken is the name to assign to the temporary file.
15267: sets $env{'form.upfile'} to the contents of the file
15268: 
15269: =cut
15270: 
15271: sub load_tmp_file {
15272:     my ($r,$datatoken) = @_;
15273:     return if ($datatoken eq '');
15274:     my @studentdata=();
15275:     {
15276:         my $studentfile = $r->dir_config('lonDaemons').
15277:                               '/tmp/'.$datatoken.'.tmp';
15278:         if ( open(my $fh,'<',$studentfile) ) {
15279:             @studentdata=<$fh>;
15280:             close($fh);
15281:         }
15282:     }
15283:     $env{'form.upfile'}=join('',@studentdata);
15284: }
15285: 
15286: sub valid_datatoken {
15287:     my ($datatoken) = @_;
15288:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
15289:         return $datatoken;
15290:     }
15291:     return;
15292: }
15293: 
15294: =pod
15295: 
15296: =item * &upfile_record_sep()
15297: 
15298: Separate uploaded file into records
15299: returns array of records,
15300: needs $env{'form.upfile'} and $env{'form.upfiletype'}
15301: 
15302: =cut
15303: 
15304: sub upfile_record_sep {
15305:     if ($env{'form.upfiletype'} eq 'xml') {
15306:     } else {
15307: 	my @records;
15308: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
15309: 	    if ($line=~/^\s*$/) { next; }
15310: 	    push(@records,$line);
15311: 	}
15312: 	return @records;
15313:     }
15314: }
15315: 
15316: =pod
15317: 
15318: =item * &record_sep($record)
15319: 
15320: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
15321: 
15322: =cut
15323: 
15324: sub takeleft {
15325:     my $index=shift;
15326:     return substr('0000'.$index,-4,4);
15327: }
15328: 
15329: sub record_sep {
15330:     my $record=shift;
15331:     my %components=();
15332:     if ($env{'form.upfiletype'} eq 'xml') {
15333:     } elsif ($env{'form.upfiletype'} eq 'space') {
15334:         my $i=0;
15335:         foreach my $field (split(/\s+/,$record)) {
15336:             $field=~s/^(\"|\')//;
15337:             $field=~s/(\"|\')$//;
15338:             $components{&takeleft($i)}=$field;
15339:             $i++;
15340:         }
15341:     } elsif ($env{'form.upfiletype'} eq 'tab') {
15342:         my $i=0;
15343:         foreach my $field (split(/\t/,$record)) {
15344:             $field=~s/^(\"|\')//;
15345:             $field=~s/(\"|\')$//;
15346:             $components{&takeleft($i)}=$field;
15347:             $i++;
15348:         }
15349:     } else {
15350:         my $separator=',';
15351:         if ($env{'form.upfiletype'} eq 'semisv') {
15352:             $separator=';';
15353:         }
15354:         my $i=0;
15355: # the character we are looking for to indicate the end of a quote or a record 
15356:         my $looking_for=$separator;
15357: # do not add the characters to the fields
15358:         my $ignore=0;
15359: # we just encountered a separator (or the beginning of the record)
15360:         my $just_found_separator=1;
15361: # store the field we are working on here
15362:         my $field='';
15363: # work our way through all characters in record
15364:         foreach my $character ($record=~/(.)/g) {
15365:             if ($character eq $looking_for) {
15366:                if ($character ne $separator) {
15367: # Found the end of a quote, again looking for separator
15368:                   $looking_for=$separator;
15369:                   $ignore=1;
15370:                } else {
15371: # Found a separator, store away what we got
15372:                   $components{&takeleft($i)}=$field;
15373: 	          $i++;
15374:                   $just_found_separator=1;
15375:                   $ignore=0;
15376:                   $field='';
15377:                }
15378:                next;
15379:             }
15380: # single or double quotation marks after a separator indicate beginning of a quote
15381: # we are now looking for the end of the quote and need to ignore separators
15382:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
15383:                $looking_for=$character;
15384:                next;
15385:             }
15386: # ignore would be true after we reached the end of a quote
15387:             if ($ignore) { next; }
15388:             if (($just_found_separator) && ($character=~/\s/)) { next; }
15389:             $field.=$character;
15390:             $just_found_separator=0; 
15391:         }
15392: # catch the very last entry, since we never encountered the separator
15393:         $components{&takeleft($i)}=$field;
15394:     }
15395:     return %components;
15396: }
15397: 
15398: ######################################################
15399: ######################################################
15400: 
15401: =pod
15402: 
15403: =item * &upfile_select_html()
15404: 
15405: Return HTML code to select a file from the users machine and specify 
15406: the file type.
15407: 
15408: =cut
15409: 
15410: ######################################################
15411: ######################################################
15412: sub upfile_select_html {
15413:     my %Types = (
15414:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
15415:                  semisv => &mt('Semicolon separated values'),
15416:                  space => &mt('Space separated'),
15417:                  tab   => &mt('Tabulator separated'),
15418: #                 xml   => &mt('HTML/XML'),
15419:                  );
15420:     my $Str = '<input type="file" name="upfile" size="50" />'.
15421:         '<br />'.&mt('Type').': <select name="upfiletype">';
15422:     foreach my $type (sort(keys(%Types))) {
15423:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
15424:     }
15425:     $Str .= "</select>\n";
15426:     return $Str;
15427: }
15428: 
15429: sub get_samples {
15430:     my ($records,$toget) = @_;
15431:     my @samples=({});
15432:     my $got=0;
15433:     foreach my $rec (@$records) {
15434: 	my %temp = &record_sep($rec);
15435: 	if (! grep(/\S/, values(%temp))) { next; }
15436: 	if (%temp) {
15437: 	    $samples[$got]=\%temp;
15438: 	    $got++;
15439: 	    if ($got == $toget) { last; }
15440: 	}
15441:     }
15442:     return \@samples;
15443: }
15444: 
15445: ######################################################
15446: ######################################################
15447: 
15448: =pod
15449: 
15450: =item * &csv_print_samples($r,$records)
15451: 
15452: Prints a table of sample values from each column uploaded $r is an
15453: Apache Request ref, $records is an arrayref from
15454: &Apache::loncommon::upfile_record_sep
15455: 
15456: =cut
15457: 
15458: ######################################################
15459: ######################################################
15460: sub csv_print_samples {
15461:     my ($r,$records) = @_;
15462:     my $samples = &get_samples($records,5);
15463: 
15464:     $r->print(&mt('Samples').'<br />'.&start_data_table().
15465:               &start_data_table_header_row());
15466:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
15467:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
15468:     $r->print(&end_data_table_header_row());
15469:     foreach my $hash (@$samples) {
15470: 	$r->print(&start_data_table_row());
15471: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
15472: 	    $r->print('<td>');
15473: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
15474: 	    $r->print('</td>');
15475: 	}
15476: 	$r->print(&end_data_table_row());
15477:     }
15478:     $r->print(&end_data_table().'<br />'."\n");
15479: }
15480: 
15481: ######################################################
15482: ######################################################
15483: 
15484: =pod
15485: 
15486: =item * &csv_print_select_table($r,$records,$d)
15487: 
15488: Prints a table to create associations between values and table columns.
15489: 
15490: $r is an Apache Request ref,
15491: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
15492: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
15493: 
15494: =cut
15495: 
15496: ######################################################
15497: ######################################################
15498: sub csv_print_select_table {
15499:     my ($r,$records,$d) = @_;
15500:     my $i=0;
15501:     my $samples = &get_samples($records,1);
15502:     $r->print(&mt('Associate columns with student attributes.')."\n".
15503: 	      &start_data_table().&start_data_table_header_row().
15504:               '<th>'.&mt('Attribute').'</th>'.
15505:               '<th>'.&mt('Column').'</th>'.
15506:               &end_data_table_header_row()."\n");
15507:     foreach my $array_ref (@$d) {
15508: 	my ($value,$display,$defaultcol)=@{ $array_ref };
15509: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
15510: 
15511: 	$r->print('<td><select name="f'.$i.'"'.
15512: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
15513: 	$r->print('<option value="none"></option>');
15514: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
15515: 	    $r->print('<option value="'.$sample.'"'.
15516:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
15517:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
15518: 	}
15519: 	$r->print('</select></td>'.&end_data_table_row()."\n");
15520: 	$i++;
15521:     }
15522:     $r->print(&end_data_table());
15523:     $i--;
15524:     return $i;
15525: }
15526: 
15527: ######################################################
15528: ######################################################
15529: 
15530: =pod
15531: 
15532: =item * &csv_samples_select_table($r,$records,$d)
15533: 
15534: Prints a table of sample values from the upload and can make associate samples to internal names.
15535: 
15536: $r is an Apache Request ref,
15537: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
15538: $d is an array of 2 element arrays (internal name, displayed name)
15539: 
15540: =cut
15541: 
15542: ######################################################
15543: ######################################################
15544: sub csv_samples_select_table {
15545:     my ($r,$records,$d) = @_;
15546:     my $i=0;
15547:     #
15548:     my $max_samples = 5;
15549:     my $samples = &get_samples($records,$max_samples);
15550:     $r->print(&start_data_table().
15551:               &start_data_table_header_row().'<th>'.
15552:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
15553:               &end_data_table_header_row());
15554: 
15555:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
15556: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
15557: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
15558: 	foreach my $option (@$d) {
15559: 	    my ($value,$display,$defaultcol)=@{ $option };
15560: 	    $r->print('<option value="'.$value.'"'.
15561:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
15562:                       $display.'</option>');
15563: 	}
15564: 	$r->print('</select></td><td>');
15565: 	foreach my $line (0..($max_samples-1)) {
15566: 	    if (defined($samples->[$line]{$key})) { 
15567: 		$r->print($samples->[$line]{$key}."<br />\n"); 
15568: 	    }
15569: 	}
15570: 	$r->print('</td>'.&end_data_table_row());
15571: 	$i++;
15572:     }
15573:     $r->print(&end_data_table());
15574:     $i--;
15575:     return($i);
15576: }
15577: 
15578: ######################################################
15579: ######################################################
15580: 
15581: =pod
15582: 
15583: =item * &clean_excel_name($name)
15584: 
15585: Returns a replacement for $name which does not contain any illegal characters.
15586: 
15587: =cut
15588: 
15589: ######################################################
15590: ######################################################
15591: sub clean_excel_name {
15592:     my ($name) = @_;
15593:     $name =~ s/[:\*\?\/\\]//g;
15594:     if (length($name) > 31) {
15595:         $name = substr($name,0,31);
15596:     }
15597:     return $name;
15598: }
15599: 
15600: =pod
15601: 
15602: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
15603: 
15604: Returns either 1 or undef
15605: 
15606: 1 if the part is to be hidden, undef if it is to be shown
15607: 
15608: Arguments are:
15609: 
15610: $id the id of the part to be checked
15611: $symb, optional the symb of the resource to check
15612: $udom, optional the domain of the user to check for
15613: $uname, optional the username of the user to check for
15614: 
15615: =cut
15616: 
15617: sub check_if_partid_hidden {
15618:     my ($id,$symb,$udom,$uname) = @_;
15619:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
15620: 					 $symb,$udom,$uname);
15621:     my $truth=1;
15622:     #if the string starts with !, then the list is the list to show not hide
15623:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
15624:     my @hiddenlist=split(/,/,$hiddenparts);
15625:     foreach my $checkid (@hiddenlist) {
15626: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
15627:     }
15628:     return !$truth;
15629: }
15630: 
15631: 
15632: ############################################################
15633: ############################################################
15634: 
15635: =pod
15636: 
15637: =back 
15638: 
15639: =head1 cgi-bin script and graphing routines
15640: 
15641: =over 4
15642: 
15643: =item * &get_cgi_id()
15644: 
15645: Inputs: none
15646: 
15647: Returns an id which can be used to pass environment variables
15648: to various cgi-bin scripts.  These environment variables will
15649: be removed from the users environment after a given time by
15650: the routine &Apache::lonnet::transfer_profile_to_env.
15651: 
15652: =cut
15653: 
15654: ############################################################
15655: ############################################################
15656: my $uniq=0;
15657: sub get_cgi_id {
15658:     $uniq=($uniq+1)%100000;
15659:     return (time.'_'.$$.'_'.$uniq);
15660: }
15661: 
15662: ############################################################
15663: ############################################################
15664: 
15665: =pod
15666: 
15667: =item * &DrawBarGraph()
15668: 
15669: Facilitates the plotting of data in a (stacked) bar graph.
15670: Puts plot definition data into the users environment in order for 
15671: graph.png to plot it.  Returns an <img> tag for the plot.
15672: The bars on the plot are labeled '1','2',...,'n'.
15673: 
15674: Inputs:
15675: 
15676: =over 4
15677: 
15678: =item $Title: string, the title of the plot
15679: 
15680: =item $xlabel: string, text describing the X-axis of the plot
15681: 
15682: =item $ylabel: string, text describing the Y-axis of the plot
15683: 
15684: =item $Max: scalar, the maximum Y value to use in the plot
15685: If $Max is < any data point, the graph will not be rendered.
15686: 
15687: =item $colors: array ref holding the colors to be used for the data sets when
15688: they are plotted.  If undefined, default values will be used.
15689: 
15690: =item $labels: array ref holding the labels to use on the x-axis for the bars.
15691: 
15692: =item @Values: An array of array references.  Each array reference holds data
15693: to be plotted in a stacked bar chart.
15694: 
15695: =item If the final element of @Values is a hash reference the key/value
15696: pairs will be added to the graph definition.
15697: 
15698: =back
15699: 
15700: Returns:
15701: 
15702: An <img> tag which references graph.png and the appropriate identifying
15703: information for the plot.
15704: 
15705: =cut
15706: 
15707: ############################################################
15708: ############################################################
15709: sub DrawBarGraph {
15710:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
15711:     #
15712:     if (! defined($colors)) {
15713:         $colors = ['#33ff00', 
15714:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
15715:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
15716:                   ]; 
15717:     }
15718:     my $extra_settings = {};
15719:     if (ref($Values[-1]) eq 'HASH') {
15720:         $extra_settings = pop(@Values);
15721:     }
15722:     #
15723:     my $identifier = &get_cgi_id();
15724:     my $id = 'cgi.'.$identifier;        
15725:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
15726:         return '';
15727:     }
15728:     #
15729:     my @Labels;
15730:     if (defined($labels)) {
15731:         @Labels = @$labels;
15732:     } else {
15733:         for (my $i=0;$i<@{$Values[0]};$i++) {
15734:             push(@Labels,$i+1);
15735:         }
15736:     }
15737:     #
15738:     my $NumBars = scalar(@{$Values[0]});
15739:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
15740:     my %ValuesHash;
15741:     my $NumSets=1;
15742:     foreach my $array (@Values) {
15743:         next if (! ref($array));
15744:         $ValuesHash{$id.'.data.'.$NumSets++} = 
15745:             join(',',@$array);
15746:     }
15747:     #
15748:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
15749:     if ($NumBars < 3) {
15750:         $width = 120+$NumBars*32;
15751:         $xskip = 1;
15752:         $bar_width = 30;
15753:     } elsif ($NumBars < 5) {
15754:         $width = 120+$NumBars*20;
15755:         $xskip = 1;
15756:         $bar_width = 20;
15757:     } elsif ($NumBars < 10) {
15758:         $width = 120+$NumBars*15;
15759:         $xskip = 1;
15760:         $bar_width = 15;
15761:     } elsif ($NumBars <= 25) {
15762:         $width = 120+$NumBars*11;
15763:         $xskip = 5;
15764:         $bar_width = 8;
15765:     } elsif ($NumBars <= 50) {
15766:         $width = 120+$NumBars*8;
15767:         $xskip = 5;
15768:         $bar_width = 4;
15769:     } else {
15770:         $width = 120+$NumBars*8;
15771:         $xskip = 5;
15772:         $bar_width = 4;
15773:     }
15774:     #
15775:     $Max = 1 if ($Max < 1);
15776:     if ( int($Max) < $Max ) {
15777:         $Max++;
15778:         $Max = int($Max);
15779:     }
15780:     $Title  = '' if (! defined($Title));
15781:     $xlabel = '' if (! defined($xlabel));
15782:     $ylabel = '' if (! defined($ylabel));
15783:     $ValuesHash{$id.'.title'}    = &escape($Title);
15784:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
15785:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
15786:     $ValuesHash{$id.'.y_max_value'} = $Max;
15787:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
15788:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
15789:     $ValuesHash{$id.'.PlotType'} = 'bar';
15790:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
15791:     $ValuesHash{$id.'.height'}   = $height;
15792:     $ValuesHash{$id.'.width'}    = $width;
15793:     $ValuesHash{$id.'.xskip'}    = $xskip;
15794:     $ValuesHash{$id.'.bar_width'} = $bar_width;
15795:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
15796:     #
15797:     # Deal with other parameters
15798:     while (my ($key,$value) = each(%$extra_settings)) {
15799:         $ValuesHash{$id.'.'.$key} = $value;
15800:     }
15801:     #
15802:     &Apache::lonnet::appenv(\%ValuesHash);
15803:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15804: }
15805: 
15806: ############################################################
15807: ############################################################
15808: 
15809: =pod
15810: 
15811: =item * &DrawXYGraph()
15812: 
15813: Facilitates the plotting of data in an XY graph.
15814: Puts plot definition data into the users environment in order for 
15815: graph.png to plot it.  Returns an <img> tag for the plot.
15816: 
15817: Inputs:
15818: 
15819: =over 4
15820: 
15821: =item $Title: string, the title of the plot
15822: 
15823: =item $xlabel: string, text describing the X-axis of the plot
15824: 
15825: =item $ylabel: string, text describing the Y-axis of the plot
15826: 
15827: =item $Max: scalar, the maximum Y value to use in the plot
15828: If $Max is < any data point, the graph will not be rendered.
15829: 
15830: =item $colors: Array ref containing the hex color codes for the data to be 
15831: plotted in.  If undefined, default values will be used.
15832: 
15833: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
15834: 
15835: =item $Ydata: Array ref containing Array refs.  
15836: Each of the contained arrays will be plotted as a separate curve.
15837: 
15838: =item %Values: hash indicating or overriding any default values which are 
15839: passed to graph.png.  
15840: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
15841: 
15842: =back
15843: 
15844: Returns:
15845: 
15846: An <img> tag which references graph.png and the appropriate identifying
15847: information for the plot.
15848: 
15849: =cut
15850: 
15851: ############################################################
15852: ############################################################
15853: sub DrawXYGraph {
15854:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
15855:     #
15856:     # Create the identifier for the graph
15857:     my $identifier = &get_cgi_id();
15858:     my $id = 'cgi.'.$identifier;
15859:     #
15860:     $Title  = '' if (! defined($Title));
15861:     $xlabel = '' if (! defined($xlabel));
15862:     $ylabel = '' if (! defined($ylabel));
15863:     my %ValuesHash = 
15864:         (
15865:          $id.'.title'  => &escape($Title),
15866:          $id.'.xlabel' => &escape($xlabel),
15867:          $id.'.ylabel' => &escape($ylabel),
15868:          $id.'.y_max_value'=> $Max,
15869:          $id.'.labels'     => join(',',@$Xlabels),
15870:          $id.'.PlotType'   => 'XY',
15871:          );
15872:     #
15873:     if (defined($colors) && ref($colors) eq 'ARRAY') {
15874:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
15875:     }
15876:     #
15877:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
15878:         return '';
15879:     }
15880:     my $NumSets=1;
15881:     foreach my $array (@{$Ydata}){
15882:         next if (! ref($array));
15883:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
15884:     }
15885:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
15886:     #
15887:     # Deal with other parameters
15888:     while (my ($key,$value) = each(%Values)) {
15889:         $ValuesHash{$id.'.'.$key} = $value;
15890:     }
15891:     #
15892:     &Apache::lonnet::appenv(\%ValuesHash);
15893:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15894: }
15895: 
15896: ############################################################
15897: ############################################################
15898: 
15899: =pod
15900: 
15901: =item * &DrawXYYGraph()
15902: 
15903: Facilitates the plotting of data in an XY graph with two Y axes.
15904: Puts plot definition data into the users environment in order for 
15905: graph.png to plot it.  Returns an <img> tag for the plot.
15906: 
15907: Inputs:
15908: 
15909: =over 4
15910: 
15911: =item $Title: string, the title of the plot
15912: 
15913: =item $xlabel: string, text describing the X-axis of the plot
15914: 
15915: =item $ylabel: string, text describing the Y-axis of the plot
15916: 
15917: =item $colors: Array ref containing the hex color codes for the data to be 
15918: plotted in.  If undefined, default values will be used.
15919: 
15920: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
15921: 
15922: =item $Ydata1: The first data set
15923: 
15924: =item $Min1: The minimum value of the left Y-axis
15925: 
15926: =item $Max1: The maximum value of the left Y-axis
15927: 
15928: =item $Ydata2: The second data set
15929: 
15930: =item $Min2: The minimum value of the right Y-axis
15931: 
15932: =item $Max2: The maximum value of the left Y-axis
15933: 
15934: =item %Values: hash indicating or overriding any default values which are 
15935: passed to graph.png.  
15936: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
15937: 
15938: =back
15939: 
15940: Returns:
15941: 
15942: An <img> tag which references graph.png and the appropriate identifying
15943: information for the plot.
15944: 
15945: =cut
15946: 
15947: ############################################################
15948: ############################################################
15949: sub DrawXYYGraph {
15950:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
15951:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
15952:     #
15953:     # Create the identifier for the graph
15954:     my $identifier = &get_cgi_id();
15955:     my $id = 'cgi.'.$identifier;
15956:     #
15957:     $Title  = '' if (! defined($Title));
15958:     $xlabel = '' if (! defined($xlabel));
15959:     $ylabel = '' if (! defined($ylabel));
15960:     my %ValuesHash = 
15961:         (
15962:          $id.'.title'  => &escape($Title),
15963:          $id.'.xlabel' => &escape($xlabel),
15964:          $id.'.ylabel' => &escape($ylabel),
15965:          $id.'.labels' => join(',',@$Xlabels),
15966:          $id.'.PlotType' => 'XY',
15967:          $id.'.NumSets' => 2,
15968:          $id.'.two_axes' => 1,
15969:          $id.'.y1_max_value' => $Max1,
15970:          $id.'.y1_min_value' => $Min1,
15971:          $id.'.y2_max_value' => $Max2,
15972:          $id.'.y2_min_value' => $Min2,
15973:          );
15974:     #
15975:     if (defined($colors) && ref($colors) eq 'ARRAY') {
15976:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
15977:     }
15978:     #
15979:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
15980:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
15981:         return '';
15982:     }
15983:     my $NumSets=1;
15984:     foreach my $array ($Ydata1,$Ydata2){
15985:         next if (! ref($array));
15986:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
15987:     }
15988:     #
15989:     # Deal with other parameters
15990:     while (my ($key,$value) = each(%Values)) {
15991:         $ValuesHash{$id.'.'.$key} = $value;
15992:     }
15993:     #
15994:     &Apache::lonnet::appenv(\%ValuesHash);
15995:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15996: }
15997: 
15998: ############################################################
15999: ############################################################
16000: 
16001: =pod
16002: 
16003: =back 
16004: 
16005: =head1 Statistics helper routines?  
16006: 
16007: Bad place for them but what the hell.
16008: 
16009: =over 4
16010: 
16011: =item * &chartlink()
16012: 
16013: Returns a link to the chart for a specific student.  
16014: 
16015: Inputs:
16016: 
16017: =over 4
16018: 
16019: =item $linktext: The text of the link
16020: 
16021: =item $sname: The students username
16022: 
16023: =item $sdomain: The students domain
16024: 
16025: =back
16026: 
16027: =back
16028: 
16029: =cut
16030: 
16031: ############################################################
16032: ############################################################
16033: sub chartlink {
16034:     my ($linktext, $sname, $sdomain) = @_;
16035:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
16036:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
16037:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
16038:        '">'.$linktext.'</a>';
16039: }
16040: 
16041: #######################################################
16042: #######################################################
16043: 
16044: =pod
16045: 
16046: =head1 Course Environment Routines
16047: 
16048: =over 4
16049: 
16050: =item * &restore_course_settings()
16051: 
16052: =item * &store_course_settings()
16053: 
16054: Restores/Store indicated form parameters from the course environment.
16055: Will not overwrite existing values of the form parameters.
16056: 
16057: Inputs: 
16058: a scalar describing the data (e.g. 'chart', 'problem_analysis')
16059: 
16060: a hash ref describing the data to be stored.  For example:
16061:    
16062: %Save_Parameters = ('Status' => 'scalar',
16063:     'chartoutputmode' => 'scalar',
16064:     'chartoutputdata' => 'scalar',
16065:     'Section' => 'array',
16066:     'Group' => 'array',
16067:     'StudentData' => 'array',
16068:     'Maps' => 'array');
16069: 
16070: Returns: both routines return nothing
16071: 
16072: =back
16073: 
16074: =cut
16075: 
16076: #######################################################
16077: #######################################################
16078: sub store_course_settings {
16079:     return &store_settings($env{'request.course.id'},@_);
16080: }
16081: 
16082: sub store_settings {
16083:     # save to the environment
16084:     # appenv the same items, just to be safe
16085:     my $udom  = $env{'user.domain'};
16086:     my $uname = $env{'user.name'};
16087:     my ($context,$prefix,$Settings) = @_;
16088:     my %SaveHash;
16089:     my %AppHash;
16090:     while (my ($setting,$type) = each(%$Settings)) {
16091:         my $basename = join('.','internal',$context,$prefix,$setting);
16092:         my $envname = 'environment.'.$basename;
16093:         if (exists($env{'form.'.$setting})) {
16094:             # Save this value away
16095:             if ($type eq 'scalar' &&
16096:                 (! exists($env{$envname}) || 
16097:                  $env{$envname} ne $env{'form.'.$setting})) {
16098:                 $SaveHash{$basename} = $env{'form.'.$setting};
16099:                 $AppHash{$envname}   = $env{'form.'.$setting};
16100:             } elsif ($type eq 'array') {
16101:                 my $stored_form;
16102:                 if (ref($env{'form.'.$setting})) {
16103:                     $stored_form = join(',',
16104:                                         map {
16105:                                             &escape($_);
16106:                                         } sort(@{$env{'form.'.$setting}}));
16107:                 } else {
16108:                     $stored_form = 
16109:                         &escape($env{'form.'.$setting});
16110:                 }
16111:                 # Determine if the array contents are the same.
16112:                 if ($stored_form ne $env{$envname}) {
16113:                     $SaveHash{$basename} = $stored_form;
16114:                     $AppHash{$envname}   = $stored_form;
16115:                 }
16116:             }
16117:         }
16118:     }
16119:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
16120:                                           $udom,$uname);
16121:     if ($put_result !~ /^(ok|delayed)/) {
16122:         &Apache::lonnet::logthis('unable to save form parameters, '.
16123:                                  'got error:'.$put_result);
16124:     }
16125:     # Make sure these settings stick around in this session, too
16126:     &Apache::lonnet::appenv(\%AppHash);
16127:     return;
16128: }
16129: 
16130: sub restore_course_settings {
16131:     return &restore_settings($env{'request.course.id'},@_);
16132: }
16133: 
16134: sub restore_settings {
16135:     my ($context,$prefix,$Settings) = @_;
16136:     while (my ($setting,$type) = each(%$Settings)) {
16137:         next if (exists($env{'form.'.$setting}));
16138:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
16139:             '.'.$setting;
16140:         if (exists($env{$envname})) {
16141:             if ($type eq 'scalar') {
16142:                 $env{'form.'.$setting} = $env{$envname};
16143:             } elsif ($type eq 'array') {
16144:                 $env{'form.'.$setting} = [ 
16145:                                            map { 
16146:                                                &unescape($_); 
16147:                                            } split(',',$env{$envname})
16148:                                            ];
16149:             }
16150:         }
16151:     }
16152: }
16153: 
16154: #######################################################
16155: #######################################################
16156: 
16157: =pod
16158: 
16159: =head1 Domain E-mail Routines  
16160: 
16161: =over 4
16162: 
16163: =item * &build_recipient_list()
16164: 
16165: Build recipient lists for following types of e-mail:
16166: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
16167: (d) Help requests, (e) Course requests needing approval, (f) loncapa
16168: module change checking, student/employee ID conflict checks, as
16169: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
16170: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
16171: 
16172: Inputs:
16173: defmail (scalar - email address of default recipient), 
16174: mailing type (scalar: errormail, packagesmail, helpdeskmail,
16175: requestsmail, updatesmail, or idconflictsmail).
16176: 
16177: defdom (domain for which to retrieve configuration settings),
16178: 
16179: origmail (scalar - email address of recipient from loncapa.conf, 
16180: i.e., predates configuration by DC via domainprefs.pm
16181: 
16182: $requname username of requester (if mailing type is helpdeskmail)
16183: 
16184: $requdom domain of requester (if mailing type is helpdeskmail)
16185: 
16186: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
16187: 
16188: 
16189: Returns: comma separated list of addresses to which to send e-mail.
16190: 
16191: =back
16192: 
16193: =cut
16194: 
16195: ############################################################
16196: ############################################################
16197: sub build_recipient_list {
16198:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
16199:     my @recipients;
16200:     my ($otheremails,$lastresort,$allbcc,$addtext);
16201:     my %domconfig =
16202:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
16203:     if (ref($domconfig{'contacts'}) eq 'HASH') {
16204:         if (exists($domconfig{'contacts'}{$mailing})) {
16205:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
16206:                 my @contacts = ('adminemail','supportemail');
16207:                 foreach my $item (@contacts) {
16208:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
16209:                         my $addr = $domconfig{'contacts'}{$item}; 
16210:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
16211:                             push(@recipients,$addr);
16212:                         }
16213:                     }
16214:                 }
16215:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
16216:                 if ($mailing eq 'helpdeskmail') {
16217:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
16218:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
16219:                         my @ok_bccs;
16220:                         foreach my $bcc (@bccs) {
16221:                             $bcc =~ s/^\s+//g;
16222:                             $bcc =~ s/\s+$//g;
16223:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
16224:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
16225:                                     push(@ok_bccs,$bcc);
16226:                                 }
16227:                             }
16228:                         }
16229:                         if (@ok_bccs > 0) {
16230:                             $allbcc = join(', ',@ok_bccs);
16231:                         }
16232:                     }
16233:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
16234:                 }
16235:             }
16236:         } elsif ($origmail ne '') {
16237:             $lastresort = $origmail;
16238:         }
16239:         if ($mailing eq 'helpdeskmail') {
16240:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
16241:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
16242:                 my ($inststatus,$inststatus_checked);
16243:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
16244:                     ($env{'user.domain'} ne 'public')) {
16245:                     $inststatus_checked = 1;
16246:                     $inststatus = $env{'environment.inststatus'};
16247:                 }
16248:                 unless ($inststatus_checked) {
16249:                     if (($requname ne '') && ($requdom ne '')) {
16250:                         if (($requname =~ /^$match_username$/) &&
16251:                             ($requdom =~ /^$match_domain$/) &&
16252:                             (&Apache::lonnet::domain($requdom))) {
16253:                             my $requhome = &Apache::lonnet::homeserver($requname,
16254:                                                                       $requdom);
16255:                             unless ($requhome eq 'no_host') {
16256:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
16257:                                 $inststatus = $userenv{'inststatus'};
16258:                                 $inststatus_checked = 1;
16259:                             }
16260:                         }
16261:                     }
16262:                 }
16263:                 unless ($inststatus_checked) {
16264:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
16265:                         my %srch = (srchby     => 'email',
16266:                                     srchdomain => $defdom,
16267:                                     srchterm   => $reqemail,
16268:                                     srchtype   => 'exact');
16269:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
16270:                         foreach my $uname (keys(%srch_results)) {
16271:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
16272:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
16273:                                 $inststatus_checked = 1;
16274:                                 last;
16275:                             }
16276:                         }
16277:                         unless ($inststatus_checked) {
16278:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
16279:                             if ($dirsrchres eq 'ok') {
16280:                                 foreach my $uname (keys(%srch_results)) {
16281:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
16282:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
16283:                                         $inststatus_checked = 1;
16284:                                         last;
16285:                                     }
16286:                                 }
16287:                             }
16288:                         }
16289:                     }
16290:                 }
16291:                 if ($inststatus ne '') {
16292:                     foreach my $status (split(/\:/,$inststatus)) {
16293:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
16294:                             my @contacts = ('adminemail','supportemail');
16295:                             foreach my $item (@contacts) {
16296:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
16297:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
16298:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
16299:                                         push(@recipients,$addr);
16300:                                     }
16301:                                 }
16302:                             }
16303:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
16304:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
16305:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
16306:                                 my @ok_bccs;
16307:                                 foreach my $bcc (@bccs) {
16308:                                     $bcc =~ s/^\s+//g;
16309:                                     $bcc =~ s/\s+$//g;
16310:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
16311:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
16312:                                             push(@ok_bccs,$bcc);
16313:                                         }
16314:                                     }
16315:                                 }
16316:                                 if (@ok_bccs > 0) {
16317:                                     $allbcc = join(', ',@ok_bccs);
16318:                                 }
16319:                             }
16320:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
16321:                             last;
16322:                         }
16323:                     }
16324:                 }
16325:             }
16326:         }
16327:     } elsif ($origmail ne '') {
16328:         $lastresort = $origmail;
16329:     }
16330:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
16331:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
16332:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
16333:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
16334:             my %what = (
16335:                           perlvar => 1,
16336:                        );
16337:             my $primary = &Apache::lonnet::domain($defdom,'primary');
16338:             if ($primary) {
16339:                 my $gotaddr;
16340:                 my ($result,$returnhash) =
16341:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
16342:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
16343:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
16344:                         $lastresort = $returnhash->{'lonSupportEMail'};
16345:                         $gotaddr = 1;
16346:                     }
16347:                 }
16348:                 unless ($gotaddr) {
16349:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
16350:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
16351:                     unless ($uintdom eq $intdom) {
16352:                         my %domconfig =
16353:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
16354:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
16355:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
16356:                                 my @contacts = ('adminemail','supportemail');
16357:                                 foreach my $item (@contacts) {
16358:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
16359:                                         my $addr = $domconfig{'contacts'}{$item};
16360:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
16361:                                             push(@recipients,$addr);
16362:                                         }
16363:                                     }
16364:                                 }
16365:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
16366:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
16367:                                 }
16368:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
16369:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
16370:                                     my @ok_bccs;
16371:                                     foreach my $bcc (@bccs) {
16372:                                         $bcc =~ s/^\s+//g;
16373:                                         $bcc =~ s/\s+$//g;
16374:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
16375:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
16376:                                                 push(@ok_bccs,$bcc);
16377:                                             }
16378:                                         }
16379:                                     }
16380:                                     if (@ok_bccs > 0) {
16381:                                         $allbcc = join(', ',@ok_bccs);
16382:                                     }
16383:                                 }
16384:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
16385:                             }
16386:                         }
16387:                     }
16388:                 }
16389:             }
16390:         }
16391:     }
16392:     if (defined($defmail)) {
16393:         if ($defmail ne '') {
16394:             push(@recipients,$defmail);
16395:         }
16396:     }
16397:     if ($otheremails) {
16398:         my @others;
16399:         if ($otheremails =~ /,/) {
16400:             @others = split(/,/,$otheremails);
16401:         } else {
16402:             push(@others,$otheremails);
16403:         }
16404:         foreach my $addr (@others) {
16405:             if (!grep(/^\Q$addr\E$/,@recipients)) {
16406:                 push(@recipients,$addr);
16407:             }
16408:         }
16409:     }
16410:     if ($mailing eq 'helpdeskmail') {
16411:         if ((!@recipients) && ($lastresort ne '')) {
16412:             push(@recipients,$lastresort);
16413:         }
16414:     } elsif ($lastresort ne '') {
16415:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
16416:             push(@recipients,$lastresort);
16417:         }
16418:     }
16419:     my $recipientlist = join(',',@recipients);
16420:     if (wantarray) {
16421:         return ($recipientlist,$allbcc,$addtext);
16422:     } else {
16423:         return $recipientlist;
16424:     }
16425: }
16426: 
16427: ############################################################
16428: ############################################################
16429: 
16430: =pod
16431: 
16432: =over 4
16433: 
16434: =item * &mime_email()
16435: 
16436: Sends an email with a possible attachment
16437: 
16438: Inputs:
16439: 
16440: =over 4
16441: 
16442: from -              Sender's email address
16443: 
16444: replyto -           Reply-To email address
16445: 
16446: to -                Email address of recipient
16447: 
16448: subject -           Subject of email
16449: 
16450: body -              Body of email
16451: 
16452: cc_string -         Carbon copy email address
16453: 
16454: bcc -               Blind carbon copy email address
16455: 
16456: attachment_path -   Path of file to be attached
16457: 
16458: file_name -         Name of file to be attached
16459: 
16460: attachment_text -   The body of an attachment of type "TEXT"
16461: 
16462: =back
16463: 
16464: =back
16465: 
16466: =cut
16467: 
16468: ############################################################
16469: ############################################################
16470: 
16471: sub mime_email {
16472:     my ($from,$replyto,$to,$subject,$body,$cc_string,$bcc,$attachment_path, 
16473:         $file_name,$attachment_text) = @_;
16474:  
16475:     my $msg = MIME::Lite->new(
16476:              From    => $from,
16477:              To      => $to,
16478:              Subject => $subject,
16479:              Type    =>'TEXT',
16480:              Data    => $body,
16481:              );
16482:     if ($replyto ne '') {
16483:         $msg->add("Reply-To" => $replyto);
16484:     }
16485:     if ($cc_string ne '') {
16486:         $msg->add("Cc" => $cc_string);
16487:     }
16488:     if ($bcc ne '') {
16489:         $msg->add("Bcc" => $bcc);
16490:     }
16491:     $msg->attr("content-type"         => "text/plain");
16492:     $msg->attr("content-type.charset" => "UTF-8");
16493:     # Attach file if given
16494:     if ($attachment_path) {
16495:         unless ($file_name) {
16496:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
16497:         }
16498:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
16499:         $msg->attach(Type     => $type,
16500:                      Path     => $attachment_path,
16501:                      Filename => $file_name
16502:                      );
16503:     # Otherwise attach text if given
16504:     } elsif ($attachment_text) {
16505:         $msg->attach(Type => 'TEXT',
16506:                      Data => $attachment_text);
16507:     }
16508:     # Send it
16509:     $msg->send('sendmail');
16510: }
16511: 
16512: ############################################################
16513: ############################################################
16514: 
16515: =pod
16516: 
16517: =head1 Course Catalog Routines
16518: 
16519: =over 4
16520: 
16521: =item * &gather_categories()
16522: 
16523: Converts category definitions - keys of categories hash stored in  
16524: coursecategories in configuration.db on the primary library server in a 
16525: domain - to an array.  Also generates javascript and idx hash used to 
16526: generate Domain Coordinator interface for editing Course Categories.
16527: 
16528: Inputs:
16529: 
16530: categories (reference to hash of category definitions).
16531: 
16532: cats (reference to array of arrays/hashes which encapsulates hierarchy of
16533:       categories and subcategories).
16534: 
16535: idx (reference to hash of counters used in Domain Coordinator interface for 
16536:       editing Course Categories).
16537: 
16538: jsarray (reference to array of categories used to create Javascript arrays for
16539:          Domain Coordinator interface for editing Course Categories).
16540: 
16541: Returns: nothing
16542: 
16543: Side effects: populates cats, idx and jsarray. 
16544: 
16545: =cut
16546: 
16547: sub gather_categories {
16548:     my ($categories,$cats,$idx,$jsarray) = @_;
16549:     my %counters;
16550:     my $num = 0;
16551:     foreach my $item (keys(%{$categories})) {
16552:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
16553:         if ($container eq '' && $depth == 0) {
16554:             $cats->[$depth][$categories->{$item}] = $cat;
16555:         } else {
16556:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
16557:         }
16558:         my ($escitem,$tail) = split(/:/,$item,2);
16559:         if ($counters{$tail} eq '') {
16560:             $counters{$tail} = $num;
16561:             $num ++;
16562:         }
16563:         if (ref($idx) eq 'HASH') {
16564:             $idx->{$item} = $counters{$tail};
16565:         }
16566:         if (ref($jsarray) eq 'ARRAY') {
16567:             push(@{$jsarray->[$counters{$tail}]},$item);
16568:         }
16569:     }
16570:     return;
16571: }
16572: 
16573: =pod
16574: 
16575: =item * &extract_categories()
16576: 
16577: Used to generate breadcrumb trails for course categories.
16578: 
16579: Inputs:
16580: 
16581: categories (reference to hash of category definitions).
16582: 
16583: cats (reference to array of arrays/hashes which encapsulates hierarchy of
16584:       categories and subcategories).
16585: 
16586: trails (reference to array of breacrumb trails for each category).
16587: 
16588: allitems (reference to hash - key is category key 
16589:          (format: escaped(name):escaped(parent category):depth in hierarchy).
16590: 
16591: idx (reference to hash of counters used in Domain Coordinator interface for
16592:       editing Course Categories).
16593: 
16594: jsarray (reference to array of categories used to create Javascript arrays for
16595:          Domain Coordinator interface for editing Course Categories).
16596: 
16597: subcats (reference to hash of arrays containing all subcategories within each 
16598:          category, -recursive)
16599: 
16600: maxd (reference to hash used to hold max depth for all top-level categories).
16601: 
16602: Returns: nothing
16603: 
16604: Side effects: populates trails and allitems hash references.
16605: 
16606: =cut
16607: 
16608: sub extract_categories {
16609:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
16610:     if (ref($categories) eq 'HASH') {
16611:         &gather_categories($categories,$cats,$idx,$jsarray);
16612:         if (ref($cats->[0]) eq 'ARRAY') {
16613:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
16614:                 my $name = $cats->[0][$i];
16615:                 my $item = &escape($name).'::0';
16616:                 my $trailstr;
16617:                 if ($name eq 'instcode') {
16618:                     $trailstr = &mt('Official courses (with institutional codes)');
16619:                 } elsif ($name eq 'communities') {
16620:                     $trailstr = &mt('Communities');
16621:                 } elsif ($name eq 'placement') {
16622:                     $trailstr = &mt('Placement Tests');
16623:                 } else {
16624:                     $trailstr = $name;
16625:                 }
16626:                 if ($allitems->{$item} eq '') {
16627:                     push(@{$trails},$trailstr);
16628:                     $allitems->{$item} = scalar(@{$trails})-1;
16629:                 }
16630:                 my @parents = ($name);
16631:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
16632:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
16633:                         my $category = $cats->[1]{$name}[$j];
16634:                         if (ref($subcats) eq 'HASH') {
16635:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
16636:                         }
16637:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
16638:                     }
16639:                 } else {
16640:                     if (ref($subcats) eq 'HASH') {
16641:                         $subcats->{$item} = [];
16642:                     }
16643:                     if (ref($maxd) eq 'HASH') {
16644:                         $maxd->{$name} = 1;
16645:                     }
16646:                 }
16647:             }
16648:         }
16649:     }
16650:     return;
16651: }
16652: 
16653: =pod
16654: 
16655: =item * &recurse_categories()
16656: 
16657: Recursively used to generate breadcrumb trails for course categories.
16658: 
16659: Inputs:
16660: 
16661: cats (reference to array of arrays/hashes which encapsulates hierarchy of
16662:       categories and subcategories).
16663: 
16664: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
16665: 
16666: category (current course category, for which breadcrumb trail is being generated).
16667: 
16668: trails (reference to array of breadcrumb trails for each category).
16669: 
16670: allitems (reference to hash - key is category key
16671:          (format: escaped(name):escaped(parent category):depth in hierarchy).
16672: 
16673: parents (array containing containers directories for current category, 
16674:          back to top level). 
16675: 
16676: Returns: nothing
16677: 
16678: Side effects: populates trails and allitems hash references
16679: 
16680: =cut
16681: 
16682: sub recurse_categories {
16683:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
16684:     my $shallower = $depth - 1;
16685:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
16686:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
16687:             my $name = $cats->[$depth]{$category}[$k];
16688:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
16689:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
16690:             if ($allitems->{$item} eq '') {
16691:                 push(@{$trails},$trailstr);
16692:                 $allitems->{$item} = scalar(@{$trails})-1;
16693:             }
16694:             my $deeper = $depth+1;
16695:             push(@{$parents},$category);
16696:             if (ref($subcats) eq 'HASH') {
16697:                 my $subcat = &escape($name).':'.$category.':'.$depth;
16698:                 for (my $j=@{$parents}; $j>=0; $j--) {
16699:                     my $higher;
16700:                     if ($j > 0) {
16701:                         $higher = &escape($parents->[$j]).':'.
16702:                                   &escape($parents->[$j-1]).':'.$j;
16703:                     } else {
16704:                         $higher = &escape($parents->[$j]).'::'.$j;
16705:                     }
16706:                     push(@{$subcats->{$higher}},$subcat);
16707:                 }
16708:             }
16709:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
16710:                                 $subcats,$maxd);
16711:             pop(@{$parents});
16712:         }
16713:     } else {
16714:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
16715:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
16716:         if ($allitems->{$item} eq '') {
16717:             push(@{$trails},$trailstr);
16718:             $allitems->{$item} = scalar(@{$trails})-1;
16719:         }
16720:         if (ref($maxd) eq 'HASH') {
16721:             if ($depth > $maxd->{$parents->[0]}) {
16722:                 $maxd->{$parents->[0]} = $depth;
16723:             }
16724:         }
16725:     }
16726:     return;
16727: }
16728: 
16729: =pod
16730: 
16731: =item * &assign_categories_table()
16732: 
16733: Create a datatable for display of hierarchical categories in a domain,
16734: with checkboxes to allow a course to be categorized. 
16735: 
16736: Inputs:
16737: 
16738: cathash - reference to hash of categories defined for the domain (from
16739:           configuration.db)
16740: 
16741: currcat - scalar with an & separated list of categories assigned to a course. 
16742: 
16743: type    - scalar contains course type (Course or Community).
16744: 
16745: disabled - scalar (optional) contains disabled="disabled" if input elements are
16746:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
16747: 
16748: Returns: $output (markup to be displayed) 
16749: 
16750: =cut
16751: 
16752: sub assign_categories_table {
16753:     my ($cathash,$currcat,$type,$disabled) = @_;
16754:     my $output;
16755:     if (ref($cathash) eq 'HASH') {
16756:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
16757:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
16758:         $maxdepth = scalar(@cats);
16759:         if (@cats > 0) {
16760:             my $itemcount = 0;
16761:             if (ref($cats[0]) eq 'ARRAY') {
16762:                 my @currcategories;
16763:                 if ($currcat ne '') {
16764:                     @currcategories = split('&',$currcat);
16765:                 }
16766:                 my $table;
16767:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
16768:                     my $parent = $cats[0][$i];
16769:                     next if ($parent eq 'instcode');
16770:                     if ($type eq 'Community') {
16771:                         next unless ($parent eq 'communities');
16772:                     } elsif ($type eq 'Placement') {
16773:                         next unless ($parent eq 'placement');
16774:                     } else {
16775:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
16776:                     }
16777:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
16778:                     my $item = &escape($parent).'::0';
16779:                     my $checked = '';
16780:                     if (@currcategories > 0) {
16781:                         if (grep(/^\Q$item\E$/,@currcategories)) {
16782:                             $checked = ' checked="checked"';
16783:                         }
16784:                     }
16785:                     my $parent_title = $parent;
16786:                     if ($parent eq 'communities') {
16787:                         $parent_title = &mt('Communities');
16788:                     } elsif ($parent eq 'placement') {
16789:                         $parent_title = &mt('Placement Tests');
16790:                     }
16791:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
16792:                               '<input type="checkbox" name="usecategory" value="'.
16793:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
16794:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
16795:                     my $depth = 1;
16796:                     push(@path,$parent);
16797:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
16798:                     pop(@path);
16799:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
16800:                     $itemcount ++;
16801:                 }
16802:                 if ($itemcount) {
16803:                     $output = &Apache::loncommon::start_data_table().
16804:                               $table.
16805:                               &Apache::loncommon::end_data_table();
16806:                 }
16807:             }
16808:         }
16809:     }
16810:     return $output;
16811: }
16812: 
16813: =pod
16814: 
16815: =item * &assign_category_rows()
16816: 
16817: Create a datatable row for display of nested categories in a domain,
16818: with checkboxes to allow a course to be categorized,called recursively.
16819: 
16820: Inputs:
16821: 
16822: itemcount - track row number for alternating colors
16823: 
16824: cats - reference to array of arrays/hashes which encapsulates hierarchy of
16825:       categories and subcategories.
16826: 
16827: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
16828: 
16829: parent - parent of current category item
16830: 
16831: path - Array containing all categories back up through the hierarchy from the
16832:        current category to the top level.
16833: 
16834: currcategories - reference to array of current categories assigned to the course
16835: 
16836: disabled - scalar (optional) contains disabled="disabled" if input elements are
16837:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
16838: 
16839: Returns: $output (markup to be displayed).
16840: 
16841: =cut
16842: 
16843: sub assign_category_rows {
16844:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
16845:     my ($text,$name,$item,$chgstr);
16846:     if (ref($cats) eq 'ARRAY') {
16847:         my $maxdepth = scalar(@{$cats});
16848:         if (ref($cats->[$depth]) eq 'HASH') {
16849:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
16850:                 my $numchildren = @{$cats->[$depth]{$parent}};
16851:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
16852:                 $text .= '<td><table class="LC_data_table">';
16853:                 for (my $j=0; $j<$numchildren; $j++) {
16854:                     $name = $cats->[$depth]{$parent}[$j];
16855:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
16856:                     my $deeper = $depth+1;
16857:                     my $checked = '';
16858:                     if (ref($currcategories) eq 'ARRAY') {
16859:                         if (@{$currcategories} > 0) {
16860:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
16861:                                 $checked = ' checked="checked"';
16862:                             }
16863:                         }
16864:                     }
16865:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
16866:                              '<input type="checkbox" name="usecategory" value="'.
16867:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
16868:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
16869:                              '</td><td>';
16870:                     if (ref($path) eq 'ARRAY') {
16871:                         push(@{$path},$name);
16872:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
16873:                         pop(@{$path});
16874:                     }
16875:                     $text .= '</td></tr>';
16876:                 }
16877:                 $text .= '</table></td>';
16878:             }
16879:         }
16880:     }
16881:     return $text;
16882: }
16883: 
16884: =pod
16885: 
16886: =back
16887: 
16888: =cut
16889: 
16890: ############################################################
16891: ############################################################
16892: 
16893: 
16894: sub commit_customrole {
16895:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context,$othdomby,$requester) = @_;
16896:     my $result = &Apache::lonnet::assigncustomrole(
16897:                      $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,
16898:                      $context,$othdomby,$requester);
16899:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
16900:                          ($start?', '.&mt('starting').' '.localtime($start):'').
16901:                          ($end?', ending '.localtime($end):'').': <b>'.$result.'</b><br />';
16902:     if (wantarray) {
16903:         return ($output,$result);
16904:     } else {
16905:         return $output;
16906:     }
16907: }
16908: 
16909: sub commit_standardrole {
16910:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits,
16911:         $othdomby,$requester) = @_;
16912:     my ($output,$logmsg,$linefeed,$result);
16913:     if ($context eq 'auto') {
16914:         $linefeed = "\n";
16915:     } else {
16916:         $linefeed = "<br />\n";
16917:     }  
16918:     if ($three eq 'st') {
16919:         $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
16920:                                       $one,$two,$sec,$context,$credits,$othdomby,
16921:                                       $requester);
16922:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
16923:             ($result eq 'unknown_course') || ($result eq 'refused')) {
16924:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
16925:         } else {
16926:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
16927:                ($start?', '.&mt('starting').' '.localtime($start):'').
16928:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
16929:             if ($context eq 'auto') {
16930:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
16931:             } else {
16932:                $output .= '<b>'.$result.'</b>'.$linefeed.
16933:                &mt('Add to classlist').': <b>ok</b>';
16934:             }
16935:             $output .= $linefeed;
16936:         }
16937:     } else {
16938:         $output = &mt('Assigning').' '.$three.' in '.$url.
16939:                ($start?', '.&mt('starting').' '.localtime($start):'').
16940:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
16941:         $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,
16942:                                               '','',$context,$othdomby,$requester);
16943:         if ($context eq 'auto') {
16944:             $output .= $result.$linefeed;
16945:         } else {
16946:             $output .= '<b>'.$result.'</b>'.$linefeed;
16947:         }
16948:     }
16949:     if (wantarray) {
16950:         return ($output,$result);
16951:     } else {
16952:         return $output;
16953:     }
16954: }
16955: 
16956: sub commit_studentrole {
16957:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
16958:         $credits,$othdomby,$requester) = @_;
16959:     my ($result,$linefeed,$oldsecurl,$newsecurl);
16960:     if ($context eq 'auto') {
16961:         $linefeed = "\n";
16962:     } else {
16963:         $linefeed = '<br />'."\n";
16964:     }
16965:     if (defined($one) && defined($two)) {
16966:         my $cid=$one.'_'.$two;
16967:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
16968:         my $secchange = 0;
16969:         my $expire_role_result;
16970:         my $modify_section_result;
16971:         if ($oldsec ne '-1') { 
16972:             if ($oldsec ne $sec) {
16973:                 $secchange = 1;
16974:                 my $now = time;
16975:                 my $uurl='/'.$cid;
16976:                 $uurl=~s/\_/\//g;
16977:                 if ($oldsec) {
16978:                     $uurl.='/'.$oldsec;
16979:                 }
16980:                 $oldsecurl = $uurl;
16981:                 $expire_role_result = 
16982:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,
16983:                                                 '','','',$context,$othdomby,$requester);
16984:                 if ($env{'request.course.sec'} ne '') {
16985:                     if ($expire_role_result eq 'refused') {
16986:                         my @roles = ('st');
16987:                         my @statuses = ('previous');
16988:                         my @roledoms = ($one);
16989:                         my $withsec = 1;
16990:                         my %roleshash = 
16991:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
16992:                                               \@statuses,\@roles,\@roledoms,$withsec);
16993:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
16994:                             my ($oldstart,$oldend) = 
16995:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
16996:                             if ($oldend > 0 && $oldend <= $now) {
16997:                                 $expire_role_result = 'ok';
16998:                             }
16999:                         }
17000:                     }
17001:                 }
17002:                 $result = $expire_role_result;
17003:             }
17004:         }
17005:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
17006:             $modify_section_result = 
17007:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
17008:                                                            undef,undef,undef,$sec,
17009:                                                            $end,$start,'','',$cid,
17010:                                                            '',$context,$credits,'',
17011:                                                            $othdomby,$requester);
17012:             if ($modify_section_result =~ /^ok/) {
17013:                 if ($secchange == 1) {
17014:                     if ($sec eq '') {
17015:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
17016:                     } else {
17017:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
17018:                     }
17019:                 } elsif ($oldsec eq '-1') {
17020:                     if ($sec eq '') {
17021:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
17022:                     } else {
17023:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
17024:                     }
17025:                 } else {
17026:                     if ($sec eq '') {
17027:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
17028:                     } else {
17029:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
17030:                     }
17031:                 }
17032:             } else {
17033:                 if ($secchange) { 
17034:                     $$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;
17035:                 } else {
17036:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
17037:                 }
17038:             }
17039:             $result = $modify_section_result;
17040:         } elsif ($secchange == 1) {
17041:             if ($oldsec eq '') {
17042:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
17043:             } else {
17044:                 $$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;
17045:             }
17046:             if ($expire_role_result eq 'refused') {
17047:                 my $newsecurl = '/'.$cid;
17048:                 $newsecurl =~ s/\_/\//g;
17049:                 if ($sec ne '') {
17050:                     $newsecurl.='/'.$sec;
17051:                 }
17052:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
17053:                     if ($sec eq '') {
17054:                         $$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;
17055:                     } else {
17056:                         $$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;
17057:                     }
17058:                 }
17059:             }
17060:         }
17061:     } else {
17062:         $$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;
17063:         $result = "error: incomplete course id\n";
17064:     }
17065:     return $result;
17066: }
17067: 
17068: sub show_role_extent {
17069:     my ($scope,$context,$role) = @_;
17070:     $scope =~ s{^/}{};
17071:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
17072:     push(@courseroles,'co');
17073:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
17074:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
17075:         $scope =~ s{/}{_};
17076:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
17077:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
17078:         my ($audom,$auname) = split(/\//,$scope);
17079:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
17080:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
17081:     } else {
17082:         $scope =~ s{/$}{};
17083:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
17084:                    &Apache::lonnet::domain($scope,'description').'</span>');
17085:     }
17086: }
17087: 
17088: ############################################################
17089: ############################################################
17090: 
17091: sub check_clone {
17092:     my ($args,$linefeed) = @_;
17093:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
17094:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
17095:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
17096:     my $clonetitle;
17097:     my @clonemsg;
17098:     my $can_clone = 0;
17099:     my $lctype = lc($args->{'crstype'});
17100:     if ($lctype ne 'community') {
17101:         $lctype = 'course';
17102:     }
17103:     if ($clonehome eq 'no_host') {
17104:         if ($args->{'crstype'} eq 'Community') {
17105:             push(@clonemsg,({
17106:                               mt => 'No new community created.',
17107:                               args => [],
17108:                             },
17109:                             {
17110:                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
17111:                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
17112:                             }));
17113:         } else {
17114:             push(@clonemsg,({
17115:                               mt => 'No new course created.',
17116:                               args => [],
17117:                             },
17118:                             {
17119:                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
17120:                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
17121:                             }));
17122:         }
17123:     } else {
17124: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
17125:         $clonetitle = $clonedesc{'description'};
17126:         if ($args->{'crstype'} eq 'Community') {
17127:             if ($clonedesc{'type'} ne 'Community') {
17128:                 push(@clonemsg,({
17129:                                   mt => 'No new community created.',
17130:                                   args => [],
17131:                                 },
17132:                                 {
17133:                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
17134:                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
17135:                                 }));
17136:                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
17137:             }
17138:         }
17139: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
17140:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
17141: 	    $can_clone = 1;
17142: 	} else {
17143: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
17144: 						 $args->{'clonedomain'},$args->{'clonecourse'});
17145:             if ($clonehash{'cloners'} eq '') {
17146:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
17147:                 if ($domdefs{'canclone'}) {
17148:                     unless ($domdefs{'canclone'} eq 'none') {
17149:                         if ($domdefs{'canclone'} eq 'domain') {
17150:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
17151:                                 $can_clone = 1;
17152:                             }
17153:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
17154:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
17155:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
17156:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
17157:                                 $can_clone = 1;
17158:                             }
17159:                         }
17160:                     }
17161:                 }
17162:             } else {
17163: 	        my @cloners = split(/,/,$clonehash{'cloners'});
17164:                 if (grep(/^\*$/,@cloners)) {
17165:                     $can_clone = 1;
17166:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
17167:                     $can_clone = 1;
17168:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
17169:                     $can_clone = 1;
17170:                 }
17171:                 unless ($can_clone) {
17172:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
17173:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
17174:                         my (%gotdomdefaults,%gotcodedefaults);
17175:                         foreach my $cloner (@cloners) {
17176:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
17177:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
17178:                                 my (%codedefaults,@code_order);
17179:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
17180:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
17181:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
17182:                                     }
17183:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
17184:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
17185:                                     }
17186:                                 } else {
17187:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
17188:                                                                             \%codedefaults,
17189:                                                                             \@code_order);
17190:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
17191:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
17192:                                 }
17193:                                 if (@code_order > 0) {
17194:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
17195:                                                                                 $cloner,$clonehash{'internal.coursecode'},
17196:                                                                                 $args->{'crscode'})) {
17197:                                         $can_clone = 1;
17198:                                         last;
17199:                                     }
17200:                                 }
17201:                             }
17202:                         }
17203:                     }
17204:                 }
17205:             }
17206:             unless ($can_clone) {
17207:                 my $ccrole = 'cc';
17208:                 if ($args->{'crstype'} eq 'Community') {
17209:                     $ccrole = 'co';
17210:                 }
17211: 	        my %roleshash =
17212: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
17213: 					          $args->{'ccdomain'},
17214:                                                   'userroles',['active'],[$ccrole],
17215: 					          [$args->{'clonedomain'}]);
17216: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
17217:                     $can_clone = 1;
17218:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
17219:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
17220:                     $can_clone = 1;
17221:                 }
17222:             }
17223:             unless ($can_clone) {
17224:                 if ($args->{'crstype'} eq 'Community') {
17225:                     push(@clonemsg,({
17226:                                       mt => 'No new community created.',
17227:                                       args => [],
17228:                                     },
17229:                                     {
17230:                                       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]).',
17231:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
17232:                                     }));
17233:                 } else {
17234:                     push(@clonemsg,({
17235:                                       mt => 'No new course created.',
17236:                                       args => [],
17237:                                     },
17238:                                     {
17239:                                       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]).',
17240:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
17241:                                     }));
17242:                 }
17243: 	    }
17244:         }
17245:     }
17246:     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
17247: }
17248: 
17249: sub construct_course {
17250:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
17251:         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
17252:     my ($outcome,$msgref,$clonemsgref);
17253:     my $linefeed =  '<br />'."\n";
17254:     if ($context eq 'auto') {
17255:         $linefeed = "\n";
17256:     }
17257: 
17258: #
17259: # Are we cloning?
17260: #
17261:     my ($can_clone,$cloneid,$clonehome,$clonetitle);
17262:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
17263: 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
17264:         if (!$can_clone) {
17265: 	    return (0,$outcome,$clonemsgref);
17266: 	}
17267:     }
17268: 
17269: #
17270: # Open course
17271: #
17272:     my $showncrstype;
17273:     if ($args->{'crstype'} eq 'Placement') {
17274:         $showncrstype = 'placement test'; 
17275:     } else {  
17276:         $showncrstype = lc($args->{'crstype'});
17277:     }
17278:     my %cenv=();
17279:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
17280:                                              $args->{'cdescr'},
17281:                                              $args->{'curl'},
17282:                                              $args->{'course_home'},
17283:                                              $args->{'nonstandard'},
17284:                                              $args->{'crscode'},
17285:                                              $args->{'ccuname'}.':'.
17286:                                              $args->{'ccdomain'},
17287:                                              $args->{'crstype'},
17288:                                              $cnum,$context,$category,
17289:                                              $callercontext);
17290: 
17291:     # Note: The testing routines depend on this being output; see 
17292:     # Utils::Course. This needs to at least be output as a comment
17293:     # if anyone ever decides to not show this, and Utils::Course::new
17294:     # will need to be suitably modified.
17295:     if (($callercontext eq 'auto') && ($user_lh ne '')) {
17296:         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
17297:     } else {
17298:         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
17299:     }
17300:     if ($$courseid =~ /^error:/) {
17301:         return (0,$outcome,$clonemsgref);
17302:     }
17303: 
17304: #
17305: # Check if created correctly
17306: #
17307:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
17308:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
17309:     if ($crsuhome eq 'no_host') {
17310:         if (($callercontext eq 'auto') && ($user_lh ne '')) {
17311:             $outcome .= &mt_user($user_lh,
17312:                             'Course creation failed, unrecognized course home server.');
17313:         } else {
17314:             $outcome .= &mt('Course creation failed, unrecognized course home server.');
17315:         }
17316:         $outcome .= $linefeed;
17317:         return (0,$outcome,$clonemsgref);
17318:     }
17319:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
17320: 
17321: #
17322: # Do the cloning
17323: #   
17324:     my @clonemsg;
17325:     if ($can_clone && $cloneid) {
17326:         push(@clonemsg,
17327:                       {
17328:                           mt => 'Created [_1] by cloning from [_2]',
17329:                           args => [$showncrstype,$clonetitle],
17330:                       });
17331: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
17332: # Copy all files
17333:         my @info =
17334: 	    &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
17335: 	                                             $args->{'dateshift'},$args->{'crscode'},
17336:                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
17337:                                                      $args->{'tinyurls'});
17338:         if (@info) {
17339:             push(@clonemsg,@info);
17340:         }
17341: # Restore URL
17342: 	$cenv{'url'}=$oldcenv{'url'};
17343: # Restore title
17344: 	$cenv{'description'}=$oldcenv{'description'};
17345: # Restore creation date, creator and creation context.
17346:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
17347:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
17348:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
17349: # Mark as cloned
17350: 	$cenv{'clonedfrom'}=$cloneid;
17351: # Need to clone grading mode
17352:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
17353:         $cenv{'grading'}=$newenv{'grading'};
17354: # Do not clone these environment entries
17355:         &Apache::lonnet::del('environment',
17356:                   ['default_enrollment_start_date',
17357:                    'default_enrollment_end_date',
17358:                    'question.email',
17359:                    'policy.email',
17360:                    'comment.email',
17361:                    'pch.users.denied',
17362:                    'plc.users.denied',
17363:                    'hidefromcat',
17364:                    'checkforpriv',
17365:                    'categories'],
17366:                    $$crsudom,$$crsunum);
17367:         if ($args->{'textbook'}) {
17368:             $cenv{'internal.textbook'} = $args->{'textbook'};
17369:         }
17370:     }
17371: 
17372: #
17373: # Set environment (will override cloned, if existing)
17374: #
17375:     my @sections = ();
17376:     my @xlists = ();
17377:     if ($args->{'crstype'}) {
17378:         $cenv{'type'}=$args->{'crstype'};
17379:     }
17380:     if ($args->{'lti'}) {
17381:         $cenv{'internal.lti'}=$args->{'lti'};
17382:     }
17383:     if ($args->{'crsid'}) {
17384:         $cenv{'courseid'}=$args->{'crsid'};
17385:     }
17386:     if ($args->{'crscode'}) {
17387:         $cenv{'internal.coursecode'}=$args->{'crscode'};
17388:     }
17389:     if ($args->{'crsquota'} ne '') {
17390:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
17391:     } else {
17392:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
17393:     }
17394:     if ($args->{'ccuname'}) {
17395:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
17396:                                         ':'.$args->{'ccdomain'};
17397:     } else {
17398:         $cenv{'internal.courseowner'} = $args->{'curruser'};
17399:     }
17400:     if ($args->{'defaultcredits'}) {
17401:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
17402:     }
17403:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
17404:     my @oklcsecs = (); # Used to accumulate LON-CAPA sections for validated institutional sections.
17405:     if ($args->{'crssections'}) {
17406:         $cenv{'internal.sectionnums'} = '';
17407:         if ($args->{'crssections'} =~ m/,/) {
17408:             @sections = split/,/,$args->{'crssections'};
17409:         } else {
17410:             $sections[0] = $args->{'crssections'};
17411:         }
17412:         if (@sections > 0) {
17413:             foreach my $item (@sections) {
17414:                 my ($sec,$gp) = split/:/,$item;
17415:                 my $class = $args->{'crscode'}.$sec;
17416:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
17417:                 $cenv{'internal.sectionnums'} .= $item.',';
17418:                 if ($addcheck eq 'ok') {
17419:                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
17420:                         push(@oklcsecs,$gp);
17421:                     }
17422:                 } else {
17423:                     push(@badclasses,$class);
17424:                 }
17425:             }
17426:             $cenv{'internal.sectionnums'} =~ s/,$//;
17427:         }
17428:     }
17429: # do not hide course coordinator from staff listing, 
17430: # even if privileged
17431:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
17432: # add course coordinator's domain to domains to check for privileged users
17433: # if different to course domain
17434:     if ($$crsudom ne $args->{'ccdomain'}) {
17435:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
17436:     }
17437: # add crosslistings
17438:     if ($args->{'crsxlist'}) {
17439:         $cenv{'internal.crosslistings'}='';
17440:         if ($args->{'crsxlist'} =~ m/,/) {
17441:             @xlists = split/,/,$args->{'crsxlist'};
17442:         } else {
17443:             $xlists[0] = $args->{'crsxlist'};
17444:         }
17445:         if (@xlists > 0) {
17446:             foreach my $item (@xlists) {
17447:                 my ($xl,$gp) = split/:/,$item;
17448:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
17449:                 $cenv{'internal.crosslistings'} .= $item.',';
17450:                 if ($addcheck eq 'ok') {
17451:                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
17452:                         push(@oklcsecs,$gp);
17453:                     }
17454:                 } else {
17455:                     push(@badclasses,$xl);
17456:                 }
17457:             }
17458:             $cenv{'internal.crosslistings'} =~ s/,$//;
17459:         }
17460:     }
17461:     if ($args->{'autoadds'}) {
17462:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
17463:     }
17464:     if ($args->{'autodrops'}) {
17465:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
17466:     }
17467: # check for notification of enrollment changes
17468:     my @notified = ();
17469:     if ($args->{'notify_owner'}) {
17470:         if ($args->{'ccuname'} ne '') {
17471:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
17472:         }
17473:     }
17474:     if ($args->{'notify_dc'}) {
17475:         if ($uname ne '') { 
17476:             push(@notified,$uname.':'.$udom);
17477:         }
17478:     }
17479:     if (@notified > 0) {
17480:         my $notifylist;
17481:         if (@notified > 1) {
17482:             $notifylist = join(',',@notified);
17483:         } else {
17484:             $notifylist = $notified[0];
17485:         }
17486:         $cenv{'internal.notifylist'} = $notifylist;
17487:     }
17488:     if (@badclasses > 0) {
17489:         my %lt=&Apache::lonlocal::texthash(
17490:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
17491:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
17492:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
17493:         );
17494:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
17495:                            &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'};
17496:         if ($context eq 'auto') {
17497:             $outcome .= $badclass_msg.$linefeed;
17498:         } else {
17499:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
17500:         }
17501:         foreach my $item (@badclasses) {
17502:             if ($context eq 'auto') {
17503:                 $outcome .= " - $item\n";
17504:             } else {
17505:                 $outcome .= "<li>$item</li>\n";
17506:             }
17507:         }
17508:         if ($context eq 'auto') {
17509:             $outcome .= $linefeed;
17510:         } else {
17511:             $outcome .= "</ul><br /><br /></div>\n";
17512:         } 
17513:     }
17514:     if ($args->{'no_end_date'}) {
17515:         $args->{'endaccess'} = 0;
17516:     }
17517: #  If an official course with institutional sections is created by cloning 
17518: #  an existing course, section-specific hiding of course totals in student's
17519: #  view of grades as copied from cloned course, will be checked for valid 
17520: #  sections.
17521:     if (($can_clone && $cloneid) &&
17522:         ($cenv{'internal.coursecode'} ne '') &&
17523:         ($cenv{'grading'} eq 'standard') &&
17524:         ($cenv{'hidetotals'} ne '') &&
17525:         ($cenv{'hidetotals'} ne 'all')) {
17526:         my @hidesecs;
17527:         my $deletehidetotals;
17528:         if (@oklcsecs) {
17529:             foreach my $sec (split(/,/,$cenv{'hidetotals'})) {
17530:                 if (grep(/^\Q$sec$/,@oklcsecs)) {
17531:                     push(@hidesecs,$sec);
17532:                 }
17533:             }
17534:             if (@hidesecs) {
17535:                 $cenv{'hidetotals'} = join(',',@hidesecs);
17536:             } else {
17537:                 $deletehidetotals = 1;
17538:             }
17539:         } else {
17540:             $deletehidetotals = 1;
17541:         }
17542:         if ($deletehidetotals) {
17543:             delete($cenv{'hidetotals'});
17544:             &Apache::lonnet::del('environment',['hidetotals'],$$crsudom,$$crsunum);
17545:         }
17546:     }
17547:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
17548:     $cenv{'internal.autoend'}=$args->{'enrollend'};
17549:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
17550:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
17551:     if ($args->{'showphotos'}) {
17552:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
17553:     }
17554:     $cenv{'internal.authtype'} = $args->{'authtype'};
17555:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
17556:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
17557:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
17558:             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'); 
17559:             if ($context eq 'auto') {
17560:                 $outcome .= $krb_msg;
17561:             } else {
17562:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
17563:             }
17564:             $outcome .= $linefeed;
17565:         }
17566:     }
17567:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
17568:        if ($args->{'setpolicy'}) {
17569:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
17570:        }
17571:        if ($args->{'setcontent'}) {
17572:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
17573:        }
17574:        if ($args->{'setcomment'}) {
17575:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
17576:        }
17577:     }
17578:     if ($args->{'reshome'}) {
17579: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
17580: 	$cenv{'reshome'}=~s/\/+$/\//;
17581:     }
17582: #
17583: # course has keyed access
17584: #
17585:     if ($args->{'setkeys'}) {
17586:        $cenv{'keyaccess'}='yes';
17587:     }
17588: # if specified, key authority is not course, but user
17589: # only active if keyaccess is yes
17590:     if ($args->{'keyauth'}) {
17591: 	my ($user,$domain) = split(':',$args->{'keyauth'});
17592: 	$user = &LONCAPA::clean_username($user);
17593: 	$domain = &LONCAPA::clean_username($domain);
17594: 	if ($user ne '' && $domain ne '') {
17595: 	    $cenv{'keyauth'}=$user.':'.$domain;
17596: 	}
17597:     }
17598: 
17599: #
17600: #  generate and store uniquecode (available to course requester), if course should have one.
17601: #
17602:     if ($args->{'uniquecode'}) {
17603:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
17604:         if ($code) {
17605:             $cenv{'internal.uniquecode'} = $code;
17606:             my %crsinfo =
17607:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
17608:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
17609:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
17610:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
17611:             } 
17612:             if (ref($coderef)) {
17613:                 $$coderef = $code;
17614:             }
17615:         }
17616:     }
17617: 
17618:     if ($args->{'disresdis'}) {
17619:         $cenv{'pch.roles.denied'}='st';
17620:     }
17621:     if ($args->{'disablechat'}) {
17622:         $cenv{'plc.roles.denied'}='st';
17623:     }
17624: 
17625:     # Record we've not yet viewed the Course Initialization Helper for this 
17626:     # course
17627:     $cenv{'course.helper.not.run'} = 1;
17628:     #
17629:     # Use new Randomseed
17630:     #
17631:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
17632:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
17633:     #
17634:     # The encryption code and receipt prefix for this course
17635:     #
17636:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
17637:     $cenv{'internal.encpref'}=100+int(9*rand(99));
17638:     #
17639:     # By default, use standard grading
17640:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
17641: 
17642:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
17643:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
17644: #
17645: # Open all assignments
17646: #
17647:     if ($args->{'openall'}) {
17648:        my $opendate = time;
17649:        if ($args->{'openallfrom'} =~ /^\d+$/) {
17650:            $opendate = $args->{'openallfrom'};
17651:        }
17652:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
17653:        my %storecontent = ($storeunder         => $opendate,
17654:                            $storeunder.'.type' => 'date_start');
17655:        $outcome .= &mt('All assignments open starting [_1]',
17656:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
17657:                    &Apache::lonnet::cput
17658:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
17659:    }
17660: #
17661: # Set first page
17662: #
17663:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
17664: 	    || ($cloneid)) {
17665: 	$outcome .= &mt('Setting first resource').': ';
17666: 
17667: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
17668:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
17669: 
17670:         $outcome .= ($fatal?$errtext:'read ok').' - ';
17671:         my $title; my $url;
17672:         if ($args->{'firstres'} eq 'syl') {
17673: 	    $title=&mt('Syllabus');
17674:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
17675:         } else {
17676:             $title=&mt('Table of Contents');
17677:             $url='/adm/navmaps';
17678:         }
17679: 
17680:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
17681: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
17682: 
17683: 	if ($errtext) { $fatal=2; }
17684:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
17685:     }
17686: 
17687: # 
17688: # Set params for Placement Tests
17689: #
17690:     if ($args->{'crstype'} eq 'Placement') {
17691:        my %storecontent; 
17692:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
17693:        my %defaults = (
17694:                         buttonshide   => { value => 'yes',
17695:                                            type => 'string_yesno',},
17696:                         type          => { value => 'randomizetry',
17697:                                            type  => 'string_questiontype',},
17698:                         maxtries      => { value => 1,
17699:                                            type => 'int_pos',},
17700:                         problemstatus => { value => 'no',
17701:                                            type  => 'string_problemstatus',},
17702:                       );
17703:        foreach my $key (keys(%defaults)) {
17704:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
17705:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
17706:        }
17707:        &Apache::lonnet::cput
17708:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
17709:     }
17710: 
17711:     return (1,$outcome,\@clonemsg);
17712: }
17713: 
17714: sub make_unique_code {
17715:     my ($cdom,$cnum) = @_;
17716:     # get lock on uniquecodes db
17717:     my $lockhash = {
17718:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
17719:                                                   ':'.$env{'user.domain'},
17720:                    };
17721:     my $tries = 0;
17722:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
17723:     my ($code,$error);
17724:   
17725:     while (($gotlock ne 'ok') && ($tries<3)) {
17726:         $tries ++;
17727:         sleep 1;
17728:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
17729:     }
17730:     if ($gotlock eq 'ok') {
17731:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
17732:         my $gotcode;
17733:         my $attempts = 0;
17734:         while ((!$gotcode) && ($attempts < 100)) {
17735:             $code = &generate_code();
17736:             if (!exists($currcodes{$code})) {
17737:                 $gotcode = 1;
17738:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
17739:                     $error = 'nostore';
17740:                 }
17741:             }
17742:             $attempts ++;
17743:         }
17744:         my @del_lock = ($cnum."\0".'uniquecodes');
17745:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
17746:     } else {
17747:         $error = 'nolock';
17748:     }
17749:     return ($code,$error);
17750: }
17751: 
17752: sub generate_code {
17753:     my $code;
17754:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
17755:     for (my $i=0; $i<6; $i++) {
17756:         my $lettnum = int (rand 2);
17757:         my $item = '';
17758:         if ($lettnum) {
17759:             $item = $letts[int( rand(18) )];
17760:         } else {
17761:             $item = 1+int( rand(8) );
17762:         }
17763:         $code .= $item;
17764:     }
17765:     return $code;
17766: }
17767: 
17768: ############################################################
17769: ############################################################
17770: 
17771: # Community, Course and Placement Test
17772: sub course_type {
17773:     my ($cid) = @_;
17774:     if (!defined($cid)) {
17775:         $cid = $env{'request.course.id'};
17776:     }
17777:     if (defined($env{'course.'.$cid.'.type'})) {
17778:         return $env{'course.'.$cid.'.type'};
17779:     } else {
17780:         return 'Course';
17781:     }
17782: }
17783: 
17784: sub group_term {
17785:     my $crstype = &course_type();
17786:     my %names = (
17787:                   'Course' => 'group',
17788:                   'Community' => 'group',
17789:                   'Placement' => 'group',
17790:                 );
17791:     return $names{$crstype};
17792: }
17793: 
17794: sub course_types {
17795:     my @types = ('official','unofficial','community','textbook','placement','lti');
17796:     my %typename = (
17797:                          official   => 'Official course',
17798:                          unofficial => 'Unofficial course',
17799:                          community  => 'Community',
17800:                          textbook   => 'Textbook course',
17801:                          placement  => 'Placement test',
17802:                          lti        => 'LTI provider',
17803:                    );
17804:     return (\@types,\%typename);
17805: }
17806: 
17807: sub icon {
17808:     my ($file)=@_;
17809:     my $curfext = lc((split(/\./,$file))[-1]);
17810:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
17811:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
17812:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
17813: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
17814: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
17815: 	            $curfext.".gif") {
17816: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
17817: 		$curfext.".gif";
17818: 	}
17819:     }
17820:     return &lonhttpdurl($iconname);
17821: } 
17822: 
17823: sub lonhttpdurl {
17824: #
17825: # Had been used for "small fry" static images on separate port 8080.
17826: # Modify here if lightweight http functionality desired again.
17827: # Currently eliminated due to increasing firewall issues.
17828: #
17829:     my ($url)=@_;
17830:     return $url;
17831: }
17832: 
17833: sub connection_aborted {
17834:     my ($r)=@_;
17835:     $r->print(" ");$r->rflush();
17836:     my $c = $r->connection;
17837:     return $c->aborted();
17838: }
17839: 
17840: #    Escapes strings that may have embedded 's that will be put into
17841: #    strings as 'strings'.
17842: sub escape_single {
17843:     my ($input) = @_;
17844:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
17845:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
17846:     return $input;
17847: }
17848: 
17849: #  Same as escape_single, but escape's "'s  This 
17850: #  can be used for  "strings"
17851: sub escape_double {
17852:     my ($input) = @_;
17853:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
17854:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
17855:     return $input;
17856: }
17857:  
17858: #   Escapes the last element of a full URL.
17859: sub escape_url {
17860:     my ($url)   = @_;
17861:     my @urlslices = split(/\//, $url,-1);
17862:     my $lastitem = &escape(pop(@urlslices));
17863:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
17864: }
17865: 
17866: sub compare_arrays {
17867:     my ($arrayref1,$arrayref2) = @_;
17868:     my (@difference,%count);
17869:     @difference = ();
17870:     %count = ();
17871:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
17872:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
17873:         foreach my $element (keys(%count)) {
17874:             if ($count{$element} == 1) {
17875:                 push(@difference,$element);
17876:             }
17877:         }
17878:     }
17879:     return @difference;
17880: }
17881: 
17882: sub lon_status_items {
17883:     my %defaults = (
17884:                      E         => 100,
17885:                      W         => 4,
17886:                      N         => 1,
17887:                      U         => 5,
17888:                      threshold => 200,
17889:                      sysmail   => 2500,
17890:                    );
17891:     my %names = (
17892:                    E => 'Errors',
17893:                    W => 'Warnings',
17894:                    N => 'Notices',
17895:                    U => 'Unsent',
17896:                 );
17897:     return (\%defaults,\%names);
17898: }
17899: 
17900: # -------------------------------------------------------- Initialize user login
17901: sub init_user_environment {
17902:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
17903:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
17904: 
17905:     my $public=($username eq 'public' && $domain eq 'public');
17906: 
17907:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv,
17908:         $coauthorenv);
17909:     my $now=time;
17910: 
17911:     if ($public) {
17912: 	my $max_public=100;
17913: 	my $oldest;
17914: 	my $oldest_time=0;
17915: 	for(my $next=1;$next<=$max_public;$next++) {
17916: 	    if (-e $lonids."/publicuser_$next.id") {
17917: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
17918: 		if ($mtime<$oldest_time || !$oldest_time) {
17919: 		    $oldest_time=$mtime;
17920: 		    $oldest=$next;
17921: 		}
17922: 	    } else {
17923: 		$cookie="publicuser_$next";
17924: 		last;
17925: 	    }
17926: 	}
17927: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
17928:     } else {
17929: 	# See if old ID present, if so, remove if this isn't a robot,
17930: 	# killing any existing non-robot sessions
17931: 	if (!$args->{'robot'}) {
17932: 	    opendir(DIR,$lonids);
17933: 	    while ($filename=readdir(DIR)) {
17934: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
17935:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
17936:                             &GDBM_READER(),0640)) {
17937:                         my $linkedfile;
17938:                         if (exists($oldenv{'user.linkedenv'})) {
17939:                             $linkedfile = $oldenv{'user.linkedenv'};
17940:                         }
17941:                         untie(%oldenv);
17942:                         if (unlink("$lonids/$filename")) {
17943:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
17944:                                 if (-l "$lonids/$linkedfile.id") {
17945:                                     unlink("$lonids/$linkedfile.id");
17946:                                 }
17947:                             }
17948:                         }
17949:                     } else {
17950:                         unlink($lonids.'/'.$filename);
17951:                     }
17952: 		}
17953: 	    }
17954: 	    closedir(DIR);
17955: # If there is a undeleted lockfile for the user's paste buffer remove it.
17956:             my $namespace = 'nohist_courseeditor';
17957:             my $lockingkey = 'paste'."\0".'locked_num';
17958:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
17959:                                                 $domain,$username);
17960:             if (exists($lockhash{$lockingkey})) {
17961:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
17962:                 unless ($delresult eq 'ok') {
17963:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
17964:                 }
17965:             }
17966: 	}
17967: # Give them a new cookie
17968: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
17969: 		                   : $now.$$.int(rand(10000)));
17970: 	$cookie="$username\_$id\_$domain\_$authhost";
17971:     
17972: # Initialize roles
17973: 
17974: 	($userroles,$firstaccenv,$timerintenv,$coauthorenv) = 
17975:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
17976:     }
17977: # ------------------------------------ Check browser type and MathML capability
17978: 
17979:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
17980:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
17981: 
17982: # ------------------------------------------------------------- Get environment
17983: 
17984:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
17985:     my ($tmp) = keys(%userenv);
17986:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
17987: 	undef(%userenv);
17988:     }
17989:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
17990: 	$form->{'interface'}=$userenv{'interface'};
17991:     }
17992:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
17993: 
17994: # --------------- Do not trust query string to be put directly into environment
17995:     foreach my $option ('interface','localpath','localres') {
17996:         $form->{$option}=~s/[\n\r\=]//gs;
17997:     }
17998: # --------------------------------------------------------- Write first profile
17999: 
18000:     {
18001:         my $ip = &Apache::lonnet::get_requestor_ip($r);
18002: 	my %initial_env = 
18003: 	    ("user.name"          => $username,
18004: 	     "user.domain"        => $domain,
18005: 	     "user.home"          => $authhost,
18006: 	     "browser.type"       => $clientbrowser,
18007: 	     "browser.version"    => $clientversion,
18008: 	     "browser.mathml"     => $clientmathml,
18009: 	     "browser.unicode"    => $clientunicode,
18010: 	     "browser.os"         => $clientos,
18011:              "browser.mobile"     => $clientmobile,
18012:              "browser.info"       => $clientinfo,
18013:              "browser.osversion"  => $clientosversion,
18014: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
18015: 	     "request.course.fn"  => '',
18016: 	     "request.course.uri" => '',
18017: 	     "request.course.sec" => '',
18018: 	     "request.role"       => 'cm',
18019: 	     "request.role.adv"   => $env{'user.adv'},
18020: 	     "request.host"       => $ip,);
18021: 
18022:         if ($form->{'localpath'}) {
18023: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
18024: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
18025:         }
18026: 	
18027: 	if ($form->{'interface'}) {
18028: 	    $form->{'interface'}=~s/\W//gs;
18029: 	    $initial_env{"browser.interface"} = $form->{'interface'};
18030: 	    $env{'browser.interface'}=$form->{'interface'};
18031: 	}
18032: 
18033:         if ($form->{'iptoken'}) {
18034:             my $lonhost = $r->dir_config('lonHostID');
18035:             $initial_env{"user.noloadbalance"} = $lonhost;
18036:             $env{'user.noloadbalance'} = $lonhost;
18037:         }
18038: 
18039:         if ($form->{'noloadbalance'}) {
18040:             my @hosts = &Apache::lonnet::current_machine_ids();
18041:             my $hosthere = $form->{'noloadbalance'};
18042:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
18043:                 $initial_env{"user.noloadbalance"} = $hosthere;
18044:                 $env{'user.noloadbalance'} = $hosthere;
18045:             }
18046:         }
18047: 
18048:         unless ($domain eq 'public') {
18049:             my %is_adv = ( is_adv => $env{'user.adv'} );
18050:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
18051: 
18052:             foreach my $tool ('aboutme','blog','webdav','portfolio','portaccess','timezone') {
18053:                 $userenv{'availabletools.'.$tool} =
18054:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
18055:                                                       undef,\%userenv,\%domdef,\%is_adv);
18056:             }
18057: 
18058:             foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
18059:                 $userenv{'canrequest.'.$crstype} =
18060:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
18061:                                                       'reload','requestcourses',
18062:                                                       \%userenv,\%domdef,\%is_adv);
18063:             }
18064: 
18065:             if ((ref($userroles) eq 'HASH') && ($userroles->{'user.author'}) &&
18066:                 (exists($userroles->{"user.role.au./$domain/"}))) {
18067:                 if ($userenv{'authoreditors'}) {
18068:                     $userenv{'editors'} = $userenv{'authoreditors'};
18069:                 } elsif ($domdef{'editors'} ne '') {
18070:                     $userenv{'editors'} = $domdef{'editors'};
18071:                 } else {
18072:                     $userenv{'editors'} = 'edit,xml';
18073:                 }
18074:             }
18075: 
18076:             $userenv{'canrequest.author'} =
18077:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
18078:                                                   'reload','requestauthor',
18079:                                                   \%userenv,\%domdef,\%is_adv);
18080:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
18081:                                                  $domain,$username);
18082:             my $reqstatus = $reqauthor{'author_status'};
18083:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
18084:                 if (ref($reqauthor{'author'}) eq 'HASH') {
18085:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
18086:                                                       $reqauthor{'author'}{'timestamp'};
18087:                 }
18088:             }
18089:             my ($types,$typename) = &course_types();
18090:             if (ref($types) eq 'ARRAY') {
18091:                 my @options = ('approval','validate','autolimit');
18092:                 my $optregex = join('|',@options);
18093:                 my (%willtrust,%trustchecked);
18094:                 foreach my $type (@{$types}) {
18095:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
18096:                     if ($dom_str ne '') {
18097:                         my $updatedstr = '';
18098:                         my @possdomains = split(',',$dom_str);
18099:                         foreach my $entry (@possdomains) {
18100:                             my ($extdom,$extopt) = split(':',$entry);
18101:                             unless ($trustchecked{$extdom}) {
18102:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
18103:                                 $trustchecked{$extdom} = 1;
18104:                             }
18105:                             if ($willtrust{$extdom}) {
18106:                                 $updatedstr .= $entry.',';
18107:                             }
18108:                         }
18109:                         $updatedstr =~ s/,$//;
18110:                         if ($updatedstr) {
18111:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
18112:                         } else {
18113:                             delete($userenv{'reqcrsotherdom.'.$type});
18114:                         }
18115:                     }
18116:                 }
18117:             }
18118:         }
18119: 	$env{'user.environment'} = "$lonids/$cookie.id";
18120: 
18121: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
18122: 		 &GDBM_WRCREAT(),0640)) {
18123: 	    &_add_to_env(\%disk_env,\%initial_env);
18124: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
18125: 	    &_add_to_env(\%disk_env,$userroles);
18126:             if (ref($firstaccenv) eq 'HASH') {
18127:                 &_add_to_env(\%disk_env,$firstaccenv);
18128:             }
18129:             if (ref($timerintenv) eq 'HASH') {
18130:                 &_add_to_env(\%disk_env,$timerintenv);
18131:             }
18132:             if (ref($coauthorenv) eq 'HASH') {
18133:                 if (keys(%{$coauthorenv})) {
18134:                     &_add_to_env(\%disk_env,$coauthorenv);
18135:                 }
18136:             }
18137: 	    if (ref($args->{'extra_env'})) {
18138: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
18139: 	    }
18140: 	    untie(%disk_env);
18141: 	} else {
18142: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
18143: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
18144: 	    return 'error: '.$!;
18145: 	}
18146:     }
18147:     $env{'request.role'}='cm';
18148:     $env{'request.role.adv'}=$env{'user.adv'};
18149:     $env{'browser.type'}=$clientbrowser;
18150: 
18151:     return $cookie;
18152: 
18153: }
18154: 
18155: sub _add_to_env {
18156:     my ($idf,$env_data,$prefix) = @_;
18157:     if (ref($env_data) eq 'HASH') {
18158:         while (my ($key,$value) = each(%$env_data)) {
18159: 	    $idf->{$prefix.$key} = $value;
18160: 	    $env{$prefix.$key}   = $value;
18161:         }
18162:     }
18163: }
18164: 
18165: # --- Get the symbolic name of a problem and the url
18166: sub get_symb {
18167:     my ($request,$silent) = @_;
18168:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
18169:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
18170:     if ($symb eq '') {
18171:         if (!$silent) {
18172:             if (ref($request)) { 
18173:                 $request->print("Unable to handle ambiguous references:$url:.");
18174:             }
18175:             return ();
18176:         }
18177:     }
18178:     &Apache::lonenc::check_decrypt(\$symb);
18179:     return ($symb);
18180: }
18181: 
18182: # --------------------------------------------------------------Get annotation
18183: 
18184: sub get_annotation {
18185:     my ($symb,$enc) = @_;
18186: 
18187:     my $key = $symb;
18188:     if (!$enc) {
18189:         $key =
18190:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
18191:     }
18192:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
18193:     return $annotation{$key};
18194: }
18195: 
18196: sub clean_symb {
18197:     my ($symb,$delete_enc) = @_;
18198: 
18199:     &Apache::lonenc::check_decrypt(\$symb);
18200:     my $enc = $env{'request.enc'};
18201:     if ($delete_enc) {
18202:         delete($env{'request.enc'});
18203:     }
18204: 
18205:     return ($symb,$enc);
18206: }
18207: 
18208: ############################################################
18209: ############################################################
18210: 
18211: =pod
18212: 
18213: =head1 Routines for building display used to search for courses
18214: 
18215: 
18216: =over 4
18217: 
18218: =item * &build_filters()
18219: 
18220: Create markup for a table used to set filters to use when selecting
18221: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
18222: and quotacheck.pl
18223: 
18224: 
18225: Inputs:
18226: 
18227: filterlist - anonymous array of fields to include as potential filters 
18228: 
18229: crstype - course type
18230: 
18231: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
18232:               to pop-open a course selector (will contain "extra element"). 
18233: 
18234: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
18235: 
18236: filter - anonymous hash of criteria and their values
18237: 
18238: action - form action
18239: 
18240: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
18241: 
18242: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
18243: 
18244: cloneruname - username of owner of new course who wants to clone
18245: 
18246: clonerudom - domain of owner of new course who wants to clone
18247: 
18248: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
18249: 
18250: codetitlesref - reference to array of titles of components in institutional codes (official courses)
18251: 
18252: codedom - domain
18253: 
18254: formname - value of form element named "form". 
18255: 
18256: fixeddom - domain, if fixed.
18257: 
18258: prevphase - value to assign to form element named "phase" when going back to the previous screen  
18259: 
18260: cnameelement - name of form element in form on opener page which will receive title of selected course 
18261: 
18262: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
18263: 
18264: cdomelement - name of form element in form on opener page which will receive domain of selected course
18265: 
18266: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
18267: 
18268: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
18269: 
18270: clonewarning - warning message about missing information for intended course owner when DC creates a course
18271: 
18272: 
18273: Returns: $output - HTML for display of search criteria, and hidden form elements.
18274: 
18275: 
18276: Side Effects: None
18277: 
18278: =cut
18279: 
18280: # ---------------------------------------------- search for courses based on last activity etc.
18281: 
18282: sub build_filters {
18283:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
18284:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
18285:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
18286:         $cnameelement,$cnumelement,$cdomelement,$setroles,
18287:         $clonetext,$clonewarning) = @_;
18288:     my ($list,$jscript);
18289:     my $onchange = 'javascript:updateFilters(this)';
18290:     my ($domainselectform,$sincefilterform,$createdfilterform,
18291:         $ownerdomselectform,$persondomselectform,$instcodeform,
18292:         $typeselectform,$instcodetitle);
18293:     if ($formname eq '') {
18294:         $formname = $caller;
18295:     }
18296:     foreach my $item (@{$filterlist}) {
18297:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
18298:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
18299:             if ($item eq 'domainfilter') {
18300:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
18301:             } elsif ($item eq 'coursefilter') {
18302:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
18303:             } elsif ($item eq 'ownerfilter') {
18304:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
18305:             } elsif ($item eq 'ownerdomfilter') {
18306:                 $filter->{'ownerdomfilter'} =
18307:                     &LONCAPA::clean_domain($filter->{$item});
18308:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
18309:                                                        'ownerdomfilter',1);
18310:             } elsif ($item eq 'personfilter') {
18311:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
18312:             } elsif ($item eq 'persondomfilter') {
18313:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
18314:                                                         'persondomfilter',1);
18315:             } else {
18316:                 $filter->{$item} =~ s/\W//g;
18317:             }
18318:             if (!$filter->{$item}) {
18319:                 $filter->{$item} = '';
18320:             }
18321:         }
18322:         if ($item eq 'domainfilter') {
18323:             my $allow_blank = 1;
18324:             if ($formname eq 'portform') {
18325:                 $allow_blank=0;
18326:             } elsif ($formname eq 'studentform') {
18327:                 $allow_blank=0;
18328:             }
18329:             if ($fixeddom) {
18330:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
18331:                                     ' value="'.$codedom.'" />'.
18332:                                     &Apache::lonnet::domain($codedom,'description');
18333:             } else {
18334:                 $domainselectform = &select_dom_form($filter->{$item},
18335:                                                      'domainfilter',
18336:                                                       $allow_blank,'',$onchange);
18337:             }
18338:         } else {
18339:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
18340:         }
18341:     }
18342: 
18343:     # last course activity filter and selection
18344:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
18345: 
18346:     # course created filter and selection
18347:     if (exists($filter->{'createdfilter'})) {
18348:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
18349:     }
18350: 
18351:     my $prefix = $crstype;
18352:     if ($crstype eq 'Placement') {
18353:         $prefix = 'Placement Test'
18354:     }
18355:     my %lt = &Apache::lonlocal::texthash(
18356:                 'cac' => "$prefix Activity",
18357:                 'ccr' => "$prefix Created",
18358:                 'cde' => "$prefix Title",
18359:                 'cdo' => "$prefix Domain",
18360:                 'ins' => 'Institutional Code',
18361:                 'inc' => 'Institutional Categorization',
18362:                 'cow' => "$prefix Owner/Co-owner",
18363:                 'cop' => "$prefix Personnel Includes",
18364:                 'cog' => 'Type',
18365:              );
18366: 
18367:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
18368:         my $typeval = 'Course';
18369:         if ($crstype eq 'Community') {
18370:             $typeval = 'Community';
18371:         } elsif ($crstype eq 'Placement') {
18372:             $typeval = 'Placement';
18373:         }
18374:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
18375:     } else {
18376:         $typeselectform =  '<select name="type" size="1"';
18377:         if ($onchange) {
18378:             $typeselectform .= ' onchange="'.$onchange.'"';
18379:         }
18380:         $typeselectform .= '>'."\n";
18381:         foreach my $posstype ('Course','Community','Placement') {
18382:             my $shown;
18383:             if ($posstype eq 'Placement') {
18384:                 $shown = &mt('Placement Test');
18385:             } else {
18386:                 $shown = &mt($posstype);
18387:             }
18388:             $typeselectform.='<option value="'.$posstype.'"'.
18389:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
18390:         }
18391:         $typeselectform.="</select>";
18392:     }
18393: 
18394:     my ($cloneableonlyform,$cloneabletitle);
18395:     if (exists($filter->{'cloneableonly'})) {
18396:         my $cloneableon = '';
18397:         my $cloneableoff = ' checked="checked"';
18398:         if ($filter->{'cloneableonly'}) {
18399:             $cloneableon = $cloneableoff;
18400:             $cloneableoff = '';
18401:         }
18402:         $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>';
18403:         if ($formname eq 'ccrs') {
18404:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
18405:         } else {
18406:             $cloneabletitle = &mt('Cloneable by you');
18407:         }
18408:     }
18409:     my $officialjs;
18410:     if ($crstype eq 'Course') {
18411:         if (exists($filter->{'instcodefilter'})) {
18412: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
18413: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
18414:             if ($codedom) { 
18415:                 $officialjs = 1;
18416:                 ($instcodeform,$jscript,$$numtitlesref) =
18417:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
18418:                                                                   $officialjs,$codetitlesref);
18419:                 if ($jscript) {
18420:                     $jscript = '<script type="text/javascript">'."\n".
18421:                                '// <![CDATA['."\n".
18422:                                $jscript."\n".
18423:                                '// ]]>'."\n".
18424:                                '</script>'."\n";
18425:                 }
18426:             }
18427:             if ($instcodeform eq '') {
18428:                 $instcodeform =
18429:                     '<input type="text" name="instcodefilter" size="10" value="'.
18430:                     $list->{'instcodefilter'}.'" />';
18431:                 $instcodetitle = $lt{'ins'};
18432:             } else {
18433:                 $instcodetitle = $lt{'inc'};
18434:             }
18435:             if ($fixeddom) {
18436:                 $instcodetitle .= '<br />('.$codedom.')';
18437:             }
18438:         }
18439:     }
18440:     my $output = qq|
18441: <form method="post" name="filterpicker" action="$action">
18442: <input type="hidden" name="form" value="$formname" />
18443: |;
18444:     if ($formname eq 'modifycourse') {
18445:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
18446:                    '<input type="hidden" name="prevphase" value="'.
18447:                    $prevphase.'" />'."\n";
18448:     } elsif ($formname eq 'quotacheck') {
18449:         $output .= qq|
18450: <input type="hidden" name="sortby" value="" />
18451: <input type="hidden" name="sortorder" value="" />
18452: |;
18453:     } else {
18454:         my $name_input;
18455:         if ($cnameelement ne '') {
18456:             $name_input = '<input type="hidden" name="cnameelement" value="'.
18457:                           $cnameelement.'" />';
18458:         }
18459:         $output .= qq|
18460: <input type="hidden" name="cnumelement" value="$cnumelement" />
18461: <input type="hidden" name="cdomelement" value="$cdomelement" />
18462: $name_input
18463: $roleelement
18464: $multelement
18465: $typeelement
18466: |;
18467:         if ($formname eq 'portform') {
18468:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
18469:         }
18470:     }
18471:     if ($fixeddom) {
18472:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
18473:     }
18474:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
18475:     if ($sincefilterform) {
18476:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
18477:                   .$sincefilterform
18478:                   .&Apache::lonhtmlcommon::row_closure();
18479:     }
18480:     if ($createdfilterform) {
18481:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
18482:                   .$createdfilterform
18483:                   .&Apache::lonhtmlcommon::row_closure();
18484:     }
18485:     if ($domainselectform) {
18486:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
18487:                   .$domainselectform
18488:                   .&Apache::lonhtmlcommon::row_closure();
18489:     }
18490:     if ($typeselectform) {
18491:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
18492:             $output .= $typeselectform;
18493:         } else {
18494:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
18495:                       .$typeselectform
18496:                       .&Apache::lonhtmlcommon::row_closure();
18497:         }
18498:     }
18499:     if ($instcodeform) {
18500:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
18501:                   .$instcodeform
18502:                   .&Apache::lonhtmlcommon::row_closure();
18503:     }
18504:     if (exists($filter->{'ownerfilter'})) {
18505:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
18506:                    '<table><tr><td>'.&mt('Username').'<br />'.
18507:                    '<input type="text" name="ownerfilter" size="20" value="'.
18508:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
18509:                    $ownerdomselectform.'</td></tr></table>'.
18510:                    &Apache::lonhtmlcommon::row_closure();
18511:     }
18512:     if (exists($filter->{'personfilter'})) {
18513:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
18514:                    '<table><tr><td>'.&mt('Username').'<br />'.
18515:                    '<input type="text" name="personfilter" size="20" value="'.
18516:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
18517:                    $persondomselectform.'</td></tr></table>'.
18518:                    &Apache::lonhtmlcommon::row_closure();
18519:     }
18520:     if (exists($filter->{'coursefilter'})) {
18521:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
18522:                   .'<input type="text" name="coursefilter" size="25" value="'
18523:                   .$list->{'coursefilter'}.'" />'
18524:                   .&Apache::lonhtmlcommon::row_closure();
18525:     }
18526:     if ($cloneableonlyform) {
18527:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
18528:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
18529:     }
18530:     if (exists($filter->{'descriptfilter'})) {
18531:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
18532:                   .'<input type="text" name="descriptfilter" size="40" value="'
18533:                   .$list->{'descriptfilter'}.'" />'
18534:                   .&Apache::lonhtmlcommon::row_closure(1);
18535:     }
18536:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
18537:                '<input type="hidden" name="updater" value="" />'."\n".
18538:                '<input type="submit" name="gosearch" value="'.
18539:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
18540:     return $jscript.$clonewarning.$output;
18541: }
18542: 
18543: =pod 
18544: 
18545: =item * &timebased_select_form()
18546: 
18547: Create markup for a dropdown list used to select a time-based
18548: filter e.g., Course Activity, Course Created, when searching for courses
18549: or communities
18550: 
18551: Inputs:
18552: 
18553: item - name of form element (sincefilter or createdfilter)
18554: 
18555: filter - anonymous hash of criteria and their values
18556: 
18557: Returns: HTML for a select box contained a blank, then six time selections,
18558:          with value set in incoming form variables currently selected. 
18559: 
18560: Side Effects: None
18561: 
18562: =cut
18563: 
18564: sub timebased_select_form {
18565:     my ($item,$filter) = @_;
18566:     if (ref($filter) eq 'HASH') {
18567:         $filter->{$item} =~ s/[^\d-]//g;
18568:         if (!$filter->{$item}) { $filter->{$item}=-1; }
18569:         return &select_form(
18570:                             $filter->{$item},
18571:                             $item,
18572:                             {      '-1' => '',
18573:                                 '86400' => &mt('today'),
18574:                                '604800' => &mt('last week'),
18575:                               '2592000' => &mt('last month'),
18576:                               '7776000' => &mt('last three months'),
18577:                              '15552000' => &mt('last six months'),
18578:                              '31104000' => &mt('last year'),
18579:                     'select_form_order' =>
18580:                            ['-1','86400','604800','2592000','7776000',
18581:                             '15552000','31104000']});
18582:     }
18583: }
18584: 
18585: =pod
18586: 
18587: =item * &js_changer()
18588: 
18589: Create script tag containing Javascript used to submit course search form
18590: when course type or domain is changed, and also to hide 'Searching ...' on
18591: page load completion for page showing search result.
18592: 
18593: Inputs: None
18594: 
18595: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
18596: 
18597: Side Effects: None
18598: 
18599: =cut
18600: 
18601: sub js_changer {
18602:     return <<ENDJS;
18603: <script type="text/javascript">
18604: // <![CDATA[
18605: function updateFilters(caller) {
18606:     if (typeof(caller) != "undefined") {
18607:         document.filterpicker.updater.value = caller.name;
18608:     }
18609:     document.filterpicker.submit();
18610: }
18611: 
18612: function hideSearching() {
18613:     if (document.getElementById('searching')) {
18614:         document.getElementById('searching').style.display = 'none';
18615:     }
18616:     return;
18617: }
18618: 
18619: // ]]>
18620: </script>
18621: 
18622: ENDJS
18623: }
18624: 
18625: =pod
18626: 
18627: =item * &search_courses()
18628: 
18629: Process selected filters form course search form and pass to lonnet::courseiddump
18630: to retrieve a hash for which keys are courseIDs which match the selected filters.
18631: 
18632: Inputs:
18633: 
18634: dom - domain being searched 
18635: 
18636: type - course type ('Course' or 'Community' or '.' if any).
18637: 
18638: filter - anonymous hash of criteria and their values
18639: 
18640: numtitles - for institutional codes - number of categories
18641: 
18642: cloneruname - optional username of new course owner
18643: 
18644: clonerudom - optional domain of new course owner
18645: 
18646: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
18647:             (used when DC is using course creation form)
18648: 
18649: codetitles - reference to array of titles of components in institutional codes (official courses).
18650: 
18651: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
18652:            (and so can clone automatically)
18653: 
18654: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
18655: 
18656: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
18657:               courses to clone 
18658: 
18659: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
18660: 
18661: 
18662: Side Effects: None
18663: 
18664: =cut
18665: 
18666: 
18667: sub search_courses {
18668:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
18669:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
18670:     my (%courses,%showcourses,$cloner);
18671:     if (($filter->{'ownerfilter'} ne '') ||
18672:         ($filter->{'ownerdomfilter'} ne '')) {
18673:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
18674:                                        $filter->{'ownerdomfilter'};
18675:     }
18676:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
18677:         if (!$filter->{$item}) {
18678:             $filter->{$item}='.';
18679:         }
18680:     }
18681:     my $now = time;
18682:     my $timefilter =
18683:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
18684:     my ($createdbefore,$createdafter);
18685:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
18686:         $createdbefore = $now;
18687:         $createdafter = $now-$filter->{'createdfilter'};
18688:     }
18689:     my ($instcodefilter,$regexpok);
18690:     if ($numtitles) {
18691:         if ($env{'form.official'} eq 'on') {
18692:             $instcodefilter =
18693:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
18694:             $regexpok = 1;
18695:         } elsif ($env{'form.official'} eq 'off') {
18696:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
18697:             unless ($instcodefilter eq '') {
18698:                 $regexpok = -1;
18699:             }
18700:         }
18701:     } else {
18702:         $instcodefilter = $filter->{'instcodefilter'};
18703:     }
18704:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
18705:     if ($type eq '') { $type = '.'; }
18706: 
18707:     if (($clonerudom ne '') && ($cloneruname ne '')) {
18708:         $cloner = $cloneruname.':'.$clonerudom;
18709:     }
18710:     %courses = &Apache::lonnet::courseiddump($dom,
18711:                                              $filter->{'descriptfilter'},
18712:                                              $timefilter,
18713:                                              $instcodefilter,
18714:                                              $filter->{'combownerfilter'},
18715:                                              $filter->{'coursefilter'},
18716:                                              undef,undef,$type,$regexpok,undef,undef,
18717:                                              undef,undef,$cloner,$cc_clone,
18718:                                              $filter->{'cloneableonly'},
18719:                                              $createdbefore,$createdafter,undef,
18720:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
18721:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
18722:         my $ccrole;
18723:         if ($type eq 'Community') {
18724:             $ccrole = 'co';
18725:         } else {
18726:             $ccrole = 'cc';
18727:         }
18728:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
18729:                                                      $filter->{'persondomfilter'},
18730:                                                      'userroles',undef,
18731:                                                      [$ccrole,'in','ad','ep','ta','cr'],
18732:                                                      $dom);
18733:         foreach my $role (keys(%rolehash)) {
18734:             my ($cnum,$cdom,$courserole) = split(':',$role);
18735:             my $cid = $cdom.'_'.$cnum;
18736:             if (exists($courses{$cid})) {
18737:                 if (ref($courses{$cid}) eq 'HASH') {
18738:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
18739:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
18740:                             push(@{$courses{$cid}{roles}},$courserole);
18741:                         }
18742:                     } else {
18743:                         $courses{$cid}{roles} = [$courserole];
18744:                     }
18745:                     $showcourses{$cid} = $courses{$cid};
18746:                 }
18747:             }
18748:         }
18749:         %courses = %showcourses;
18750:     }
18751:     return %courses;
18752: }
18753: 
18754: =pod
18755: 
18756: =back
18757: 
18758: =head1 Routines for version requirements for current course.
18759: 
18760: =over 4
18761: 
18762: =item * &check_release_required()
18763: 
18764: Compares required LON-CAPA version with version on server, and
18765: if required version is newer looks for a server with the required version.
18766: 
18767: Looks first at servers in user's owen domain; if none suitable, looks at
18768: servers in course's domain are permitted to host sessions for user's domain.
18769: 
18770: Inputs:
18771: 
18772: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
18773: 
18774: $courseid - Course ID of current course
18775: 
18776: $rolecode - User's current role in course (for switchserver query string).
18777: 
18778: $required - LON-CAPA version needed by course (format: Major.Minor).
18779: 
18780: 
18781: Returns:
18782: 
18783: $switchserver - query string tp append to /adm/switchserver call (if 
18784:                 current server's LON-CAPA version is too old. 
18785: 
18786: $warning - Message is displayed if no suitable server could be found.
18787: 
18788: =cut
18789: 
18790: sub check_release_required {
18791:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
18792:     my ($switchserver,$warning);
18793:     if ($required ne '') {
18794:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
18795:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
18796:         if ($reqdmajor ne '' && $reqdminor ne '') {
18797:             my $otherserver;
18798:             if (($major eq '' && $minor eq '') ||
18799:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
18800:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
18801:                 my $switchlcrev =
18802:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
18803:                                                            $userdomserver);
18804:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
18805:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
18806:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
18807:                     my $cdom = $env{'course.'.$courseid.'.domain'};
18808:                     if ($cdom ne $env{'user.domain'}) {
18809:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
18810:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
18811:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
18812:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
18813:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
18814:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
18815:                         my $canhost =
18816:                             &Apache::lonnet::can_host_session($env{'user.domain'},
18817:                                                               $coursedomserver,
18818:                                                               $remoterev,
18819:                                                               $udomdefaults{'remotesessions'},
18820:                                                               $defdomdefaults{'hostedsessions'});
18821: 
18822:                         if ($canhost) {
18823:                             $otherserver = $coursedomserver;
18824:                         } else {
18825:                             $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.");
18826:                         }
18827:                     } else {
18828:                         $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).");
18829:                     }
18830:                 } else {
18831:                     $otherserver = $userdomserver;
18832:                 }
18833:             }
18834:             if ($otherserver ne '') {
18835:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
18836:             }
18837:         }
18838:     }
18839:     return ($switchserver,$warning);
18840: }
18841: 
18842: =pod
18843: 
18844: =item * &check_release_result()
18845: 
18846: Inputs:
18847: 
18848: $switchwarning - Warning message if no suitable server found to host session.
18849: 
18850: $switchserver - query string to append to /adm/switchserver containing lonHostID
18851:                 and current role.
18852: 
18853: Returns: HTML to display with information about requirement to switch server.
18854:          Either displaying warning with link to Roles/Courses screen or
18855:          display link to switchserver.
18856: 
18857: =cut
18858: 
18859: sub check_release_result {
18860:     my ($switchwarning,$switchserver) = @_;
18861:     my $output = &start_page('Selected course unavailable on this server').
18862:                  '<p class="LC_warning">';
18863:     if ($switchwarning) {
18864:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
18865:         if (&show_course()) {
18866:             $output .= &mt('Display courses');
18867:         } else {
18868:             $output .= &mt('Display roles');
18869:         }
18870:         $output .= '</a>';
18871:     } elsif ($switchserver) {
18872:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
18873:                    '<br />'.
18874:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
18875:                    &mt('Switch Server').
18876:                    '</a>';
18877:     }
18878:     $output .= '</p>'.&end_page();
18879:     return $output;
18880: }
18881: 
18882: =pod
18883: 
18884: =item * &needs_coursereinit()
18885: 
18886: Determine if course contents stored for user's session needs to be
18887: refreshed, because content has changed since "Big Hash" last tied.
18888: 
18889: Check for change is made if time last checked is more than 10 minutes ago
18890: (by default).
18891: 
18892: Inputs:
18893: 
18894: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
18895: 
18896: $interval (optional) - Time which may elapse (in s) between last check for content
18897:                        change in current course. (default: 600 s).  
18898: 
18899: Returns: an array; first element is:
18900: 
18901: =over 4
18902: 
18903: 'switch' - if content updates mean user's session
18904:            needs to be switched to a server running a newer LON-CAPA version
18905:  
18906: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
18907:            on current server hosting user's session                
18908: 
18909: ''       - if no action required.
18910: 
18911: =back
18912: 
18913: If first item element is 'switch':
18914: 
18915: second item is $switchwarning - Warning message if no suitable server found to host session. 
18916: 
18917: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
18918:                               and current role. 
18919: 
18920: otherwise: no other elements returned.
18921: 
18922: =back
18923: 
18924: =cut
18925: 
18926: sub needs_coursereinit {
18927:     my ($loncaparev,$interval) = @_;
18928:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
18929:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
18930:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
18931:     my $now = time;
18932:     if ($interval eq '') {
18933:         $interval = 600;
18934:     }
18935:     if (($now-$env{'request.course.timechecked'})>$interval) {
18936:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
18937:         my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
18938:         if ($blocked) {
18939:             return ();
18940:         }
18941:         my $update;
18942:         my $lastmainchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
18943:         my $lastsuppchange = &Apache::lonnet::get_suppchange($cdom,$cnum);
18944:         if ($lastmainchange > $env{'request.course.tied'}) {
18945:             my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
18946:             if ($needswitch) {
18947:                 return ('switch',$switchwarning,$switchserver);
18948:             }
18949:             $update = 'main';
18950:         }
18951:         if ($lastsuppchange > $env{'request.course.suppupdated'}) {
18952:             if ($update) {
18953:                 $update = 'both';
18954:             } else {
18955:                 my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
18956:                 if ($needswitch) {
18957:                     return ('switch',$switchwarning,$switchserver);
18958:                 } else {
18959:                     $update = 'supp';
18960:                 }
18961:             }
18962:             return ($update);
18963:         }
18964:     }
18965:     return ();
18966: }
18967: 
18968: sub switch_for_update {
18969:     my ($loncaparev,$cdom,$cnum) = @_;
18970:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
18971:     if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
18972:         my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
18973:         if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
18974:             &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
18975:                                     $curr_reqd_hash{'internal.releaserequired'}});
18976:             my ($switchserver,$switchwarning) =
18977:                 &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
18978:                                         $curr_reqd_hash{'internal.releaserequired'});
18979:             if ($switchwarning ne '' || $switchserver ne '') {
18980:                 return ('switch',$switchwarning,$switchserver);
18981:             }
18982:         }
18983:     }
18984:     return ();
18985: }
18986: 
18987: sub update_content_constraints {
18988:     my ($cdom,$cnum,$chome,$cid) = @_;
18989:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
18990:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
18991:     my (%checkresponsetypes,%checkcrsrestypes);
18992:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
18993:         my ($item,$name,$value) = split(/:/,$key);
18994:         if ($item eq 'resourcetag') {
18995:             if ($name eq 'responsetype') {
18996:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
18997:             }
18998:         } elsif ($item eq 'course') {
18999:             if ($name eq 'courserestype') {
19000:                 $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
19001:             }
19002:         }
19003:     }
19004:     my $navmap = Apache::lonnavmaps::navmap->new();
19005:     if (defined($navmap)) {
19006:         my (%allresponses,%allcrsrestypes);
19007:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
19008:             if ($res->is_tool()) {
19009:                 if ($allcrsrestypes{'exttool'}) {
19010:                     $allcrsrestypes{'exttool'} ++;
19011:                 } else {
19012:                     $allcrsrestypes{'exttool'} = 1;
19013:                 }
19014:                 next;
19015:             }
19016:             my %responses = $res->responseTypes();
19017:             foreach my $key (keys(%responses)) {
19018:                 next unless(exists($checkresponsetypes{$key}));
19019:                 $allresponses{$key} += $responses{$key};
19020:             }
19021:         }
19022:         foreach my $key (keys(%allresponses)) {
19023:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
19024:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
19025:                 ($reqdmajor,$reqdminor) = ($major,$minor);
19026:             }
19027:         }
19028:         foreach my $key (keys(%allcrsrestypes)) {
19029:             my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
19030:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
19031:                 ($reqdmajor,$reqdminor) = ($major,$minor);
19032:             }
19033:         }
19034:         undef($navmap);
19035:     }
19036:     if (&Apache::lonnet::count_supptools($cnum,$cdom,1)) {
19037:         my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
19038:         if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
19039:             ($reqdmajor,$reqdminor) = ($major,$minor);
19040:         }
19041:     }
19042:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
19043:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
19044:     }
19045:     return;
19046: }
19047: 
19048: sub allmaps_incourse {
19049:     my ($cdom,$cnum,$chome,$cid) = @_;
19050:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
19051:         $cid = $env{'request.course.id'};
19052:         $cdom = $env{'course.'.$cid.'.domain'};
19053:         $cnum = $env{'course.'.$cid.'.num'};
19054:         $chome = $env{'course.'.$cid.'.home'};
19055:     }
19056:     my %allmaps = ();
19057:     my $lastchange =
19058:         &Apache::lonnet::get_coursechange($cdom,$cnum);
19059:     if ($lastchange > $env{'request.course.tied'}) {
19060:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
19061:         unless ($ferr) {
19062:             &update_content_constraints($cdom,$cnum,$chome,$cid);
19063:         }
19064:     }
19065:     my $navmap = Apache::lonnavmaps::navmap->new();
19066:     if (defined($navmap)) {
19067:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
19068:             $allmaps{$res->src()} = 1;
19069:         }
19070:     }
19071:     return \%allmaps;
19072: }
19073: 
19074: sub parse_supplemental_title {
19075:     my ($title) = @_;
19076: 
19077:     my ($foldertitle,$renametitle);
19078:     if ($title =~ /&amp;&amp;&amp;/) {
19079:         $title = &HTML::Entites::decode($title);
19080:     }
19081:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
19082:         $renametitle=$4;
19083:         my ($time,$uname,$udom) = ($1,$2,$3);
19084:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
19085:         my $name =  &plainname($uname,$udom);
19086:         $name = &HTML::Entities::encode($name,'"<>&\'');
19087:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
19088:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.$name;
19089:         if ($foldertitle ne '') {
19090:             $title .= ': <br />'.$foldertitle;
19091:         }
19092:     }
19093:     if (wantarray) {
19094:         return ($title,$foldertitle,$renametitle);
19095:     }
19096:     return $title;
19097: }
19098: 
19099: sub get_supplemental {
19100:     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
19101:     my $hashid=$cnum.':'.$cdom;
19102:     my ($supplemental,$cached,$set_httprefs);
19103:     unless ($ignorecache) {
19104:         ($supplemental,$cached) = &Apache::lonnet::is_cached_new('supplemental',$hashid);
19105:     }
19106:     unless (defined($cached)) {
19107:         my $chome=&Apache::lonnet::homeserver($cnum,$cdom);
19108:         unless ($chome eq 'no_host') {
19109:             my @order = @LONCAPA::map::order;
19110:             my @resources = @LONCAPA::map::resources;
19111:             my @resparms = @LONCAPA::map::resparms;
19112:             my @zombies = @LONCAPA::map::zombies;
19113:             my ($errors,%ids,%hidden);
19114:             $errors =
19115:                 &recurse_supplemental($cnum,$cdom,'supplemental.sequence',
19116:                                       $errors,$possdel,\%ids,\%hidden);
19117:             @LONCAPA::map::order = @order;
19118:             @LONCAPA::map::resources = @resources;
19119:             @LONCAPA::map::resparms = @resparms;
19120:             @LONCAPA::map::zombies = @zombies;
19121:             $set_httprefs = 1;
19122:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
19123:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
19124:             }
19125:             $supplemental = {
19126:                                ids => \%ids,
19127:                                hidden => \%hidden,
19128:                             };
19129:             &Apache::lonnet::do_cache_new('supplemental',$hashid,$supplemental,600);
19130:         }
19131:     }
19132:     return ($supplemental,$set_httprefs);
19133: }
19134: 
19135: sub recurse_supplemental {
19136:     my ($cnum,$cdom,$suppmap,$errors,$possdel,$suppids,$hiddensupp,$hidden) = @_;
19137:     if (($suppmap) && (ref($suppids) eq 'HASH') && (ref($hiddensupp) eq 'HASH')) {
19138:         my $mapnum;
19139:         if ($suppmap eq 'supplemental.sequence') {
19140:             $mapnum = 0;
19141:         } else {
19142:             ($mapnum) = ($suppmap =~ /^supplemental_(\d+)\.sequence$/);
19143:         }
19144:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
19145:         if ($fatal) {
19146:             $errors ++;
19147:         } else {
19148:             my @order = @LONCAPA::map::order;
19149:             if (@order > 0) {
19150:                 my @resources = @LONCAPA::map::resources;
19151:                 my @resparms = @LONCAPA::map::resparms;
19152:                 foreach my $idx (@order) {
19153:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$resources[$idx]);
19154:                     if (($src ne '') && ($status eq 'res')) {
19155:                         my $id = $mapnum.':'.$idx;
19156:                         push(@{$suppids->{$src}},$id);
19157:                         if (($hidden) || (&get_supp_parameter($resparms[$idx],'parameter_hiddenresource') =~ /^yes/i)) {
19158:                             $hiddensupp->{$id} = 1;
19159:                         }
19160:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
19161:                             $errors = &recurse_supplemental($cnum,$cdom,$1,$errors,$possdel,$suppids,
19162:                                                             $hiddensupp,$hiddensupp->{$id});
19163:                         } else {
19164:                             my $allowed;
19165:                             if (($env{'request.role.adv'}) || (!$hiddensupp->{$id})) {
19166:                                 $allowed = 1;
19167:                             } elsif ($possdel) {
19168:                                 foreach my $item (@{$suppids->{$src}}) {
19169:                                     next if ($item eq $id);
19170:                                     unless ($hiddensupp->{$item}) {
19171:                                        $allowed = 1;
19172:                                        last;
19173:                                     }
19174:                                 }
19175:                                 if ((!$allowed) && (exists($env{'httpref.'.$src}))) {
19176:                                     &Apache::lonnet::delenv('httpref.'.$src);
19177:                                 }
19178:                             }
19179:                             if ($allowed && (!exists($env{'httpref.'.$src}))) {
19180:                                 &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
19181:                             }
19182:                         }
19183:                     }
19184:                 }
19185:             }
19186:         }
19187:     }
19188:     return $errors;
19189: }
19190: 
19191: sub set_supp_httprefs {
19192:     my ($cnum,$cdom,$supplemental,$possdel) = @_;
19193:     if (ref($supplemental) eq 'HASH') {
19194:         if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
19195:             foreach my $src (keys(%{$supplemental->{'ids'}})) {
19196:                 next if ($src =~ /\.sequence$/);
19197:                 if (ref($supplemental->{'ids'}->{$src}) eq 'ARRAY') {
19198:                     my $allowed;
19199:                     if ($env{'request.role.adv'}) {
19200:                         $allowed = 1;
19201:                     } else {
19202:                         foreach my $id (@{$supplemental->{'ids'}->{$src}}) {
19203:                             unless ($supplemental->{'hidden'}->{$id}) {
19204:                                 $allowed = 1;
19205:                                 last;
19206:                             }
19207:                         }
19208:                     }
19209:                     if (exists($env{'httpref.'.$src})) {
19210:                         if ($possdel) {
19211:                             unless ($allowed) {
19212:                                 &Apache::lonnet::delenv('httpref.'.$src);
19213:                             }
19214:                         }
19215:                     } elsif ($allowed) {
19216:                         &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
19217:                     }
19218:                 }
19219:             }
19220:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
19221:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
19222:             }
19223:         }
19224:     }
19225: }
19226: 
19227: sub get_supp_parameter {
19228:     my ($resparm,$name)=@_;
19229:     return if ($resparm eq '');
19230:     my $value=undef;
19231:     my $ptype=undef;
19232:     foreach (split('&&&',$resparm)) {
19233:         my ($thistype,$thisname,$thisvalue)=split('___',$_);
19234:         if ($thisname eq $name) {
19235:             $value=$thisvalue;
19236:             $ptype=$thistype;
19237:         }
19238:     }
19239:     return $value;
19240: }
19241: 
19242: sub symb_to_docspath {
19243:     my ($symb,$navmapref) = @_;
19244:     return unless ($symb && ref($navmapref));
19245:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
19246:     if ($resurl=~/\.(sequence|page)$/) {
19247:         $mapurl=$resurl;
19248:     } elsif ($resurl eq 'adm/navmaps') {
19249:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
19250:     }
19251:     my $mapresobj;
19252:     unless (ref($$navmapref)) {
19253:         $$navmapref = Apache::lonnavmaps::navmap->new();
19254:     }
19255:     if (ref($$navmapref)) {
19256:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
19257:     }
19258:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
19259:     my $type=$2;
19260:     my $path;
19261:     if (ref($mapresobj)) {
19262:         my $pcslist = $mapresobj->map_hierarchy();
19263:         if ($pcslist ne '') {
19264:             foreach my $pc (split(/,/,$pcslist)) {
19265:                 next if ($pc <= 1);
19266:                 my $res = $$navmapref->getByMapPc($pc);
19267:                 if (ref($res)) {
19268:                     my $thisurl = $res->src();
19269:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
19270:                     my $thistitle = $res->title();
19271:                     $path .= '&'.
19272:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
19273:                              &escape($thistitle).
19274:                              ':'.$res->randompick().
19275:                              ':'.$res->randomout().
19276:                              ':'.$res->encrypted().
19277:                              ':'.$res->randomorder().
19278:                              ':'.$res->is_page();
19279:                 }
19280:             }
19281:         }
19282:         $path =~ s/^\&//;
19283:         my $maptitle = $mapresobj->title();
19284:         if ($mapurl eq 'default') {
19285:             $maptitle = 'Main Content';
19286:         }
19287:         $path .= (($path ne '')? '&' : '').
19288:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
19289:                  &escape($maptitle).
19290:                  ':'.$mapresobj->randompick().
19291:                  ':'.$mapresobj->randomout().
19292:                  ':'.$mapresobj->encrypted().
19293:                  ':'.$mapresobj->randomorder().
19294:                  ':'.$mapresobj->is_page();
19295:     } else {
19296:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
19297:         my $ispage = (($type eq 'page')? 1 : '');
19298:         if ($mapurl eq 'default') {
19299:             $maptitle = 'Main Content';
19300:         }
19301:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
19302:                 &escape($maptitle).':::::'.$ispage;
19303:     }
19304:     unless ($mapurl eq 'default') {
19305:         $path = 'default&'.
19306:                 &escape('Main Content').
19307:                 ':::::&'.$path;
19308:     }
19309:     return $path;
19310: }
19311: 
19312: sub validate_folderpath {
19313:     my ($supplementalflag,$allowed,$coursenum,$coursedom) = @_;
19314:     if ($env{'form.folderpath'} ne '') {
19315:         my @items = split(/\&/,$env{'form.folderpath'});
19316:         my ($badpath,$changed,$got_supp,$supppath,%supphidden,%suppids);
19317:         for (my $i=0; $i<@items; $i++) {
19318:             my $odd = $i%2;
19319:             if (($odd) && (!$supplementalflag) && ($items[$i] !~ /^[^:]*:(|\d+):(|1):(|1):(|1):(|1)$/)) {
19320:                 $badpath = 1;
19321:             } elsif ($odd && $supplementalflag) {
19322:                 my $idx = $i-1;
19323:                 if ($items[$i] =~ /^([^:]*)::(|1):::$/) {
19324:                     my $esc_name = $1;
19325:                     if ((!$allowed) || ($items[$idx] eq 'supplemental')) {
19326:                         $supppath .= '&'.$esc_name;
19327:                         $changed = 1;
19328:                     } else {
19329:                         $supppath .= '&'.$items[$i];
19330:                     }
19331:                 } elsif (($allowed) && ($items[$idx] ne 'supplemental')) {
19332:                     $changed = 1;
19333:                     my $is_hidden;
19334:                     unless ($got_supp) {
19335:                         my ($supplemental) = &get_supplemental($coursenum,$coursedom);
19336:                         if (ref($supplemental) eq 'HASH') {
19337:                             if (ref($supplemental->{'hidden'}) eq 'HASH') {
19338:                                 %supphidden = %{$supplemental->{'hidden'}};
19339:                             }
19340:                             if (ref($supplemental->{'ids'}) eq 'HASH') {
19341:                                 %suppids = %{$supplemental->{'ids'}};
19342:                             }
19343:                         }
19344:                         $got_supp = 1;
19345:                     }
19346:                     if (ref($suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}) eq 'ARRAY') {
19347:                         my $mapid = $suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}->[0];
19348:                         if ($supphidden{$mapid}) {
19349:                             $is_hidden = 1;
19350:                         }
19351:                     }
19352:                     $supppath .= '&'.$items[$i].'::'.$is_hidden.':::';
19353:                 } else {
19354:                     $supppath .= '&'.$items[$i];
19355:                 }
19356:             } elsif ((!$odd) && ($items[$i] !~ /^(default|supplemental)(|_\d+)$/)) {
19357:                 $badpath = 1;
19358:             } elsif ($supplementalflag) {
19359:                 $supppath .= '&'.$items[$i];
19360:             }
19361:             last if ($badpath);
19362:         }
19363:         if ($badpath) {
19364:             delete($env{'form.folderpath'});
19365:         } elsif ($changed && $supplementalflag) {
19366:             $supppath =~ s/^\&//;
19367:             $env{'form.folderpath'} = $supppath;
19368:         }
19369:     }
19370:     return;
19371: }
19372: 
19373: sub captcha_display {
19374:     my ($context,$lonhost,$defdom) = @_;
19375:     my ($output,$error);
19376:     my ($captcha,$pubkey,$privkey,$version) = 
19377:         &get_captcha_config($context,$lonhost,$defdom);
19378:     if ($captcha eq 'original') {
19379:         $output = &create_captcha();
19380:         unless ($output) {
19381:             $error = 'captcha';
19382:         }
19383:     } elsif ($captcha eq 'recaptcha') {
19384:         $output = &create_recaptcha($pubkey,$version);
19385:         unless ($output) {
19386:             $error = 'recaptcha';
19387:         }
19388:     }
19389:     return ($output,$error,$captcha,$version);
19390: }
19391: 
19392: sub captcha_response {
19393:     my ($context,$lonhost,$defdom) = @_;
19394:     my ($captcha_chk,$captcha_error);
19395:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
19396:     if ($captcha eq 'original') {
19397:         ($captcha_chk,$captcha_error) = &check_captcha();
19398:     } elsif ($captcha eq 'recaptcha') {
19399:         $captcha_chk = &check_recaptcha($privkey,$version);
19400:     } else {
19401:         $captcha_chk = 1;
19402:     }
19403:     return ($captcha_chk,$captcha_error);
19404: }
19405: 
19406: sub get_captcha_config {
19407:     my ($context,$lonhost,$dom_in_effect) = @_;
19408:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
19409:     my $hostname = &Apache::lonnet::hostname($lonhost);
19410:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
19411:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
19412:     if ($context eq 'usercreation') {
19413:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
19414:         if (ref($domconfig{$context}) eq 'HASH') {
19415:             $hashtocheck = $domconfig{$context}{'cancreate'};
19416:             if (ref($hashtocheck) eq 'HASH') {
19417:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
19418:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
19419:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
19420:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
19421:                     }
19422:                     if ($privkey && $pubkey) {
19423:                         $captcha = 'recaptcha';
19424:                         $version = $hashtocheck->{'recaptchaversion'};
19425:                         if ($version ne '2') {
19426:                             $version = 1;
19427:                         }
19428:                     } else {
19429:                         $captcha = 'original';
19430:                     }
19431:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
19432:                     $captcha = 'original';
19433:                 }
19434:             }
19435:         } else {
19436:             $captcha = 'captcha';
19437:         }
19438:     } elsif ($context eq 'login') {
19439:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
19440:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
19441:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
19442:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
19443:             if ($privkey && $pubkey) {
19444:                 $captcha = 'recaptcha';
19445:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
19446:                 if ($version ne '2') {
19447:                     $version = 1; 
19448:                 }
19449:             } else {
19450:                 $captcha = 'original';
19451:             }
19452:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
19453:             $captcha = 'original';
19454:         }
19455:     } elsif ($context eq 'passwords') {
19456:         if ($dom_in_effect) {
19457:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
19458:             if ($passwdconf{'captcha'} eq 'recaptcha') {
19459:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
19460:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
19461:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
19462:                 }
19463:                 if ($privkey && $pubkey) {
19464:                     $captcha = 'recaptcha';
19465:                     $version = $passwdconf{'recaptchaversion'};
19466:                     if ($version ne '2') {
19467:                         $version = 1;
19468:                     }
19469:                 } else {
19470:                     $captcha = 'original';
19471:                 }
19472:             } elsif ($passwdconf{'captcha'} ne 'notused') {
19473:                 $captcha = 'original';
19474:             }
19475:         }
19476:     } 
19477:     return ($captcha,$pubkey,$privkey,$version);
19478: }
19479: 
19480: sub create_captcha {
19481:     my %captcha_params = &captcha_settings();
19482:     my ($output,$maxtries,$tries) = ('',10,0);
19483:     while ($tries < $maxtries) {
19484:         $tries ++;
19485:         my $captcha = Authen::Captcha->new (
19486:                                            output_folder => $captcha_params{'output_dir'},
19487:                                            data_folder   => $captcha_params{'db_dir'},
19488:                                           );
19489:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
19490: 
19491:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
19492:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
19493:                       '<span class="LC_nobreak">'.
19494:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
19495:                       '<input type="text" size="5" name="code" value="" autocomplete="new-password" />'.
19496:                       '</span><br />'.
19497:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
19498:             last;
19499:         }
19500:     }
19501:     if ($output eq '') {
19502:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
19503:     }
19504:     return $output;
19505: }
19506: 
19507: sub captcha_settings {
19508:     my %captcha_params = (
19509:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
19510:                            www_output_dir => "/captchaspool",
19511:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
19512:                            numchars       => '5',
19513:                          );
19514:     return %captcha_params;
19515: }
19516: 
19517: sub check_captcha {
19518:     my ($captcha_chk,$captcha_error);
19519:     my $code = $env{'form.code'};
19520:     my $md5sum = $env{'form.crypt'};
19521:     my %captcha_params = &captcha_settings();
19522:     my $captcha = Authen::Captcha->new(
19523:                       output_folder => $captcha_params{'output_dir'},
19524:                       data_folder   => $captcha_params{'db_dir'},
19525:                   );
19526:     $captcha_chk = $captcha->check_code($code,$md5sum);
19527:     my %captcha_hash = (
19528:                         0       => 'Code not checked (file error)',
19529:                        -1      => 'Failed: code expired',
19530:                        -2      => 'Failed: invalid code (not in database)',
19531:                        -3      => 'Failed: invalid code (code does not match crypt)',
19532:     );
19533:     if ($captcha_chk != 1) {
19534:         $captcha_error = $captcha_hash{$captcha_chk}
19535:     }
19536:     return ($captcha_chk,$captcha_error);
19537: }
19538: 
19539: sub create_recaptcha {
19540:     my ($pubkey,$version) = @_;
19541:     if ($version >= 2) {
19542:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
19543:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
19544:     } else {
19545:         my $use_ssl;
19546:         if ($ENV{'SERVER_PORT'} == 443) {
19547:             $use_ssl = 1;
19548:         }
19549:         my $captcha = Captcha::reCAPTCHA->new;
19550:         return $captcha->get_options_setter({theme => 'white'})."\n".
19551:                $captcha->get_html($pubkey,undef,$use_ssl).
19552:                &mt('If the text is hard to read, [_1] will replace them.',
19553:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
19554:                '<br /><br />';
19555:     }
19556: }
19557: 
19558: sub check_recaptcha {
19559:     my ($privkey,$version) = @_;
19560:     my $captcha_chk;
19561:     my $ip = &Apache::lonnet::get_requestor_ip();
19562:     if ($version >= 2) {
19563:         my %info = (
19564:                      secret   => $privkey, 
19565:                      response => $env{'form.g-recaptcha-response'},
19566:                      remoteip => $ip,
19567:                    );
19568:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
19569:         $request->content(join('&',map {
19570:                          my $name = escape($_);
19571:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
19572:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
19573:                          : &escape($info{$_}) );
19574:         } keys(%info)));
19575:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
19576:         if ($response->is_success)  {
19577:             my $data = JSON::DWIW->from_json($response->decoded_content);
19578:             if (ref($data) eq 'HASH') {
19579:                 if ($data->{'success'}) {
19580:                     $captcha_chk = 1;
19581:                 }
19582:             }
19583:         }
19584:     } else {
19585:         my $captcha = Captcha::reCAPTCHA->new;
19586:         my $captcha_result =
19587:             $captcha->check_answer(
19588:                                     $privkey,
19589:                                     $ip,
19590:                                     $env{'form.recaptcha_challenge_field'},
19591:                                     $env{'form.recaptcha_response_field'},
19592:                                   );
19593:         if ($captcha_result->{is_valid}) {
19594:             $captcha_chk = 1;
19595:         }
19596:     }
19597:     return $captcha_chk;
19598: }
19599: 
19600: sub emailusername_info {
19601:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
19602:     my %titles = &Apache::lonlocal::texthash (
19603:                      lastname      => 'Last Name',
19604:                      firstname     => 'First Name',
19605:                      institution   => 'School/college/university',
19606:                      location      => "School's city, state/province, country",
19607:                      web           => "School's web address",
19608:                      officialemail => 'E-mail address at institution (if different)',
19609:                      id            => 'Student/Employee ID',
19610:                  );
19611:     return (\@fields,\%titles);
19612: }
19613: 
19614: sub cleanup_html {
19615:     my ($incoming) = @_;
19616:     my $outgoing;
19617:     if ($incoming ne '') {
19618:         $outgoing = $incoming;
19619:         $outgoing =~ s/;/&#059;/g;
19620:         $outgoing =~ s/\#/&#035;/g;
19621:         $outgoing =~ s/\&/&#038;/g;
19622:         $outgoing =~ s/</&#060;/g;
19623:         $outgoing =~ s/>/&#062;/g;
19624:         $outgoing =~ s/\(/&#040/g;
19625:         $outgoing =~ s/\)/&#041;/g;
19626:         $outgoing =~ s/"/&#034;/g;
19627:         $outgoing =~ s/'/&#039;/g;
19628:         $outgoing =~ s/\$/&#036;/g;
19629:         $outgoing =~ s{/}{&#047;}g;
19630:         $outgoing =~ s/=/&#061;/g;
19631:         $outgoing =~ s/\\/&#092;/g
19632:     }
19633:     return $outgoing;
19634: }
19635: 
19636: # Checks for critical messages and returns a redirect url if one exists.
19637: # $interval indicates how often to check for messages.
19638: # $context is the calling context -- roles, grades, contents, menu or flip. 
19639: sub critical_redirect {
19640:     my ($interval,$context) = @_;
19641:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
19642:         return ();
19643:     }
19644:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
19645:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
19646:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
19647:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
19648:             my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
19649:             if ($blocked) {
19650:                 my $checkrole = "cm./$cdom/$cnum";
19651:                 if ($env{'request.course.sec'} ne '') {
19652:                     $checkrole .= "/$env{'request.course.sec'}";
19653:                 }
19654:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
19655:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
19656:                     return;
19657:                 }
19658:             }
19659:         }
19660:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
19661:                                         $env{'user.name'});
19662:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
19663:         my $redirecturl;
19664:         if ($what[0]) {
19665: 	    if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
19666: 	        $redirecturl='/adm/email?critical=display';
19667: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
19668:                 return (1, $url);
19669:             }
19670:         }
19671:     } 
19672:     return ();
19673: }
19674: 
19675: # Use:
19676: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
19677: #
19678: ##################################################
19679: #          password associated functions         #
19680: ##################################################
19681: sub des_keys {
19682:     # Make a new key for DES encryption.
19683:     # Each key has two parts which are returned separately.
19684:     # Please note:  Each key must be passed through the &hex function
19685:     # before it is output to the web browser.  The hex versions cannot
19686:     # be used to decrypt.
19687:     my @hexstr=('0','1','2','3','4','5','6','7',
19688:                 '8','9','a','b','c','d','e','f');
19689:     my $lkey='';
19690:     for (0..7) {
19691:         $lkey.=$hexstr[rand(15)];
19692:     }
19693:     my $ukey='';
19694:     for (0..7) {
19695:         $ukey.=$hexstr[rand(15)];
19696:     }
19697:     return ($lkey,$ukey);
19698: }
19699: 
19700: sub des_decrypt {
19701:     my ($key,$cyphertext) = @_;
19702:     my $keybin=pack("H16",$key);
19703:     my $cypher;
19704:     if ($Crypt::DES::VERSION>=2.03) {
19705:         $cypher=new Crypt::DES $keybin;
19706:     } else {
19707:         $cypher=new DES $keybin;
19708:     }
19709:     my $plaintext='';
19710:     my $cypherlength = length($cyphertext);
19711:     my $numchunks = int($cypherlength/32);
19712:     for (my $j=0; $j<$numchunks; $j++) {
19713:         my $start = $j*32;
19714:         my $cypherblock = substr($cyphertext,$start,32);
19715:         my $chunk =
19716:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
19717:         $chunk .=
19718:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
19719:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
19720:         $plaintext .= $chunk;
19721:     }
19722:     return $plaintext;
19723: }
19724: 
19725: sub get_requested_shorturls {
19726:     my ($cdom,$cnum,$navmap) = @_;
19727:     return unless (ref($navmap));
19728:     my ($numnew,$errors);
19729:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
19730:     if (@toshorten) {
19731:         my (%maps,%resources,%titles);
19732:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
19733:                                                                'shorturls',$cdom,$cnum);
19734:         if (keys(%resources)) {
19735:             my %tocreate;
19736:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
19737:                 my $symb = $resources{$item};
19738:                 if ($symb) {
19739:                     $tocreate{$cnum.'&'.$symb} = 1;
19740:                 }
19741:             }
19742:             if (keys(%tocreate)) {
19743:                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
19744:                                                       \%tocreate);
19745:             }
19746:         }
19747:     }
19748:     return ($numnew,$errors);
19749: }
19750: 
19751: sub make_short_symbs {
19752:     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
19753:     my ($numnew,@errors);
19754:     if (ref($tocreateref) eq 'HASH') {
19755:         my %tocreate = %{$tocreateref};
19756:         if (keys(%tocreate)) {
19757:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
19758:             my $su = Short::URL->new(no_vowels => 1);
19759:             my $init = '';
19760:             my (%newunique,%addcourse,%courseonly,%failed);
19761:             # get lock on tiny db
19762:             my $now = time;
19763:             if ($lockuser eq '') {
19764:                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
19765:             }
19766:             my $lockhash = {
19767:                                 "lock\0$now" => $lockuser,
19768:                             };
19769:             my $tries = 0;
19770:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
19771:             my ($code,$error);
19772:             while (($gotlock ne 'ok') && ($tries<3)) {
19773:                 $tries ++;
19774:                 sleep 1;
19775:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
19776:             }
19777:             if ($gotlock eq 'ok') {
19778:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
19779:                                        \%addcourse,\%courseonly,\%failed);
19780:                 if (keys(%failed)) {
19781:                     my $numfailed = scalar(keys(%failed));
19782:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
19783:                 }
19784:                 if (keys(%newunique)) {
19785:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
19786:                     if ($putres eq 'ok') {
19787:                         $numnew = scalar(keys(%newunique));
19788:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
19789:                         unless ($newputres eq 'ok') {
19790:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
19791:                         }
19792:                     } else {
19793:                         push(@errors,&mt('error: could not store unique six character URLs'));
19794:                     }
19795:                 }
19796:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
19797:                 unless ($dellockres eq 'ok') {
19798:                     push(@errors,&mt('error: could not release lockfile'));
19799:                 }
19800:             } else {
19801:                 push(@errors,&mt('error: could not obtain lockfile'));
19802:             }
19803:             if (keys(%courseonly)) {
19804:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
19805:                 if ($result ne 'ok') {
19806:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
19807:                 }
19808:             }
19809:         }
19810:     }
19811:     return ($numnew,\@errors);
19812: }
19813: 
19814: sub shorten_symbs {
19815:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
19816:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
19817:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
19818:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
19819:     my (%possibles,%collisions);
19820:     foreach my $key (keys(%{$tocreate})) {
19821:         my $num = String::CRC32::crc32($key);
19822:         my $tiny = $su->encode($num,$init);
19823:         if ($tiny) {
19824:             $possibles{$tiny} = $key;
19825:         }
19826:     }
19827:     if (!$init) {
19828:         $init = 1;
19829:     } else {
19830:         $init ++;
19831:     }
19832:     if (keys(%possibles)) {
19833:         my @posstiny = keys(%possibles);
19834:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
19835:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
19836:         if (keys(%currtiny)) {
19837:             foreach my $key (keys(%currtiny)) {
19838:                 next if ($currtiny{$key} eq '');
19839:                 if ($currtiny{$key} eq $possibles{$key}) {
19840:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
19841:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
19842:                         $courseonly->{$tsymb} = $key;
19843:                     }
19844:                 } else {
19845:                     $collisions{$possibles{$key}} = 1;
19846:                 }
19847:                 delete($possibles{$key});
19848:             }
19849:         }
19850:         foreach my $key (keys(%possibles)) {
19851:             $newunique->{$key} = $possibles{$key};
19852:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
19853:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
19854:                 $addcourse->{$tsymb} = $key;
19855:             }
19856:         }
19857:     }
19858:     if (keys(%collisions)) {
19859:         if ($init <5) {
19860:             if (!$init) {
19861:                 $init = 1;
19862:             } else {
19863:                 $init ++;
19864:             }
19865:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
19866:                                    $newunique,$addcourse,$courseonly,$failed);
19867:         } else {
19868:             foreach my $key (keys(%collisions)) {
19869:                 $failed->{$key} = 1;
19870:             }
19871:         }
19872:     }
19873:     return $init;
19874: }
19875: 
19876: sub is_nonframeable {
19877:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
19878:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
19879:     return if (($remprotocol eq '') || ($remhost eq ''));
19880: 
19881:     $remprotocol = lc($remprotocol);
19882:     $remhost = lc($remhost);
19883:     my $remport = 80;
19884:     if ($remprotocol eq 'https') {
19885:         $remport = 443;
19886:     }
19887:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
19888:     if ($cached) {
19889:         unless ($nocache) {
19890:             if ($result) {
19891:                 return 1;
19892:             } else {
19893:                 return 0;
19894:             }
19895:         }
19896:     }
19897:     my $uselink;
19898:     my $request = new HTTP::Request('HEAD',$url);
19899:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
19900:     if ($response->is_success()) {
19901:         my $secpolicy = lc($response->header('content-security-policy'));
19902:         my $xframeop = lc($response->header('x-frame-options'));
19903:         $secpolicy =~ s/^\s+|\s+$//g;
19904:         $xframeop =~ s/^\s+|\s+$//g;
19905:         if (($secpolicy ne '') || ($xframeop ne '')) {
19906:             my $remotehost = $remprotocol.'://'.$remhost;
19907:             my ($origin,$protocol,$port);
19908:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
19909:                 $port = $ENV{'SERVER_PORT'};
19910:             } else {
19911:                 $port = 80;
19912:             }
19913:             if ($absolute eq '') {
19914:                 $protocol = 'http:';
19915:                 if ($port == 443) {
19916:                     $protocol = 'https:';
19917:                 }
19918:                 $origin = $protocol.'//'.lc($hostname);
19919:             } else {
19920:                 $origin = lc($absolute);
19921:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
19922:             }
19923:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
19924:                 my $framepolicy = $1;
19925:                 $framepolicy =~ s/^\s+|\s+$//g;
19926:                 my @policies = split(/\s+/,$framepolicy);
19927:                 if (@policies) {
19928:                     if (grep(/^\Q'none'\E$/,@policies)) {
19929:                         $uselink = 1;
19930:                     } else {
19931:                         $uselink = 1;
19932:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
19933:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
19934:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
19935:                             undef($uselink);
19936:                         }
19937:                         if ($uselink) {
19938:                             if (grep(/^\Q'self'\E$/,@policies)) {
19939:                                 if (($origin ne '') && ($remotehost eq $origin)) {
19940:                                     undef($uselink);
19941:                                 }
19942:                             }
19943:                         }
19944:                         if ($uselink) {
19945:                             my @possok;
19946:                             if ($ip ne '') {
19947:                                 push(@possok,$ip);
19948:                             }
19949:                             my $hoststr = '';
19950:                             foreach my $part (reverse(split(/\./,$hostname))) {
19951:                                 if ($hoststr eq '') {
19952:                                     $hoststr = $part;
19953:                                 } else {
19954:                                     $hoststr = "$part.$hoststr";
19955:                                 }
19956:                                 if ($hoststr eq $hostname) {
19957:                                     push(@possok,$hostname);
19958:                                 } else {
19959:                                     push(@possok,"*.$hoststr");
19960:                                 }
19961:                             }
19962:                             if (@possok) {
19963:                                 foreach my $poss (@possok) {
19964:                                     last if (!$uselink);
19965:                                     foreach my $policy (@policies) {
19966:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
19967:                                             undef($uselink);
19968:                                             last;
19969:                                         }
19970:                                     }
19971:                                 }
19972:                             }
19973:                         }
19974:                     }
19975:                 }
19976:             } elsif ($xframeop ne '') {
19977:                 $uselink = 1;
19978:                 my @policies = split(/\s*,\s*/,$xframeop);
19979:                 if (@policies) {
19980:                     unless (grep(/^deny$/,@policies)) {
19981:                         if ($origin ne '') {
19982:                             if (grep(/^sameorigin$/,@policies)) {
19983:                                 if ($remotehost eq $origin) {
19984:                                     undef($uselink);
19985:                                 }
19986:                             }
19987:                             if ($uselink) {
19988:                                 foreach my $policy (@policies) {
19989:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
19990:                                         my $allowfrom = $1;
19991:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
19992:                                             undef($uselink);
19993:                                             last;
19994:                                         }
19995:                                     }
19996:                                 }
19997:                             }
19998:                         }
19999:                     }
20000:                 }
20001:             }
20002:         }
20003:     }
20004:     if ($nocache) {
20005:         if ($cached) {
20006:             my $devalidate;
20007:             if ($uselink && !$result) {
20008:                 $devalidate = 1;
20009:             } elsif (!$uselink && $result) {
20010:                 $devalidate = 1;
20011:             }
20012:             if ($devalidate) {
20013:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
20014:             }
20015:         }
20016:     } else {
20017:         if ($uselink) {
20018:             $result = 1;
20019:         } else {
20020:             $result = 0;
20021:         }
20022:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
20023:     }
20024:     return $uselink;
20025: }
20026: 
20027: sub page_menu {
20028:     my ($menucolls,$menunum) = @_;
20029:     my %menu;
20030:     foreach my $item (split(/;/,$menucolls)) {
20031:         my ($num,$value) = split(/\%/,$item);
20032:         if ($num eq $menunum) {
20033:             my @entries = split(/\&/,$value);
20034:             foreach my $entry (@entries) {
20035:                 my ($name,$fields) = split(/=/,$entry);
20036:                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
20037:                     $menu{$name} = $fields;
20038:                 } else {
20039:                     my @shown;
20040:                     if ($fields =~ /,/) {
20041:                         @shown = split(/,/,$fields);
20042:                     } else {
20043:                         @shown = ($fields);
20044:                     }
20045:                     if (@shown) {
20046:                         foreach my $field (@shown) {
20047:                             next if ($field eq '');
20048:                             $menu{$field} = 1;
20049:                         }
20050:                     }
20051:                 }
20052:             }
20053:         }
20054:     }
20055:     return %menu;
20056: }
20057: 
20058: 1;
20059: __END__;
20060: 

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