File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1075.2.161.2.16: download - view: text, annotated - select for diffs
Sun Mar 12 02:20:43 2023 UTC (14 months, 1 week ago) by raeburn
Branches: version_2_11_4_msu
- For 2.11.4 (modified)
  Include changes in 1.1401

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1075.2.161.2.16 2023/03/12 02:20:43 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::map();
   75: use HTTP::Request;
   76: use DateTime::TimeZone;
   77: use DateTime::Locale;
   78: use Encode();
   79: use Authen::Captcha;
   80: use Captcha::reCAPTCHA;
   81: use JSON::DWIW;
   82: use LWP::UserAgent;
   83: use Crypt::DES;
   84: use DynaLoader; # for Crypt::DES version
   85: use File::Copy();
   86: use File::Path();
   87: use String::CRC32();
   88: use Short::URL();
   89: 
   90: # ---------------------------------------------- Designs
   91: use vars qw(%defaultdesign);
   92: 
   93: my $readit;
   94: 
   95: 
   96: ##
   97: ## Global Variables
   98: ##
   99: 
  100: 
  101: # ----------------------------------------------- SSI with retries:
  102: #
  103: 
  104: =pod
  105: 
  106: =head1 Server Side include with retries:
  107: 
  108: =over 4
  109: 
  110: =item * &ssi_with_retries(resource,retries form)
  111: 
  112: Performs an ssi with some number of retries.  Retries continue either
  113: until the result is ok or until the retry count supplied by the
  114: caller is exhausted.  
  115: 
  116: Inputs:
  117: 
  118: =over 4
  119: 
  120: resource   - Identifies the resource to insert.
  121: 
  122: retries    - Count of the number of retries allowed.
  123: 
  124: form       - Hash that identifies the rendering options.
  125: 
  126: =back
  127: 
  128: Returns:
  129: 
  130: =over 4
  131: 
  132: content    - The content of the response.  If retries were exhausted this is empty.
  133: 
  134: response   - The response from the last attempt (which may or may not have been successful.
  135: 
  136: =back
  137: 
  138: =back
  139: 
  140: =cut
  141: 
  142: sub ssi_with_retries {
  143:     my ($resource, $retries, %form) = @_;
  144: 
  145: 
  146:     my $ok = 0;			# True if we got a good response.
  147:     my $content;
  148:     my $response;
  149: 
  150:     # Try to get the ssi done. within the retries count:
  151: 
  152:     do {
  153: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  154: 	$ok      = $response->is_success;
  155:         if (!$ok) {
  156:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  157:         }
  158: 	$retries--;
  159:     } while (!$ok && ($retries > 0));
  160: 
  161:     if (!$ok) {
  162: 	$content = '';		# On error return an empty content.
  163:     }
  164:     return ($content, $response);
  165: 
  166: }
  167: 
  168: 
  169: 
  170: # ----------------------------------------------- Filetypes/Languages/Copyright
  171: my %language;
  172: my %supported_language;
  173: my %latex_language;		# For choosing hyphenation in <transl..>
  174: my %latex_language_bykey;	# for choosing hyphenation from metadata
  175: my %cprtag;
  176: my %scprtag;
  177: my %fe; my %fd; my %fm;
  178: my %category_extensions;
  179: 
  180: # ---------------------------------------------- Thesaurus variables
  181: #
  182: # %Keywords:
  183: #      A hash used by &keyword to determine if a word is considered a keyword.
  184: # $thesaurus_db_file 
  185: #      Scalar containing the full path to the thesaurus database.
  186: 
  187: my %Keywords;
  188: my $thesaurus_db_file;
  189: 
  190: #
  191: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  192: # thesaurus.tab, and filecategories.tab.
  193: #
  194: BEGIN {
  195:     # Variable initialization
  196:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  197:     #
  198:     unless ($readit) {
  199: # ------------------------------------------------------------------- languages
  200:     {
  201:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  202:                                    '/language.tab';
  203:         if ( open(my $fh,'<',$langtabfile) ) {
  204:             while (my $line = <$fh>) {
  205:                 next if ($line=~/^\#/);
  206:                 chomp($line);
  207:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  208:                 $language{$key}=$val.' - '.$enc;
  209:                 if ($sup) {
  210:                     $supported_language{$key}=$sup;
  211:                 }
  212: 		if ($latex) {
  213: 		    $latex_language_bykey{$key} = $latex;
  214: 		    $latex_language{$two} = $latex;
  215: 		}
  216:             }
  217:             close($fh);
  218:         }
  219:     }
  220: # ------------------------------------------------------------------ copyrights
  221:     {
  222:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  223:                                   '/copyright.tab';
  224:         if ( open (my $fh,'<',$copyrightfile) ) {
  225:             while (my $line = <$fh>) {
  226:                 next if ($line=~/^\#/);
  227:                 chomp($line);
  228:                 my ($key,$val)=(split(/\s+/,$line,2));
  229:                 $cprtag{$key}=$val;
  230:             }
  231:             close($fh);
  232:         }
  233:     }
  234: # ----------------------------------------------------------- source copyrights
  235:     {
  236:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  237:                                   '/source_copyright.tab';
  238:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
  239:             while (my $line = <$fh>) {
  240:                 next if ($line =~ /^\#/);
  241:                 chomp($line);
  242:                 my ($key,$val)=(split(/\s+/,$line,2));
  243:                 $scprtag{$key}=$val;
  244:             }
  245:             close($fh);
  246:         }
  247:     }
  248: 
  249: # -------------------------------------------------------------- default domain designs
  250:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  251:     my $designfile = $designdir.'/default.tab';
  252:     if ( open (my $fh,'<',$designfile) ) {
  253:         while (my $line = <$fh>) {
  254:             next if ($line =~ /^\#/);
  255:             chomp($line);
  256:             my ($key,$val)=(split(/\=/,$line));
  257:             if ($val) { $defaultdesign{$key}=$val; }
  258:         }
  259:         close($fh);
  260:     }
  261: 
  262: # ------------------------------------------------------------- file categories
  263:     {
  264:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  265:                                   '/filecategories.tab';
  266:         if ( open (my $fh,'<',$categoryfile) ) {
  267: 	    while (my $line = <$fh>) {
  268: 		next if ($line =~ /^\#/);
  269: 		chomp($line);
  270:                 my ($extension,$category)=(split(/\s+/,$line,2));
  271:                 push(@{$category_extensions{lc($category)}},$extension);
  272:             }
  273:             close($fh);
  274:         }
  275: 
  276:     }
  277: # ------------------------------------------------------------------ file types
  278:     {
  279:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  280:                '/filetypes.tab';
  281:         if ( open (my $fh,'<',$typesfile) ) {
  282:             while (my $line = <$fh>) {
  283: 		next if ($line =~ /^\#/);
  284: 		chomp($line);
  285:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  286:                 if ($descr ne '') {
  287:                     $fe{$ending}=lc($emb);
  288:                     $fd{$ending}=$descr;
  289:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  290:                 }
  291:             }
  292:             close($fh);
  293:         }
  294:     }
  295:     &Apache::lonnet::logthis(
  296:              "<span style='color:yellow;'>INFO: Read file types</span>");
  297:     $readit=1;
  298:     }  # end of unless($readit) 
  299:     
  300: }
  301: 
  302: ###############################################################
  303: ##           HTML and Javascript Helper Functions            ##
  304: ###############################################################
  305: 
  306: =pod 
  307: 
  308: =head1 HTML and Javascript Functions
  309: 
  310: =over 4
  311: 
  312: =item * &browser_and_searcher_javascript()
  313: 
  314: X<browsing, javascript>X<searching, javascript>Returns a string
  315: containing javascript with two functions, C<openbrowser> and
  316: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  317: tags.
  318: 
  319: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  320: 
  321: inputs: formname, elementname, only, omit
  322: 
  323: formname and elementname indicate the name of the html form and name of
  324: the element that the results of the browsing selection are to be placed in. 
  325: 
  326: Specifying 'only' will restrict the browser to displaying only files
  327: with the given extension.  Can be a comma separated list.
  328: 
  329: Specifying 'omit' will restrict the browser to NOT displaying files
  330: with the given extension.  Can be a comma separated list.
  331: 
  332: =item * &opensearcher(formname,elementname) [javascript]
  333: 
  334: Inputs: formname, elementname
  335: 
  336: formname and elementname specify the name of the html form and the name
  337: of the element the selection from the search results will be placed in.
  338: 
  339: =cut
  340: 
  341: sub browser_and_searcher_javascript {
  342:     my ($mode)=@_;
  343:     if (!defined($mode)) { $mode='edit'; }
  344:     my $resurl=&escape_single(&lastresurl());
  345:     return <<END;
  346: // <!-- BEGIN LON-CAPA Internal
  347:     var editbrowser = null;
  348:     function openbrowser(formname,elementname,only,omit,titleelement) {
  349:         var url = '$resurl/?';
  350:         if (editbrowser == null) {
  351:             url += 'launch=1&';
  352:         }
  353:         url += 'catalogmode=interactive&';
  354:         url += 'mode=$mode&';
  355:         url += 'inhibitmenu=yes&';
  356:         url += 'form=' + formname + '&';
  357:         if (only != null) {
  358:             url += 'only=' + only + '&';
  359:         } else {
  360:             url += 'only=&';
  361: 	}
  362:         if (omit != null) {
  363:             url += 'omit=' + omit + '&';
  364:         } else {
  365:             url += 'omit=&';
  366: 	}
  367:         if (titleelement != null) {
  368:             url += 'titleelement=' + titleelement + '&';
  369:         } else {
  370: 	    url += 'titleelement=&';
  371: 	}
  372:         url += 'element=' + elementname + '';
  373:         var title = 'Browser';
  374:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  375:         options += ',width=700,height=600';
  376:         editbrowser = open(url,title,options,'1');
  377:         editbrowser.focus();
  378:     }
  379:     var editsearcher;
  380:     function opensearcher(formname,elementname,titleelement) {
  381:         var url = '/adm/searchcat?';
  382:         if (editsearcher == null) {
  383:             url += 'launch=1&';
  384:         }
  385:         url += 'catalogmode=interactive&';
  386:         url += 'mode=$mode&';
  387:         url += 'form=' + formname + '&';
  388:         if (titleelement != null) {
  389:             url += 'titleelement=' + titleelement + '&';
  390:         } else {
  391: 	    url += 'titleelement=&';
  392: 	}
  393:         url += 'element=' + elementname + '';
  394:         var title = 'Search';
  395:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  396:         options += ',width=700,height=600';
  397:         editsearcher = open(url,title,options,'1');
  398:         editsearcher.focus();
  399:     }
  400: // END LON-CAPA Internal -->
  401: END
  402: }
  403: 
  404: sub lastresurl {
  405:     if ($env{'environment.lastresurl'}) {
  406: 	return $env{'environment.lastresurl'}
  407:     } else {
  408: 	return '/res';
  409:     }
  410: }
  411: 
  412: sub storeresurl {
  413:     my $resurl=&Apache::lonnet::clutter(shift);
  414:     unless ($resurl=~/^\/res/) { return 0; }
  415:     $resurl=~s/\/$//;
  416:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  417:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  418:     return 1;
  419: }
  420: 
  421: sub studentbrowser_javascript {
  422:    unless (
  423:             (($env{'request.course.id'}) && 
  424:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  425: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  426: 					  '/'.$env{'request.course.sec'})
  427: 	      ))
  428:          || ($env{'request.role'}=~/^(au|dc|su)/)
  429:           ) { return ''; }  
  430:    return (<<'ENDSTDBRW');
  431: <script type="text/javascript" language="Javascript">
  432: // <![CDATA[
  433:     var stdeditbrowser;
  434:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv) {
  435:         var url = '/adm/pickstudent?';
  436:         var filter;
  437: 	if (!ignorefilter) {
  438: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  439: 	}
  440:         if (filter != null) {
  441:            if (filter != '') {
  442:                url += 'filter='+filter+'&';
  443: 	   }
  444:         }
  445:         url += 'form=' + formname + '&unameelement='+uname+
  446:                                     '&udomelement='+udom+
  447:                                     '&clicker='+clicker;
  448: 	if (roleflag) { url+="&roles=1"; }
  449:         if (courseadv == 'condition') {
  450:             if (document.getElementById('courseadv')) {
  451:                 courseadv = document.getElementById('courseadv').value;
  452:             }
  453:         }
  454:         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
  455:         var title = 'Student_Browser';
  456:         var options = 'scrollbars=1,resizable=1,menubar=0';
  457:         options += ',width=700,height=600';
  458:         stdeditbrowser = open(url,title,options,'1');
  459:         stdeditbrowser.focus();
  460:     }
  461: // ]]>
  462: </script>
  463: ENDSTDBRW
  464: }
  465: 
  466: sub resourcebrowser_javascript {
  467:    unless ($env{'request.course.id'}) { return ''; }
  468:    return (<<'ENDRESBRW');
  469: <script type="text/javascript" language="Javascript">
  470: // <![CDATA[
  471:     var reseditbrowser;
  472:     function openresbrowser(formname,reslink) {
  473:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  474:         var title = 'Resource_Browser';
  475:         var options = 'scrollbars=1,resizable=1,menubar=0';
  476:         options += ',width=700,height=500';
  477:         reseditbrowser = open(url,title,options,'1');
  478:         reseditbrowser.focus();
  479:     }
  480: // ]]>
  481: </script>
  482: ENDRESBRW
  483: }
  484: 
  485: sub selectstudent_link {
  486:    my ($form,$unameele,$udomele,$courseadv,$clickerid)=@_;
  487:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  488:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  489:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  490:    if ($env{'request.course.id'}) {  
  491:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  492: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  493: 					'/'.$env{'request.course.sec'})) {
  494: 	   return '';
  495:        }
  496:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  497:        if ($courseadv eq 'only') {
  498:            $callargs .= ",'',1,'$courseadv'";
  499:        } elsif ($courseadv eq 'none') {
  500:            $callargs .= ",'','','$courseadv'";
  501:        } elsif ($courseadv eq 'condition') {
  502:            $callargs .= ",'','','$courseadv'";
  503:        }
  504:        return '<span class="LC_nobreak">'.
  505:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  506:               &mt('Select User').'</a></span>';
  507:    }
  508:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  509:        $callargs .= ",'',1"; 
  510:        return '<span class="LC_nobreak">'.
  511:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  512:               &mt('Select User').'</a></span>';
  513:    }
  514:    return '';
  515: }
  516: 
  517: sub selectresource_link {
  518:    my ($form,$reslink,$arg)=@_;
  519:    
  520:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  521:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  522:    unless ($env{'request.course.id'}) { return $arg; }
  523:    return '<span class="LC_nobreak">'.
  524:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  525:               $arg.'</a></span>';
  526: }
  527: 
  528: 
  529: 
  530: sub authorbrowser_javascript {
  531:     return <<"ENDAUTHORBRW";
  532: <script type="text/javascript" language="JavaScript">
  533: // <![CDATA[
  534: var stdeditbrowser;
  535: 
  536: function openauthorbrowser(formname,udom) {
  537:     var url = '/adm/pickauthor?';
  538:     url += 'form='+formname+'&roledom='+udom;
  539:     var title = 'Author_Browser';
  540:     var options = 'scrollbars=1,resizable=1,menubar=0';
  541:     options += ',width=700,height=600';
  542:     stdeditbrowser = open(url,title,options,'1');
  543:     stdeditbrowser.focus();
  544: }
  545: 
  546: // ]]>
  547: </script>
  548: ENDAUTHORBRW
  549: }
  550: 
  551: sub coursebrowser_javascript {
  552:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
  553:         $credits_element,$instcode) = @_;
  554:     my $wintitle = 'Course_Browser';
  555:     if ($crstype eq 'Community') {
  556:         $wintitle = 'Community_Browser';
  557:     }
  558:     my $id_functions = &javascript_index_functions();
  559:     my $output = '
  560: <script type="text/javascript" language="JavaScript">
  561: // <![CDATA[
  562:     var stdeditbrowser;'."\n";
  563: 
  564:     $output .= <<"ENDSTDBRW";
  565:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  566:         var url = '/adm/pickcourse?';
  567:         var formid = getFormIdByName(formname);
  568:         var domainfilter = getDomainFromSelectbox(formname,udom);
  569:         if (domainfilter != null) {
  570:            if (domainfilter != '') {
  571:                url += 'domainfilter='+domainfilter+'&';
  572: 	   }
  573:         }
  574:         url += 'form=' + formname + '&cnumelement='+uname+
  575: 	                            '&cdomelement='+udom+
  576:                                     '&cnameelement='+desc;
  577:         if (extra_element !=null && extra_element != '') {
  578:             if (formname == 'rolechoice' || formname == 'studentform') {
  579:                 url += '&roleelement='+extra_element;
  580:                 if (domainfilter == null || domainfilter == '') {
  581:                     url += '&domainfilter='+extra_element;
  582:                 }
  583:             }
  584:             else {
  585:                 if (formname == 'portform') {
  586:                     url += '&setroles='+extra_element;
  587:                 } else {
  588:                     if (formname == 'rules') {
  589:                         url += '&fixeddom='+extra_element; 
  590:                     }
  591:                 }
  592:             }     
  593:         }
  594:         if (type != null && type != '') {
  595:             url += '&type='+type;
  596:         }
  597:         if (type_elem != null && type_elem != '') {
  598:             url += '&typeelement='+type_elem;
  599:         }
  600:         if (formname == 'ccrs') {
  601:             var ownername = document.forms[formid].ccuname.value;
  602:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  603:             url += '&cloner='+ownername+':'+ownerdom;
  604:             if (type == 'Course') {
  605:                 url += '&crscode='+document.forms[formid].crscode.value;
  606:             }
  607:         }
  608:         if (formname == 'requestcrs') {
  609:             url += '&crsdom=$domainfilter&crscode=$instcode';
  610:         }
  611:         if (multflag !=null && multflag != '') {
  612:             url += '&multiple='+multflag;
  613:         }
  614:         var title = '$wintitle';
  615:         var options = 'scrollbars=1,resizable=1,menubar=0';
  616:         options += ',width=700,height=600';
  617:         stdeditbrowser = open(url,title,options,'1');
  618:         stdeditbrowser.focus();
  619:     }
  620: $id_functions
  621: ENDSTDBRW
  622:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
  623:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
  624:                                       $credits_element);
  625:     }
  626:     $output .= '
  627: // ]]>
  628: </script>';
  629:     return $output;
  630: }
  631: 
  632: sub javascript_index_functions {
  633:     return <<"ENDJS";
  634: 
  635: function getFormIdByName(formname) {
  636:     for (var i=0;i<document.forms.length;i++) {
  637:         if (document.forms[i].name == formname) {
  638:             return i;
  639:         }
  640:     }
  641:     return -1;
  642: }
  643: 
  644: function getIndexByName(formid,item) {
  645:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  646:         if (document.forms[formid].elements[i].name == item) {
  647:             return i;
  648:         }
  649:     }
  650:     return -1;
  651: }
  652: 
  653: function getDomainFromSelectbox(formname,udom) {
  654:     var userdom;
  655:     var formid = getFormIdByName(formname);
  656:     if (formid > -1) {
  657:         var domid = getIndexByName(formid,udom);
  658:         if (domid > -1) {
  659:             if (document.forms[formid].elements[domid].type == 'select-one') {
  660:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  661:             }
  662:             if (document.forms[formid].elements[domid].type == 'hidden') {
  663:                 userdom=document.forms[formid].elements[domid].value;
  664:             }
  665:         }
  666:     }
  667:     return userdom;
  668: }
  669: 
  670: ENDJS
  671: 
  672: }
  673: 
  674: sub javascript_array_indexof {
  675:     return <<ENDJS;
  676: <script type="text/javascript" language="JavaScript">
  677: // <![CDATA[
  678: 
  679: if (!Array.prototype.indexOf) {
  680:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  681:         "use strict";
  682:         if (this === void 0 || this === null) {
  683:             throw new TypeError();
  684:         }
  685:         var t = Object(this);
  686:         var len = t.length >>> 0;
  687:         if (len === 0) {
  688:             return -1;
  689:         }
  690:         var n = 0;
  691:         if (arguments.length > 0) {
  692:             n = Number(arguments[1]);
  693:             if (n !== n) { // shortcut for verifying if it's NaN
  694:                 n = 0;
  695:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  696:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  697:             }
  698:         }
  699:         if (n >= len) {
  700:             return -1;
  701:         }
  702:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  703:         for (; k < len; k++) {
  704:             if (k in t && t[k] === searchElement) {
  705:                 return k;
  706:             }
  707:         }
  708:         return -1;
  709:     }
  710: }
  711: 
  712: // ]]>
  713: </script>
  714: 
  715: ENDJS
  716: 
  717: }
  718: 
  719: sub userbrowser_javascript {
  720:     my $id_functions = &javascript_index_functions();
  721:     return <<"ENDUSERBRW";
  722: 
  723: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  724:     var url = '/adm/pickuser?';
  725:     var userdom = getDomainFromSelectbox(formname,udom);
  726:     if (userdom != null) {
  727:        if (userdom != '') {
  728:            url += 'srchdom='+userdom+'&';
  729:        }
  730:     }
  731:     url += 'form=' + formname + '&unameelement='+uname+
  732:                                 '&udomelement='+udom+
  733:                                 '&ulastelement='+ulast+
  734:                                 '&ufirstelement='+ufirst+
  735:                                 '&uemailelement='+uemail+
  736:                                 '&hideudomelement='+hideudom+
  737:                                 '&coursedom='+crsdom;
  738:     if ((caller != null) && (caller != undefined)) {
  739:         url += '&caller='+caller;
  740:     }
  741:     var title = 'User_Browser';
  742:     var options = 'scrollbars=1,resizable=1,menubar=0';
  743:     options += ',width=700,height=600';
  744:     var stdeditbrowser = open(url,title,options,'1');
  745:     stdeditbrowser.focus();
  746: }
  747: 
  748: function fix_domain (formname,udom,origdom,uname) {
  749:     var formid = getFormIdByName(formname);
  750:     if (formid > -1) {
  751:         var unameid = getIndexByName(formid,uname);
  752:         var domid = getIndexByName(formid,udom);
  753:         var hidedomid = getIndexByName(formid,origdom);
  754:         if (hidedomid > -1) {
  755:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  756:             var unameval = document.forms[formid].elements[unameid].value;
  757:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  758:                 if (domid > -1) {
  759:                     var slct = document.forms[formid].elements[domid];
  760:                     if (slct.type == 'select-one') {
  761:                         var i;
  762:                         for (i=0;i<slct.length;i++) {
  763:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  764:                         }
  765:                     }
  766:                     if (slct.type == 'hidden') {
  767:                         slct.value = fixeddom;
  768:                     }
  769:                 }
  770:             }
  771:         }
  772:     }
  773:     return;
  774: }
  775: 
  776: $id_functions
  777: ENDUSERBRW
  778: }
  779: 
  780: sub setsec_javascript {
  781:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
  782:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  783:         $communityrolestr);
  784:     if ($role_element ne '') {
  785:         my @allroles = ('st','ta','ep','in','ad');
  786:         foreach my $crstype ('Course','Community') {
  787:             if ($crstype eq 'Community') {
  788:                 foreach my $role (@allroles) {
  789:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  790:                 }
  791:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  792:             } else {
  793:                 foreach my $role (@allroles) {
  794:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  795:                 }
  796:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  797:             }
  798:         }
  799:         $rolestr = '"'.join('","',@allroles).'"';
  800:         $courserolestr = '"'.join('","',@courserolenames).'"';
  801:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  802:     }
  803:     my $setsections = qq|
  804: function setSect(sectionlist) {
  805:     var sectionsArray = new Array();
  806:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  807:         sectionsArray = sectionlist.split(",");
  808:     }
  809:     var numSections = sectionsArray.length;
  810:     document.$formname.$sec_element.length = 0;
  811:     if (numSections == 0) {
  812:         document.$formname.$sec_element.multiple=false;
  813:         document.$formname.$sec_element.size=1;
  814:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  815:     } else {
  816:         if (numSections == 1) {
  817:             document.$formname.$sec_element.multiple=false;
  818:             document.$formname.$sec_element.size=1;
  819:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  820:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  821:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  822:         } else {
  823:             for (var i=0; i<numSections; i++) {
  824:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  825:             }
  826:             document.$formname.$sec_element.multiple=true
  827:             if (numSections < 3) {
  828:                 document.$formname.$sec_element.size=numSections;
  829:             } else {
  830:                 document.$formname.$sec_element.size=3;
  831:             }
  832:             document.$formname.$sec_element.options[0].selected = false
  833:         }
  834:     }
  835: }
  836: 
  837: function setRole(crstype) {
  838: |;
  839:     if ($role_element eq '') {
  840:         $setsections .= '    return;
  841: }
  842: ';
  843:     } else {
  844:         $setsections .= qq|
  845:     var elementLength = document.$formname.$role_element.length;
  846:     var allroles = Array($rolestr);
  847:     var courserolenames = Array($courserolestr);
  848:     var communityrolenames = Array($communityrolestr);
  849:     if (elementLength != undefined) {
  850:         if (document.$formname.$role_element.options[5].value == 'cc') {
  851:             if (crstype == 'Course') {
  852:                 return;
  853:             } else {
  854:                 allroles[5] = 'co';
  855:                 for (var i=0; i<6; i++) {
  856:                     document.$formname.$role_element.options[i].value = allroles[i];
  857:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  858:                 }
  859:             }
  860:         } else {
  861:             if (crstype == 'Community') {
  862:                 return;
  863:             } else {
  864:                 allroles[5] = 'cc';
  865:                 for (var i=0; i<6; i++) {
  866:                     document.$formname.$role_element.options[i].value = allroles[i];
  867:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  868:                 }
  869:             }
  870:         }
  871:     }
  872:     return;
  873: }
  874: |;
  875:     }
  876:     if ($credits_element) {
  877:         $setsections .= qq|
  878: function setCredits(defaultcredits) {
  879:     document.$formname.$credits_element.value = defaultcredits;
  880:     return;
  881: }
  882: |;
  883:     }
  884:     return $setsections;
  885: }
  886: 
  887: sub selectcourse_link {
  888:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  889:        $typeelement) = @_;
  890:    my $type = $selecttype;
  891:    my $linktext = &mt('Select Course');
  892:    if ($selecttype eq 'Community') {
  893:        $linktext = &mt('Select Community');
  894:    } elsif ($selecttype eq 'Course/Community') {
  895:        $linktext = &mt('Select Course/Community');
  896:        $type = '';
  897:    } elsif ($selecttype eq 'Select') {
  898:        $linktext = &mt('Select');
  899:        $type = '';
  900:    }
  901:    return '<span class="LC_nobreak">'
  902:          ."<a href='"
  903:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  904:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  905:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  906:          ."'>".$linktext.'</a>'
  907:          .'</span>';
  908: }
  909: 
  910: sub selectauthor_link {
  911:    my ($form,$udom)=@_;
  912:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  913:           &mt('Select Author').'</a>';
  914: }
  915: 
  916: sub selectuser_link {
  917:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  918:         $coursedom,$linktext,$caller) = @_;
  919:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  920:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  921:            ');">'.$linktext.'</a>';
  922: }
  923: 
  924: sub check_uncheck_jscript {
  925:     my $jscript = <<"ENDSCRT";
  926: function checkAll(field) {
  927:     if (field.length > 0) {
  928:         for (i = 0; i < field.length; i++) {
  929:             if (!field[i].disabled) {
  930:                 field[i].checked = true;
  931:             }
  932:         }
  933:     } else {
  934:         if (!field.disabled) {
  935:             field.checked = true;
  936:         }
  937:     }
  938: }
  939:  
  940: function uncheckAll(field) {
  941:     if (field.length > 0) {
  942:         for (i = 0; i < field.length; i++) {
  943:             field[i].checked = false ;
  944:         }
  945:     } else {
  946:         field.checked = false ;
  947:     }
  948: }
  949: ENDSCRT
  950:     return $jscript;
  951: }
  952: 
  953: sub select_timezone {
  954:    my ($name,$selected,$onchange,$includeempty,$id,$disabled)=@_;
  955:    my $output='<select name="'.$name.'" '.$id.$onchange.$disabled.'>'."\n";
  956:    if ($includeempty) {
  957:        $output .= '<option value=""';
  958:        if (($selected eq '') || ($selected eq 'local')) {
  959:            $output .= ' selected="selected" ';
  960:        }
  961:        $output .= '> </option>';
  962:    }
  963:    my @timezones = DateTime::TimeZone->all_names;
  964:    foreach my $tzone (@timezones) {
  965:        $output.= '<option value="'.$tzone.'"';
  966:        if ($tzone eq $selected) {
  967:            $output.=' selected="selected"';
  968:        }
  969:        $output.=">$tzone</option>\n";
  970:    }
  971:    $output.="</select>";
  972:    return $output;
  973: }
  974: 
  975: sub select_datelocale {
  976:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  977:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  978:     if ($includeempty) {
  979:         $output .= '<option value=""';
  980:         if ($selected eq '') {
  981:             $output .= ' selected="selected" ';
  982:         }
  983:         $output .= '> </option>';
  984:     }
  985:     my @languages = &Apache::lonlocal::preferred_languages();
  986:     my (@possibles,%locale_names);
  987:     my @locales = DateTime::Locale->ids();
  988:     foreach my $id (@locales) {
  989:         if ($id ne '') {
  990:             my ($en_terr,$native_terr);
  991:             my $loc = DateTime::Locale->load($id);
  992:             if (ref($loc)) {
  993:                 $en_terr = $loc->name();
  994:                 $native_terr = $loc->native_name();
  995:                 if (grep(/^en$/,@languages) || !@languages) {
  996:                     if ($en_terr ne '') {
  997:                         $locale_names{$id} = '('.$en_terr.')';
  998:                     } elsif ($native_terr ne '') {
  999:                         $locale_names{$id} = $native_terr;
 1000:                     }
 1001:                 } else {
 1002:                     if ($native_terr ne '') {
 1003:                         $locale_names{$id} = $native_terr.' ';
 1004:                     } elsif ($en_terr ne '') {
 1005:                         $locale_names{$id} = '('.$en_terr.')';
 1006:                     }
 1007:                 }
 1008:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
 1009:                 push(@possibles,$id);
 1010:             }
 1011:         }
 1012:     }
 1013:     foreach my $item (sort(@possibles)) {
 1014:         $output.= '<option value="'.$item.'"';
 1015:         if ($item eq $selected) {
 1016:             $output.=' selected="selected"';
 1017:         }
 1018:         $output.=">$item";
 1019:         if ($locale_names{$item} ne '') {
 1020:             $output.='  '.$locale_names{$item};
 1021:         }
 1022:         $output.="</option>\n";
 1023:     }
 1024:     $output.="</select>";
 1025:     return $output;
 1026: }
 1027: 
 1028: sub select_language {
 1029:     my ($name,$selected,$includeempty,$noedit) = @_;
 1030:     my %langchoices;
 1031:     if ($includeempty) {
 1032:         %langchoices = ('' => 'No language preference');
 1033:     }
 1034:     foreach my $id (&languageids()) {
 1035:         my $code = &supportedlanguagecode($id);
 1036:         if ($code) {
 1037:             $langchoices{$code} = &plainlanguagedescription($id);
 1038:         }
 1039:     }
 1040:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
 1041:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
 1042: }
 1043: 
 1044: =pod
 1045: 
 1046: =item * &linked_select_forms(...)
 1047: 
 1048: linked_select_forms returns a string containing a <script></script> block
 1049: and html for two <select> menus.  The select menus will be linked in that
 1050: changing the value of the first menu will result in new values being placed
 1051: in the second menu.  The values in the select menu will appear in alphabetical
 1052: order unless a defined order is provided.
 1053: 
 1054: linked_select_forms takes the following ordered inputs:
 1055: 
 1056: =over 4
 1057: 
 1058: =item * $formname, the name of the <form> tag
 1059: 
 1060: =item * $middletext, the text which appears between the <select> tags
 1061: 
 1062: =item * $firstdefault, the default value for the first menu
 1063: 
 1064: =item * $firstselectname, the name of the first <select> tag
 1065: 
 1066: =item * $secondselectname, the name of the second <select> tag
 1067: 
 1068: =item * $hashref, a reference to a hash containing the data for the menus.
 1069: 
 1070: =item * $menuorder, the order of values in the first menu
 1071: 
 1072: =item * $onchangefirst, additional javascript call to execute for an onchange
 1073:         event for the first <select> tag
 1074: 
 1075: =item * $onchangesecond, additional javascript call to execute for an onchange
 1076:         event for the second <select> tag
 1077: 
 1078: =back 
 1079: 
 1080: Below is an example of such a hash.  Only the 'text', 'default', and 
 1081: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1082: values for the first select menu.  The text that coincides with the 
 1083: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1084: and text for the second menu are given in the hash pointed to by 
 1085: $menu{$choice1}->{'select2'}.  
 1086: 
 1087:  my %menu = ( A1 => { text =>"Choice A1" ,
 1088:                        default => "B3",
 1089:                        select2 => { 
 1090:                            B1 => "Choice B1",
 1091:                            B2 => "Choice B2",
 1092:                            B3 => "Choice B3",
 1093:                            B4 => "Choice B4"
 1094:                            },
 1095:                        order => ['B4','B3','B1','B2'],
 1096:                    },
 1097:                A2 => { text =>"Choice A2" ,
 1098:                        default => "C2",
 1099:                        select2 => { 
 1100:                            C1 => "Choice C1",
 1101:                            C2 => "Choice C2",
 1102:                            C3 => "Choice C3"
 1103:                            },
 1104:                        order => ['C2','C1','C3'],
 1105:                    },
 1106:                A3 => { text =>"Choice A3" ,
 1107:                        default => "D6",
 1108:                        select2 => { 
 1109:                            D1 => "Choice D1",
 1110:                            D2 => "Choice D2",
 1111:                            D3 => "Choice D3",
 1112:                            D4 => "Choice D4",
 1113:                            D5 => "Choice D5",
 1114:                            D6 => "Choice D6",
 1115:                            D7 => "Choice D7"
 1116:                            },
 1117:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1118:                    }
 1119:                );
 1120: 
 1121: =cut
 1122: 
 1123: sub linked_select_forms {
 1124:     my ($formname,
 1125:         $middletext,
 1126:         $firstdefault,
 1127:         $firstselectname,
 1128:         $secondselectname, 
 1129:         $hashref,
 1130:         $menuorder,
 1131:         $onchangefirst,
 1132:         $onchangesecond
 1133:         ) = @_;
 1134:     my $second = "document.$formname.$secondselectname";
 1135:     my $first = "document.$formname.$firstselectname";
 1136:     # output the javascript to do the changing
 1137:     my $result = '';
 1138:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1139:     $result.="// <![CDATA[\n";
 1140:     $result.="var select2data = new Object();\n";
 1141:     $" = '","';
 1142:     my $debug = '';
 1143:     foreach my $s1 (sort(keys(%$hashref))) {
 1144:         $result.="select2data.d_$s1 = new Object();\n";        
 1145:         $result.="select2data.d_$s1.def = new String('".
 1146:             $hashref->{$s1}->{'default'}."');\n";
 1147:         $result.="select2data.d_$s1.values = new Array(";
 1148:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1149:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1150:             @s2values = @{$hashref->{$s1}->{'order'}};
 1151:         }
 1152:         $result.="\"@s2values\");\n";
 1153:         $result.="select2data.d_$s1.texts = new Array(";        
 1154:         my @s2texts;
 1155:         foreach my $value (@s2values) {
 1156:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
 1157:         }
 1158:         $result.="\"@s2texts\");\n";
 1159:     }
 1160:     $"=' ';
 1161:     $result.= <<"END";
 1162: 
 1163: function select1_changed() {
 1164:     // Determine new choice
 1165:     var newvalue = "d_" + $first.value;
 1166:     // update select2
 1167:     var values     = select2data[newvalue].values;
 1168:     var texts      = select2data[newvalue].texts;
 1169:     var select2def = select2data[newvalue].def;
 1170:     var i;
 1171:     // out with the old
 1172:     for (i = 0; i < $second.options.length; i++) {
 1173:         $second.options[i] = null;
 1174:     }
 1175:     // in with the nuclear
 1176:     for (i=0;i<values.length; i++) {
 1177:         $second.options[i] = new Option(values[i]);
 1178:         $second.options[i].value = values[i];
 1179:         $second.options[i].text = texts[i];
 1180:         if (values[i] == select2def) {
 1181:             $second.options[i].selected = true;
 1182:         }
 1183:     }
 1184: }
 1185: // ]]>
 1186: </script>
 1187: END
 1188:     # output the initial values for the selection lists
 1189:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
 1190:     my @order = sort(keys(%{$hashref}));
 1191:     if (ref($menuorder) eq 'ARRAY') {
 1192:         @order = @{$menuorder};
 1193:     }
 1194:     foreach my $value (@order) {
 1195:         $result.="    <option value=\"$value\" ";
 1196:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1197:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1198:     }
 1199:     $result .= "</select>\n";
 1200:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1201:     $result .= $middletext;
 1202:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
 1203:     if ($onchangesecond) {
 1204:         $result .= ' onchange="'.$onchangesecond.'"';
 1205:     }
 1206:     $result .= ">\n";
 1207:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1208:     
 1209:     my @secondorder = sort(keys(%select2));
 1210:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1211:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1212:     }
 1213:     foreach my $value (@secondorder) {
 1214:         $result.="    <option value=\"$value\" ";        
 1215:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1216:         $result.=">".&mt($select2{$value})."</option>\n";
 1217:     }
 1218:     $result .= "</select>\n";
 1219:     #    return $debug;
 1220:     return $result;
 1221: }   #  end of sub linked_select_forms {
 1222: 
 1223: =pod
 1224: 
 1225: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid,$links_target)
 1226: 
 1227: Returns a string corresponding to an HTML link to the given help
 1228: $topic, where $topic corresponds to the name of a .tex file in
 1229: /home/httpd/html/adm/help/tex, with underscores replaced by
 1230: spaces. 
 1231: 
 1232: $text will optionally be linked to the same topic, allowing you to
 1233: link text in addition to the graphic. If you do not want to link
 1234: text, but wish to specify one of the later parameters, pass an
 1235: empty string. 
 1236: 
 1237: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1238: the link will not open a new window. If false, the link will open
 1239: a new window using Javascript. (Default is false.) 
 1240: 
 1241: $width and $height are optional numerical parameters that will
 1242: override the width and height of the popped up window, which may
 1243: be useful for certain help topics with big pictures included.
 1244: 
 1245: $imgid is the id of the img tag used for the help icon. This may be
 1246: used in a javascript call to switch the image src.  See 
 1247: lonhtmlcommon::htmlareaselectactive() for an example.
 1248: 
 1249: $links_target will optionally be set to a target (_top, _parent or _self).
 1250: 
 1251: =cut
 1252: 
 1253: sub help_open_topic {
 1254:     my ($topic, $text, $stayOnPage, $width, $height, $imgid, $links_target) = @_;
 1255:     $text = "" if (not defined $text);
 1256:     $stayOnPage = 0 if (not defined $stayOnPage);
 1257:     $width = 500 if (not defined $width);
 1258:     $height = 400 if (not defined $height);
 1259:     my $filename = $topic;
 1260:     $filename =~ s/ /_/g;
 1261: 
 1262:     my $template = "";
 1263:     my $link;
 1264:     
 1265:     $topic=~s/\W/\_/g;
 1266: 
 1267:     if (!$stayOnPage) {
 1268:         if ($env{'browser.mobile'}) {
 1269: 	    $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1270:         } else {
 1271:             $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1272:         }
 1273:     } elsif ($stayOnPage eq 'popup') {
 1274:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1275:     } else {
 1276: 	$link = "/adm/help/${filename}.hlp";
 1277:     }
 1278: 
 1279:     # Add the text
 1280:     my $target = ' target="_top"';
 1281:     if ($links_target) {
 1282:         $target = ' target="'.$links_target.'"';
 1283:     } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self')) {
 1284:         $target = '';
 1285:     }
 1286:     if ($text ne "") {	
 1287: 	$template.='<span class="LC_help_open_topic">'
 1288:                   .'<a'.$target.' href="'.$link.'">'
 1289:                   .$text.'</a>';
 1290:     }
 1291: 
 1292:     # (Always) Add the graphic
 1293:     my $title = &mt('Online Help');
 1294:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1295:     if ($imgid ne '') {
 1296:         $imgid = ' id="'.$imgid.'"';
 1297:     }
 1298:     $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
 1299:               .'<img src="'.$helpicon.'" border="0"'
 1300:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1301:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1302:               .' /></a>';
 1303:     if ($text ne "") {	
 1304:         $template.='</span>';
 1305:     }
 1306:     return $template;
 1307: 
 1308: }
 1309: 
 1310: # This is a quicky function for Latex cheatsheet editing, since it 
 1311: # appears in at least four places
 1312: sub helpLatexCheatsheet {
 1313:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1314:     my $out;
 1315:     my $addOther = '';
 1316:     if ($topic) {
 1317: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1318:     }
 1319:     $out = '<span>' # Start cheatsheet
 1320: 	  .$addOther
 1321:           .'<span>'
 1322: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1323: 	  .'</span> <span>'
 1324: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1325: 	  .'</span>';
 1326:     unless ($not_author) {
 1327:         $out .= ' <span>'
 1328: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1329: 	       .'</span> <span>'
 1330:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
 1331:                .'</span>';
 1332:     }
 1333:     $out .= '</span>'; # End cheatsheet
 1334:     return $out;
 1335: }
 1336: 
 1337: sub general_help {
 1338:     my $helptopic='Student_Intro';
 1339:     if ($env{'request.role'}=~/^(ca|au)/) {
 1340: 	$helptopic='Authoring_Intro';
 1341:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1342: 	$helptopic='Course_Coordination_Intro';
 1343:     } elsif ($env{'request.role'}=~/^dc/) {
 1344:         $helptopic='Domain_Coordination_Intro';
 1345:     }
 1346:     return $helptopic;
 1347: }
 1348: 
 1349: sub update_help_link {
 1350:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1351:     my $origurl = $ENV{'REQUEST_URI'};
 1352:     $origurl=~s|^/~|/priv/|;
 1353:     my $timestamp = time;
 1354:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1355:         $$datum = &escape($$datum);
 1356:     }
 1357: 
 1358:     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";
 1359:     my $output .= <<"ENDOUTPUT";
 1360: <script type="text/javascript">
 1361: // <![CDATA[
 1362: banner_link = '$banner_link';
 1363: // ]]>
 1364: </script>
 1365: ENDOUTPUT
 1366:     return $output;
 1367: }
 1368: 
 1369: # now just updates the help link and generates a blue icon
 1370: sub help_open_menu {
 1371:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text,$links_target) 
 1372: 	= @_;    
 1373:     $stayOnPage = 1;
 1374:     my $output;
 1375:     if ($component_help) {
 1376: 	if (!$text) {
 1377: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1378: 				       $width,$height,'',$links_target);
 1379: 	} else {
 1380: 	    my $help_text;
 1381: 	    $help_text=&unescape($topic);
 1382: 	    $output='<table><tr><td>'.
 1383: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1384: 				 $width,$height,'',$links_target).'</td></tr></table>';
 1385: 	}
 1386:     }
 1387:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1388:     return $output.$banner_link;
 1389: }
 1390: 
 1391: sub top_nav_help {
 1392:     my ($text,$linkattr) = @_;
 1393:     $text = &mt($text);
 1394:     my $stay_on_page;
 1395:     unless ($env{'environment.remote'} eq 'on') {
 1396:         $stay_on_page = 1;
 1397:     }
 1398:     my ($link,$banner_link);
 1399:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
 1400:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1401: 	                         : "javascript:helpMenu('open')";
 1402:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1403:     }
 1404:     my $title = &mt('Get help');
 1405:     if ($link) {
 1406:         return <<"END";
 1407: $banner_link
 1408: <a href="$link" title="$title" $linkattr>$text</a>
 1409: END
 1410:     } else {
 1411:         return '&nbsp;'.$text.'&nbsp;';
 1412:     }
 1413: }
 1414: 
 1415: sub help_menu_js {
 1416:     my ($httphost) = @_;
 1417:     my $stayOnPage = 1;
 1418:     my $width = 620;
 1419:     my $height = 600;
 1420:     my $helptopic=&general_help();
 1421:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
 1422:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1423:     my $start_page =
 1424:         &Apache::loncommon::start_page('Help Menu', undef,
 1425: 				       {'frameset'    => 1,
 1426: 					'js_ready'    => 1,
 1427:                                         'use_absolute' => $httphost,
 1428: 					'add_entries' => {
 1429: 					    'border' => '0',
 1430: 					    'rows'   => "110,*",},});
 1431:     my $end_page =
 1432:         &Apache::loncommon::end_page({'frameset' => 1,
 1433: 				      'js_ready' => 1,});
 1434: 
 1435:     my $template .= <<"ENDTEMPLATE";
 1436: <script type="text/javascript">
 1437: // <![CDATA[
 1438: // <!-- BEGIN LON-CAPA Internal
 1439: var banner_link = '';
 1440: function helpMenu(target) {
 1441:     var caller = this;
 1442:     if (target == 'open') {
 1443:         var newWindow = null;
 1444:         try {
 1445:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1446:         }
 1447:         catch(error) {
 1448:             writeHelp(caller);
 1449:             return;
 1450:         }
 1451:         if (newWindow) {
 1452:             caller = newWindow;
 1453:         }
 1454:     }
 1455:     writeHelp(caller);
 1456:     return;
 1457: }
 1458: function writeHelp(caller) {
 1459:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
 1460:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
 1461:     caller.document.close();
 1462:     caller.focus();
 1463: }
 1464: // END LON-CAPA Internal -->
 1465: // ]]>
 1466: </script>
 1467: ENDTEMPLATE
 1468:     return $template;
 1469: }
 1470: 
 1471: sub help_open_bug {
 1472:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1473:     unless ($env{'user.adv'}) { return ''; }
 1474:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1475:     $text = "" if (not defined $text);
 1476: 	$stayOnPage=1;
 1477:     $width = 600 if (not defined $width);
 1478:     $height = 600 if (not defined $height);
 1479: 
 1480:     $topic=~s/\W+/\+/g;
 1481:     my $link='';
 1482:     my $template='';
 1483:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1484: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1485:     if (!$stayOnPage)
 1486:     {
 1487: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1488:     }
 1489:     else
 1490:     {
 1491: 	$link = $url;
 1492:     }
 1493: 
 1494:     my $target = '_top';
 1495:     if ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
 1496:         (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
 1497:         $target = '_blank';
 1498:     }
 1499: 
 1500:     # Add the text
 1501:     if ($text ne "")
 1502:     {
 1503: 	$template .= 
 1504:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1505:   "<td bgcolor='#FF5555'><a target=\"$target\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1506:     }
 1507: 
 1508:     # Add the graphic
 1509:     my $title = &mt('Report a Bug');
 1510:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1511:     $template .= <<"ENDTEMPLATE";
 1512:  <a target="$target" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1513: ENDTEMPLATE
 1514:     if ($text ne '') { $template.='</td></tr></table>' };
 1515:     return $template;
 1516: 
 1517: }
 1518: 
 1519: sub help_open_faq {
 1520:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1521:     unless ($env{'user.adv'}) { return ''; }
 1522:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1523:     $text = "" if (not defined $text);
 1524: 	$stayOnPage=1;
 1525:     $width = 350 if (not defined $width);
 1526:     $height = 400 if (not defined $height);
 1527: 
 1528:     $topic=~s/\W+/\+/g;
 1529:     my $link='';
 1530:     my $template='';
 1531:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1532:     if (!$stayOnPage)
 1533:     {
 1534: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1535:     }
 1536:     else
 1537:     {
 1538: 	$link = $url;
 1539:     }
 1540: 
 1541:     # Add the text
 1542:     if ($text ne "")
 1543:     {
 1544: 	$template .= 
 1545:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1546:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1547:     }
 1548: 
 1549:     # Add the graphic
 1550:     my $title = &mt('View the FAQ');
 1551:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1552:     $template .= <<"ENDTEMPLATE";
 1553:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1554: ENDTEMPLATE
 1555:     if ($text ne '') { $template.='</td></tr></table>' };
 1556:     return $template;
 1557: 
 1558: }
 1559: 
 1560: ###############################################################
 1561: ###############################################################
 1562: 
 1563: =pod
 1564: 
 1565: =item * &change_content_javascript():
 1566: 
 1567: This and the next function allow you to create small sections of an
 1568: otherwise static HTML page that you can update on the fly with
 1569: Javascript, even in Netscape 4.
 1570: 
 1571: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1572: must be written to the HTML page once. It will prove the Javascript
 1573: function "change(name, content)". Calling the change function with the
 1574: name of the section 
 1575: you want to update, matching the name passed to C<changable_area>, and
 1576: the new content you want to put in there, will put the content into
 1577: that area.
 1578: 
 1579: B<Note>: Netscape 4 only reserves enough space for the changable area
 1580: to contain room for the original contents. You need to "make space"
 1581: for whatever changes you wish to make, and be B<sure> to check your
 1582: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1583: it's adequate for updating a one-line status display, but little more.
 1584: This script will set the space to 100% width, so you only need to
 1585: worry about height in Netscape 4.
 1586: 
 1587: Modern browsers are much less limiting, and if you can commit to the
 1588: user not using Netscape 4, this feature may be used freely with
 1589: pretty much any HTML.
 1590: 
 1591: =cut
 1592: 
 1593: sub change_content_javascript {
 1594:     # If we're on Netscape 4, we need to use Layer-based code
 1595:     if ($env{'browser.type'} eq 'netscape' &&
 1596: 	$env{'browser.version'} =~ /^4\./) {
 1597: 	return (<<NETSCAPE4);
 1598: 	function change(name, content) {
 1599: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1600: 	    doc.open();
 1601: 	    doc.write(content);
 1602: 	    doc.close();
 1603: 	}
 1604: NETSCAPE4
 1605:     } else {
 1606: 	# Otherwise, we need to use semi-standards-compliant code
 1607: 	# (technically, "innerHTML" isn't standard but the equivalent
 1608: 	# is really scary, and every useful browser supports it
 1609: 	return (<<DOMBASED);
 1610: 	function change(name, content) {
 1611: 	    element = document.getElementById(name);
 1612: 	    element.innerHTML = content;
 1613: 	}
 1614: DOMBASED
 1615:     }
 1616: }
 1617: 
 1618: =pod
 1619: 
 1620: =item * &changable_area($name,$origContent):
 1621: 
 1622: This provides a "changable area" that can be modified on the fly via
 1623: the Javascript code provided in C<change_content_javascript>. $name is
 1624: the name you will use to reference the area later; do not repeat the
 1625: same name on a given HTML page more then once. $origContent is what
 1626: the area will originally contain, which can be left blank.
 1627: 
 1628: =cut
 1629: 
 1630: sub changable_area {
 1631:     my ($name, $origContent) = @_;
 1632: 
 1633:     if ($env{'browser.type'} eq 'netscape' &&
 1634: 	$env{'browser.version'} =~ /^4\./) {
 1635: 	# If this is netscape 4, we need to use the Layer tag
 1636: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1637:     } else {
 1638: 	return "<span id='$name'>$origContent</span>";
 1639:     }
 1640: }
 1641: 
 1642: =pod
 1643: 
 1644: =item * &viewport_geometry_js 
 1645: 
 1646: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1647: 
 1648: =cut
 1649: 
 1650: 
 1651: sub viewport_geometry_js { 
 1652:     return <<"GEOMETRY";
 1653: var Geometry = {};
 1654: function init_geometry() {
 1655:     if (Geometry.init) { return };
 1656:     Geometry.init=1;
 1657:     if (window.innerHeight) {
 1658:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1659:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1660:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1661:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1662:     }
 1663:     else if (document.documentElement && document.documentElement.clientHeight) {
 1664:         Geometry.getViewportHeight =
 1665:             function() { return document.documentElement.clientHeight; };
 1666:         Geometry.getViewportWidth =
 1667:             function() { return document.documentElement.clientWidth; };
 1668: 
 1669:         Geometry.getHorizontalScroll =
 1670:             function() { return document.documentElement.scrollLeft; };
 1671:         Geometry.getVerticalScroll =
 1672:             function() { return document.documentElement.scrollTop; };
 1673:     }
 1674:     else if (document.body.clientHeight) {
 1675:         Geometry.getViewportHeight =
 1676:             function() { return document.body.clientHeight; };
 1677:         Geometry.getViewportWidth =
 1678:             function() { return document.body.clientWidth; };
 1679:         Geometry.getHorizontalScroll =
 1680:             function() { return document.body.scrollLeft; };
 1681:         Geometry.getVerticalScroll =
 1682:             function() { return document.body.scrollTop; };
 1683:     }
 1684: }
 1685: 
 1686: GEOMETRY
 1687: }
 1688: 
 1689: =pod
 1690: 
 1691: =item * &viewport_size_js()
 1692: 
 1693: 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. 
 1694: 
 1695: =cut
 1696: 
 1697: sub viewport_size_js {
 1698:     my $geometry = &viewport_geometry_js();
 1699:     return <<"DIMS";
 1700: 
 1701: $geometry
 1702: 
 1703: function getViewportDims(width,height) {
 1704:     init_geometry();
 1705:     width.value = Geometry.getViewportWidth();
 1706:     height.value = Geometry.getViewportHeight();
 1707:     return;
 1708: }
 1709: 
 1710: DIMS
 1711: }
 1712: 
 1713: =pod
 1714: 
 1715: =item * &resize_textarea_js()
 1716: 
 1717: emits the needed javascript to resize a textarea to be as big as possible
 1718: 
 1719: creates a function resize_textrea that takes two IDs first should be
 1720: the id of the element to resize, second should be the id of a div that
 1721: surrounds everything that comes after the textarea, this routine needs
 1722: to be attached to the <body> for the onload and onresize events.
 1723: 
 1724: =back
 1725: 
 1726: =cut
 1727: 
 1728: sub resize_textarea_js {
 1729:     my $geometry = &viewport_geometry_js();
 1730:     return <<"RESIZE";
 1731:     <script type="text/javascript">
 1732: // <![CDATA[
 1733: $geometry
 1734: 
 1735: function getX(element) {
 1736:     var x = 0;
 1737:     while (element) {
 1738: 	x += element.offsetLeft;
 1739: 	element = element.offsetParent;
 1740:     }
 1741:     return x;
 1742: }
 1743: function getY(element) {
 1744:     var y = 0;
 1745:     while (element) {
 1746: 	y += element.offsetTop;
 1747: 	element = element.offsetParent;
 1748:     }
 1749:     return y;
 1750: }
 1751: 
 1752: 
 1753: function resize_textarea(textarea_id,bottom_id) {
 1754:     init_geometry();
 1755:     var textarea        = document.getElementById(textarea_id);
 1756:     //alert(textarea);
 1757: 
 1758:     var textarea_top    = getY(textarea);
 1759:     var textarea_height = textarea.offsetHeight;
 1760:     var bottom          = document.getElementById(bottom_id);
 1761:     var bottom_top      = getY(bottom);
 1762:     var bottom_height   = bottom.offsetHeight;
 1763:     var window_height   = Geometry.getViewportHeight();
 1764:     var fudge           = 23;
 1765:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1766:     if (new_height < 300) {
 1767: 	new_height = 300;
 1768:     }
 1769:     textarea.style.height=new_height+'px';
 1770: }
 1771: // ]]>
 1772: </script>
 1773: RESIZE
 1774: 
 1775: }
 1776: 
 1777: sub colorfuleditor_js {
 1778:     return <<"COLORFULEDIT"
 1779: <script type="text/javascript">
 1780: // <![CDATA[>
 1781:     function fold_box(curDepth, lastresource){
 1782: 
 1783:     // we need a list because there can be several blocks you need to fold in one tag
 1784:         var block = document.getElementsByName('foldblock_'+curDepth);
 1785:     // but there is only one folding button per tag
 1786:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
 1787: 
 1788:         if(block.item(0).style.display == 'none'){
 1789: 
 1790:             foldbutton.value = '@{[&mt("Hide")]}';
 1791:             for (i = 0; i < block.length; i++){
 1792:                 block.item(i).style.display = '';
 1793:             }
 1794:         }else{
 1795: 
 1796:             foldbutton.value = '@{[&mt("Show")]}';
 1797:             for (i = 0; i < block.length; i++){
 1798:                 // block.item(i).style.visibility = 'collapse';
 1799:                 block.item(i).style.display = 'none';
 1800:             }
 1801:         };
 1802:         saveState(lastresource);
 1803:     }
 1804: 
 1805:     function saveState (lastresource) {
 1806: 
 1807:         var tag_list = getTagList();
 1808:         if(tag_list != null){
 1809:             var timestamp = new Date().getTime();
 1810:             var key = lastresource;
 1811: 
 1812:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
 1813:             // starting with timestamp
 1814:             var value = timestamp+';';
 1815: 
 1816:             // building the list of key-value pairs
 1817:             for(var i = 0; i < tag_list.length; i++){
 1818:                 value += tag_list[i]+',';
 1819:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
 1820:             }
 1821: 
 1822:             // only iterate whole storage if nothing to override
 1823:             if(localStorage.getItem(key) == null){
 1824: 
 1825:                 // prevent storage from growing large
 1826:                 if(localStorage.length > 50){
 1827:                     var regex_getTimestamp = /^(?:\d)+;/;
 1828:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
 1829:                     var oldest_key;
 1830: 
 1831:                     for(var i = 1; i < localStorage.length; i++){
 1832:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
 1833:                             oldest_key = localStorage.key(i);
 1834:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
 1835:                         }
 1836:                     }
 1837:                     localStorage.removeItem(oldest_key);
 1838:                 }
 1839:             }
 1840:             localStorage.setItem(key,value);
 1841:         }
 1842:     }
 1843: 
 1844:     // restore folding status of blocks (on page load)
 1845:     function restoreState (lastresource) {
 1846:         if(localStorage.getItem(lastresource) != null){
 1847:             var key = lastresource;
 1848:             var value = localStorage.getItem(key);
 1849:             var regex_delTimestamp = /^\d+;/;
 1850: 
 1851:             value.replace(regex_delTimestamp, '');
 1852: 
 1853:             var valueArr = value.split(';');
 1854:             var pairs;
 1855:             var elements;
 1856:             for (var i = 0; i < valueArr.length; i++){
 1857:                 pairs = valueArr[i].split(',');
 1858:                 elements = document.getElementsByName(pairs[0]);
 1859: 
 1860:                 for (var j = 0; j < elements.length; j++){
 1861:                     elements[j].style.display = pairs[1];
 1862:                     if (pairs[1] == "none"){
 1863:                         var regex_id = /([_\\d]+)\$/;
 1864:                         regex_id.exec(pairs[0]);
 1865:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
 1866:                     }
 1867:                 }
 1868:             }
 1869:         }
 1870:     }
 1871: 
 1872:     function getTagList () {
 1873: 
 1874:         var stringToSearch = document.lonhomework.innerHTML;
 1875: 
 1876:         var ret = new Array();
 1877:         var regex_findBlock = /(foldblock_.*?)"/g;
 1878:         var tag_list = stringToSearch.match(regex_findBlock);
 1879: 
 1880:         if(tag_list != null){
 1881:             for(var i = 0; i < tag_list.length; i++){
 1882:                 ret.push(tag_list[i].replace(/"/, ''));
 1883:             }
 1884:         }
 1885:         return ret;
 1886:     }
 1887: 
 1888:     function saveScrollPosition (resource) {
 1889:         var tag_list = getTagList();
 1890: 
 1891:         // we dont always want to jump to the first block
 1892:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
 1893:         if(\$(window).scrollTop() > 170){
 1894:             if(tag_list != null){
 1895:                 var result;
 1896:                 for(var i = 0; i < tag_list.length; i++){
 1897:                     if(isElementInViewport(tag_list[i])){
 1898:                         result += tag_list[i]+';';
 1899:                     }
 1900:                 }
 1901:                 sessionStorage.setItem('anchor_'+resource, result);
 1902:             }
 1903:         } else {
 1904:             // we dont need to save zero, just delete the item to leave everything tidy
 1905:             sessionStorage.removeItem('anchor_'+resource);
 1906:         }
 1907:     }
 1908: 
 1909:     function restoreScrollPosition(resource){
 1910: 
 1911:         var elem = sessionStorage.getItem('anchor_'+resource);
 1912:         if(elem != null){
 1913:             var tag_list = elem.split(';');
 1914:             var elem_list;
 1915: 
 1916:             for(var i = 0; i < tag_list.length; i++){
 1917:                 elem_list = document.getElementsByName(tag_list[i]);
 1918: 
 1919:                 if(elem_list.length > 0){
 1920:                     elem = elem_list[0];
 1921:                     break;
 1922:                 }
 1923:             }
 1924:             elem.scrollIntoView();
 1925:         }
 1926:     }
 1927: 
 1928:     function isElementInViewport(el) {
 1929: 
 1930:         // change to last element instead of first
 1931:         var elem = document.getElementsByName(el);
 1932:         var rect = elem[0].getBoundingClientRect();
 1933: 
 1934:         return (
 1935:             rect.top >= 0 &&
 1936:             rect.left >= 0 &&
 1937:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
 1938:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
 1939:         );
 1940:     }
 1941: 
 1942:     function autosize(depth){
 1943:         var cmInst = window['cm'+depth];
 1944:         var fitsizeButton = document.getElementById('fitsize'+depth);
 1945: 
 1946:         // is fixed size, switching to dynamic
 1947:         if (sessionStorage.getItem("autosized_"+depth) == null) {
 1948:             cmInst.setSize("","auto");
 1949:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
 1950:             sessionStorage.setItem("autosized_"+depth, "yes");
 1951: 
 1952:         // is dynamic size, switching to fixed
 1953:         } else {
 1954:             cmInst.setSize("","300px");
 1955:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
 1956:             sessionStorage.removeItem("autosized_"+depth);
 1957:         }
 1958:     }
 1959: 
 1960: 
 1961: 
 1962: // ]]>
 1963: </script>
 1964: COLORFULEDIT
 1965: }
 1966: 
 1967: sub xmleditor_js {
 1968:     return <<XMLEDIT
 1969: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
 1970: <script type="text/javascript">
 1971: // <![CDATA[>
 1972: 
 1973:     function saveScrollPosition (resource) {
 1974: 
 1975:         var scrollPos = \$(window).scrollTop();
 1976:         sessionStorage.setItem(resource,scrollPos);
 1977:     }
 1978: 
 1979:     function restoreScrollPosition(resource){
 1980: 
 1981:         var scrollPos = sessionStorage.getItem(resource);
 1982:         \$(window).scrollTop(scrollPos);
 1983:     }
 1984: 
 1985:     // unless internet explorer
 1986:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
 1987: 
 1988:         \$(document).ready(function() {
 1989:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
 1990:         });
 1991:     }
 1992: 
 1993:     // inserts text at cursor position into codemirror (xml editor only)
 1994:     function insertText(text){
 1995:         cm.focus();
 1996:         var curPos = cm.getCursor();
 1997:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
 1998:     }
 1999: // ]]>
 2000: </script>
 2001: XMLEDIT
 2002: }
 2003: 
 2004: sub insert_folding_button {
 2005:     my $curDepth = $Apache::lonxml::curdepth;
 2006:     my $lastresource = $env{'request.ambiguous'};
 2007: 
 2008:     return "<input type=\"button\" id=\"folding_btn_$curDepth\"
 2009:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
 2010: }
 2011: 
 2012: 
 2013: =pod
 2014: 
 2015: =head1 Excel and CSV file utility routines
 2016: 
 2017: =cut
 2018: 
 2019: ###############################################################
 2020: ###############################################################
 2021: 
 2022: =pod
 2023: 
 2024: =over 4
 2025: 
 2026: =item * &csv_translate($text) 
 2027: 
 2028: Translate $text to allow it to be output as a 'comma separated values' 
 2029: format.
 2030: 
 2031: =cut
 2032: 
 2033: ###############################################################
 2034: ###############################################################
 2035: sub csv_translate {
 2036:     my $text = shift;
 2037:     $text =~ s/\"/\"\"/g;
 2038:     $text =~ s/\n/ /g;
 2039:     return $text;
 2040: }
 2041: 
 2042: ###############################################################
 2043: ###############################################################
 2044: 
 2045: =pod
 2046: 
 2047: =item * &define_excel_formats()
 2048: 
 2049: Define some commonly used Excel cell formats.
 2050: 
 2051: Currently supported formats:
 2052: 
 2053: =over 4
 2054: 
 2055: =item header
 2056: 
 2057: =item bold
 2058: 
 2059: =item h1
 2060: 
 2061: =item h2
 2062: 
 2063: =item h3
 2064: 
 2065: =item h4
 2066: 
 2067: =item i
 2068: 
 2069: =item date
 2070: 
 2071: =back
 2072: 
 2073: Inputs: $workbook
 2074: 
 2075: Returns: $format, a hash reference.
 2076: 
 2077: 
 2078: =cut
 2079: 
 2080: ###############################################################
 2081: ###############################################################
 2082: sub define_excel_formats {
 2083:     my ($workbook) = @_;
 2084:     my $format;
 2085:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 2086:                                                 bottom    => 1,
 2087:                                                 align     => 'center');
 2088:     $format->{'bold'} = $workbook->add_format(bold=>1);
 2089:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 2090:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 2091:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 2092:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 2093:     $format->{'i'}    = $workbook->add_format(italic=>1);
 2094:     $format->{'date'} = $workbook->add_format(num_format=>
 2095:                                             'mm/dd/yyyy hh:mm:ss');
 2096:     return $format;
 2097: }
 2098: 
 2099: ###############################################################
 2100: ###############################################################
 2101: 
 2102: =pod
 2103: 
 2104: =item * &create_workbook()
 2105: 
 2106: Create an Excel worksheet.  If it fails, output message on the
 2107: request object and return undefs.
 2108: 
 2109: Inputs: Apache request object
 2110: 
 2111: Returns (undef) on failure, 
 2112:     Excel worksheet object, scalar with filename, and formats 
 2113:     from &Apache::loncommon::define_excel_formats on success
 2114: 
 2115: =cut
 2116: 
 2117: ###############################################################
 2118: ###############################################################
 2119: sub create_workbook {
 2120:     my ($r) = @_;
 2121:         #
 2122:     # Create the excel spreadsheet
 2123:     my $filename = '/prtspool/'.
 2124:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2125:         time.'_'.rand(1000000000).'.xls';
 2126:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 2127:     if (! defined($workbook)) {
 2128:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 2129:         $r->print(
 2130:             '<p class="LC_error">'
 2131:            .&mt('Problems occurred in creating the new Excel file.')
 2132:            .' '.&mt('This error has been logged.')
 2133:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2134:            .'</p>'
 2135:         );
 2136:         return (undef);
 2137:     }
 2138:     #
 2139:     $workbook->set_tempdir(LONCAPA::tempdir());
 2140:     #
 2141:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 2142:     return ($workbook,$filename,$format);
 2143: }
 2144: 
 2145: ###############################################################
 2146: ###############################################################
 2147: 
 2148: =pod
 2149: 
 2150: =item * &create_text_file()
 2151: 
 2152: Create a file to write to and eventually make available to the user.
 2153: If file creation fails, outputs an error message on the request object and 
 2154: return undefs.
 2155: 
 2156: Inputs: Apache request object, and file suffix
 2157: 
 2158: Returns (undef) on failure, 
 2159:     Filehandle and filename on success.
 2160: 
 2161: =cut
 2162: 
 2163: ###############################################################
 2164: ###############################################################
 2165: sub create_text_file {
 2166:     my ($r,$suffix) = @_;
 2167:     if (! defined($suffix)) { $suffix = 'txt'; };
 2168:     my $fh;
 2169:     my $filename = '/prtspool/'.
 2170:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2171:         time.'_'.rand(1000000000).'.'.$suffix;
 2172:     $fh = Apache::File->new('>/home/httpd'.$filename);
 2173:     if (! defined($fh)) {
 2174:         $r->log_error("Couldn't open $filename for output $!");
 2175:         $r->print(
 2176:             '<p class="LC_error">'
 2177:            .&mt('Problems occurred in creating the output file.')
 2178:            .' '.&mt('This error has been logged.')
 2179:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2180:            .'</p>'
 2181:         );
 2182:     }
 2183:     return ($fh,$filename)
 2184: }
 2185: 
 2186: 
 2187: =pod 
 2188: 
 2189: =back
 2190: 
 2191: =cut
 2192: 
 2193: ###############################################################
 2194: ##        Home server <option> list generating code          ##
 2195: ###############################################################
 2196: 
 2197: # ------------------------------------------
 2198: 
 2199: sub domain_select {
 2200:     my ($name,$value,$multiple)=@_;
 2201:     my %domains=map { 
 2202: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 2203:     } &Apache::lonnet::all_domains();
 2204:     if ($multiple) {
 2205: 	$domains{''}=&mt('Any domain');
 2206: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2207: 	return &multiple_select_form($name,$value,4,\%domains);
 2208:     } else {
 2209: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2210: 	return &select_form($name,$value,\%domains);
 2211:     }
 2212: }
 2213: 
 2214: #-------------------------------------------
 2215: 
 2216: =pod
 2217: 
 2218: =head1 Routines for form select boxes
 2219: 
 2220: =over 4
 2221: 
 2222: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 2223: 
 2224: Returns a string containing a <select> element int multiple mode
 2225: 
 2226: 
 2227: Args:
 2228:   $name - name of the <select> element
 2229:   $value - scalar or array ref of values that should already be selected
 2230:   $size - number of rows long the select element is
 2231:   $hash - the elements should be 'option' => 'shown text'
 2232:           (shown text should already have been &mt())
 2233:   $order - (optional) array ref of the order to show the elements in
 2234: 
 2235: =cut
 2236: 
 2237: #-------------------------------------------
 2238: sub multiple_select_form {
 2239:     my ($name,$value,$size,$hash,$order)=@_;
 2240:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 2241:     my $output='';
 2242:     if (! defined($size)) {
 2243:         $size = 4;
 2244:         if (scalar(keys(%$hash))<4) {
 2245:             $size = scalar(keys(%$hash));
 2246:         }
 2247:     }
 2248:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 2249:     my @order;
 2250:     if (ref($order) eq 'ARRAY')  {
 2251:         @order = @{$order};
 2252:     } else {
 2253:         @order = sort(keys(%$hash));
 2254:     }
 2255:     if (exists($$hash{'select_form_order'})) {
 2256:         @order = @{$$hash{'select_form_order'}};
 2257:     }
 2258:         
 2259:     foreach my $key (@order) {
 2260:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 2261:         $output.='selected="selected" ' if ($selected{$key});
 2262:         $output.='>'.$hash->{$key}."</option>\n";
 2263:     }
 2264:     $output.="</select>\n";
 2265:     return $output;
 2266: }
 2267: 
 2268: #-------------------------------------------
 2269: 
 2270: =pod
 2271: 
 2272: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
 2273: 
 2274: Returns a string containing a <select name='$name' size='1'> form to 
 2275: allow a user to select options from a ref to a hash containing:
 2276: option_name => displayed text. An optional $onchange can include
 2277: a javascript onchange item, e.g., onchange="this.form.submit();".
 2278: An optional arg -- $readonly -- if true will cause the select form
 2279: to be disabled, e.g., for the case where an instructor has a section-
 2280: specific role, and is viewing/modifying parameters.  
 2281: 
 2282: See lonrights.pm for an example invocation and use.
 2283: 
 2284: =cut
 2285: 
 2286: #-------------------------------------------
 2287: sub select_form {
 2288:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
 2289:     return unless (ref($hashref) eq 'HASH');
 2290:     if ($onchange) {
 2291:         $onchange = ' onchange="'.$onchange.'"';
 2292:     }
 2293:     my $disabled;
 2294:     if ($readonly) {
 2295:         $disabled = ' disabled="disabled"';
 2296:     }
 2297:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2298:     my @keys;
 2299:     if (exists($hashref->{'select_form_order'})) {
 2300: 	@keys=@{$hashref->{'select_form_order'}};
 2301:     } else {
 2302: 	@keys=sort(keys(%{$hashref}));
 2303:     }
 2304:     foreach my $key (@keys) {
 2305:         $selectform.=
 2306: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2307:             ($key eq $def ? 'selected="selected" ' : '').
 2308:                 ">".$hashref->{$key}."</option>\n";
 2309:     }
 2310:     $selectform.="</select>";
 2311:     return $selectform;
 2312: }
 2313: 
 2314: # For display filters
 2315: 
 2316: sub display_filter {
 2317:     my ($context) = @_;
 2318:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2319:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2320:     my $phraseinput = 'hidden';
 2321:     my $includeinput = 'hidden';
 2322:     my ($checked,$includetypestext);
 2323:     if ($env{'form.displayfilter'} eq 'containing') {
 2324:         $phraseinput = 'text'; 
 2325:         if ($context eq 'parmslog') {
 2326:             $includeinput = 'checkbox';
 2327:             if ($env{'form.includetypes'}) {
 2328:                 $checked = ' checked="checked"';
 2329:             }
 2330:             $includetypestext = &mt('Include parameter types');
 2331:         }
 2332:     } else {
 2333:         $includetypestext = '&nbsp;';
 2334:     }
 2335:     my ($additional,$secondid,$thirdid);
 2336:     if ($context eq 'parmslog') {
 2337:         $additional = 
 2338:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2339:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2340:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2341:             '</label>';
 2342:         $secondid = 'includetypes';
 2343:         $thirdid = 'includetypestext';
 2344:     }
 2345:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2346:                                                     '$secondid','$thirdid')";
 2347:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2348: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 2349: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2350: 	   '</label></span> <span class="LC_nobreak">'.
 2351:            &mt('Filter: [_1]',
 2352: 	   &select_form($env{'form.displayfilter'},
 2353: 			'displayfilter',
 2354: 			{'currentfolder' => 'Current folder/page',
 2355: 			 'containing' => 'Containing phrase',
 2356: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2357: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2358:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2359:                          '" />'.$additional;
 2360: }
 2361: 
 2362: sub display_filter_js {
 2363:     my $includetext = &mt('Include parameter types');
 2364:     return <<"ENDJS";
 2365:   
 2366: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2367:     var firstType = 'hidden';
 2368:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2369:         firstType = 'text';
 2370:     }
 2371:     firstObject = document.getElementById(firstid);
 2372:     if (typeof(firstObject) == 'object') {
 2373:         if (firstObject.type != firstType) {
 2374:             changeInputType(firstObject,firstType);
 2375:         }
 2376:     }
 2377:     if (context == 'parmslog') {
 2378:         var secondType = 'hidden';
 2379:         if (firstType == 'text') {
 2380:             secondType = 'checkbox';
 2381:         }
 2382:         secondObject = document.getElementById(secondid);  
 2383:         if (typeof(secondObject) == 'object') {
 2384:             if (secondObject.type != secondType) {
 2385:                 changeInputType(secondObject,secondType);
 2386:             }
 2387:         }
 2388:         var textItem = document.getElementById(thirdid);
 2389:         var currtext = textItem.innerHTML;
 2390:         var newtext;
 2391:         if (firstType == 'text') {
 2392:             newtext = '$includetext';
 2393:         } else {
 2394:             newtext = '&nbsp;';
 2395:         }
 2396:         if (currtext != newtext) {
 2397:             textItem.innerHTML = newtext;
 2398:         }
 2399:     }
 2400:     return;
 2401: }
 2402: 
 2403: function changeInputType(oldObject,newType) {
 2404:     var newObject = document.createElement('input');
 2405:     newObject.type = newType;
 2406:     if (oldObject.size) {
 2407:         newObject.size = oldObject.size;
 2408:     }
 2409:     if (oldObject.value) {
 2410:         newObject.value = oldObject.value;
 2411:     }
 2412:     if (oldObject.name) {
 2413:         newObject.name = oldObject.name;
 2414:     }
 2415:     if (oldObject.id) {
 2416:         newObject.id = oldObject.id;
 2417:     }
 2418:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2419:     return;
 2420: }
 2421: 
 2422: ENDJS
 2423: }
 2424: 
 2425: sub gradeleveldescription {
 2426:     my $gradelevel=shift;
 2427:     my %gradelevels=(0 => 'Not specified',
 2428: 		     1 => 'Grade 1',
 2429: 		     2 => 'Grade 2',
 2430: 		     3 => 'Grade 3',
 2431: 		     4 => 'Grade 4',
 2432: 		     5 => 'Grade 5',
 2433: 		     6 => 'Grade 6',
 2434: 		     7 => 'Grade 7',
 2435: 		     8 => 'Grade 8',
 2436: 		     9 => 'Grade 9',
 2437: 		     10 => 'Grade 10',
 2438: 		     11 => 'Grade 11',
 2439: 		     12 => 'Grade 12',
 2440: 		     13 => 'Grade 13',
 2441: 		     14 => '100 Level',
 2442: 		     15 => '200 Level',
 2443: 		     16 => '300 Level',
 2444: 		     17 => '400 Level',
 2445: 		     18 => 'Graduate Level');
 2446:     return &mt($gradelevels{$gradelevel});
 2447: }
 2448: 
 2449: sub select_level_form {
 2450:     my ($deflevel,$name)=@_;
 2451:     unless ($deflevel) { $deflevel=0; }
 2452:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2453:     for (my $i=0; $i<=18; $i++) {
 2454:         $selectform.="<option value=\"$i\" ".
 2455:             ($i==$deflevel ? 'selected="selected" ' : '').
 2456:                 ">".&gradeleveldescription($i)."</option>\n";
 2457:     }
 2458:     $selectform.="</select>";
 2459:     return $selectform;
 2460: }
 2461: 
 2462: #-------------------------------------------
 2463: 
 2464: =pod
 2465: 
 2466: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
 2467: 
 2468: Returns a string containing a <select name='$name' size='1'> form to 
 2469: allow a user to select the domain to preform an operation in.  
 2470: See loncreateuser.pm for an example invocation and use.
 2471: 
 2472: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2473: selected");
 2474: 
 2475: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2476: 
 2477: 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.
 2478: 
 2479: The optional $incdoms is a reference to an array of domains which will be the only available options.
 2480: 
 2481: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
 2482: 
 2483: The optional $disabled argument, if true, adds the disabled attribute to the select tag. 
 2484: 
 2485: =cut
 2486: 
 2487: #-------------------------------------------
 2488: sub select_dom_form {
 2489:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
 2490:     if ($onchange) {
 2491:         $onchange = ' onchange="'.$onchange.'"';
 2492:     }
 2493:     if ($disabled) {
 2494:         $disabled = ' disabled="disabled"';
 2495:     }
 2496:     my (@domains,%exclude);
 2497:     if (ref($incdoms) eq 'ARRAY') {
 2498:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2499:     } else {
 2500:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2501:     }
 2502:     if ($includeempty) { @domains=('',@domains); }
 2503:     if (ref($excdoms) eq 'ARRAY') {
 2504:         map { $exclude{$_} = 1; } @{$excdoms};
 2505:     }
 2506:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2507:     foreach my $dom (@domains) {
 2508:         next if ($exclude{$dom});
 2509:         $selectdomain.="<option value=\"$dom\" ".
 2510:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2511:         if ($showdomdesc) {
 2512:             if ($dom ne '') {
 2513:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2514:                 if ($domdesc ne '') {
 2515:                     $selectdomain .= ' ('.$domdesc.')';
 2516:                 }
 2517:             } 
 2518:         }
 2519:         $selectdomain .= "</option>\n";
 2520:     }
 2521:     $selectdomain.="</select>";
 2522:     return $selectdomain;
 2523: }
 2524: 
 2525: #-------------------------------------------
 2526: 
 2527: =pod
 2528: 
 2529: =item * &home_server_form_item($domain,$name,$defaultflag)
 2530: 
 2531: input: 4 arguments (two required, two optional) - 
 2532:     $domain - domain of new user
 2533:     $name - name of form element
 2534:     $default - Value of 'default' causes a default item to be first 
 2535:                             option, and selected by default. 
 2536:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2537:                             if 1 server found, or default, if 0 found.
 2538: output: returns 2 items: 
 2539: (a) form element which contains either:
 2540:    (i) <select name="$name">
 2541:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2542:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2543:        </select>
 2544:        form item if there are multiple library servers in $domain, or
 2545:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2546:        if there is only one library server in $domain.
 2547: 
 2548: (b) number of library servers found.
 2549: 
 2550: See loncreateuser.pm for example of use.
 2551: 
 2552: =cut
 2553: 
 2554: #-------------------------------------------
 2555: sub home_server_form_item {
 2556:     my ($domain,$name,$default,$hide) = @_;
 2557:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2558:     my $result;
 2559:     my $numlib = keys(%servers);
 2560:     if ($numlib > 1) {
 2561:         $result .= '<select name="'.$name.'" />'."\n";
 2562:         if ($default) {
 2563:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2564:                        '</option>'."\n";
 2565:         }
 2566:         foreach my $hostid (sort(keys(%servers))) {
 2567:             $result.= '<option value="'.$hostid.'">'.
 2568: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2569:         }
 2570:         $result .= '</select>'."\n";
 2571:     } elsif ($numlib == 1) {
 2572:         my $hostid;
 2573:         foreach my $item (keys(%servers)) {
 2574:             $hostid = $item;
 2575:         }
 2576:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2577:                    $hostid.'" />';
 2578:                    if (!$hide) {
 2579:                        $result .= $hostid.' '.$servers{$hostid};
 2580:                    }
 2581:                    $result .= "\n";
 2582:     } elsif ($default) {
 2583:         $result .= '<input type="hidden" name="'.$name.
 2584:                    '" value="default" />';
 2585:                    if (!$hide) {
 2586:                        $result .= &mt('default');
 2587:                    }
 2588:                    $result .= "\n";
 2589:     }
 2590:     return ($result,$numlib);
 2591: }
 2592: 
 2593: =pod
 2594: 
 2595: =back 
 2596: 
 2597: =cut
 2598: 
 2599: ###############################################################
 2600: ##                  Decoding User Agent                      ##
 2601: ###############################################################
 2602: 
 2603: =pod
 2604: 
 2605: =head1 Decoding the User Agent
 2606: 
 2607: =over 4
 2608: 
 2609: =item * &decode_user_agent()
 2610: 
 2611: Inputs: $r
 2612: 
 2613: Outputs:
 2614: 
 2615: =over 4
 2616: 
 2617: =item * $httpbrowser
 2618: 
 2619: =item * $clientbrowser
 2620: 
 2621: =item * $clientversion
 2622: 
 2623: =item * $clientmathml
 2624: 
 2625: =item * $clientunicode
 2626: 
 2627: =item * $clientos
 2628: 
 2629: =item * $clientmobile
 2630: 
 2631: =item * $clientinfo
 2632: 
 2633: =item * $clientosversion
 2634: 
 2635: =back
 2636: 
 2637: =back 
 2638: 
 2639: =cut
 2640: 
 2641: ###############################################################
 2642: ###############################################################
 2643: sub decode_user_agent {
 2644:     my ($r)=@_;
 2645:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2646:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2647:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2648:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2649:     my $clientbrowser='unknown';
 2650:     my $clientversion='0';
 2651:     my $clientmathml='';
 2652:     my $clientunicode='0';
 2653:     my $clientmobile=0;
 2654:     my $clientosversion='';
 2655:     for (my $i=0;$i<=$#browsertype;$i++) {
 2656:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
 2657: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2658: 	    $clientbrowser=$bname;
 2659:             $httpbrowser=~/$vreg/i;
 2660: 	    $clientversion=$1;
 2661:             $clientmathml=($clientversion>=$minv);
 2662:             $clientunicode=($clientversion>=$univ);
 2663: 	}
 2664:     }
 2665:     my $clientos='unknown';
 2666:     my $clientinfo;
 2667:     if (($httpbrowser=~/linux/i) ||
 2668:         ($httpbrowser=~/unix/i) ||
 2669:         ($httpbrowser=~/ux/i) ||
 2670:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2671:     if (($httpbrowser=~/vax/i) ||
 2672:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2673:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2674:     if (($httpbrowser=~/mac/i) ||
 2675:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2676:     if ($httpbrowser=~/win/i) {
 2677:         $clientos='win';
 2678:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
 2679:             $clientosversion = $1;
 2680:         }
 2681:     }
 2682:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2683:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 2684:         $clientmobile=lc($1);
 2685:     }
 2686:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 2687:         $clientinfo = 'firefox-'.$1;
 2688:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 2689:         $clientinfo = 'chromeframe-'.$1;
 2690:     }
 2691:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2692:             $clientunicode,$clientos,$clientmobile,$clientinfo,
 2693:             $clientosversion);
 2694: }
 2695: 
 2696: ###############################################################
 2697: ##    Authentication changing form generation subroutines    ##
 2698: ###############################################################
 2699: ##
 2700: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2701: ## hash, and have reasonable default values.
 2702: ##
 2703: ##    formname = the name given in the <form> tag.
 2704: #-------------------------------------------
 2705: 
 2706: =pod
 2707: 
 2708: =head1 Authentication Routines
 2709: 
 2710: =over 4
 2711: 
 2712: =item * &authform_xxxxxx()
 2713: 
 2714: The authform_xxxxxx subroutines provide javascript and html forms which 
 2715: handle some of the conveniences required for authentication forms.  
 2716: This is not an optimal method, but it works.  
 2717: 
 2718: =over 4
 2719: 
 2720: =item * authform_header
 2721: 
 2722: =item * authform_authorwarning
 2723: 
 2724: =item * authform_nochange
 2725: 
 2726: =item * authform_kerberos
 2727: 
 2728: =item * authform_internal
 2729: 
 2730: =item * authform_filesystem
 2731: 
 2732: =back
 2733: 
 2734: See loncreateuser.pm for invocation and use examples.
 2735: 
 2736: =cut
 2737: 
 2738: #-------------------------------------------
 2739: sub authform_header{  
 2740:     my %in = (
 2741:         formname => 'cu',
 2742:         kerb_def_dom => '',
 2743:         @_,
 2744:     );
 2745:     $in{'formname'} = 'document.' . $in{'formname'};
 2746:     my $result='';
 2747: 
 2748: #---------------------------------------------- Code for upper case translation
 2749:     my $Javascript_toUpperCase;
 2750:     unless ($in{kerb_def_dom}) {
 2751:         $Javascript_toUpperCase =<<"END";
 2752:         switch (choice) {
 2753:            case 'krb': currentform.elements[choicearg].value =
 2754:                currentform.elements[choicearg].value.toUpperCase();
 2755:                break;
 2756:            default:
 2757:         }
 2758: END
 2759:     } else {
 2760:         $Javascript_toUpperCase = "";
 2761:     }
 2762: 
 2763:     my $radioval = "'nochange'";
 2764:     if (defined($in{'curr_authtype'})) {
 2765:         if ($in{'curr_authtype'} ne '') {
 2766:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2767:         }
 2768:     }
 2769:     my $argfield = 'null';
 2770:     if (defined($in{'mode'})) {
 2771:         if ($in{'mode'} eq 'modifycourse')  {
 2772:             if (defined($in{'curr_autharg'})) {
 2773:                 if ($in{'curr_autharg'} ne '') {
 2774:                     $argfield = "'$in{'curr_autharg'}'";
 2775:                 }
 2776:             }
 2777:         }
 2778:     }
 2779: 
 2780:     $result.=<<"END";
 2781: var current = new Object();
 2782: current.radiovalue = $radioval;
 2783: current.argfield = $argfield;
 2784: 
 2785: function changed_radio(choice,currentform) {
 2786:     var choicearg = choice + 'arg';
 2787:     // If a radio button in changed, we need to change the argfield
 2788:     if (current.radiovalue != choice) {
 2789:         current.radiovalue = choice;
 2790:         if (current.argfield != null) {
 2791:             currentform.elements[current.argfield].value = '';
 2792:         }
 2793:         if (choice == 'nochange') {
 2794:             current.argfield = null;
 2795:         } else {
 2796:             current.argfield = choicearg;
 2797:             switch(choice) {
 2798:                 case 'krb': 
 2799:                     currentform.elements[current.argfield].value = 
 2800:                         "$in{'kerb_def_dom'}";
 2801:                 break;
 2802:               default:
 2803:                 break;
 2804:             }
 2805:         }
 2806:     }
 2807:     return;
 2808: }
 2809: 
 2810: function changed_text(choice,currentform) {
 2811:     var choicearg = choice + 'arg';
 2812:     if (currentform.elements[choicearg].value !='') {
 2813:         $Javascript_toUpperCase
 2814:         // clear old field
 2815:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2816:             currentform.elements[current.argfield].value = '';
 2817:         }
 2818:         current.argfield = choicearg;
 2819:     }
 2820:     set_auth_radio_buttons(choice,currentform);
 2821:     return;
 2822: }
 2823: 
 2824: function set_auth_radio_buttons(newvalue,currentform) {
 2825:     var numauthchoices = currentform.login.length;
 2826:     if (typeof numauthchoices  == "undefined") {
 2827:         return;
 2828:     } 
 2829:     var i=0;
 2830:     while (i < numauthchoices) {
 2831:         if (currentform.login[i].value == newvalue) { break; }
 2832:         i++;
 2833:     }
 2834:     if (i == numauthchoices) {
 2835:         return;
 2836:     }
 2837:     current.radiovalue = newvalue;
 2838:     currentform.login[i].checked = true;
 2839:     return;
 2840: }
 2841: END
 2842:     return $result;
 2843: }
 2844: 
 2845: sub authform_authorwarning {
 2846:     my $result='';
 2847:     $result='<i>'.
 2848:         &mt('As a general rule, only authors or co-authors should be '.
 2849:             'filesystem authenticated '.
 2850:             '(which allows access to the server filesystem).')."</i>\n";
 2851:     return $result;
 2852: }
 2853: 
 2854: sub authform_nochange {
 2855:     my %in = (
 2856:               formname => 'document.cu',
 2857:               kerb_def_dom => 'MSU.EDU',
 2858:               @_,
 2859:           );
 2860:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
 2861:     my $result;
 2862:     if (!$authnum) {
 2863:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 2864:     } else {
 2865:         $result = '<label>'.&mt('[_1] Do not change login data',
 2866:                   '<input type="radio" name="login" value="nochange" '.
 2867:                   'checked="checked" onclick="'.
 2868:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2869: 	    '</label>';
 2870:     }
 2871:     return $result;
 2872: }
 2873: 
 2874: sub authform_kerberos {
 2875:     my %in = (
 2876:               formname => 'document.cu',
 2877:               kerb_def_dom => 'MSU.EDU',
 2878:               kerb_def_auth => 'krb4',
 2879:               @_,
 2880:               );
 2881:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2882:         $autharg,$jscall,$disabled);
 2883:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2884:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2885:        $check5 = ' checked="checked"';
 2886:     } else {
 2887:        $check4 = ' checked="checked"';
 2888:     }
 2889:     if ($in{'readonly'}) {
 2890:         $disabled = ' disabled="disabled"';
 2891:     }
 2892:     $krbarg = $in{'kerb_def_dom'};
 2893:     if (defined($in{'curr_authtype'})) {
 2894:         if ($in{'curr_authtype'} eq 'krb') {
 2895:             $krbcheck = ' checked="checked"';
 2896:             if (defined($in{'mode'})) {
 2897:                 if ($in{'mode'} eq 'modifyuser') {
 2898:                     $krbcheck = '';
 2899:                 }
 2900:             }
 2901:             if (defined($in{'curr_kerb_ver'})) {
 2902:                 if ($in{'curr_krb_ver'} eq '5') {
 2903:                     $check5 = ' checked="checked"';
 2904:                     $check4 = '';
 2905:                 } else {
 2906:                     $check4 = ' checked="checked"';
 2907:                     $check5 = '';
 2908:                 }
 2909:             }
 2910:             if (defined($in{'curr_autharg'})) {
 2911:                 $krbarg = $in{'curr_autharg'};
 2912:             }
 2913:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2914:                 if (defined($in{'curr_autharg'})) {
 2915:                     $result = 
 2916:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2917:         $in{'curr_autharg'},$krbver);
 2918:                 } else {
 2919:                     $result =
 2920:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2921:                 }
 2922:                 return $result; 
 2923:             }
 2924:         }
 2925:     } else {
 2926:         if ($authnum == 1) {
 2927:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2928:         }
 2929:     }
 2930:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2931:         return;
 2932:     } elsif ($authtype eq '') {
 2933:         if (defined($in{'mode'})) {
 2934:             if ($in{'mode'} eq 'modifycourse') {
 2935:                 if ($authnum == 1) {
 2936:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
 2937:                 }
 2938:             }
 2939:         }
 2940:     }
 2941:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2942:     if ($authtype eq '') {
 2943:         $authtype = '<input type="radio" name="login" value="krb" '.
 2944:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2945:                     $krbcheck.$disabled.' />';
 2946:     }
 2947:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2948:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 2949:          $in{'curr_authtype'} eq 'krb5') ||
 2950:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 2951:          $in{'curr_authtype'} eq 'krb4')) {
 2952:         $result .= &mt
 2953:         ('[_1] Kerberos authenticated with domain [_2] '.
 2954:          '[_3] Version 4 [_4] Version 5 [_5]',
 2955:          '<label>'.$authtype,
 2956:          '</label><input type="text" size="10" name="krbarg" '.
 2957:              'value="'.$krbarg.'" '.
 2958:              'onchange="'.$jscall.'"'.$disabled.' />',
 2959:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
 2960:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
 2961: 	 '</label>');
 2962:     } elsif ($can_assign{'krb4'}) {
 2963:         $result .= &mt
 2964:         ('[_1] Kerberos authenticated with domain [_2] '.
 2965:          '[_3] Version 4 [_4]',
 2966:          '<label>'.$authtype,
 2967:          '</label><input type="text" size="10" name="krbarg" '.
 2968:              'value="'.$krbarg.'" '.
 2969:              'onchange="'.$jscall.'"'.$disabled.' />',
 2970:          '<label><input type="hidden" name="krbver" value="4" />',
 2971:          '</label>');
 2972:     } elsif ($can_assign{'krb5'}) {
 2973:         $result .= &mt
 2974:         ('[_1] Kerberos authenticated with domain [_2] '.
 2975:          '[_3] Version 5 [_4]',
 2976:          '<label>'.$authtype,
 2977:          '</label><input type="text" size="10" name="krbarg" '.
 2978:              'value="'.$krbarg.'" '.
 2979:              'onchange="'.$jscall.'"'.$disabled.' />',
 2980:          '<label><input type="hidden" name="krbver" value="5" />',
 2981:          '</label>');
 2982:     }
 2983:     return $result;
 2984: }
 2985: 
 2986: sub authform_internal {
 2987:     my %in = (
 2988:                 formname => 'document.cu',
 2989:                 kerb_def_dom => 'MSU.EDU',
 2990:                 @_,
 2991:                 );
 2992:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
 2993:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2994:     if ($in{'readonly'}) {
 2995:         $disabled = ' disabled="disabled"';
 2996:     }
 2997:     if (defined($in{'curr_authtype'})) {
 2998:         if ($in{'curr_authtype'} eq 'int') {
 2999:             if ($can_assign{'int'}) {
 3000:                 $intcheck = 'checked="checked" ';
 3001:                 if (defined($in{'mode'})) {
 3002:                     if ($in{'mode'} eq 'modifyuser') {
 3003:                         $intcheck = '';
 3004:                     }
 3005:                 }
 3006:                 if (defined($in{'curr_autharg'})) {
 3007:                     $intarg = $in{'curr_autharg'};
 3008:                 }
 3009:             } else {
 3010:                 $result = &mt('Currently internally authenticated.');
 3011:                 return $result;
 3012:             }
 3013:         }
 3014:     } else {
 3015:         if ($authnum == 1) {
 3016:             $authtype = '<input type="hidden" name="login" value="int" />';
 3017:         }
 3018:     }
 3019:     if (!$can_assign{'int'}) {
 3020:         return;
 3021:     } elsif ($authtype eq '') {
 3022:         if (defined($in{'mode'})) {
 3023:             if ($in{'mode'} eq 'modifycourse') {
 3024:                 if ($authnum == 1) {
 3025:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
 3026:                 }
 3027:             }
 3028:         }
 3029:     }
 3030:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 3031:     if ($authtype eq '') {
 3032:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 3033:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
 3034:     }
 3035:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 3036:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3037:     $result = &mt
 3038:         ('[_1] Internally authenticated (with initial password [_2])',
 3039:          '<label>'.$authtype,'</label>'.$autharg);
 3040:     $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>';
 3041:     return $result;
 3042: }
 3043: 
 3044: sub authform_local {
 3045:     my %in = (
 3046:               formname => 'document.cu',
 3047:               kerb_def_dom => 'MSU.EDU',
 3048:               @_,
 3049:               );
 3050:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
 3051:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3052:     if ($in{'readonly'}) {
 3053:         $disabled = ' disabled="disabled"';
 3054:     }
 3055:     if (defined($in{'curr_authtype'})) {
 3056:         if ($in{'curr_authtype'} eq 'loc') {
 3057:             if ($can_assign{'loc'}) {
 3058:                 $loccheck = 'checked="checked" ';
 3059:                 if (defined($in{'mode'})) {
 3060:                     if ($in{'mode'} eq 'modifyuser') {
 3061:                         $loccheck = '';
 3062:                     }
 3063:                 }
 3064:                 if (defined($in{'curr_autharg'})) {
 3065:                     $locarg = $in{'curr_autharg'};
 3066:                 }
 3067:             } else {
 3068:                 $result = &mt('Currently using local (institutional) authentication.');
 3069:                 return $result;
 3070:             }
 3071:         }
 3072:     } else {
 3073:         if ($authnum == 1) {
 3074:             $authtype = '<input type="hidden" name="login" value="loc" />';
 3075:         }
 3076:     }
 3077:     if (!$can_assign{'loc'}) {
 3078:         return;
 3079:     } elsif ($authtype eq '') {
 3080:         if (defined($in{'mode'})) {
 3081:             if ($in{'mode'} eq 'modifycourse') {
 3082:                 if ($authnum == 1) {
 3083:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
 3084:                 }
 3085:             }
 3086:         }
 3087:     }
 3088:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 3089:     if ($authtype eq '') {
 3090:         $authtype = '<input type="radio" name="login" value="loc" '.
 3091:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 3092:                     $jscall.'"'.$disabled.' />';
 3093:     }
 3094:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 3095:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3096:     $result = &mt('[_1] Local Authentication with argument [_2]',
 3097:                   '<label>'.$authtype,'</label>'.$autharg);
 3098:     return $result;
 3099: }
 3100: 
 3101: sub authform_filesystem {
 3102:     my %in = (
 3103:               formname => 'document.cu',
 3104:               kerb_def_dom => 'MSU.EDU',
 3105:               @_,
 3106:               );
 3107:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
 3108:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3109:     if ($in{'readonly'}) {
 3110:         $disabled = ' disabled="disabled"';
 3111:     }
 3112:     if (defined($in{'curr_authtype'})) {
 3113:         if ($in{'curr_authtype'} eq 'fsys') {
 3114:             if ($can_assign{'fsys'}) {
 3115:                 $fsyscheck = 'checked="checked" ';
 3116:                 if (defined($in{'mode'})) {
 3117:                     if ($in{'mode'} eq 'modifyuser') {
 3118:                         $fsyscheck = '';
 3119:                     }
 3120:                 }
 3121:             } else {
 3122:                 $result = &mt('Currently Filesystem Authenticated.');
 3123:                 return $result;
 3124:             }           
 3125:         }
 3126:     } else {
 3127:         if ($authnum == 1) {
 3128:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 3129:         }
 3130:     }
 3131:     if (!$can_assign{'fsys'}) {
 3132:         return;
 3133:     } elsif ($authtype eq '') {
 3134:         if (defined($in{'mode'})) {
 3135:             if ($in{'mode'} eq 'modifycourse') {
 3136:                 if ($authnum == 1) {
 3137:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
 3138:                 }
 3139:             }
 3140:         }
 3141:     }
 3142:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 3143:     if ($authtype eq '') {
 3144:         $authtype = '<input type="radio" name="login" value="fsys" '.
 3145:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 3146:                     $jscall.'"'.$disabled.' />';
 3147:     }
 3148:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
 3149:                ' onchange="'.$jscall.'"'.$disabled.' />';
 3150:     $result = &mt
 3151:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 3152:          '<label>'.$authtype,'</label>'.$autharg);
 3153:     return $result;
 3154: }
 3155: 
 3156: sub get_assignable_auth {
 3157:     my ($dom) = @_;
 3158:     if ($dom eq '') {
 3159:         $dom = $env{'request.role.domain'};
 3160:     }
 3161:     my %can_assign = (
 3162:                           krb4 => 1,
 3163:                           krb5 => 1,
 3164:                           int  => 1,
 3165:                           loc  => 1,
 3166:                      );
 3167:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 3168:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 3169:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 3170:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 3171:             my $context;
 3172:             if ($env{'request.role'} =~ /^au/) {
 3173:                 $context = 'author';
 3174:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
 3175:                 $context = 'domain';
 3176:             } elsif ($env{'request.course.id'}) {
 3177:                 $context = 'course';
 3178:             }
 3179:             if ($context) {
 3180:                 if (ref($authhash->{$context}) eq 'HASH') {
 3181:                    %can_assign = %{$authhash->{$context}}; 
 3182:                 }
 3183:             }
 3184:         }
 3185:     }
 3186:     my $authnum = 0;
 3187:     foreach my $key (keys(%can_assign)) {
 3188:         if ($can_assign{$key}) {
 3189:             $authnum ++;
 3190:         }
 3191:     }
 3192:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 3193:         $authnum --;
 3194:     }
 3195:     return ($authnum,%can_assign);
 3196: }
 3197: 
 3198: sub check_passwd_rules {
 3199:     my ($domain,$plainpass) = @_;
 3200:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
 3201:     my ($min,$max,@chars,@brokerule,$warning);
 3202:     $min = $Apache::lonnet::passwdmin;
 3203:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
 3204:         if ($passwdconf{'min'} =~ /^\d+$/) {
 3205:             if ($passwdconf{'min'} > $min) {
 3206:                 $min = $passwdconf{'min'};
 3207:             }
 3208:         }
 3209:         if ($passwdconf{'max'} =~ /^\d+$/) {
 3210:             $max = $passwdconf{'max'};
 3211:         }
 3212:         @chars = @{$passwdconf{'chars'}};
 3213:     }
 3214:     if (($min) && (length($plainpass) < $min)) {
 3215:         push(@brokerule,'min');
 3216:     }
 3217:     if (($max) && (length($plainpass) > $max)) {
 3218:         push(@brokerule,'max');
 3219:     }
 3220:     if (@chars) {
 3221:         my %rules;
 3222:         map { $rules{$_} = 1; } @chars;
 3223:         if ($rules{'uc'}) {
 3224:             unless ($plainpass =~ /[A-Z]/) {
 3225:                 push(@brokerule,'uc');
 3226:             }
 3227:         }
 3228:         if ($rules{'lc'}) {
 3229:             unless ($plainpass =~ /[a-z]/) {
 3230:                 push(@brokerule,'lc');
 3231:             }
 3232:         }
 3233:         if ($rules{'num'}) {
 3234:             unless ($plainpass =~ /\d/) {
 3235:                 push(@brokerule,'num');
 3236:             }
 3237:         }
 3238:         if ($rules{'spec'}) {
 3239:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
 3240:                 push(@brokerule,'spec');
 3241:             }
 3242:         }
 3243:     }
 3244:     if (@brokerule) {
 3245:         my %rulenames = &Apache::lonlocal::texthash(
 3246:             uc   => 'At least one upper case letter',
 3247:             lc   => 'At least one lower case letter',
 3248:             num  => 'At least one number',
 3249:             spec => 'At least one non-alphanumeric',
 3250:         );
 3251:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
 3252:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
 3253:         $rulenames{'num'} .= ': 0123456789';
 3254:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
 3255:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
 3256:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
 3257:         $warning = &mt('Password did not satisfy the following:').'<ul>';
 3258:         foreach my $rule ('min','max','uc','lc','num','spec') {
 3259:             if (grep(/^$rule$/,@brokerule)) {
 3260:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
 3261:             }
 3262:         }
 3263:         $warning .= '</ul>';
 3264:     }
 3265:     if (wantarray) {
 3266:         return @brokerule;
 3267:     }
 3268:     return $warning;
 3269: }
 3270: 
 3271: sub passwd_validation_js {
 3272:     my ($currpasswdval,$domain,$context,$id) = @_;
 3273:     my (%passwdconf,$alertmsg);
 3274:     if ($context eq 'linkprot') {
 3275:         my %domconfig = &Apache::lonnet::get_dom('configuration',['ltisec'],$domain);
 3276:         if (ref($domconfig{'ltisec'}) eq 'HASH') {
 3277:             if (ref($domconfig{'ltisec'}{'rules'}) eq 'HASH') {
 3278:                 %passwdconf = %{$domconfig{'ltisec'}{'rules'}};
 3279:             }
 3280:         }
 3281:         if ($id eq 'add') {
 3282:             $alertmsg = &mt('Secret for added launcher did not satisfy requirement(s):').'\n\n';
 3283:         } elsif ($id =~ /^\d+$/) {
 3284:             my $pos = $id+1;
 3285:             $alertmsg = &mt('Secret for launcher [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
 3286:         } else {
 3287:             $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
 3288:         }
 3289:     } else {
 3290:         %passwdconf = &Apache::lonnet::get_passwdconf($domain);
 3291:         $alertmsg = &mt('Initial password did not satisfy requirement(s):').'\n\n';
 3292:     }
 3293:     my ($min,$max,@chars,$numrules,$intargjs,%alert);
 3294:     $numrules = 0;
 3295:     $min = $Apache::lonnet::passwdmin;
 3296:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
 3297:         if ($passwdconf{'min'} =~ /^\d+$/) {
 3298:             if ($passwdconf{'min'} > $min) {
 3299:                 $min = $passwdconf{'min'};
 3300:             }
 3301:         }
 3302:         if ($passwdconf{'max'} =~ /^\d+$/) {
 3303:             $max = $passwdconf{'max'};
 3304:             $numrules ++;
 3305:         }
 3306:         @chars = @{$passwdconf{'chars'}};
 3307:         if (@chars) {
 3308:             $numrules ++;
 3309:         }
 3310:     }
 3311:     if ($min > 0) {
 3312:         $numrules ++;
 3313:     }
 3314:     if (($min > 0) || ($max ne '') || (@chars > 0)) {
 3315:         if ($min) {
 3316:             $alert{'min'} = &mt('minimum [quant,_1,character]',$min).'\n';
 3317:         }
 3318:         if ($max) {
 3319:             $alert{'max'} = &mt('maximum [quant,_1,character]',$max).'\n';
 3320:         }
 3321:         my (@charalerts,@charrules);
 3322:         if (@chars) {
 3323:             if (grep(/^uc$/,@chars)) {
 3324:                 push(@charalerts,&mt('contain at least one upper case letter'));
 3325:                 push(@charrules,'uc');
 3326:             }
 3327:             if (grep(/^lc$/,@chars)) {
 3328:                 push(@charalerts,&mt('contain at least one lower case letter'));
 3329:                 push(@charrules,'lc');
 3330:             }
 3331:             if (grep(/^num$/,@chars)) {
 3332:                 push(@charalerts,&mt('contain at least one number'));
 3333:                 push(@charrules,'num');
 3334:             }
 3335:             if (grep(/^spec$/,@chars)) {
 3336:                 push(@charalerts,&mt('contain at least one non-alphanumeric'));
 3337:                 push(@charrules,'spec');
 3338:             }
 3339:         }
 3340:         $intargjs = qq|            var rulesmsg = '';\n|.
 3341:                     qq|            var currpwval = $currpasswdval;\n|;
 3342:             if ($min) {
 3343:                 $intargjs .= qq|
 3344:             if (currpwval.length < $min) {
 3345:                 rulesmsg += ' - $alert{min}';
 3346:             }
 3347: |;
 3348:             }
 3349:             if ($max) {
 3350:                 $intargjs .= qq|
 3351:             if (currpwval.length > $max) {
 3352:                 rulesmsg += ' - $alert{max}';
 3353:             }
 3354: |;
 3355:             }
 3356:             if (@chars > 0) {
 3357:                 my $charrulestr = '"'.join('","',@charrules).'"';
 3358:                 my $charalertstr = '"'.join('","',@charalerts).'"';
 3359:                 $intargjs .= qq|            var brokerules = new Array();\n|.
 3360:                              qq|            var charrules = new Array($charrulestr);\n|.
 3361:                              qq|            var charalerts = new Array($charalertstr);\n|;
 3362:                 my %rules;
 3363:                 map { $rules{$_} = 1; } @chars;
 3364:                 if ($rules{'uc'}) {
 3365:                     $intargjs .= qq|
 3366:             var ucRegExp = /[A-Z]/;
 3367:             if (!ucRegExp.test(currpwval)) {
 3368:                 brokerules.push('uc');
 3369:             }
 3370: |;
 3371:                 }
 3372:                 if ($rules{'lc'}) {
 3373:                     $intargjs .= qq|
 3374:             var lcRegExp = /[a-z]/;
 3375:             if (!lcRegExp.test(currpwval)) {
 3376:                 brokerules.push('lc');
 3377:             }
 3378: |;
 3379:                 }
 3380:                 if ($rules{'num'}) {
 3381:                      $intargjs .= qq|
 3382:             var numRegExp = /[0-9]/;
 3383:             if (!numRegExp.test(currpwval)) {
 3384:                 brokerules.push('num');
 3385:             }
 3386: |;
 3387:                 }
 3388:                 if ($rules{'spec'}) {
 3389:                      $intargjs .= q|
 3390:             var specRegExp = /[!"#$%&'()*+,\-.\/:;<=>?@[\\^\]_`{\|}~]/;
 3391:             if (!specRegExp.test(currpwval)) {
 3392:                 brokerules.push('spec');
 3393:             }
 3394: |;
 3395:                 }
 3396:                 $intargjs .= qq|
 3397:             if (brokerules.length > 0) {
 3398:                 for (var i=0; i<brokerules.length; i++) {
 3399:                     for (var j=0; j<charrules.length; j++) {
 3400:                         if (brokerules[i] == charrules[j]) {
 3401:                             rulesmsg += ' - '+charalerts[j]+'\\n';
 3402:                             break;
 3403:                         }
 3404:                     }
 3405:                 }
 3406:             }
 3407: |;
 3408:             }
 3409:             $intargjs .= qq|
 3410:             if (rulesmsg != '') {
 3411:                 rulesmsg = '$alertmsg'+rulesmsg;
 3412:                 alert(rulesmsg);
 3413:                 return false;
 3414:             }
 3415: |;
 3416:     }
 3417:     return ($numrules,$intargjs);
 3418: }
 3419: 
 3420: ###############################################################
 3421: ##    Get Kerberos Defaults for Domain                 ##
 3422: ###############################################################
 3423: ##
 3424: ## Returns default kerberos version and an associated argument
 3425: ## as listed in file domain.tab. If not listed, provides
 3426: ## appropriate default domain and kerberos version.
 3427: ##
 3428: #-------------------------------------------
 3429: 
 3430: =pod
 3431: 
 3432: =item * &get_kerberos_defaults()
 3433: 
 3434: get_kerberos_defaults($target_domain) returns the default kerberos
 3435: version and domain. If not found, it defaults to version 4 and the 
 3436: domain of the server.
 3437: 
 3438: =over 4
 3439: 
 3440: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 3441: 
 3442: =back
 3443: 
 3444: =back
 3445: 
 3446: =cut
 3447: 
 3448: #-------------------------------------------
 3449: sub get_kerberos_defaults {
 3450:     my $domain=shift;
 3451:     my ($krbdef,$krbdefdom);
 3452:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 3453:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 3454:         $krbdef = $domdefaults{'auth_def'};
 3455:         $krbdefdom = $domdefaults{'auth_arg_def'};
 3456:     } else {
 3457:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 3458:         my $krbdefdom=$1;
 3459:         $krbdefdom=~tr/a-z/A-Z/;
 3460:         $krbdef = "krb4";
 3461:     }
 3462:     return ($krbdef,$krbdefdom);
 3463: }
 3464: 
 3465: 
 3466: ###############################################################
 3467: ##                Thesaurus Functions                        ##
 3468: ###############################################################
 3469: 
 3470: =pod
 3471: 
 3472: =head1 Thesaurus Functions
 3473: 
 3474: =over 4
 3475: 
 3476: =item * &initialize_keywords()
 3477: 
 3478: Initializes the package variable %Keywords if it is empty.  Uses the
 3479: package variable $thesaurus_db_file.
 3480: 
 3481: =cut
 3482: 
 3483: ###################################################
 3484: 
 3485: sub initialize_keywords {
 3486:     return 1 if (scalar keys(%Keywords));
 3487:     # If we are here, %Keywords is empty, so fill it up
 3488:     #   Make sure the file we need exists...
 3489:     if (! -e $thesaurus_db_file) {
 3490:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 3491:                                  " failed because it does not exist");
 3492:         return 0;
 3493:     }
 3494:     #   Set up the hash as a database
 3495:     my %thesaurus_db;
 3496:     if (! tie(%thesaurus_db,'GDBM_File',
 3497:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3498:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 3499:                                  $thesaurus_db_file);
 3500:         return 0;
 3501:     } 
 3502:     #  Get the average number of appearances of a word.
 3503:     my $avecount = $thesaurus_db{'average.count'};
 3504:     #  Put keywords (those that appear > average) into %Keywords
 3505:     while (my ($word,$data)=each (%thesaurus_db)) {
 3506:         my ($count,undef) = split /:/,$data;
 3507:         $Keywords{$word}++ if ($count > $avecount);
 3508:     }
 3509:     untie %thesaurus_db;
 3510:     # Remove special values from %Keywords.
 3511:     foreach my $value ('total.count','average.count') {
 3512:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 3513:   }
 3514:     return 1;
 3515: }
 3516: 
 3517: ###################################################
 3518: 
 3519: =pod
 3520: 
 3521: =item * &keyword($word)
 3522: 
 3523: Returns true if $word is a keyword.  A keyword is a word that appears more 
 3524: than the average number of times in the thesaurus database.  Calls 
 3525: &initialize_keywords
 3526: 
 3527: =cut
 3528: 
 3529: ###################################################
 3530: 
 3531: sub keyword {
 3532:     return if (!&initialize_keywords());
 3533:     my $word=lc(shift());
 3534:     $word=~s/\W//g;
 3535:     return exists($Keywords{$word});
 3536: }
 3537: 
 3538: ###############################################################
 3539: 
 3540: =pod 
 3541: 
 3542: =item * &get_related_words()
 3543: 
 3544: Look up a word in the thesaurus.  Takes a scalar argument and returns
 3545: an array of words.  If the keyword is not in the thesaurus, an empty array
 3546: will be returned.  The order of the words returned is determined by the
 3547: database which holds them.
 3548: 
 3549: Uses global $thesaurus_db_file.
 3550: 
 3551: 
 3552: =cut
 3553: 
 3554: ###############################################################
 3555: sub get_related_words {
 3556:     my $keyword = shift;
 3557:     my %thesaurus_db;
 3558:     if (! -e $thesaurus_db_file) {
 3559:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 3560:                                  "failed because the file does not exist");
 3561:         return ();
 3562:     }
 3563:     if (! tie(%thesaurus_db,'GDBM_File',
 3564:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3565:         return ();
 3566:     } 
 3567:     my @Words=();
 3568:     my $count=0;
 3569:     if (exists($thesaurus_db{$keyword})) {
 3570: 	# The first element is the number of times
 3571: 	# the word appears.  We do not need it now.
 3572: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 3573: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 3574: 	my $threshold=$mostfrequentcount/10;
 3575:         foreach my $possibleword (@RelatedWords) {
 3576:             my ($word,$wordcount)=split(/\,/,$possibleword);
 3577:             if ($wordcount>$threshold) {
 3578: 		push(@Words,$word);
 3579:                 $count++;
 3580:                 if ($count>10) { last; }
 3581: 	    }
 3582:         }
 3583:     }
 3584:     untie %thesaurus_db;
 3585:     return @Words;
 3586: }
 3587: 
 3588: =pod
 3589: 
 3590: =back
 3591: 
 3592: =cut
 3593: 
 3594: # -------------------------------------------------------------- Plaintext name
 3595: =pod
 3596: 
 3597: =head1 User Name Functions
 3598: 
 3599: =over 4
 3600: 
 3601: =item * &plainname($uname,$udom,$first)
 3602: 
 3603: Takes a users logon name and returns it as a string in
 3604: "first middle last generation" form 
 3605: if $first is set to 'lastname' then it returns it as
 3606: 'lastname generation, firstname middlename' if their is a lastname
 3607: 
 3608: =cut
 3609: 
 3610: 
 3611: ###############################################################
 3612: sub plainname {
 3613:     my ($uname,$udom,$first)=@_;
 3614:     return if (!defined($uname) || !defined($udom));
 3615:     my %names=&getnames($uname,$udom);
 3616:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 3617: 					  $names{'middlename'},
 3618: 					  $names{'lastname'},
 3619: 					  $names{'generation'},$first);
 3620:     $name=~s/^\s+//;
 3621:     $name=~s/\s+$//;
 3622:     $name=~s/\s+/ /g;
 3623:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 3624:     return $name;
 3625: }
 3626: 
 3627: # -------------------------------------------------------------------- Nickname
 3628: =pod
 3629: 
 3630: =item * &nickname($uname,$udom)
 3631: 
 3632: Gets a users name and returns it as a string as
 3633: 
 3634: "&quot;nickname&quot;"
 3635: 
 3636: if the user has a nickname or
 3637: 
 3638: "first middle last generation"
 3639: 
 3640: if the user does not
 3641: 
 3642: =cut
 3643: 
 3644: sub nickname {
 3645:     my ($uname,$udom)=@_;
 3646:     return if (!defined($uname) || !defined($udom));
 3647:     my %names=&getnames($uname,$udom);
 3648:     my $name=$names{'nickname'};
 3649:     if ($name) {
 3650:        $name='&quot;'.$name.'&quot;'; 
 3651:     } else {
 3652:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 3653: 	     $names{'lastname'}.' '.$names{'generation'};
 3654:        $name=~s/\s+$//;
 3655:        $name=~s/\s+/ /g;
 3656:     }
 3657:     return $name;
 3658: }
 3659: 
 3660: sub getnames {
 3661:     my ($uname,$udom)=@_;
 3662:     return if (!defined($uname) || !defined($udom));
 3663:     if ($udom eq 'public' && $uname eq 'public') {
 3664: 	return ('lastname' => &mt('Public'));
 3665:     }
 3666:     my $id=$uname.':'.$udom;
 3667:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 3668:     if ($cached) {
 3669: 	return %{$names};
 3670:     } else {
 3671: 	my %loadnames=&Apache::lonnet::get('environment',
 3672:                     ['firstname','middlename','lastname','generation','nickname'],
 3673: 					 $udom,$uname);
 3674: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 3675: 	return %loadnames;
 3676:     }
 3677: }
 3678: 
 3679: # -------------------------------------------------------------------- getemails
 3680: 
 3681: =pod
 3682: 
 3683: =item * &getemails($uname,$udom)
 3684: 
 3685: Gets a user's email information and returns it as a hash with keys:
 3686: notification, critnotification, permanentemail
 3687: 
 3688: For notification and critnotification, values are comma-separated lists 
 3689: of e-mail addresses; for permanentemail, value is a single e-mail address.
 3690:  
 3691: 
 3692: =cut
 3693: 
 3694: 
 3695: sub getemails {
 3696:     my ($uname,$udom)=@_;
 3697:     if ($udom eq 'public' && $uname eq 'public') {
 3698: 	return;
 3699:     }
 3700:     if (!$udom) { $udom=$env{'user.domain'}; }
 3701:     if (!$uname) { $uname=$env{'user.name'}; }
 3702:     my $id=$uname.':'.$udom;
 3703:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 3704:     if ($cached) {
 3705: 	return %{$names};
 3706:     } else {
 3707: 	my %loadnames=&Apache::lonnet::get('environment',
 3708:                     			   ['notification','critnotification',
 3709: 					    'permanentemail'],
 3710: 					   $udom,$uname);
 3711: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 3712: 	return %loadnames;
 3713:     }
 3714: }
 3715: 
 3716: sub flush_email_cache {
 3717:     my ($uname,$udom)=@_;
 3718:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3719:     if (!$uname) { $uname=$env{'user.name'};   }
 3720:     return if ($udom eq 'public' && $uname eq 'public');
 3721:     my $id=$uname.':'.$udom;
 3722:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 3723: }
 3724: 
 3725: # -------------------------------------------------------------------- getlangs
 3726: 
 3727: =pod
 3728: 
 3729: =item * &getlangs($uname,$udom)
 3730: 
 3731: Gets a user's language preference and returns it as a hash with key:
 3732: language.
 3733: 
 3734: =cut
 3735: 
 3736: 
 3737: sub getlangs {
 3738:     my ($uname,$udom) = @_;
 3739:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3740:     if (!$uname) { $uname=$env{'user.name'};   }
 3741:     my $id=$uname.':'.$udom;
 3742:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 3743:     if ($cached) {
 3744:         return %{$langs};
 3745:     } else {
 3746:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 3747:                                            $udom,$uname);
 3748:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 3749:         return %loadlangs;
 3750:     }
 3751: }
 3752: 
 3753: sub flush_langs_cache {
 3754:     my ($uname,$udom)=@_;
 3755:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3756:     if (!$uname) { $uname=$env{'user.name'};   }
 3757:     return if ($udom eq 'public' && $uname eq 'public');
 3758:     my $id=$uname.':'.$udom;
 3759:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 3760: }
 3761: 
 3762: # ------------------------------------------------------------------ Screenname
 3763: 
 3764: =pod
 3765: 
 3766: =item * &screenname($uname,$udom)
 3767: 
 3768: Gets a users screenname and returns it as a string
 3769: 
 3770: =cut
 3771: 
 3772: sub screenname {
 3773:     my ($uname,$udom)=@_;
 3774:     if ($uname eq $env{'user.name'} &&
 3775: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 3776:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 3777:     return $names{'screenname'};
 3778: }
 3779: 
 3780: 
 3781: # ------------------------------------------------------------- Confirm Wrapper
 3782: =pod
 3783: 
 3784: =item * &confirmwrapper($message)
 3785: 
 3786: Wrap messages about completion of operation in box
 3787: 
 3788: =cut
 3789: 
 3790: sub confirmwrapper {
 3791:     my ($message)=@_;
 3792:     if ($message) {
 3793:         return "\n".'<div class="LC_confirm_box">'."\n"
 3794:                .$message."\n"
 3795:                .'</div>'."\n";
 3796:     } else {
 3797:         return $message;
 3798:     }
 3799: }
 3800: 
 3801: # ------------------------------------------------------------- Message Wrapper
 3802: 
 3803: sub messagewrapper {
 3804:     my ($link,$username,$domain,$subject,$text)=@_;
 3805:     return 
 3806:         '<a href="/adm/email?compose=individual&amp;'.
 3807:         'recname='.$username.'&amp;recdom='.$domain.
 3808: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3809:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3810: }
 3811: 
 3812: # --------------------------------------------------------------- Notes Wrapper
 3813: 
 3814: sub noteswrapper {
 3815:     my ($link,$un,$do)=@_;
 3816:     return 
 3817: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3818: }
 3819: 
 3820: # ------------------------------------------------------------- Aboutme Wrapper
 3821: 
 3822: sub aboutmewrapper {
 3823:     my ($link,$username,$domain,$target,$class)=@_;
 3824:     if (!defined($username)  && !defined($domain)) {
 3825:         return;
 3826:     }
 3827:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 3828: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3829: }
 3830: 
 3831: # ------------------------------------------------------------ Syllabus Wrapper
 3832: 
 3833: sub syllabuswrapper {
 3834:     my ($linktext,$coursedir,$domain)=@_;
 3835:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3836: }
 3837: 
 3838: sub aboutme_on {
 3839:     my ($uname,$udom)=@_;
 3840:     unless ($uname) { $uname=$env{'user.name'}; }
 3841:     unless ($udom)  { $udom=$env{'user.domain'}; }
 3842:     return if ($udom eq 'public' && $uname eq 'public');
 3843:     my $hashkey=$uname.':'.$udom;
 3844:     my ($aboutme,$cached)=&Apache::lonnet::is_cached_new('aboutme',$hashkey);
 3845:     if ($cached) {
 3846:         return $aboutme;
 3847:     }
 3848:     $aboutme = &Apache::lonnet::usertools_access($uname,$udom,'aboutme');
 3849:     &Apache::lonnet::do_cache_new('aboutme',$hashkey,$aboutme,3600);
 3850:     return $aboutme;
 3851: }
 3852: 
 3853: sub devalidate_aboutme_cache {
 3854:     my ($uname,$udom)=@_;
 3855:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3856:     if (!$uname) { $uname=$env{'user.name'};   }
 3857:     return if ($udom eq 'public' && $uname eq 'public');
 3858:     my $id=$uname.':'.$udom;
 3859:     &Apache::lonnet::devalidate_cache_new('aboutme',$id);
 3860: }
 3861: 
 3862: # -----------------------------------------------------------------------------
 3863: 
 3864: sub track_student_link {
 3865:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3866:     my $link ="/adm/trackstudent?";
 3867:     my $title = 'View recent activity';
 3868:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3869:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3870:         $link .= "selected_student=$sname:$sdom";
 3871:         $title .= ' of this student';
 3872:     } 
 3873:     if (defined($target) && $target !~ /^\s*$/) {
 3874:         $target = qq{target="$target"};
 3875:     } else {
 3876:         $target = '';
 3877:     }
 3878:     if ($start) { $link.='&amp;start='.$start; }
 3879:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3880:     $title = &mt($title);
 3881:     $linktext = &mt($linktext);
 3882:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3883: 	&help_open_topic('View_recent_activity');
 3884: }
 3885: 
 3886: sub slot_reservations_link {
 3887:     my ($linktext,$sname,$sdom,$target) = @_;
 3888:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3889:     my $title = 'View slot reservation history';
 3890:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3891:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3892:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3893:         $title .= ' of this student';
 3894:     }
 3895:     if (defined($target) && $target !~ /^\s*$/) {
 3896:         $target = qq{target="$target"};
 3897:     } else {
 3898:         $target = '';
 3899:     }
 3900:     $title = &mt($title);
 3901:     $linktext = &mt($linktext);
 3902:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3903: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3904: 
 3905: }
 3906: 
 3907: # ===================================================== Display a student photo
 3908: 
 3909: 
 3910: sub student_image_tag {
 3911:     my ($domain,$user)=@_;
 3912:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3913:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3914: 	return '<img src="'.$imgsrc.'" align="right" />';
 3915:     } else {
 3916: 	return '';
 3917:     }
 3918: }
 3919: 
 3920: =pod
 3921: 
 3922: =back
 3923: 
 3924: =head1 Access .tab File Data
 3925: 
 3926: =over 4
 3927: 
 3928: =item * &languageids() 
 3929: 
 3930: returns list of all language ids
 3931: 
 3932: =cut
 3933: 
 3934: sub languageids {
 3935:     return sort(keys(%language));
 3936: }
 3937: 
 3938: =pod
 3939: 
 3940: =item * &languagedescription() 
 3941: 
 3942: returns description of a specified language id
 3943: 
 3944: =cut
 3945: 
 3946: sub languagedescription {
 3947:     my $code=shift;
 3948:     return  ($supported_language{$code}?'* ':'').
 3949:             $language{$code}.
 3950: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 3951: }
 3952: 
 3953: =pod
 3954: 
 3955: =item * &plainlanguagedescription
 3956: 
 3957: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 3958: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 3959: 
 3960: =cut
 3961: 
 3962: sub plainlanguagedescription {
 3963:     my $code=shift;
 3964:     return $language{$code};
 3965: }
 3966: 
 3967: =pod
 3968: 
 3969: =item * &supportedlanguagecode
 3970: 
 3971: Returns the supported language code (e.g. sptutf maps to pt) given a language
 3972: code.
 3973: 
 3974: =cut
 3975: 
 3976: sub supportedlanguagecode {
 3977:     my $code=shift;
 3978:     return $supported_language{$code};
 3979: }
 3980: 
 3981: =pod
 3982: 
 3983: =item * &latexlanguage()
 3984: 
 3985: Given a language key code returns the correspondnig language to use
 3986: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 3987: is no supported hyphenation for the language code.
 3988: 
 3989: =cut
 3990: 
 3991: sub latexlanguage {
 3992:     my $code = shift;
 3993:     return $latex_language{$code};
 3994: }
 3995: 
 3996: =pod
 3997: 
 3998: =item * &latexhyphenation()
 3999: 
 4000: Same as above but what's supplied is the language as it might be stored
 4001: in the metadata.
 4002: 
 4003: =cut
 4004: 
 4005: sub latexhyphenation {
 4006:     my $key = shift;
 4007:     return $latex_language_bykey{$key};
 4008: }
 4009: 
 4010: =pod
 4011: 
 4012: =item * &copyrightids() 
 4013: 
 4014: returns list of all copyrights
 4015: 
 4016: =cut
 4017: 
 4018: sub copyrightids {
 4019:     return sort(keys(%cprtag));
 4020: }
 4021: 
 4022: =pod
 4023: 
 4024: =item * &copyrightdescription() 
 4025: 
 4026: returns description of a specified copyright id
 4027: 
 4028: =cut
 4029: 
 4030: sub copyrightdescription {
 4031:     return &mt($cprtag{shift(@_)});
 4032: }
 4033: 
 4034: =pod
 4035: 
 4036: =item * &source_copyrightids() 
 4037: 
 4038: returns list of all source copyrights
 4039: 
 4040: =cut
 4041: 
 4042: sub source_copyrightids {
 4043:     return sort(keys(%scprtag));
 4044: }
 4045: 
 4046: =pod
 4047: 
 4048: =item * &source_copyrightdescription() 
 4049: 
 4050: returns description of a specified source copyright id
 4051: 
 4052: =cut
 4053: 
 4054: sub source_copyrightdescription {
 4055:     return &mt($scprtag{shift(@_)});
 4056: }
 4057: 
 4058: =pod
 4059: 
 4060: =item * &filecategories() 
 4061: 
 4062: returns list of all file categories
 4063: 
 4064: =cut
 4065: 
 4066: sub filecategories {
 4067:     return sort(keys(%category_extensions));
 4068: }
 4069: 
 4070: =pod
 4071: 
 4072: =item * &filecategorytypes() 
 4073: 
 4074: returns list of file types belonging to a given file
 4075: category
 4076: 
 4077: =cut
 4078: 
 4079: sub filecategorytypes {
 4080:     my ($cat) = @_;
 4081:     return @{$category_extensions{lc($cat)}};
 4082: }
 4083: 
 4084: =pod
 4085: 
 4086: =item * &fileembstyle() 
 4087: 
 4088: returns embedding style for a specified file type
 4089: 
 4090: =cut
 4091: 
 4092: sub fileembstyle {
 4093:     return $fe{lc(shift(@_))};
 4094: }
 4095: 
 4096: sub filemimetype {
 4097:     return $fm{lc(shift(@_))};
 4098: }
 4099: 
 4100: 
 4101: sub filecategoryselect {
 4102:     my ($name,$value)=@_;
 4103:     return &select_form($value,$name,
 4104:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 4105: }
 4106: 
 4107: =pod
 4108: 
 4109: =item * &filedescription() 
 4110: 
 4111: returns description for a specified file type
 4112: 
 4113: =cut
 4114: 
 4115: sub filedescription {
 4116:     my $file_description = $fd{lc(shift())};
 4117:     $file_description =~ s:([\[\]]):~$1:g;
 4118:     return &mt($file_description);
 4119: }
 4120: 
 4121: =pod
 4122: 
 4123: =item * &filedescriptionex() 
 4124: 
 4125: returns description for a specified file type with
 4126: extra formatting
 4127: 
 4128: =cut
 4129: 
 4130: sub filedescriptionex {
 4131:     my $ex=shift;
 4132:     my $file_description = $fd{lc($ex)};
 4133:     $file_description =~ s:([\[\]]):~$1:g;
 4134:     return '.'.$ex.' '.&mt($file_description);
 4135: }
 4136: 
 4137: # End of .tab access
 4138: =pod
 4139: 
 4140: =back
 4141: 
 4142: =cut
 4143: 
 4144: # ------------------------------------------------------------------ File Types
 4145: sub fileextensions {
 4146:     return sort(keys(%fe));
 4147: }
 4148: 
 4149: # ----------------------------------------------------------- Display Languages
 4150: # returns a hash with all desired display languages
 4151: #
 4152: 
 4153: sub display_languages {
 4154:     my %languages=();
 4155:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 4156: 	$languages{$lang}=1;
 4157:     }
 4158:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 4159:     if ($env{'form.displaylanguage'}) {
 4160: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 4161: 	    $languages{$lang}=1;
 4162:         }
 4163:     }
 4164:     return %languages;
 4165: }
 4166: 
 4167: sub languages {
 4168:     my ($possible_langs) = @_;
 4169:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 4170:     if (!ref($possible_langs)) {
 4171: 	if( wantarray ) {
 4172: 	    return @preferred_langs;
 4173: 	} else {
 4174: 	    return $preferred_langs[0];
 4175: 	}
 4176:     }
 4177:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 4178:     my @preferred_possibilities;
 4179:     foreach my $preferred_lang (@preferred_langs) {
 4180: 	if (exists($possibilities{$preferred_lang})) {
 4181: 	    push(@preferred_possibilities, $preferred_lang);
 4182: 	}
 4183:     }
 4184:     if( wantarray ) {
 4185: 	return @preferred_possibilities;
 4186:     }
 4187:     return $preferred_possibilities[0];
 4188: }
 4189: 
 4190: sub user_lang {
 4191:     my ($touname,$toudom,$fromcid) = @_;
 4192:     my @userlangs;
 4193:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 4194:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 4195:                     $env{'course.'.$fromcid.'.languages'}));
 4196:     } else {
 4197:         my %langhash = &getlangs($touname,$toudom);
 4198:         if ($langhash{'languages'} ne '') {
 4199:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 4200:         } else {
 4201:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 4202:             if ($domdefs{'lang_def'} ne '') {
 4203:                 @userlangs = ($domdefs{'lang_def'});
 4204:             }
 4205:         }
 4206:     }
 4207:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 4208:     my $user_lh = Apache::localize->get_handle(@languages);
 4209:     return $user_lh;
 4210: }
 4211: 
 4212: 
 4213: ###############################################################
 4214: ##               Student Answer Attempts                     ##
 4215: ###############################################################
 4216: 
 4217: =pod
 4218: 
 4219: =head1 Alternate Problem Views
 4220: 
 4221: =over 4
 4222: 
 4223: =item * &get_previous_attempt($symb, $username, $domain, $course,
 4224:     $getattempt, $regexp, $gradesub, $usec, $identifier)
 4225: 
 4226: Return string with previous attempt on problem. Arguments:
 4227: 
 4228: =over 4
 4229: 
 4230: =item * $symb: Problem, including path
 4231: 
 4232: =item * $username: username of the desired student
 4233: 
 4234: =item * $domain: domain of the desired student
 4235: 
 4236: =item * $course: Course ID
 4237: 
 4238: =item * $getattempt: Leave blank for all attempts, otherwise put
 4239:     something
 4240: 
 4241: =item * $regexp: if string matches this regexp, the string will be
 4242:     sent to $gradesub
 4243: 
 4244: =item * $gradesub: routine that processes the string if it matches $regexp
 4245: 
 4246: =item * $usec: section of the desired student
 4247: 
 4248: =item * $identifier: counter for student (multiple students one problem) or
 4249:     problem (one student; whole sequence).
 4250: 
 4251: =back
 4252: 
 4253: The output string is a table containing all desired attempts, if any.
 4254: 
 4255: =cut
 4256: 
 4257: sub get_previous_attempt {
 4258:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
 4259:   my $prevattempts='';
 4260:   no strict 'refs';
 4261:   if ($symb) {
 4262:     my (%returnhash)=
 4263:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 4264:     if ($returnhash{'version'}) {
 4265:       my %lasthash=();
 4266:       my $version;
 4267:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 4268:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
 4269:             if ($key =~ /\.rawrndseed$/) {
 4270:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
 4271:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
 4272:             } else {
 4273:                 $lasthash{$key}=$returnhash{$version.':'.$key};
 4274:             }
 4275:         }
 4276:       }
 4277:       $prevattempts=&start_data_table().&start_data_table_header_row();
 4278:       $prevattempts.='<th>'.&mt('History').'</th>';
 4279:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
 4280:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 4281:       foreach my $key (sort(keys(%lasthash))) {
 4282: 	my ($ign,@parts) = split(/\./,$key);
 4283: 	if ($#parts > 0) {
 4284: 	  my $data=$parts[-1];
 4285:           next if ($data eq 'foilorder');
 4286: 	  pop(@parts);
 4287:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 4288:           if ($data eq 'type') {
 4289:               unless ($showsurv) {
 4290:                   my $id = join(',',@parts);
 4291:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 4292:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 4293:                       $lasthidden{$ign.'.'.$id} = 1;
 4294:                   }
 4295:               }
 4296:               if ($identifier ne '') {
 4297:                   my $id = join(',',@parts);
 4298:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
 4299:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
 4300:                       $hidestatus{$ign.'.'.$id} = 1;
 4301:                   }
 4302:               }
 4303:           } elsif ($data eq 'regrader') {
 4304:               if (($identifier ne '') && (@parts)) {
 4305:                   my $id = join(',',@parts);
 4306:                   $regraded{$ign.'.'.$id} = 1;
 4307:               }
 4308:           } 
 4309: 	} else {
 4310: 	  if ($#parts == 0) {
 4311: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 4312: 	  } else {
 4313: 	    $prevattempts.='<th>'.$ign.'</th>';
 4314: 	  }
 4315: 	}
 4316:       }
 4317:       $prevattempts.=&end_data_table_header_row();
 4318:       if ($getattempt eq '') {
 4319:         my (%solved,%resets,%probstatus);
 4320:         if (($identifier ne '') && (keys(%regraded) > 0)) {
 4321:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 4322:                 foreach my $id (keys(%regraded)) {
 4323:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
 4324:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
 4325:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
 4326:                         push(@{$resets{$id}},$version);
 4327:                     }
 4328:                 }
 4329:             }
 4330:         }
 4331: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 4332:             my (@hidden,@unsolved);
 4333:             if (%typeparts) {
 4334:                 foreach my $id (keys(%typeparts)) {
 4335:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
 4336:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 4337:                         push(@hidden,$id);
 4338:                     } elsif ($identifier ne '') {
 4339:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
 4340:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
 4341:                                 ($hidestatus{$id})) {
 4342:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
 4343:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
 4344:                                 push(@{$solved{$id}},$version);
 4345:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
 4346:                                      (ref($solved{$id}) eq 'ARRAY')) {
 4347:                                 my $skip;
 4348:                                 if (ref($resets{$id}) eq 'ARRAY') {
 4349:                                     foreach my $reset (@{$resets{$id}}) {
 4350:                                         if ($reset > $solved{$id}[-1]) {
 4351:                                             $skip=1;
 4352:                                             last;
 4353:                                         }
 4354:                                     }
 4355:                                 }
 4356:                                 unless ($skip) {
 4357:                                     my ($ign,$partslist) = split(/\./,$id,2);
 4358:                                     push(@unsolved,$partslist);
 4359:                                 }
 4360:                             }
 4361:                         }
 4362:                     }
 4363:                 }
 4364:             }
 4365:             $prevattempts.=&start_data_table_row().
 4366:                            '<td>'.&mt('Transaction [_1]',$version);
 4367:             if (@unsolved) {
 4368:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
 4369:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
 4370:                                  &mt('Hide').'</label></span>';
 4371:             }
 4372:             $prevattempts .= '</td>';
 4373:             if (@hidden) {
 4374:                 foreach my $key (sort(keys(%lasthash))) {
 4375:                     next if ($key =~ /\.foilorder$/);
 4376:                     my $hide;
 4377:                     foreach my $id (@hidden) {
 4378:                         if ($key =~ /^\Q$id\E/) {
 4379:                             $hide = 1;
 4380:                             last;
 4381:                         }
 4382:                     }
 4383:                     if ($hide) {
 4384:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4385:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 4386:                             my $value = &format_previous_attempt_value($key,
 4387:                                              $returnhash{$version.':'.$key});
 4388:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4389:                         } else {
 4390:                             $prevattempts.='<td>&nbsp;</td>';
 4391:                         }
 4392:                     } else {
 4393:                         if ($key =~ /\./) {
 4394:                             my $value = $returnhash{$version.':'.$key};
 4395:                             if ($key =~ /\.rndseed$/) {
 4396:                                 my ($id) = ($key =~ /^(.+)\.rndseed$/);
 4397:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4398:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4399:                                 }
 4400:                             }
 4401:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4402:                                            '&nbsp;</td>';
 4403:                         } else {
 4404:                             $prevattempts.='<td>&nbsp;</td>';
 4405:                         }
 4406:                     }
 4407:                 }
 4408:             } else {
 4409: 	        foreach my $key (sort(keys(%lasthash))) {
 4410:                     next if ($key =~ /\.foilorder$/);
 4411:                     my $value = $returnhash{$version.':'.$key};
 4412:                     if ($key =~ /\.rndseed$/) {
 4413:                         my ($id) = ($key =~ /^(.+)\.rndseed$/);
 4414:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4415:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4416:                         }
 4417:                     }
 4418:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4419:                                    '&nbsp;</td>';
 4420: 	        }
 4421:             }
 4422: 	    $prevattempts.=&end_data_table_row();
 4423: 	 }
 4424:       }
 4425:       my @currhidden = keys(%lasthidden);
 4426:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 4427:       foreach my $key (sort(keys(%lasthash))) {
 4428:           next if ($key =~ /\.foilorder$/);
 4429:           if (%typeparts) {
 4430:               my $hidden;
 4431:               foreach my $id (@currhidden) {
 4432:                   if ($key =~ /^\Q$id\E/) {
 4433:                       $hidden = 1;
 4434:                       last;
 4435:                   }
 4436:               }
 4437:               if ($hidden) {
 4438:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4439:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 4440:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4441:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4442:                           $value = &$gradesub($value);
 4443:                       }
 4444:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4445:                   } else {
 4446:                       $prevattempts.='<td>&nbsp;</td>';
 4447:                   }
 4448:               } else {
 4449:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4450:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4451:                       $value = &$gradesub($value);
 4452:                   }
 4453:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4454:               }
 4455:           } else {
 4456: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4457: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4458:                   $value = &$gradesub($value);
 4459:               }
 4460: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4461:           }
 4462:       }
 4463:       $prevattempts.= &end_data_table_row().&end_data_table();
 4464:     } else {
 4465:       $prevattempts=
 4466: 	  &start_data_table().&start_data_table_row().
 4467: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 4468: 	  &end_data_table_row().&end_data_table();
 4469:     }
 4470:   } else {
 4471:     $prevattempts=
 4472: 	  &start_data_table().&start_data_table_row().
 4473: 	  '<td>'.&mt('No data.').'</td>'.
 4474: 	  &end_data_table_row().&end_data_table();
 4475:   }
 4476: }
 4477: 
 4478: sub format_previous_attempt_value {
 4479:     my ($key,$value) = @_;
 4480:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 4481: 	$value = &Apache::lonlocal::locallocaltime($value);
 4482:     } elsif (ref($value) eq 'ARRAY') {
 4483: 	$value = '('.join(', ', @{ $value }).')';
 4484:     } elsif ($key =~ /answerstring$/) {
 4485:         my %answers = &Apache::lonnet::str2hash($value);
 4486:         my @anskeys = sort(keys(%answers));
 4487:         if (@anskeys == 1) {
 4488:             my $answer = $answers{$anskeys[0]};
 4489:             if ($answer =~ m{\0}) {
 4490:                 $answer =~ s{\0}{,}g;
 4491:             }
 4492:             my $tag_internal_answer_name = 'INTERNAL';
 4493:             if ($anskeys[0] eq $tag_internal_answer_name) {
 4494:                 $value = $answer; 
 4495:             } else {
 4496:                 $value = $anskeys[0].'='.$answer;
 4497:             }
 4498:         } else {
 4499:             foreach my $ans (@anskeys) {
 4500:                 my $answer = $answers{$ans};
 4501:                 if ($answer =~ m{\0}) {
 4502:                     $answer =~ s{\0}{,}g;
 4503:                 }
 4504:                 $value .=  $ans.'='.$answer.'<br />';;
 4505:             } 
 4506:         }
 4507:     } else {
 4508: 	$value = &unescape($value);
 4509:     }
 4510:     return $value;
 4511: }
 4512: 
 4513: 
 4514: sub relative_to_absolute {
 4515:     my ($url,$output)=@_;
 4516:     my $parser=HTML::TokeParser->new(\$output);
 4517:     my $token;
 4518:     my $thisdir=$url;
 4519:     my @rlinks=();
 4520:     while ($token=$parser->get_token) {
 4521: 	if ($token->[0] eq 'S') {
 4522: 	    if ($token->[1] eq 'a') {
 4523: 		if ($token->[2]->{'href'}) {
 4524: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 4525: 		}
 4526: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 4527: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 4528: 	    } elsif ($token->[1] eq 'base') {
 4529: 		$thisdir=$token->[2]->{'href'};
 4530: 	    }
 4531: 	}
 4532:     }
 4533:     $thisdir=~s-/[^/]*$--;
 4534:     foreach my $link (@rlinks) {
 4535: 	unless (($link=~/^https?\:\/\//i) ||
 4536: 		($link=~/^\//) ||
 4537: 		($link=~/^javascript:/i) ||
 4538: 		($link=~/^mailto:/i) ||
 4539: 		($link=~/^\#/)) {
 4540: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 4541: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 4542: 	}
 4543:     }
 4544: # -------------------------------------------------- Deal with Applet codebases
 4545:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 4546:     return $output;
 4547: }
 4548: 
 4549: =pod
 4550: 
 4551: =item * &get_student_view()
 4552: 
 4553: show a snapshot of what student was looking at
 4554: 
 4555: =cut
 4556: 
 4557: sub get_student_view {
 4558:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 4559:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4560:   my (%form);
 4561:   my @elements=('symb','courseid','domain','username');
 4562:   foreach my $element (@elements) {
 4563:       $form{'grade_'.$element}=eval '$'.$element #'
 4564:   }
 4565:   if (defined($moreenv)) {
 4566:       %form=(%form,%{$moreenv});
 4567:   }
 4568:   if (defined($target)) { $form{'grade_target'} = $target; }
 4569:   $feedurl=&Apache::lonnet::clutter($feedurl);
 4570:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 4571:   $userview=~s/\<body[^\>]*\>//gi;
 4572:   $userview=~s/\<\/body\>//gi;
 4573:   $userview=~s/\<html\>//gi;
 4574:   $userview=~s/\<\/html\>//gi;
 4575:   $userview=~s/\<head\>//gi;
 4576:   $userview=~s/\<\/head\>//gi;
 4577:   $userview=~s/action\s*\=/would_be_action\=/gi;
 4578:   $userview=&relative_to_absolute($feedurl,$userview);
 4579:   if (wantarray) {
 4580:      return ($userview,$response);
 4581:   } else {
 4582:      return $userview;
 4583:   }
 4584: }
 4585: 
 4586: sub get_student_view_with_retries {
 4587:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 4588: 
 4589:     my $ok = 0;                 # True if we got a good response.
 4590:     my $content;
 4591:     my $response;
 4592: 
 4593:     # Try to get the student_view done. within the retries count:
 4594:     
 4595:     do {
 4596:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 4597:          $ok      = $response->is_success;
 4598:          if (!$ok) {
 4599:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 4600:          }
 4601:          $retries--;
 4602:     } while (!$ok && ($retries > 0));
 4603:     
 4604:     if (!$ok) {
 4605:        $content = '';          # On error return an empty content.
 4606:     }
 4607:     if (wantarray) {
 4608:        return ($content, $response);
 4609:     } else {
 4610:        return $content;
 4611:     }
 4612: }
 4613: 
 4614: sub css_links {
 4615:     my ($currsymb,$level) = @_;
 4616:     my ($links,@symbs,%cssrefs,%httpref);
 4617:     if ($level eq 'map') {
 4618:         my $navmap = Apache::lonnavmaps::navmap->new();
 4619:         if (ref($navmap)) {
 4620:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
 4621:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
 4622:             foreach my $res (@resources) {
 4623:                 if (ref($res) && $res->symb()) {
 4624:                     push(@symbs,$res->symb());
 4625:                 }
 4626:             }
 4627:         }
 4628:     } else {
 4629:         @symbs = ($currsymb);
 4630:     }
 4631:     foreach my $symb (@symbs) {
 4632:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
 4633:         if ($css_href =~ /\S/) {
 4634:             unless ($css_href =~ m{https?://}) {
 4635:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
 4636:                 my $proburl =  &Apache::lonnet::clutter($url);
 4637:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
 4638:                 unless ($css_href =~ m{^/}) {
 4639:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
 4640:                 }
 4641:                 if ($css_href =~ m{^/(res|uploaded)/}) {
 4642:                     unless (($httpref{'httpref.'.$css_href}) ||
 4643:                             (&Apache::lonnet::is_on_map($css_href))) {
 4644:                         my $thisurl = $proburl;
 4645:                         if ($env{'httpref.'.$proburl}) {
 4646:                             $thisurl = $env{'httpref.'.$proburl};
 4647:                         }
 4648:                         $httpref{'httpref.'.$css_href} = $thisurl;
 4649:                     }
 4650:                 }
 4651:             }
 4652:             $cssrefs{$css_href} = 1;
 4653:         }
 4654:     }
 4655:     if (keys(%httpref)) {
 4656:         &Apache::lonnet::appenv(\%httpref);
 4657:     }
 4658:     if (keys(%cssrefs)) {
 4659:         foreach my $css_href (keys(%cssrefs)) {
 4660:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
 4661:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
 4662:         }
 4663:     }
 4664:     return $links;
 4665: }
 4666: 
 4667: =pod
 4668: 
 4669: =item * &get_student_answers() 
 4670: 
 4671: show a snapshot of how student was answering problem
 4672: 
 4673: =cut
 4674: 
 4675: sub get_student_answers {
 4676:   my ($symb,$username,$domain,$courseid,%form) = @_;
 4677:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4678:   my (%moreenv);
 4679:   my @elements=('symb','courseid','domain','username');
 4680:   foreach my $element (@elements) {
 4681:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 4682:   }
 4683:   $moreenv{'grade_target'}='answer';
 4684:   %moreenv=(%form,%moreenv);
 4685:   $feedurl = &Apache::lonnet::clutter($feedurl);
 4686:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 4687:   return $userview;
 4688: }
 4689: 
 4690: =pod
 4691: 
 4692: =item * &submlink()
 4693: 
 4694: Inputs: $text $uname $udom $symb $target
 4695: 
 4696: Returns: A link to grades.pm such as to see the SUBM view of a student
 4697: 
 4698: =cut
 4699: 
 4700: ###############################################
 4701: sub submlink {
 4702:     my ($text,$uname,$udom,$symb,$target)=@_;
 4703:     if (!($uname && $udom)) {
 4704: 	(my $cursymb, my $courseid,$udom,$uname)=
 4705: 	    &Apache::lonnet::whichuser($symb);
 4706: 	if (!$symb) { $symb=$cursymb; }
 4707:     }
 4708:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4709:     $symb=&escape($symb);
 4710:     if ($target) { $target=" target=\"$target\""; }
 4711:     return
 4712:         '<a href="/adm/grades?command=submission'.
 4713:         '&amp;symb='.$symb.
 4714:         '&amp;student='.$uname.
 4715:         '&amp;userdom='.$udom.'"'.
 4716:         $target.'>'.$text.'</a>';
 4717: }
 4718: ##############################################
 4719: 
 4720: =pod
 4721: 
 4722: =item * &pgrdlink()
 4723: 
 4724: Inputs: $text $uname $udom $symb $target
 4725: 
 4726: Returns: A link to grades.pm such as to see the PGRD view of a student
 4727: 
 4728: =cut
 4729: 
 4730: ###############################################
 4731: sub pgrdlink {
 4732:     my $link=&submlink(@_);
 4733:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 4734:     return $link;
 4735: }
 4736: ##############################################
 4737: 
 4738: =pod
 4739: 
 4740: =item * &pprmlink()
 4741: 
 4742: Inputs: $text $uname $udom $symb $target
 4743: 
 4744: Returns: A link to parmset.pm such as to see the PPRM view of a
 4745: student and a specific resource
 4746: 
 4747: =cut
 4748: 
 4749: ###############################################
 4750: sub pprmlink {
 4751:     my ($text,$uname,$udom,$symb,$target)=@_;
 4752:     if (!($uname && $udom)) {
 4753: 	(my $cursymb, my $courseid,$udom,$uname)=
 4754: 	    &Apache::lonnet::whichuser($symb);
 4755: 	if (!$symb) { $symb=$cursymb; }
 4756:     }
 4757:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4758:     $symb=&escape($symb);
 4759:     if ($target) { $target="target=\"$target\""; }
 4760:     return '<a href="/adm/parmset?command=set&amp;'.
 4761: 	'symb='.$symb.'&amp;uname='.$uname.
 4762: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 4763: }
 4764: ##############################################
 4765: 
 4766: =pod
 4767: 
 4768: =back
 4769: 
 4770: =cut
 4771: 
 4772: ###############################################
 4773: 
 4774: 
 4775: sub timehash {
 4776:     my ($thistime) = @_;
 4777:     my $timezone = &Apache::lonlocal::gettimezone();
 4778:     my $dt = DateTime->from_epoch(epoch => $thistime)
 4779:                      ->set_time_zone($timezone);
 4780:     my $wday = $dt->day_of_week();
 4781:     if ($wday == 7) { $wday = 0; }
 4782:     return ( 'second' => $dt->second(),
 4783:              'minute' => $dt->minute(),
 4784:              'hour'   => $dt->hour(),
 4785:              'day'     => $dt->day_of_month(),
 4786:              'month'   => $dt->month(),
 4787:              'year'    => $dt->year(),
 4788:              'weekday' => $wday,
 4789:              'dayyear' => $dt->day_of_year(),
 4790:              'dlsav'   => $dt->is_dst() );
 4791: }
 4792: 
 4793: sub utc_string {
 4794:     my ($date)=@_;
 4795:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 4796: }
 4797: 
 4798: sub maketime {
 4799:     my %th=@_;
 4800:     my ($epoch_time,$timezone,$dt);
 4801:     $timezone = &Apache::lonlocal::gettimezone();
 4802:     eval {
 4803:         $dt = DateTime->new( year   => $th{'year'},
 4804:                              month  => $th{'month'},
 4805:                              day    => $th{'day'},
 4806:                              hour   => $th{'hour'},
 4807:                              minute => $th{'minute'},
 4808:                              second => $th{'second'},
 4809:                              time_zone => $timezone,
 4810:                          );
 4811:     };
 4812:     if (!$@) {
 4813:         $epoch_time = $dt->epoch;
 4814:         if ($epoch_time) {
 4815:             return $epoch_time;
 4816:         }
 4817:     }
 4818:     return POSIX::mktime(
 4819:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 4820:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 4821: }
 4822: 
 4823: #########################################
 4824: 
 4825: sub findallcourses {
 4826:     my ($roles,$uname,$udom) = @_;
 4827:     my %roles;
 4828:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 4829:     my %courses;
 4830:     my $now=time;
 4831:     if (!defined($uname)) {
 4832:         $uname = $env{'user.name'};
 4833:     }
 4834:     if (!defined($udom)) {
 4835:         $udom = $env{'user.domain'};
 4836:     }
 4837:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 4838:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 4839:         if (!%roles) {
 4840:             %roles = (
 4841:                        cc => 1,
 4842:                        co => 1,
 4843:                        in => 1,
 4844:                        ep => 1,
 4845:                        ta => 1,
 4846:                        cr => 1,
 4847:                        st => 1,
 4848:              );
 4849:         }
 4850:         foreach my $entry (keys(%roleshash)) {
 4851:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 4852:             if ($trole =~ /^cr/) { 
 4853:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 4854:             } else {
 4855:                 next if (!exists($roles{$trole}));
 4856:             }
 4857:             if ($tend) {
 4858:                 next if ($tend < $now);
 4859:             }
 4860:             if ($tstart) {
 4861:                 next if ($tstart > $now);
 4862:             }
 4863:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 4864:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 4865:             my $value = $trole.'/'.$cdom.'/';
 4866:             if ($secpart eq '') {
 4867:                 ($cnum,$role) = split(/_/,$cnumpart); 
 4868:                 $sec = 'none';
 4869:                 $value .= $cnum.'/';
 4870:             } else {
 4871:                 $cnum = $cnumpart;
 4872:                 ($sec,$role) = split(/_/,$secpart);
 4873:                 $value .= $cnum.'/'.$sec;
 4874:             }
 4875:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4876:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4877:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4878:                 }
 4879:             } else {
 4880:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4881:             }
 4882:         }
 4883:     } else {
 4884:         foreach my $key (keys(%env)) {
 4885: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 4886:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 4887: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 4888: 	        next if ($role eq 'ca' || $role eq 'aa');
 4889: 	        next if (%roles && !exists($roles{$role}));
 4890: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 4891:                 my $active=1;
 4892:                 if ($starttime) {
 4893: 		    if ($now<$starttime) { $active=0; }
 4894:                 }
 4895:                 if ($endtime) {
 4896:                     if ($now>$endtime) { $active=0; }
 4897:                 }
 4898:                 if ($active) {
 4899:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 4900:                     if ($sec eq '') {
 4901:                         $sec = 'none';
 4902:                     } else {
 4903:                         $value .= $sec;
 4904:                     }
 4905:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4906:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4907:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4908:                         }
 4909:                     } else {
 4910:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4911:                     }
 4912:                 }
 4913:             }
 4914:         }
 4915:     }
 4916:     return %courses;
 4917: }
 4918: 
 4919: ###############################################
 4920: 
 4921: sub blockcheck {
 4922:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
 4923: 
 4924:     unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
 4925:         my ($has_evb,$check_ipaccess);
 4926:         my $dom = $env{'user.domain'};
 4927:         if ($env{'request.course.id'}) {
 4928:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4929:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4930:             my $checkrole = "cm./$cdom/$cnum";
 4931:             my $sec = $env{'request.course.sec'};
 4932:             if ($sec ne '') {
 4933:                 $checkrole .= "/$sec";
 4934:             }
 4935:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 4936:                 ($env{'request.role'} !~ /^st/)) {
 4937:                 $has_evb = 1;
 4938:             }
 4939:             unless ($has_evb) {
 4940:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
 4941:                     ($activity eq 'boards') || ($activity eq 'groups') || ($activity eq 'chat')) {
 4942:                     if ($udom eq $cdom) {
 4943:                         $check_ipaccess = 1;
 4944:                     }
 4945:                 }
 4946:             }
 4947:         } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
 4948:                 ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
 4949:             my $checkrole;
 4950:             if ($env{'request.role.domain'} eq '') {
 4951:                 $checkrole = "cm./$env{'user.domain'}/";
 4952:             } else {
 4953:                 $checkrole = "cm./$env{'request.role.domain'}/";
 4954:             }
 4955:             if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
 4956:                 $has_evb = 1;
 4957:             }
 4958:         }
 4959:         unless ($has_evb || $check_ipaccess) {
 4960:             my @machinedoms = &Apache::lonnet::current_machine_domains();
 4961:             if (($dom eq 'public') && ($activity eq 'port')) {
 4962:                 $dom = $udom;
 4963:             }
 4964:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
 4965:                 $check_ipaccess = 1;
 4966:             } else {
 4967:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 4968:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
 4969:                 my $prim = &Apache::lonnet::domain($dom,'primary');
 4970:                 my $intdom = &Apache::lonnet::internet_dom($prim);
 4971:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
 4972:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
 4973:                         $check_ipaccess = 1;
 4974:                     }
 4975:                 }
 4976:             }
 4977:         }
 4978:         if ($check_ipaccess) {
 4979:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
 4980:             unless (defined($cached)) {
 4981:                 my %domconfig =
 4982:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
 4983:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
 4984:             }
 4985:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
 4986:                 foreach my $id (keys(%{$ipaccessref})) {
 4987:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
 4988:                         my $range = $ipaccessref->{$id}->{'ip'};
 4989:                         if ($range) {
 4990:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
 4991:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
 4992:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
 4993:                                         return ('','','',$id,$dom);
 4994:                                         last;
 4995:                                     }
 4996:                                 }
 4997:                             }
 4998:                         }
 4999:                     }
 5000:                 }
 5001:             }
 5002:         }
 5003:         if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
 5004:             return ();
 5005:         }
 5006:     }
 5007:     if (defined($udom) && defined($uname)) {
 5008:         # If uname and udom are for a course, check for blocks in the course.
 5009:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
 5010:             my ($startblock,$endblock,$triggerblock) =
 5011:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
 5012:             return ($startblock,$endblock,$triggerblock);
 5013:         }
 5014:     } else {
 5015:         $udom = $env{'user.domain'};
 5016:         $uname = $env{'user.name'};
 5017:     }
 5018: 
 5019:     my $startblock = 0;
 5020:     my $endblock = 0;
 5021:     my $triggerblock = '';
 5022:     my %live_courses;
 5023:     unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
 5024:         %live_courses = &findallcourses(undef,$uname,$udom);
 5025:     }
 5026: 
 5027:     # If uname is for a user, and activity is course-specific, i.e.,
 5028:     # boards, chat or groups, check for blocking in current course only.
 5029: 
 5030:     if (($activity eq 'boards' || $activity eq 'chat' ||
 5031:          $activity eq 'groups' || $activity eq 'printout' ||
 5032:          $activity eq 'search' || $activity eq 'reinit' ||
 5033:          $activity eq 'alert') && ($env{'request.course.id'})) {
 5034:         foreach my $key (keys(%live_courses)) {
 5035:             if ($key ne $env{'request.course.id'}) {
 5036:                 delete($live_courses{$key});
 5037:             }
 5038:         }
 5039:     }
 5040: 
 5041:     my $otheruser = 0;
 5042:     my %own_courses;
 5043:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 5044:         # Resource belongs to user other than current user.
 5045:         $otheruser = 1;
 5046:         # Gather courses for current user
 5047:         %own_courses = 
 5048:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 5049:     }
 5050: 
 5051:     # Gather active course roles - course coordinator, instructor, 
 5052:     # exam proctor, ta, student, or custom role.
 5053: 
 5054:     foreach my $course (keys(%live_courses)) {
 5055:         my ($cdom,$cnum);
 5056:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 5057:             $cdom = $env{'course.'.$course.'.domain'};
 5058:             $cnum = $env{'course.'.$course.'.num'};
 5059:         } else {
 5060:             ($cdom,$cnum) = split(/_/,$course); 
 5061:         }
 5062:         my $no_ownblock = 0;
 5063:         my $no_userblock = 0;
 5064:         if ($otheruser && $activity ne 'com') {
 5065:             # Check if current user has 'evb' priv for this
 5066:             if (defined($own_courses{$course})) {
 5067:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 5068:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5069:                     if ($sec ne 'none') {
 5070:                         $checkrole .= '/'.$sec;
 5071:                     }
 5072:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5073:                         $no_ownblock = 1;
 5074:                         last;
 5075:                     }
 5076:                 }
 5077:             }
 5078:             # if they have 'evb' priv and are currently not playing student
 5079:             next if (($no_ownblock) &&
 5080:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 5081:         }
 5082:         foreach my $sec (keys(%{$live_courses{$course}})) {
 5083:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5084:             if ($sec ne 'none') {
 5085:                 $checkrole .= '/'.$sec;
 5086:             }
 5087:             if ($otheruser) {
 5088:                 # Resource belongs to user other than current user.
 5089:                 # Assemble privs for that user, and check for 'evb' priv.
 5090:                 my (%allroles,%userroles);
 5091:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 5092:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 5093:                         my ($trole,$tdom,$tnum,$tsec);
 5094:                         if ($entry =~ /^cr/) {
 5095:                             ($trole,$tdom,$tnum,$tsec) = 
 5096:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 5097:                         } else {
 5098:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 5099:                         }
 5100:                         my ($spec,$area,$trest);
 5101:                         $area = '/'.$tdom.'/'.$tnum;
 5102:                         $trest = $tnum;
 5103:                         if ($tsec ne '') {
 5104:                             $area .= '/'.$tsec;
 5105:                             $trest .= '/'.$tsec;
 5106:                         }
 5107:                         $spec = $trole.'.'.$area;
 5108:                         if ($trole =~ /^cr/) {
 5109:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 5110:                                                               $tdom,$spec,$trest,$area);
 5111:                         } else {
 5112:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 5113:                                                                 $tdom,$spec,$trest,$area);
 5114:                         }
 5115:                     }
 5116:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 5117:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 5118:                         if ($1) {
 5119:                             $no_userblock = 1;
 5120:                             last;
 5121:                         }
 5122:                     }
 5123:                 }
 5124:             } else {
 5125:                 # Resource belongs to current user
 5126:                 # Check for 'evb' priv via lonnet::allowed().
 5127:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5128:                     $no_ownblock = 1;
 5129:                     last;
 5130:                 }
 5131:             }
 5132:         }
 5133:         # if they have the evb priv and are currently not playing student
 5134:         next if (($no_ownblock) &&
 5135:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 5136:         next if ($no_userblock);
 5137: 
 5138:         # Retrieve blocking times and identity of blocker for course
 5139:         # of specified user, unless user has 'evb' privilege.
 5140:         
 5141:         my ($start,$end,$trigger) = 
 5142:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
 5143:         if (($start != 0) && 
 5144:             (($startblock == 0) || ($startblock > $start))) {
 5145:             $startblock = $start;
 5146:             if ($trigger ne '') {
 5147:                 $triggerblock = $trigger;
 5148:             }
 5149:         }
 5150:         if (($end != 0)  &&
 5151:             (($endblock == 0) || ($endblock < $end))) {
 5152:             $endblock = $end;
 5153:             if ($trigger ne '') {
 5154:                 $triggerblock = $trigger;
 5155:             }
 5156:         }
 5157:     }
 5158:     return ($startblock,$endblock,$triggerblock);
 5159: }
 5160: 
 5161: sub get_blocks {
 5162:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
 5163:     my $startblock = 0;
 5164:     my $endblock = 0;
 5165:     my $triggerblock = '';
 5166:     my $course = $cdom.'_'.$cnum;
 5167:     $setters->{$course} = {};
 5168:     $setters->{$course}{'staff'} = [];
 5169:     $setters->{$course}{'times'} = [];
 5170:     $setters->{$course}{'triggers'} = [];
 5171:     my (@blockers,%triggered);
 5172:     my $now = time;
 5173:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 5174:     if ($activity eq 'docs') {
 5175:         my ($blocked,$nosymbcache,$noenccheck);
 5176:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
 5177:             $blocked = 1;
 5178:             $nosymbcache = 1;
 5179:             $noenccheck = 1;
 5180:         }
 5181:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
 5182:         foreach my $block (@blockers) {
 5183:             if ($block =~ /^firstaccess____(.+)$/) {
 5184:                 my $item = $1;
 5185:                 my $type = 'map';
 5186:                 my $timersymb = $item;
 5187:                 if ($item eq 'course') {
 5188:                     $type = 'course';
 5189:                 } elsif ($item =~ /___\d+___/) {
 5190:                     $type = 'resource';
 5191:                 } else {
 5192:                     $timersymb = &Apache::lonnet::symbread($item);
 5193:                 }
 5194:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5195:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 5196:                 $triggered{$block} = {
 5197:                                        start => $start,
 5198:                                        end   => $end,
 5199:                                        type  => $type,
 5200:                                      };
 5201:             }
 5202:         }
 5203:     } else {
 5204:         foreach my $block (keys(%commblocks)) {
 5205:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 5206:                 my ($start,$end) = ($1,$2);
 5207:                 if ($start <= time && $end >= time) {
 5208:                     if (ref($commblocks{$block}) eq 'HASH') {
 5209:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5210:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5211:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 5212:                                     push(@blockers,$block);
 5213:                                 }
 5214:                             }
 5215:                         }
 5216:                     }
 5217:                 }
 5218:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 5219:                 my $item = $1;
 5220:                 my $timersymb = $item; 
 5221:                 my $type = 'map';
 5222:                 if ($item eq 'course') {
 5223:                     $type = 'course';
 5224:                 } elsif ($item =~ /___\d+___/) {
 5225:                     $type = 'resource';
 5226:                 } else {
 5227:                     $timersymb = &Apache::lonnet::symbread($item);
 5228:                 }
 5229:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5230:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 5231:                 if ($start && $end) {
 5232:                     if (($start <= time) && ($end >= time)) {
 5233:                         if (ref($commblocks{$block}) eq 'HASH') {
 5234:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5235:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5236:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
 5237:                                         push(@blockers,$block);
 5238:                                         $triggered{$block} = {
 5239:                                                                start => $start,
 5240:                                                                end   => $end,
 5241:                                                                type  => $type,
 5242:                                                              };
 5243:                                     }
 5244:                                 }
 5245:                             }
 5246:                         }
 5247:                     }
 5248:                 }
 5249:             }
 5250:         }
 5251:     }
 5252:     foreach my $blocker (@blockers) {
 5253:         my ($staff_name,$staff_dom,$title,$blocks) =
 5254:             &parse_block_record($commblocks{$blocker});
 5255:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 5256:         my ($start,$end,$triggertype);
 5257:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 5258:             ($start,$end) = ($1,$2);
 5259:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 5260:             $start = $triggered{$blocker}{'start'};
 5261:             $end = $triggered{$blocker}{'end'};
 5262:             $triggertype = $triggered{$blocker}{'type'};
 5263:         }
 5264:         if ($start) {
 5265:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 5266:             if ($triggertype) {
 5267:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 5268:             } else {
 5269:                 push(@{$$setters{$course}{'triggers'}},0);
 5270:             }
 5271:             if ( ($startblock == 0) || ($startblock > $start) ) {
 5272:                 $startblock = $start;
 5273:                 if ($triggertype) {
 5274:                     $triggerblock = $blocker;
 5275:                 }
 5276:             }
 5277:             if ( ($endblock == 0) || ($endblock < $end) ) {
 5278:                $endblock = $end;
 5279:                if ($triggertype) {
 5280:                    $triggerblock = $blocker;
 5281:                }
 5282:             }
 5283:         }
 5284:     }
 5285:     return ($startblock,$endblock,$triggerblock);
 5286: }
 5287: 
 5288: sub parse_block_record {
 5289:     my ($record) = @_;
 5290:     my ($setuname,$setudom,$title,$blocks);
 5291:     if (ref($record) eq 'HASH') {
 5292:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 5293:         $title = &unescape($record->{'event'});
 5294:         $blocks = $record->{'blocks'};
 5295:     } else {
 5296:         my @data = split(/:/,$record,3);
 5297:         if (scalar(@data) eq 2) {
 5298:             $title = $data[1];
 5299:             ($setuname,$setudom) = split(/@/,$data[0]);
 5300:         } else {
 5301:             ($setuname,$setudom,$title) = @data;
 5302:         }
 5303:         $blocks = { 'com' => 'on' };
 5304:     }
 5305:     return ($setuname,$setudom,$title,$blocks);
 5306: }
 5307: 
 5308: sub blocking_status {
 5309:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
 5310:     my %setters;
 5311: 
 5312: # check for active blocking
 5313:     if ($clientip eq '') {
 5314:         $clientip = &Apache::lonnet::get_requestor_ip();
 5315:     }
 5316:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
 5317:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
 5318:     my $blocked = 0;
 5319:     if (($startblock && $endblock) || ($by_ip)) {
 5320:         $blocked = 1;
 5321:     }
 5322: 
 5323: # caller just wants to know whether a block is active
 5324:     if (!wantarray) { return $blocked; }
 5325: 
 5326: # build a link to a popup window containing the details
 5327:     my $querystring  = "?activity=$activity";
 5328: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
 5329:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
 5330:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/);
 5331:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
 5332:     } elsif ($activity eq 'docs') {
 5333:         my $showurl = &Apache::lonenc::check_encrypt($url);
 5334:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
 5335:         if ($symb) {
 5336:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
 5337:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
 5338:         }
 5339:     }
 5340: 
 5341:     my $output .= <<'END_MYBLOCK';
 5342: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 5343:     var options = "width=" + w + ",height=" + h + ",";
 5344:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 5345:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 5346:     var newWin = window.open(url, wdwName, options);
 5347:     newWin.focus();
 5348: }
 5349: END_MYBLOCK
 5350: 
 5351:     $output = Apache::lonhtmlcommon::scripttag($output);
 5352:   
 5353:     my $popupUrl = "/adm/blockingstatus/$querystring";
 5354:     my $text = &mt('Communication Blocked');
 5355:     my $class = 'LC_comblock';
 5356:     if ($activity eq 'docs') {
 5357:         $text = &mt('Content Access Blocked');
 5358:         $class = '';
 5359:     } elsif ($activity eq 'printout') {
 5360:         $text = &mt('Printing Blocked');
 5361:     } elsif ($activity eq 'passwd') {
 5362:         $text = &mt('Password Changing Blocked');
 5363:     } elsif ($activity eq 'grades') {
 5364:         $text = &mt('Gradebook Blocked');
 5365:     } elsif ($activity eq 'search') {
 5366:         $text = &mt('Search Blocked');
 5367:     } elsif ($activity eq 'alert') {
 5368:         $text = &mt('Checking Critical Messages Blocked');
 5369:     } elsif ($activity eq 'reinit') {
 5370:         $text = &mt('Checking Course Update Blocked');
 5371:     } elsif ($activity eq 'about') {
 5372:         $text = &mt('Access to User Information Pages Blocked');
 5373:     } elsif ($activity eq 'wishlist') {
 5374:         $text = &mt('Access to Stored Links Blocked');
 5375:     } elsif ($activity eq 'annotate') {
 5376:         $text = &mt('Access to Annotations Blocked');
 5377:     }
 5378:     $output .= <<"END_BLOCK";
 5379: <div class='$class'>
 5380:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 5381:   title='$text'>
 5382:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 5383:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 5384:   title='$text'>$text</a>
 5385: </div>
 5386: 
 5387: END_BLOCK
 5388: 
 5389:     return ($blocked, $output);
 5390: }
 5391: 
 5392: ###############################################
 5393: 
 5394: sub check_ip_acc {
 5395:     my ($acc,$clientip)=@_;
 5396:     &Apache::lonxml::debug("acc is $acc");
 5397:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 5398:         return 1;
 5399:     }
 5400:     my $allowed=0;
 5401:     my $ip;
 5402:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
 5403:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
 5404:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
 5405:     } else {
 5406:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
 5407:         $ip = $remote_ip || $env{'request.host'} || $clientip;
 5408:     }
 5409: 
 5410:     my $name;
 5411:     my %access = (
 5412:                      allowfrom => 1,
 5413:                      denyfrom  => 0,
 5414:                  );
 5415:     my @allows;
 5416:     my @denies;
 5417:     foreach my $item (split(',',$acc)) {
 5418:         $item =~ s/^\s*//;
 5419:         $item =~ s/\s*$//;
 5420:         if ($item =~ /^\!(.+)$/) {
 5421:             push(@denies,$1);
 5422:         } else {
 5423:             push(@allows,$item);
 5424:         }
 5425:     }
 5426:     my $numdenies = scalar(@denies);
 5427:     my $numallows = scalar(@allows);
 5428:     my $count = 0;
 5429:     foreach my $pattern (@denies,@allows) {
 5430:         $count ++;
 5431:         my $acctype = 'allowfrom';
 5432:         if ($count <= $numdenies) {
 5433:             $acctype = 'denyfrom';
 5434:         }
 5435:         if ($pattern =~ /\*$/) {
 5436:             #35.8.*
 5437:             $pattern=~s/\*//;
 5438:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 5439:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 5440:             #35.8.3.[34-56]
 5441:             my $low=$2;
 5442:             my $high=$3;
 5443:             $pattern=$1;
 5444:             if ($ip =~ /^\Q$pattern\E/) {
 5445:                 my $last=(split(/\./,$ip))[3];
 5446:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
 5447:             }
 5448:         } elsif ($pattern =~ /^\*/) {
 5449:             #*.msu.edu
 5450:             $pattern=~s/\*//;
 5451:             if (!defined($name)) {
 5452:                 use Socket;
 5453:                 my $netaddr=inet_aton($ip);
 5454:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5455:             }
 5456:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5457:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 5458:             #127.0.0.1
 5459:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 5460:         } else {
 5461:             #some.name.com
 5462:             if (!defined($name)) {
 5463:                 use Socket;
 5464:                 my $netaddr=inet_aton($ip);
 5465:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5466:             }
 5467:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5468:         }
 5469:         if ($allowed =~ /^(0|1)$/) { last; }
 5470:     }
 5471:     if ($allowed eq '') {
 5472:         if ($numdenies && !$numallows) {
 5473:             $allowed = 1;
 5474:         } else {
 5475:             $allowed = 0;
 5476:         }
 5477:     }
 5478:     return $allowed;
 5479: }
 5480: 
 5481: ###############################################
 5482: 
 5483: =pod
 5484: 
 5485: =head1 Domain Template Functions
 5486: 
 5487: =over 4
 5488: 
 5489: =item * &determinedomain()
 5490: 
 5491: Inputs: $domain (usually will be undef)
 5492: 
 5493: Returns: Determines which domain should be used for designs
 5494: 
 5495: =cut
 5496: 
 5497: ###############################################
 5498: sub determinedomain {
 5499:     my $domain=shift;
 5500:     if (! $domain) {
 5501:         # Determine domain if we have not been given one
 5502:         $domain = &Apache::lonnet::default_login_domain();
 5503:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 5504:         if ($env{'request.role.domain'}) { 
 5505:             $domain=$env{'request.role.domain'}; 
 5506:         }
 5507:     }
 5508:     return $domain;
 5509: }
 5510: ###############################################
 5511: 
 5512: sub devalidate_domconfig_cache {
 5513:     my ($udom)=@_;
 5514:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 5515: }
 5516: 
 5517: # ---------------------- Get domain configuration for a domain
 5518: sub get_domainconf {
 5519:     my ($udom) = @_;
 5520:     my $cachetime=1800;
 5521:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 5522:     if (defined($cached)) { return %{$result}; }
 5523: 
 5524:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 5525: 					     ['login','rolecolors','autoenroll'],$udom);
 5526:     my (%designhash,%legacy);
 5527:     if (keys(%domconfig) > 0) {
 5528:         if (ref($domconfig{'login'}) eq 'HASH') {
 5529:             if (keys(%{$domconfig{'login'}})) {
 5530:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 5531:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5532:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
 5533:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5534:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
 5535:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
 5536:                                         if ($key eq 'loginvia') {
 5537:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 5538:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 5539:                                                 $designhash{$udom.'.login.loginvia'} = $server;
 5540:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 5541:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 5542:                                                 } else {
 5543:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 5544:                                                 }
 5545:                                             }
 5546:                                         } elsif ($key eq 'headtag') {
 5547:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
 5548:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
 5549:                                             }
 5550:                                         }
 5551:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
 5552:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
 5553:                                         }
 5554:                                     }
 5555:                                 }
 5556:                             }
 5557:                         } elsif ($key eq 'saml') {
 5558:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5559:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
 5560:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
 5561:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
 5562:                                         foreach my $item ('text','img','alt','url','title','window','notsso') {
 5563:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
 5564:                                         }
 5565:                                     }
 5566:                                 }
 5567:                             }
 5568:                         } else {
 5569:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 5570:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 5571:                                     $domconfig{'login'}{$key}{$img};
 5572:                             }
 5573:                         }
 5574:                     } else {
 5575:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 5576:                     }
 5577:                 }
 5578:             } else {
 5579:                 $legacy{'login'} = 1;
 5580:             }
 5581:         } else {
 5582:             $legacy{'login'} = 1;
 5583:         }
 5584:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 5585:             if (keys(%{$domconfig{'rolecolors'}})) {
 5586:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 5587:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 5588:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 5589:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 5590:                         }
 5591:                     }
 5592:                 }
 5593:             } else {
 5594:                 $legacy{'rolecolors'} = 1;
 5595:             }
 5596:         } else {
 5597:             $legacy{'rolecolors'} = 1;
 5598:         }
 5599:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5600:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 5601:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 5602:             }
 5603:         }
 5604:         if (keys(%legacy) > 0) {
 5605:             my %legacyhash = &get_legacy_domconf($udom);
 5606:             foreach my $item (keys(%legacyhash)) {
 5607:                 if ($item =~ /^\Q$udom\E\.login/) {
 5608:                     if ($legacy{'login'}) { 
 5609:                         $designhash{$item} = $legacyhash{$item};
 5610:                     }
 5611:                 } else {
 5612:                     if ($legacy{'rolecolors'}) {
 5613:                         $designhash{$item} = $legacyhash{$item};
 5614:                     }
 5615:                 }
 5616:             }
 5617:         }
 5618:     } else {
 5619:         %designhash = &get_legacy_domconf($udom); 
 5620:     }
 5621:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 5622: 				  $cachetime);
 5623:     return %designhash;
 5624: }
 5625: 
 5626: sub get_legacy_domconf {
 5627:     my ($udom) = @_;
 5628:     my %legacyhash;
 5629:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 5630:     my $designfile =  $designdir.'/'.$udom.'.tab';
 5631:     if (-e $designfile) {
 5632:         if ( open (my $fh,'<',$designfile) ) {
 5633:             while (my $line = <$fh>) {
 5634:                 next if ($line =~ /^\#/);
 5635:                 chomp($line);
 5636:                 my ($key,$val)=(split(/\=/,$line));
 5637:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 5638:             }
 5639:             close($fh);
 5640:         }
 5641:     }
 5642:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 5643:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 5644:     }
 5645:     return %legacyhash;
 5646: }
 5647: 
 5648: =pod
 5649: 
 5650: =item * &domainlogo()
 5651: 
 5652: Inputs: $domain (usually will be undef)
 5653: 
 5654: Returns: A link to a domain logo, if the domain logo exists.
 5655: If the domain logo does not exist, a description of the domain.
 5656: 
 5657: =cut
 5658: 
 5659: ###############################################
 5660: sub domainlogo {
 5661:     my $domain = &determinedomain(shift);
 5662:     my %designhash = &get_domainconf($domain);    
 5663:     # See if there is a logo
 5664:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 5665:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 5666:         if ($imgsrc =~ m{^/(adm|res)/}) {
 5667: 	    if ($imgsrc =~ m{^/res/}) {
 5668: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 5669: 		&Apache::lonnet::repcopy($local_name);
 5670: 	    }
 5671: 	   $imgsrc = &lonhttpdurl($imgsrc);
 5672:         }
 5673:         my $alttext = $domain;
 5674:         if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
 5675:             $alttext = $designhash{$domain.'.login.alttext_domlogo'};
 5676:         }
 5677:         return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
 5678:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 5679:         return &Apache::lonnet::domain($domain,'description');
 5680:     } else {
 5681:         return '';
 5682:     }
 5683: }
 5684: ##############################################
 5685: 
 5686: =pod
 5687: 
 5688: =item * &designparm()
 5689: 
 5690: Inputs: $which parameter; $domain (usually will be undef)
 5691: 
 5692: Returns: value of designparamter $which
 5693: 
 5694: =cut
 5695: 
 5696: 
 5697: ##############################################
 5698: sub designparm {
 5699:     my ($which,$domain)=@_;
 5700:     if (exists($env{'environment.color.'.$which})) {
 5701:         return $env{'environment.color.'.$which};
 5702:     }
 5703:     $domain=&determinedomain($domain);
 5704:     my %domdesign;
 5705:     unless ($domain eq 'public') {
 5706:         %domdesign = &get_domainconf($domain);
 5707:     }
 5708:     my $output;
 5709:     if ($domdesign{$domain.'.'.$which} ne '') {
 5710:         $output = $domdesign{$domain.'.'.$which};
 5711:     } else {
 5712:         $output = $defaultdesign{$which};
 5713:     }
 5714:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 5715:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 5716:         if ($output =~ m{^/(adm|res)/}) {
 5717:             if ($output =~ m{^/res/}) {
 5718:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 5719:                 &Apache::lonnet::repcopy($local_name);
 5720:             }
 5721:             $output = &lonhttpdurl($output);
 5722:         }
 5723:     }
 5724:     return $output;
 5725: }
 5726: 
 5727: ##############################################
 5728: =pod
 5729: 
 5730: =item * &authorspace()
 5731: 
 5732: Inputs: $url (usually will be undef).
 5733: 
 5734: Returns: Path to Authoring Space containing the resource or 
 5735:          directory being viewed (or for which action is being taken). 
 5736:          If $url is provided, and begins /priv/<domain>/<uname>
 5737:          the path will be that portion of the $context argument.
 5738:          Otherwise the path will be for the author space of the current
 5739:          user when the current role is author, or for that of the 
 5740:          co-author/assistant co-author space when the current role 
 5741:          is co-author or assistant co-author.
 5742: 
 5743: =cut
 5744: 
 5745: sub authorspace {
 5746:     my ($url) = @_;
 5747:     if ($url ne '') {
 5748:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 5749:            return $1;
 5750:         }
 5751:     }
 5752:     my $caname = '';
 5753:     my $cadom = '';
 5754:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 5755:         ($cadom,$caname) =
 5756:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 5757:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 5758:         $caname = $env{'user.name'};
 5759:         $cadom = $env{'user.domain'};
 5760:     }
 5761:     if (($caname ne '') && ($cadom ne '')) {
 5762:         return "/priv/$cadom/$caname/";
 5763:     }
 5764:     return;
 5765: }
 5766: 
 5767: ##############################################
 5768: =pod
 5769: 
 5770: =item * &head_subbox()
 5771: 
 5772: Inputs: $content (contains HTML code with page functions, etc.)
 5773: 
 5774: Returns: HTML div with $content
 5775:          To be included in page header
 5776: 
 5777: =cut
 5778: 
 5779: sub head_subbox {
 5780:     my ($content)=@_;
 5781:     my $output =
 5782:         '<div class="LC_head_subbox">'
 5783:        .$content
 5784:        .'</div>'
 5785: }
 5786: 
 5787: ##############################################
 5788: =pod
 5789: 
 5790: =item * &CSTR_pageheader()
 5791: 
 5792: Input: (optional) filename from which breadcrumb trail is built.
 5793:        In most cases no input as needed, as $env{'request.filename'}
 5794:        is appropriate for use in building the breadcrumb trail.
 5795:        frameset flag
 5796:        If page header is being requested for use in a frameset, then
 5797:        the second (option) argument -- frameset will be true, and
 5798:        the target attribute set for links should be target="_parent".
 5799: 
 5800: Returns: HTML div with CSTR path and recent box
 5801:          To be included on Authoring Space pages
 5802: 
 5803: =cut
 5804: 
 5805: sub CSTR_pageheader {
 5806:     my ($trailfile,$frameset) = @_;
 5807:     if ($trailfile eq '') {
 5808:         $trailfile = $env{'request.filename'};
 5809:     }
 5810: 
 5811: # this is for resources; directories have customtitle, and crumbs
 5812: # and select recent are created in lonpubdir.pm
 5813: 
 5814:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 5815:     my ($udom,$uname,$thisdisfn)=
 5816:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 5817:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 5818:     $formaction =~ s{/+}{/}g;
 5819: 
 5820:     my $parentpath = '';
 5821:     my $lastitem = '';
 5822:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 5823:         $parentpath = $1;
 5824:         $lastitem = $2;
 5825:     } else {
 5826:         $lastitem = $thisdisfn;
 5827:     }
 5828: 
 5829:     my ($target,$crumbtarget) = (' target="_top"','_top');
 5830:     if ($frameset) {
 5831:         $target = ' target="_parent"';
 5832:         $crumbtarget = '_parent';
 5833:     } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
 5834:         $target = ' target="'.$env{'request.deeplink.target'}.'"';
 5835:         $crumbtarget = $env{'request.deeplink.target'};
 5836:     }
 5837: 
 5838:     my $output =
 5839:          '<div>'
 5840:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 5841:         .'<b>'.&mt('Authoring Space:').'</b> '
 5842:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
 5843:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
 5844: 
 5845:     if ($lastitem) {
 5846:         $output .=
 5847:              '<span class="LC_filename">'
 5848:             .$lastitem
 5849:             .'</span>';
 5850:     }
 5851:     $output .=
 5852:          '<br />'
 5853:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
 5854:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 5855:         .'</form>'
 5856:         .&Apache::lonmenu::constspaceform($frameset)
 5857:         .'</div>';
 5858: 
 5859:     return $output;
 5860: }
 5861: 
 5862: ###############################################
 5863: ###############################################
 5864: 
 5865: =pod
 5866: 
 5867: =back
 5868: 
 5869: =head1 HTML Helpers
 5870: 
 5871: =over 4
 5872: 
 5873: =item * &bodytag()
 5874: 
 5875: Returns a uniform header for LON-CAPA web pages.
 5876: 
 5877: Inputs: 
 5878: 
 5879: =over 4
 5880: 
 5881: =item * $title, A title to be displayed on the page.
 5882: 
 5883: =item * $function, the current role (can be undef).
 5884: 
 5885: =item * $addentries, extra parameters for the <body> tag.
 5886: 
 5887: =item * $bodyonly, if defined, only return the <body> tag.
 5888: 
 5889: =item * $domain, if defined, force a given domain.
 5890: 
 5891: =item * $forcereg, if page should register as content page (relevant for 
 5892:             text interface only)
 5893: 
 5894: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 5895:                      navigational links
 5896: 
 5897: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 5898: 
 5899: =item * $no_inline_link, if true and in remote mode, don't show the
 5900:          'Switch To Inline Menu' link
 5901: 
 5902: =item * $args, optional argument valid values are
 5903:             no_auto_mt_title -> prevents &mt()ing the title arg
 5904:             use_absolute     -> for external resource or syllabus, this will
 5905:                                 contain https://<hostname> if server uses
 5906:                                 https (as per hosts.tab), but request is for http
 5907:             hostname         -> hostname, from $r->hostname().
 5908: 
 5909: =item * $advtoolsref, optional argument, ref to an array containing
 5910:             inlineremote items to be added in "Functions" menu below
 5911:             breadcrumbs.
 5912: 
 5913: =item * $ltiscope, optional argument, will be one of: resource, map or
 5914:             course, if LON-CAPA is in LTI Provider context. Value is
 5915:             the scope of use, i.e., launch was for access to a single, a map
 5916:             or the entire course.
 5917: 
 5918: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
 5919:             context, this will contain the URL for the landing item in
 5920:             the course, after launch from an LTI Consumer
 5921: 
 5922: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
 5923:             context, this will contain a reference to hash of items
 5924:             to be included in the page header and/or inline menu.
 5925: 
 5926: =item * $menucoll, optional argument, if specific menu collection is in
 5927:             effect, either set as the default for the course, or set for
 5928:             the deeplink paramater for $env{'request.deeplink.login'}
 5929:             then $menucoll will be the number of that collection.
 5930: 
 5931: =item * $menuref, optional argument, reference to a hash, containing the
 5932:             menu options included for the menu in effect, based on the
 5933:             configuration for the numbered menu collection in use.
 5934: 
 5935: =item * $showncrumbsref, reference to a scalar. Calls to lonmenu::innerregister
 5936:             within &bodytag() can result in calls to lonhtmlcommon::breadcrumbs(),
 5937:             if so, $showncrumbsref is set there to 1, and will propagate back
 5938:             via &bodytag() to &start_page(), to prevent lonhtmlcommon::breadcrumbs()
 5939:             being called a second time.
 5940: 
 5941: =back
 5942: 
 5943: Returns: A uniform header for LON-CAPA web pages.  
 5944: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 5945: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 5946: other decorations will be returned.
 5947: 
 5948: =cut
 5949: 
 5950: sub bodytag {
 5951:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 5952:         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref,
 5953:         $ltiscope,$ltiuri,$ltimenu,$menucoll,$menuref,$showncrumbsref)=@_;
 5954: 
 5955:     my $public;
 5956:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 5957:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 5958:         $public = 1;
 5959:     }
 5960:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5961:     my $httphost = $args->{'use_absolute'};
 5962:     my $hostname = $args->{'hostname'};
 5963: 
 5964:     $function = &get_users_function() if (!$function);
 5965:     my $img =    &designparm($function.'.img',$domain);
 5966:     my $font =   &designparm($function.'.font',$domain);
 5967:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 5968: 
 5969:     my %design = ( 'style'   => 'margin-top: 0',
 5970: 		   'bgcolor' => $pgbg,
 5971: 		   'text'    => $font,
 5972:                    'alink'   => &designparm($function.'.alink',$domain),
 5973: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 5974: 		   'link'    => &designparm($function.'.link',$domain),);
 5975:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 5976: 
 5977:  # role and realm
 5978:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
 5979:     if ($realm) {
 5980:         $realm = '/'.$realm;
 5981:     }
 5982:     if ($role eq 'ca') {
 5983:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 5984:         $realm = &plainname($rname,$rdom);
 5985:     } 
 5986: # realm
 5987:     my ($cid,$sec);
 5988:     if ($env{'request.course.id'}) {
 5989:         $cid = $env{'request.course.id'};
 5990:         if ($env{'request.course.sec'}) {
 5991:             $sec = $env{'request.course.sec'};
 5992:         }
 5993:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
 5994:         if (&Apache::lonnet::is_course($1,$2)) {
 5995:             $cid = $1.'_'.$2;
 5996:             $sec = $3;
 5997:         }
 5998:     }
 5999:     if ($cid) {
 6000:         if ($env{'request.role'} !~ /^cr/) {
 6001:             $role = &Apache::lonnet::plaintext($role,&course_type());
 6002:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
 6003:             if ($env{'request.role.desc'}) {
 6004:                 $role = $env{'request.role.desc'};
 6005:             } else {
 6006:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
 6007:             }
 6008:         } else {
 6009:             $role = (split(/\//,$role,4))[-1];
 6010:         }
 6011:         if ($sec) {
 6012:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
 6013:         }   
 6014: 	$realm = $env{'course.'.$cid.'.description'};
 6015:     } else {
 6016:         $role = &Apache::lonnet::plaintext($role);
 6017:     }
 6018: 
 6019:     if (!$realm) { $realm='&nbsp;'; }
 6020: 
 6021:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 6022: 
 6023: # construct main body tag
 6024:     my $bodytag = "<body $extra_body_attr>".
 6025: 	&Apache::lontexconvert::init_math_support();
 6026: 
 6027:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 6028: 
 6029:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 6030:         return $bodytag;
 6031:     }
 6032: 
 6033:     if ($public) {
 6034: 	undef($role);
 6035:     }
 6036: 
 6037:     my $showcrstitle = 1;
 6038:     if (($cid) && ($env{'request.lti.login'})) {
 6039:         if (ref($ltimenu) eq 'HASH') {
 6040:             unless ($ltimenu->{'role'}) {
 6041:                 undef($role);
 6042:             }
 6043:             unless ($ltimenu->{'coursetitle'}) {
 6044:                 $realm='&nbsp;';
 6045:                 $showcrstitle = 0;
 6046:             }
 6047:         }
 6048:     } elsif (($cid) && ($menucoll)) {
 6049:         if (ref($menuref) eq 'HASH') {
 6050:             unless ($menuref->{'role'}) {
 6051:                 undef($role);
 6052:             }
 6053:             unless ($menuref->{'crs'}) {
 6054:                 $realm='&nbsp;';
 6055:                 $showcrstitle = 0;
 6056:             }
 6057:         }
 6058:     }
 6059: 
 6060:     my $titleinfo = '<h1>'.$title.'</h1>';
 6061:     #
 6062:     # Extra info if you are the DC
 6063:     my $dc_info = '';
 6064:     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
 6065:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
 6066:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 6067:         $dc_info =~ s/\s+$//;
 6068:     }
 6069: 
 6070:     my $crstype;
 6071:     if ($cid) {
 6072:         $crstype = $env{'course.'.$cid.'.type'};
 6073:     } elsif ($args->{'crstype'}) {
 6074:         $crstype = $args->{'crstype'};
 6075:     }
 6076: 
 6077:     $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
 6078: 
 6079:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 6080: 
 6081: 
 6082: 
 6083:     my $funclist;
 6084:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
 6085:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
 6086:                     Apache::lonmenu::serverform();
 6087:         my $forbodytag;
 6088:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 6089:                                             $forcereg,$args->{'group'},
 6090:                                             $args->{'bread_crumbs'},
 6091:                                             $advtoolsref,'','',\$forbodytag);
 6092:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 6093:             $funclist = $forbodytag;
 6094:         }
 6095:     } else {
 6096: 
 6097:         #    if ($env{'request.state'} eq 'construct') {
 6098:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 6099:         #    }
 6100: 
 6101:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 6102:             Apache::lonmenu::utilityfunctions($httphost), 'start');
 6103: 
 6104:         unless ($args->{'no_primary_menu'}) {
 6105:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
 6106:                                                               $args->{'links_disabled'},
 6107:                                                               $args->{'links_target'});
 6108:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 6109:                 if ($dc_info) {
 6110:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 6111:                 }
 6112:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 6113:                                <em>$realm</em> $dc_info</div>|;
 6114:                 return $bodytag;
 6115:             }
 6116: 
 6117:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 6118:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 6119:             }
 6120: 
 6121:             $bodytag .= $right;
 6122: 
 6123:             if ($dc_info) {
 6124:                 $dc_info = &dc_courseid_toggle($dc_info);
 6125:             }
 6126:             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 6127:         }
 6128: 
 6129:         #if directed to not display the secondary menu, don't.
 6130:         if ($args->{'no_secondary_menu'}) {
 6131:             return $bodytag;
 6132:         }
 6133:         #don't show menus for public users
 6134:         if (!$public){
 6135:             unless ($args->{'no_inline_menu'}) {
 6136:                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
 6137:                                                             $args->{'no_primary_menu'},
 6138:                                                             $menucoll,$menuref,
 6139:                                                             $args->{'links_disabled'},
 6140:                                                             $args->{'links_target'});
 6141:             }
 6142:             $bodytag .= Apache::lonmenu::serverform();
 6143:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 6144:             if ($env{'request.state'} eq 'construct') {
 6145:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 6146:                                 $args->{'bread_crumbs'},'','',$hostname,
 6147:                                 $ltiscope,$ltiuri,$showncrumbsref);
 6148:             } elsif ($forcereg) {
 6149:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 6150:                                 $args->{'group'},$args->{'hide_buttons'},
 6151:                                 $hostname,$ltiscope,$ltiuri,$showncrumbsref);
 6152:             } else {
 6153:                 my $forbodytag;
 6154:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 6155:                                                     $forcereg,$args->{'group'},
 6156:                                                     $args->{'bread_crumbs'},
 6157:                                                     $advtoolsref,'',$hostname,
 6158:                                                     \$forbodytag);
 6159:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 6160:                     $bodytag .= $forbodytag;
 6161:                 }
 6162:             }
 6163:         }else{
 6164:             # this is to seperate menu from content when there's no secondary
 6165:             # menu. Especially needed for public accessible ressources.
 6166:             $bodytag .= '<hr style="clear:both" />';
 6167:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 6168:         }
 6169: 
 6170:         return $bodytag;
 6171:     }
 6172: 
 6173: #
 6174: # Top frame rendering, Remote is up
 6175: #
 6176: 
 6177:     my $imgsrc = $img;
 6178:     if ($img =~ /^\/adm/) {
 6179:         $imgsrc = &lonhttpdurl($img);
 6180:     }
 6181:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 6182: 
 6183:     my $help=($no_inline_link?''
 6184:               :&Apache::loncommon::top_nav_help('Help'));
 6185: 
 6186:     # Explicit link to get inline menu
 6187:     my $menu= ($no_inline_link?''
 6188:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
 6189: 
 6190:     if ($dc_info) {
 6191:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
 6192:     }
 6193: 
 6194:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 6195:     unless ($public) {
 6196:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
 6197:                                 undef,'LC_menubuttons_link');
 6198:     }
 6199: 
 6200:     unless ($env{'form.inhibitmenu'}) {
 6201:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
 6202:                        <ol class="LC_primary_menu LC_floatright LC_right">
 6203:                        <li>$help</li>
 6204:                        <li>$menu</li>
 6205:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
 6206:     }
 6207:     if ($env{'request.state'} eq 'construct') {
 6208:         if (!$public){
 6209:             if ($env{'request.state'} eq 'construct') {
 6210:                 $funclist = &Apache::lonhtmlcommon::scripttag(
 6211:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
 6212:                             &Apache::lonhtmlcommon::scripttag('','end').
 6213:                             &Apache::lonmenu::innerregister($forcereg,
 6214:                                                             $args->{'bread_crumbs'});
 6215:             }
 6216:         }
 6217:     }
 6218:     return $bodytag."\n".$funclist;
 6219: }
 6220: 
 6221: sub dc_courseid_toggle {
 6222:     my ($dc_info) = @_;
 6223:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 6224:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 6225:            &mt('(More ...)').'</a></span>'.
 6226:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 6227: }
 6228: 
 6229: sub make_attr_string {
 6230:     my ($register,$attr_ref) = @_;
 6231: 
 6232:     if ($attr_ref && !ref($attr_ref)) {
 6233: 	die("addentries Must be a hash ref ".
 6234: 	    join(':',caller(1))." ".
 6235: 	    join(':',caller(0))." ");
 6236:     }
 6237: 
 6238:     if ($register) {
 6239: 	my ($on_load,$on_unload);
 6240: 	foreach my $key (keys(%{$attr_ref})) {
 6241: 	    if      (lc($key) eq 'onload') {
 6242: 		$on_load.=$attr_ref->{$key}.';';
 6243: 		delete($attr_ref->{$key});
 6244: 
 6245: 	    } elsif (lc($key) eq 'onunload') {
 6246: 		$on_unload.=$attr_ref->{$key}.';';
 6247: 		delete($attr_ref->{$key});
 6248: 	    }
 6249: 	}
 6250:         if ($env{'environment.remote'} eq 'on') {
 6251:             $attr_ref->{'onload'}  =
 6252:                 &Apache::lonmenu::loadevents().  $on_load;
 6253:             $attr_ref->{'onunload'}=
 6254:                 &Apache::lonmenu::unloadevents().$on_unload;
 6255:         } else {  
 6256: 	    $attr_ref->{'onload'}  = $on_load;
 6257: 	    $attr_ref->{'onunload'}= $on_unload;
 6258:         }
 6259:     }
 6260: 
 6261:     my $attr_string;
 6262:     foreach my $attr (sort(keys(%$attr_ref))) {
 6263: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 6264:     }
 6265:     return $attr_string;
 6266: }
 6267: 
 6268: 
 6269: ###############################################
 6270: ###############################################
 6271: 
 6272: =pod
 6273: 
 6274: =item * &endbodytag()
 6275: 
 6276: Returns a uniform footer for LON-CAPA web pages.
 6277: 
 6278: Inputs: 1 - optional reference to an args hash
 6279: If in the hash, key for noredirectlink has a value which evaluates to true,
 6280: a 'Continue' link is not displayed if the page contains an
 6281: internal redirect in the <head></head> section,
 6282: i.e., $env{'internal.head.redirect'} exists   
 6283: 
 6284: =cut
 6285: 
 6286: sub endbodytag {
 6287:     my ($args) = @_;
 6288:     my $endbodytag;
 6289:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 6290:         $endbodytag='</body>';
 6291:     }
 6292:     if ( exists( $env{'internal.head.redirect'} ) ) {
 6293:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 6294:             my ($endbodyjs,$idattr);
 6295:             if ($env{'internal.head.to_opener'}) {
 6296:                 my $linkid = 'LC_continue_link';
 6297:                 $idattr = ' id="'.$linkid.'"';
 6298:                 my $redirect_for_js = &js_escape($env{'internal.head.redirect'});
 6299:                 $endbodyjs=<<ENDJS;
 6300: <script type="text/javascript">
 6301: // <![CDATA[
 6302: function ebFunction(evt) {
 6303:     evt.preventDefault();
 6304:     var dest = '$redirect_for_js';
 6305:     if (window.opener != null && !window.opener.closed) {
 6306:         window.opener.location.href=dest;
 6307:         window.close();
 6308:     } else {
 6309:         window.location.href=dest;
 6310:     }
 6311:     return false;
 6312: }
 6313: 
 6314: \$(document).ready(function () {
 6315:   if (document.getElementById('$linkid')) {
 6316:     var clickelem = document.getElementById('$linkid');
 6317:     clickelem.addEventListener('click',ebFunction,false);
 6318:   }
 6319: });
 6320: // ]]>
 6321: </script>
 6322: ENDJS
 6323:             }
 6324: 	    $endbodytag=
 6325: 	        "$endbodyjs<br /><a href=\"$env{'internal.head.redirect'}\"$idattr>".
 6326: 	        &mt('Continue').'</a>'.
 6327: 	        $endbodytag;
 6328:         }
 6329:     }
 6330:     return $endbodytag;
 6331: }
 6332: 
 6333: =pod
 6334: 
 6335: =item * &standard_css()
 6336: 
 6337: Returns a style sheet
 6338: 
 6339: Inputs: (all optional)
 6340:             domain         -> force to color decorate a page for a specific
 6341:                                domain
 6342:             function       -> force usage of a specific rolish color scheme
 6343:             bgcolor        -> override the default page bgcolor
 6344: 
 6345: =cut
 6346: 
 6347: sub standard_css {
 6348:     my ($function,$domain,$bgcolor) = @_;
 6349:     $function  = &get_users_function() if (!$function);
 6350:     my $img    = &designparm($function.'.img',   $domain);
 6351:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 6352:     my $font   = &designparm($function.'.font',  $domain);
 6353:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 6354: #second colour for later usage
 6355:     my $sidebg = &designparm($function.'.sidebg',$domain);
 6356:     my $pgbg_or_bgcolor =
 6357: 	         $bgcolor ||
 6358: 	         &designparm($function.'.pgbg',  $domain);
 6359:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 6360:     my $alink  = &designparm($function.'.alink', $domain);
 6361:     my $vlink  = &designparm($function.'.vlink', $domain);
 6362:     my $link   = &designparm($function.'.link',  $domain);
 6363: 
 6364:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 6365:     my $mono                 = 'monospace';
 6366:     my $data_table_head      = $sidebg;
 6367:     my $data_table_light     = '#FAFAFA';
 6368:     my $data_table_dark      = '#E0E0E0';
 6369:     my $data_table_darker    = '#CCCCCC';
 6370:     my $data_table_highlight = '#FFFF00';
 6371:     my $mail_new             = '#FFBB77';
 6372:     my $mail_new_hover       = '#DD9955';
 6373:     my $mail_read            = '#BBBB77';
 6374:     my $mail_read_hover      = '#999944';
 6375:     my $mail_replied         = '#AAAA88';
 6376:     my $mail_replied_hover   = '#888855';
 6377:     my $mail_other           = '#99BBBB';
 6378:     my $mail_other_hover     = '#669999';
 6379:     my $table_header         = '#DDDDDD';
 6380:     my $feedback_link_bg     = '#BBBBBB';
 6381:     my $lg_border_color      = '#C8C8C8';
 6382:     my $button_hover         = '#BF2317';
 6383: 
 6384:     my $border = ($env{'browser.type'} eq 'explorer' ||
 6385:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 6386:                                              : '0 3px 0 4px';
 6387: 
 6388: 
 6389:     return <<END;
 6390: 
 6391: /* needed for iframe to allow 100% height in FF */
 6392: body, html { 
 6393:     margin: 0;
 6394:     padding: 0 0.5%;
 6395:     height: 99%; /* to avoid scrollbars */
 6396: }
 6397: 
 6398: body {
 6399:   font-family: $sans;
 6400:   line-height:130%;
 6401:   font-size:0.83em;
 6402:   color:$font;
 6403: }
 6404: 
 6405: a:focus,
 6406: a:focus img {
 6407:   color: red;
 6408: }
 6409: 
 6410: form, .inline {
 6411:   display: inline;
 6412: }
 6413: 
 6414: .LC_right {
 6415:   text-align:right;
 6416: }
 6417: 
 6418: .LC_middle {
 6419:   vertical-align:middle;
 6420: }
 6421: 
 6422: .LC_floatleft {
 6423:   float: left;
 6424: }
 6425: 
 6426: .LC_floatright {
 6427:   float: right;
 6428: }
 6429: 
 6430: .LC_400Box {
 6431:   width:400px;
 6432: }
 6433: 
 6434: .LC_iframecontainer {
 6435:     width: 98%;
 6436:     margin: 0;
 6437:     position: fixed;
 6438:     top: 8.5em;
 6439:     bottom: 0;
 6440: }
 6441: 
 6442: .LC_iframecontainer iframe{
 6443:     border: none;
 6444:     width: 100%;
 6445:     height: 100%;
 6446: }
 6447: 
 6448: .LC_filename {
 6449:   font-family: $mono;
 6450:   white-space:pre;
 6451:   font-size: 120%;
 6452: }
 6453: 
 6454: .LC_fileicon {
 6455:   border: none;
 6456:   height: 1.3em;
 6457:   vertical-align: text-bottom;
 6458:   margin-right: 0.3em;
 6459:   text-decoration:none;
 6460: }
 6461: 
 6462: .LC_setting {
 6463:   text-decoration:underline;
 6464: }
 6465: 
 6466: .LC_error {
 6467:   color: red;
 6468: }
 6469: 
 6470: .LC_warning {
 6471:   color: darkorange;
 6472: }
 6473: 
 6474: .LC_diff_removed {
 6475:   color: red;
 6476: }
 6477: 
 6478: .LC_info,
 6479: .LC_success,
 6480: .LC_diff_added {
 6481:   color: green;
 6482: }
 6483: 
 6484: div.LC_confirm_box {
 6485:   background-color: #FAFAFA;
 6486:   border: 1px solid $lg_border_color;
 6487:   margin-right: 0;
 6488:   padding: 5px;
 6489: }
 6490: 
 6491: div.LC_confirm_box .LC_error img,
 6492: div.LC_confirm_box .LC_success img {
 6493:   vertical-align: middle;
 6494: }
 6495: 
 6496: .LC_maxwidth {
 6497:   max-width: 100%;
 6498:   height: auto;
 6499: }
 6500: 
 6501: .LC_textsize_mobile {
 6502:   \@media only screen and (max-device-width: 480px) {
 6503:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
 6504:   }
 6505: }
 6506: 
 6507: .LC_icon {
 6508:   border: none;
 6509:   vertical-align: middle;
 6510: }
 6511: 
 6512: .LC_docs_spacer {
 6513:   width: 25px;
 6514:   height: 1px;
 6515:   border: none;
 6516: }
 6517: 
 6518: .LC_internal_info {
 6519:   color: #999999;
 6520: }
 6521: 
 6522: .LC_discussion {
 6523:   background: $data_table_dark;
 6524:   border: 1px solid black;
 6525:   margin: 2px;
 6526: }
 6527: 
 6528: .LC_disc_action_left {
 6529:   background: $sidebg;
 6530:   text-align: left;
 6531:   padding: 4px;
 6532:   margin: 2px;
 6533: }
 6534: 
 6535: .LC_disc_action_right {
 6536:   background: $sidebg;
 6537:   text-align: right;
 6538:   padding: 4px;
 6539:   margin: 2px;
 6540: }
 6541: 
 6542: .LC_disc_new_item {
 6543:   background: white;
 6544:   border: 2px solid red;
 6545:   margin: 4px;
 6546:   padding: 4px;
 6547: }
 6548: 
 6549: .LC_disc_old_item {
 6550:   background: white;
 6551:   margin: 4px;
 6552:   padding: 4px;
 6553: }
 6554: 
 6555: table.LC_pastsubmission {
 6556:   border: 1px solid black;
 6557:   margin: 2px;
 6558: }
 6559: 
 6560: table#LC_menubuttons {
 6561:   width: 100%;
 6562:   background: $pgbg;
 6563:   border: 2px;
 6564:   border-collapse: separate;
 6565:   padding: 0;
 6566: }
 6567: 
 6568: table#LC_title_bar a {
 6569:   color: $fontmenu;
 6570: }
 6571: 
 6572: table#LC_title_bar {
 6573:   clear: both;
 6574:   display: none;
 6575: }
 6576: 
 6577: table#LC_title_bar,
 6578: table.LC_breadcrumbs, /* obsolete? */
 6579: table#LC_title_bar.LC_with_remote {
 6580:   width: 100%;
 6581:   border-color: $pgbg;
 6582:   border-style: solid;
 6583:   border-width: $border;
 6584:   background: $pgbg;
 6585:   color: $fontmenu;
 6586:   border-collapse: collapse;
 6587:   padding: 0;
 6588:   margin: 0;
 6589: }
 6590: 
 6591: ul.LC_breadcrumb_tools_outerlist {
 6592:     margin: 0;
 6593:     padding: 0;
 6594:     position: relative;
 6595:     list-style: none;
 6596: }
 6597: ul.LC_breadcrumb_tools_outerlist li {
 6598:     display: inline;
 6599: }
 6600: 
 6601: .LC_breadcrumb_tools_navigation {
 6602:     padding: 0;
 6603:     margin: 0;
 6604:     float: left;
 6605: }
 6606: .LC_breadcrumb_tools_tools {
 6607:     padding: 0;
 6608:     margin: 0;
 6609:     float: right;
 6610: }
 6611: 
 6612: table#LC_title_bar td {
 6613:   background: $tabbg;
 6614: }
 6615: 
 6616: table#LC_menubuttons img {
 6617:   border: none;
 6618: }
 6619: 
 6620: .LC_breadcrumbs_component {
 6621:   float: right;
 6622:   margin: 0 1em;
 6623: }
 6624: .LC_breadcrumbs_component img {
 6625:   vertical-align: middle;
 6626: }
 6627: 
 6628: .LC_breadcrumbs_hoverable {
 6629:   background: $sidebg;
 6630: }
 6631: 
 6632: td.LC_table_cell_checkbox {
 6633:   text-align: center;
 6634: }
 6635: 
 6636: .LC_fontsize_small {
 6637:   font-size: 70%;
 6638: }
 6639: 
 6640: #LC_breadcrumbs {
 6641:   clear:both;
 6642:   background: $sidebg;
 6643:   border-bottom: 1px solid $lg_border_color;
 6644:   line-height: 2.5em;
 6645:   overflow: hidden;
 6646:   margin: 0;
 6647:   padding: 0;
 6648:   text-align: left;
 6649: }
 6650: 
 6651: .LC_head_subbox, .LC_actionbox {
 6652:   clear:both;
 6653:   background: #F8F8F8; /* $sidebg; */
 6654:   border: 1px solid $sidebg;
 6655:   margin: 0 0 10px 0;
 6656:   padding: 3px;
 6657:   text-align: left;
 6658: }
 6659: 
 6660: .LC_fontsize_medium {
 6661:   font-size: 85%;
 6662: }
 6663: 
 6664: .LC_fontsize_large {
 6665:   font-size: 120%;
 6666: }
 6667: 
 6668: .LC_menubuttons_inline_text {
 6669:   color: $font;
 6670:   font-size: 90%;
 6671:   padding-left:3px;
 6672: }
 6673: 
 6674: .LC_menubuttons_inline_text img{
 6675:   vertical-align: middle;
 6676: }
 6677: 
 6678: li.LC_menubuttons_inline_text img {
 6679:   cursor:pointer;
 6680:   text-decoration: none;
 6681: }
 6682: 
 6683: .LC_menubuttons_link {
 6684:   text-decoration: none;
 6685: }
 6686: 
 6687: .LC_menubuttons_category {
 6688:   color: $font;
 6689:   background: $pgbg;
 6690:   font-size: larger;
 6691:   font-weight: bold;
 6692: }
 6693: 
 6694: td.LC_menubuttons_text {
 6695:   color: $font;
 6696: }
 6697: 
 6698: .LC_current_location {
 6699:   background: $tabbg;
 6700: }
 6701: 
 6702: td.LC_zero_height {
 6703:   line-height: 0;
 6704:   cellpadding: 0;
 6705: }
 6706: 
 6707: table.LC_data_table {
 6708:   border: 1px solid #000000;
 6709:   border-collapse: separate;
 6710:   border-spacing: 1px;
 6711:   background: $pgbg;
 6712: }
 6713: 
 6714: .LC_data_table_dense {
 6715:   font-size: small;
 6716: }
 6717: 
 6718: table.LC_nested_outer {
 6719:   border: 1px solid #000000;
 6720:   border-collapse: collapse;
 6721:   border-spacing: 0;
 6722:   width: 100%;
 6723: }
 6724: 
 6725: table.LC_innerpickbox,
 6726: table.LC_nested {
 6727:   border: none;
 6728:   border-collapse: collapse;
 6729:   border-spacing: 0;
 6730:   width: 100%;
 6731: }
 6732: 
 6733: table.LC_data_table tr th,
 6734: table.LC_calendar tr th,
 6735: table.LC_prior_tries tr th,
 6736: table.LC_innerpickbox tr th {
 6737:   font-weight: bold;
 6738:   background-color: $data_table_head;
 6739:   color:$fontmenu;
 6740:   font-size:90%;
 6741: }
 6742: 
 6743: table.LC_innerpickbox tr th,
 6744: table.LC_innerpickbox tr td {
 6745:   vertical-align: top;
 6746: }
 6747: 
 6748: table.LC_data_table tr.LC_info_row > td {
 6749:   background-color: #CCCCCC;
 6750:   font-weight: bold;
 6751:   text-align: left;
 6752: }
 6753: 
 6754: table.LC_data_table tr.LC_odd_row > td {
 6755:   background-color: $data_table_light;
 6756:   padding: 2px;
 6757:   vertical-align: top;
 6758: }
 6759: 
 6760: table.LC_pick_box tr > td.LC_odd_row {
 6761:   background-color: $data_table_light;
 6762:   vertical-align: top;
 6763: }
 6764: 
 6765: table.LC_data_table tr.LC_even_row > td {
 6766:   background-color: $data_table_dark;
 6767:   padding: 2px;
 6768:   vertical-align: top;
 6769: }
 6770: 
 6771: table.LC_pick_box tr > td.LC_even_row {
 6772:   background-color: $data_table_dark;
 6773:   vertical-align: top;
 6774: }
 6775: 
 6776: table.LC_data_table tr.LC_data_table_highlight td {
 6777:   background-color: $data_table_darker;
 6778: }
 6779: 
 6780: table.LC_data_table tr td.LC_leftcol_header {
 6781:   background-color: $data_table_head;
 6782:   font-weight: bold;
 6783: }
 6784: 
 6785: table.LC_data_table tr.LC_empty_row td,
 6786: table.LC_nested tr.LC_empty_row td {
 6787:   font-weight: bold;
 6788:   font-style: italic;
 6789:   text-align: center;
 6790:   padding: 8px;
 6791: }
 6792: 
 6793: table.LC_data_table tr.LC_empty_row td,
 6794: table.LC_data_table tr.LC_footer_row td {
 6795:   background-color: $sidebg;
 6796: }
 6797: 
 6798: table.LC_nested tr.LC_empty_row td {
 6799:   background-color: #FFFFFF;
 6800: }
 6801: 
 6802: table.LC_caption {
 6803: }
 6804: 
 6805: table.LC_nested tr.LC_empty_row td {
 6806:   padding: 4ex
 6807: }
 6808: 
 6809: table.LC_nested_outer tr th {
 6810:   font-weight: bold;
 6811:   color:$fontmenu;
 6812:   background-color: $data_table_head;
 6813:   font-size: small;
 6814:   border-bottom: 1px solid #000000;
 6815: }
 6816: 
 6817: table.LC_nested_outer tr td.LC_subheader {
 6818:   background-color: $data_table_head;
 6819:   font-weight: bold;
 6820:   font-size: small;
 6821:   border-bottom: 1px solid #000000;
 6822:   text-align: right;
 6823: }
 6824: 
 6825: table.LC_nested tr.LC_info_row td {
 6826:   background-color: #CCCCCC;
 6827:   font-weight: bold;
 6828:   font-size: small;
 6829:   text-align: center;
 6830: }
 6831: 
 6832: table.LC_nested tr.LC_info_row td.LC_left_item,
 6833: table.LC_nested_outer tr th.LC_left_item {
 6834:   text-align: left;
 6835: }
 6836: 
 6837: table.LC_nested td {
 6838:   background-color: #FFFFFF;
 6839:   font-size: small;
 6840: }
 6841: 
 6842: table.LC_nested_outer tr th.LC_right_item,
 6843: table.LC_nested tr.LC_info_row td.LC_right_item,
 6844: table.LC_nested tr.LC_odd_row td.LC_right_item,
 6845: table.LC_nested tr td.LC_right_item {
 6846:   text-align: right;
 6847: }
 6848: 
 6849: table.LC_nested tr.LC_odd_row td {
 6850:   background-color: #EEEEEE;
 6851: }
 6852: 
 6853: table.LC_createuser {
 6854: }
 6855: 
 6856: table.LC_createuser tr.LC_section_row td {
 6857:   font-size: small;
 6858: }
 6859: 
 6860: table.LC_createuser tr.LC_info_row td  {
 6861:   background-color: #CCCCCC;
 6862:   font-weight: bold;
 6863:   text-align: center;
 6864: }
 6865: 
 6866: table.LC_calendar {
 6867:   border: 1px solid #000000;
 6868:   border-collapse: collapse;
 6869:   width: 98%;
 6870: }
 6871: 
 6872: table.LC_calendar_pickdate {
 6873:   font-size: xx-small;
 6874: }
 6875: 
 6876: table.LC_calendar tr td {
 6877:   border: 1px solid #000000;
 6878:   vertical-align: top;
 6879:   width: 14%;
 6880: }
 6881: 
 6882: table.LC_calendar tr td.LC_calendar_day_empty {
 6883:   background-color: $data_table_dark;
 6884: }
 6885: 
 6886: table.LC_calendar tr td.LC_calendar_day_current {
 6887:   background-color: $data_table_highlight;
 6888: }
 6889: 
 6890: table.LC_data_table tr td.LC_mail_new {
 6891:   background-color: $mail_new;
 6892: }
 6893: 
 6894: table.LC_data_table tr.LC_mail_new:hover {
 6895:   background-color: $mail_new_hover;
 6896: }
 6897: 
 6898: table.LC_data_table tr td.LC_mail_read {
 6899:   background-color: $mail_read;
 6900: }
 6901: 
 6902: /*
 6903: table.LC_data_table tr.LC_mail_read:hover {
 6904:   background-color: $mail_read_hover;
 6905: }
 6906: */
 6907: 
 6908: table.LC_data_table tr td.LC_mail_replied {
 6909:   background-color: $mail_replied;
 6910: }
 6911: 
 6912: /*
 6913: table.LC_data_table tr.LC_mail_replied:hover {
 6914:   background-color: $mail_replied_hover;
 6915: }
 6916: */
 6917: 
 6918: table.LC_data_table tr td.LC_mail_other {
 6919:   background-color: $mail_other;
 6920: }
 6921: 
 6922: /*
 6923: table.LC_data_table tr.LC_mail_other:hover {
 6924:   background-color: $mail_other_hover;
 6925: }
 6926: */
 6927: 
 6928: table.LC_data_table tr > td.LC_browser_file,
 6929: table.LC_data_table tr > td.LC_browser_file_published {
 6930:   background: #AAEE77;
 6931: }
 6932: 
 6933: table.LC_data_table tr > td.LC_browser_file_locked,
 6934: table.LC_data_table tr > td.LC_browser_file_unpublished {
 6935:   background: #FFAA99;
 6936: }
 6937: 
 6938: table.LC_data_table tr > td.LC_browser_file_obsolete {
 6939:   background: #888888;
 6940: }
 6941: 
 6942: table.LC_data_table tr > td.LC_browser_file_modified,
 6943: table.LC_data_table tr > td.LC_browser_file_metamodified {
 6944:   background: #F8F866;
 6945: }
 6946: 
 6947: table.LC_data_table tr.LC_browser_folder > td {
 6948:   background: #E0E8FF;
 6949: }
 6950: 
 6951: table.LC_data_table tr > td.LC_roles_is {
 6952:   /* background: #77FF77; */
 6953: }
 6954: 
 6955: table.LC_data_table tr > td.LC_roles_future {
 6956:   border-right: 8px solid #FFFF77;
 6957: }
 6958: 
 6959: table.LC_data_table tr > td.LC_roles_will {
 6960:   border-right: 8px solid #FFAA77;
 6961: }
 6962: 
 6963: table.LC_data_table tr > td.LC_roles_expired {
 6964:   border-right: 8px solid #FF7777;
 6965: }
 6966: 
 6967: table.LC_data_table tr > td.LC_roles_will_not {
 6968:   border-right: 8px solid #AAFF77;
 6969: }
 6970: 
 6971: table.LC_data_table tr > td.LC_roles_selected {
 6972:   border-right: 8px solid #11CC55;
 6973: }
 6974: 
 6975: span.LC_current_location {
 6976:   font-size:larger;
 6977:   background: $pgbg;
 6978: }
 6979: 
 6980: span.LC_current_nav_location {
 6981:   font-weight:bold;
 6982:   background: $sidebg;
 6983: }
 6984: 
 6985: span.LC_parm_menu_item {
 6986:   font-size: larger;
 6987: }
 6988: 
 6989: span.LC_parm_scope_all {
 6990:   color: red;
 6991: }
 6992: 
 6993: span.LC_parm_scope_folder {
 6994:   color: green;
 6995: }
 6996: 
 6997: span.LC_parm_scope_resource {
 6998:   color: orange;
 6999: }
 7000: 
 7001: span.LC_parm_part {
 7002:   color: blue;
 7003: }
 7004: 
 7005: span.LC_parm_folder,
 7006: span.LC_parm_symb {
 7007:   font-size: x-small;
 7008:   font-family: $mono;
 7009:   color: #AAAAAA;
 7010: }
 7011: 
 7012: ul.LC_parm_parmlist li {
 7013:   display: inline-block;
 7014:   padding: 0.3em 0.8em;
 7015:   vertical-align: top;
 7016:   width: 150px;
 7017:   border-top:1px solid $lg_border_color;
 7018: }
 7019: 
 7020: td.LC_parm_overview_level_menu,
 7021: td.LC_parm_overview_map_menu,
 7022: td.LC_parm_overview_parm_selectors,
 7023: td.LC_parm_overview_restrictions  {
 7024:   border: 1px solid black;
 7025:   border-collapse: collapse;
 7026: }
 7027: 
 7028: table.LC_parm_overview_restrictions td {
 7029:   border-width: 1px 4px 1px 4px;
 7030:   border-style: solid;
 7031:   border-color: $pgbg;
 7032:   text-align: center;
 7033: }
 7034: 
 7035: table.LC_parm_overview_restrictions th {
 7036:   background: $tabbg;
 7037:   border-width: 1px 4px 1px 4px;
 7038:   border-style: solid;
 7039:   border-color: $pgbg;
 7040: }
 7041: 
 7042: table#LC_helpmenu {
 7043:   border: none;
 7044:   height: 55px;
 7045:   border-spacing: 0;
 7046: }
 7047: 
 7048: table#LC_helpmenu fieldset legend {
 7049:   font-size: larger;
 7050: }
 7051: 
 7052: table#LC_helpmenu_links {
 7053:   width: 100%;
 7054:   border: 1px solid black;
 7055:   background: $pgbg;
 7056:   padding: 0;
 7057:   border-spacing: 1px;
 7058: }
 7059: 
 7060: table#LC_helpmenu_links tr td {
 7061:   padding: 1px;
 7062:   background: $tabbg;
 7063:   text-align: center;
 7064:   font-weight: bold;
 7065: }
 7066: 
 7067: table#LC_helpmenu_links a:link,
 7068: table#LC_helpmenu_links a:visited,
 7069: table#LC_helpmenu_links a:active {
 7070:   text-decoration: none;
 7071:   color: $font;
 7072: }
 7073: 
 7074: table#LC_helpmenu_links a:hover {
 7075:   text-decoration: underline;
 7076:   color: $vlink;
 7077: }
 7078: 
 7079: .LC_chrt_popup_exists {
 7080:   border: 1px solid #339933;
 7081:   margin: -1px;
 7082: }
 7083: 
 7084: .LC_chrt_popup_up {
 7085:   border: 1px solid yellow;
 7086:   margin: -1px;
 7087: }
 7088: 
 7089: .LC_chrt_popup {
 7090:   border: 1px solid #8888FF;
 7091:   background: #CCCCFF;
 7092: }
 7093: 
 7094: table.LC_pick_box {
 7095:   border-collapse: separate;
 7096:   background: white;
 7097:   border: 1px solid black;
 7098:   border-spacing: 1px;
 7099: }
 7100: 
 7101: table.LC_pick_box td.LC_pick_box_title {
 7102:   background: $sidebg;
 7103:   font-weight: bold;
 7104:   text-align: left;
 7105:   vertical-align: top;
 7106:   width: 184px;
 7107:   padding: 8px;
 7108: }
 7109: 
 7110: table.LC_pick_box td.LC_pick_box_value {
 7111:   text-align: left;
 7112:   padding: 8px;
 7113: }
 7114: 
 7115: table.LC_pick_box td.LC_pick_box_select {
 7116:   text-align: left;
 7117:   padding: 8px;
 7118: }
 7119: 
 7120: table.LC_pick_box td.LC_pick_box_separator {
 7121:   padding: 0;
 7122:   height: 1px;
 7123:   background: black;
 7124: }
 7125: 
 7126: table.LC_pick_box td.LC_pick_box_submit {
 7127:   text-align: right;
 7128: }
 7129: 
 7130: table.LC_pick_box td.LC_evenrow_value {
 7131:   text-align: left;
 7132:   padding: 8px;
 7133:   background-color: $data_table_light;
 7134: }
 7135: 
 7136: table.LC_pick_box td.LC_oddrow_value {
 7137:   text-align: left;
 7138:   padding: 8px;
 7139:   background-color: $data_table_light;
 7140: }
 7141: 
 7142: span.LC_helpform_receipt_cat {
 7143:   font-weight: bold;
 7144: }
 7145: 
 7146: table.LC_group_priv_box {
 7147:   background: white;
 7148:   border: 1px solid black;
 7149:   border-spacing: 1px;
 7150: }
 7151: 
 7152: table.LC_group_priv_box td.LC_pick_box_title {
 7153:   background: $tabbg;
 7154:   font-weight: bold;
 7155:   text-align: right;
 7156:   width: 184px;
 7157: }
 7158: 
 7159: table.LC_group_priv_box td.LC_groups_fixed {
 7160:   background: $data_table_light;
 7161:   text-align: center;
 7162: }
 7163: 
 7164: table.LC_group_priv_box td.LC_groups_optional {
 7165:   background: $data_table_dark;
 7166:   text-align: center;
 7167: }
 7168: 
 7169: table.LC_group_priv_box td.LC_groups_functionality {
 7170:   background: $data_table_darker;
 7171:   text-align: center;
 7172:   font-weight: bold;
 7173: }
 7174: 
 7175: table.LC_group_priv td {
 7176:   text-align: left;
 7177:   padding: 0;
 7178: }
 7179: 
 7180: .LC_navbuttons {
 7181:   margin: 2ex 0ex 2ex 0ex;
 7182: }
 7183: 
 7184: .LC_topic_bar {
 7185:   font-weight: bold;
 7186:   background: $tabbg;
 7187:   margin: 1em 0em 1em 2em;
 7188:   padding: 3px;
 7189:   font-size: 1.2em;
 7190: }
 7191: 
 7192: .LC_topic_bar span {
 7193:   left: 0.5em;
 7194:   position: absolute;
 7195:   vertical-align: middle;
 7196:   font-size: 1.2em;
 7197: }
 7198: 
 7199: table.LC_course_group_status {
 7200:   margin: 20px;
 7201: }
 7202: 
 7203: table.LC_status_selector td {
 7204:   vertical-align: top;
 7205:   text-align: center;
 7206:   padding: 4px;
 7207: }
 7208: 
 7209: div.LC_feedback_link {
 7210:   clear: both;
 7211:   background: $sidebg;
 7212:   width: 100%;
 7213:   padding-bottom: 10px;
 7214:   border: 1px $tabbg solid;
 7215:   height: 22px;
 7216:   line-height: 22px;
 7217:   padding-top: 5px;
 7218: }
 7219: 
 7220: div.LC_feedback_link img {
 7221:   height: 22px;
 7222:   vertical-align:middle;
 7223: }
 7224: 
 7225: div.LC_feedback_link a {
 7226:   text-decoration: none;
 7227: }
 7228: 
 7229: div.LC_comblock {
 7230:   display:inline;
 7231:   color:$font;
 7232:   font-size:90%;
 7233: }
 7234: 
 7235: div.LC_feedback_link div.LC_comblock {
 7236:   padding-left:5px;
 7237: }
 7238: 
 7239: div.LC_feedback_link div.LC_comblock a {
 7240:   color:$font;
 7241: }
 7242: 
 7243: span.LC_feedback_link {
 7244:   /* background: $feedback_link_bg; */
 7245:   font-size: larger;
 7246: }
 7247: 
 7248: span.LC_message_link {
 7249:   /* background: $feedback_link_bg; */
 7250:   font-size: larger;
 7251:   position: absolute;
 7252:   right: 1em;
 7253: }
 7254: 
 7255: table.LC_prior_tries {
 7256:   border: 1px solid #000000;
 7257:   border-collapse: separate;
 7258:   border-spacing: 1px;
 7259: }
 7260: 
 7261: table.LC_prior_tries td {
 7262:   padding: 2px;
 7263: }
 7264: 
 7265: .LC_answer_correct {
 7266:   background: lightgreen;
 7267:   color: darkgreen;
 7268:   padding: 6px;
 7269: }
 7270: 
 7271: .LC_answer_charged_try {
 7272:   background: #FFAAAA;
 7273:   color: darkred;
 7274:   padding: 6px;
 7275: }
 7276: 
 7277: .LC_answer_not_charged_try,
 7278: .LC_answer_no_grade,
 7279: .LC_answer_late {
 7280:   background: lightyellow;
 7281:   color: black;
 7282:   padding: 6px;
 7283: }
 7284: 
 7285: .LC_answer_previous {
 7286:   background: lightblue;
 7287:   color: darkblue;
 7288:   padding: 6px;
 7289: }
 7290: 
 7291: .LC_answer_no_message {
 7292:   background: #FFFFFF;
 7293:   color: black;
 7294:   padding: 6px;
 7295: }
 7296: 
 7297: .LC_answer_unknown,
 7298: .LC_answer_warning {
 7299:   background: orange;
 7300:   color: black;
 7301:   padding: 6px;
 7302: }
 7303: 
 7304: span.LC_prior_numerical,
 7305: span.LC_prior_string,
 7306: span.LC_prior_custom,
 7307: span.LC_prior_reaction,
 7308: span.LC_prior_math {
 7309:   font-family: $mono;
 7310:   white-space: pre;
 7311: }
 7312: 
 7313: span.LC_prior_string {
 7314:   font-family: $mono;
 7315:   white-space: pre;
 7316: }
 7317: 
 7318: table.LC_prior_option {
 7319:   width: 100%;
 7320:   border-collapse: collapse;
 7321: }
 7322: 
 7323: table.LC_prior_rank,
 7324: table.LC_prior_match {
 7325:   border-collapse: collapse;
 7326: }
 7327: 
 7328: table.LC_prior_option tr td,
 7329: table.LC_prior_rank tr td,
 7330: table.LC_prior_match tr td {
 7331:   border: 1px solid #000000;
 7332: }
 7333: 
 7334: .LC_nobreak {
 7335:   white-space: nowrap;
 7336: }
 7337: 
 7338: span.LC_cusr_emph {
 7339:   font-style: italic;
 7340: }
 7341: 
 7342: span.LC_cusr_subheading {
 7343:   font-weight: normal;
 7344:   font-size: 85%;
 7345: }
 7346: 
 7347: div.LC_docs_entry_move {
 7348:   border: 1px solid #BBBBBB;
 7349:   background: #DDDDDD;
 7350:   width: 22px;
 7351:   padding: 1px;
 7352:   margin: 0;
 7353: }
 7354: 
 7355: table.LC_data_table tr > td.LC_docs_entry_commands,
 7356: table.LC_data_table tr > td.LC_docs_entry_parameter {
 7357:   font-size: x-small;
 7358: }
 7359: 
 7360: .LC_docs_entry_parameter {
 7361:   white-space: nowrap;
 7362: }
 7363: 
 7364: .LC_docs_copy {
 7365:   color: #000099;
 7366: }
 7367: 
 7368: .LC_docs_cut {
 7369:   color: #550044;
 7370: }
 7371: 
 7372: .LC_docs_rename {
 7373:   color: #009900;
 7374: }
 7375: 
 7376: .LC_docs_remove {
 7377:   color: #990000;
 7378: }
 7379: 
 7380: .LC_domprefs_email,
 7381: .LC_docs_reinit_warn,
 7382: .LC_docs_ext_edit {
 7383:   font-size: x-small;
 7384: }
 7385: 
 7386: table.LC_docs_adddocs td,
 7387: table.LC_docs_adddocs th {
 7388:   border: 1px solid #BBBBBB;
 7389:   padding: 4px;
 7390:   background: #DDDDDD;
 7391: }
 7392: 
 7393: table.LC_sty_begin {
 7394:   background: #BBFFBB;
 7395: }
 7396: 
 7397: table.LC_sty_end {
 7398:   background: #FFBBBB;
 7399: }
 7400: 
 7401: table.LC_double_column {
 7402:   border-width: 0;
 7403:   border-collapse: collapse;
 7404:   width: 100%;
 7405:   padding: 2px;
 7406: }
 7407: 
 7408: table.LC_double_column tr td.LC_left_col {
 7409:   top: 2px;
 7410:   left: 2px;
 7411:   width: 47%;
 7412:   vertical-align: top;
 7413: }
 7414: 
 7415: table.LC_double_column tr td.LC_right_col {
 7416:   top: 2px;
 7417:   right: 2px;
 7418:   width: 47%;
 7419:   vertical-align: top;
 7420: }
 7421: 
 7422: div.LC_left_float {
 7423:   float: left;
 7424:   padding-right: 5%;
 7425:   padding-bottom: 4px;
 7426: }
 7427: 
 7428: div.LC_clear_float_header {
 7429:   padding-bottom: 2px;
 7430: }
 7431: 
 7432: div.LC_clear_float_footer {
 7433:   padding-top: 10px;
 7434:   clear: both;
 7435: }
 7436: 
 7437: div.LC_grade_show_user {
 7438: /*  border-left: 5px solid $sidebg; */
 7439:   border-top: 5px solid #000000;
 7440:   margin: 50px 0 0 0;
 7441:   padding: 15px 0 5px 10px;
 7442: }
 7443: 
 7444: div.LC_grade_show_user_odd_row {
 7445: /*  border-left: 5px solid #000000; */
 7446: }
 7447: 
 7448: div.LC_grade_show_user div.LC_Box {
 7449:   margin-right: 50px;
 7450: }
 7451: 
 7452: div.LC_grade_submissions,
 7453: div.LC_grade_message_center,
 7454: div.LC_grade_info_links {
 7455:   margin: 5px;
 7456:   width: 99%;
 7457:   background: #FFFFFF;
 7458: }
 7459: 
 7460: div.LC_grade_submissions_header,
 7461: div.LC_grade_message_center_header {
 7462:   font-weight: bold;
 7463:   font-size: large;
 7464: }
 7465: 
 7466: div.LC_grade_submissions_body,
 7467: div.LC_grade_message_center_body {
 7468:   border: 1px solid black;
 7469:   width: 99%;
 7470:   background: #FFFFFF;
 7471: }
 7472: 
 7473: table.LC_scantron_action {
 7474:   width: 100%;
 7475: }
 7476: 
 7477: table.LC_scantron_action tr th {
 7478:   font-weight:bold;
 7479:   font-style:normal;
 7480: }
 7481: 
 7482: .LC_edit_problem_header,
 7483: div.LC_edit_problem_footer {
 7484:   font-weight: normal;
 7485:   font-size:  medium;
 7486:   margin: 2px;
 7487:   background-color: $sidebg;
 7488: }
 7489: 
 7490: div.LC_edit_problem_header,
 7491: div.LC_edit_problem_header div,
 7492: div.LC_edit_problem_footer,
 7493: div.LC_edit_problem_footer div,
 7494: div.LC_edit_problem_editxml_header,
 7495: div.LC_edit_problem_editxml_header div {
 7496:   z-index: 100;
 7497: }
 7498: 
 7499: div.LC_edit_problem_header_title {
 7500:   font-weight: bold;
 7501:   font-size: larger;
 7502:   background: $tabbg;
 7503:   padding: 3px;
 7504:   margin: 0 0 5px 0;
 7505: }
 7506: 
 7507: table.LC_edit_problem_header_title {
 7508:   width: 100%;
 7509:   background: $tabbg;
 7510: }
 7511: 
 7512: div.LC_edit_actionbar {
 7513:     background-color: $sidebg;
 7514:     margin: 0;
 7515:     padding: 0;
 7516:     line-height: 200%;
 7517: }
 7518: 
 7519: div.LC_edit_actionbar div{
 7520:     padding: 0;
 7521:     margin: 0;
 7522:     display: inline-block;
 7523: }
 7524: 
 7525: .LC_edit_opt {
 7526:   padding-left: 1em;
 7527:   white-space: nowrap;
 7528: }
 7529: 
 7530: .LC_edit_problem_latexhelper{
 7531:     text-align: right;
 7532: }
 7533: 
 7534: #LC_edit_problem_colorful div{
 7535:     margin-left: 40px;
 7536: }
 7537: 
 7538: #LC_edit_problem_codemirror div{
 7539:     margin-left: 0px;
 7540: }
 7541: 
 7542: img.stift {
 7543:   border-width: 0;
 7544:   vertical-align: middle;
 7545: }
 7546: 
 7547: table td.LC_mainmenu_col_fieldset {
 7548:   vertical-align: top;
 7549: }
 7550: 
 7551: div.LC_createcourse {
 7552:   margin: 10px 10px 10px 10px;
 7553: }
 7554: 
 7555: .LC_dccid {
 7556:   float: right;
 7557:   margin: 0.2em 0 0 0;
 7558:   padding: 0;
 7559:   font-size: 90%;
 7560:   display:none;
 7561: }
 7562: 
 7563: ol.LC_primary_menu a:hover,
 7564: ol#LC_MenuBreadcrumbs a:hover,
 7565: ol#LC_PathBreadcrumbs a:hover,
 7566: ul#LC_secondary_menu a:hover,
 7567: .LC_FormSectionClearButton input:hover
 7568: ul.LC_TabContent   li:hover a {
 7569:   color:$button_hover;
 7570:   text-decoration:none;
 7571: }
 7572: 
 7573: h1 {
 7574:   padding: 0;
 7575:   line-height:130%;
 7576: }
 7577: 
 7578: h2,
 7579: h3,
 7580: h4,
 7581: h5,
 7582: h6 {
 7583:   margin: 5px 0 5px 0;
 7584:   padding: 0;
 7585:   line-height:130%;
 7586: }
 7587: 
 7588: .LC_hcell {
 7589:   padding:3px 15px 3px 15px;
 7590:   margin: 0;
 7591:   background-color:$tabbg;
 7592:   color:$fontmenu;
 7593:   border-bottom:solid 1px $lg_border_color;
 7594: }
 7595: 
 7596: .LC_Box > .LC_hcell {
 7597:   margin: 0 -10px 10px -10px;
 7598: }
 7599: 
 7600: .LC_noBorder {
 7601:   border: 0;
 7602: }
 7603: 
 7604: .LC_FormSectionClearButton input {
 7605:   background-color:transparent;
 7606:   border: none;
 7607:   cursor:pointer;
 7608:   text-decoration:underline;
 7609: }
 7610: 
 7611: .LC_help_open_topic {
 7612:   color: #FFFFFF;
 7613:   background-color: #EEEEFF;
 7614:   margin: 1px;
 7615:   padding: 4px;
 7616:   border: 1px solid #000033;
 7617:   white-space: nowrap;
 7618:   /* vertical-align: middle; */
 7619: }
 7620: 
 7621: dl,
 7622: ul,
 7623: div,
 7624: fieldset {
 7625:   margin: 10px 10px 10px 0;
 7626:   /* overflow: hidden; */
 7627: }
 7628: 
 7629: article.geogebraweb div {
 7630:     margin: 0;
 7631: }
 7632: 
 7633: fieldset > legend {
 7634:   font-weight: bold;
 7635:   padding: 0 5px 0 5px;
 7636: }
 7637: 
 7638: #LC_nav_bar {
 7639:   float: left;
 7640:   background-color: $pgbg_or_bgcolor;
 7641:   margin: 0 0 2px 0;
 7642: }
 7643: 
 7644: #LC_realm {
 7645:   margin: 0.2em 0 0 0;
 7646:   padding: 0;
 7647:   font-weight: bold;
 7648:   text-align: center;
 7649:   background-color: $pgbg_or_bgcolor;
 7650: }
 7651: 
 7652: #LC_nav_bar em {
 7653:   font-weight: bold;
 7654:   font-style: normal;
 7655: }
 7656: 
 7657: ol.LC_primary_menu {
 7658:   margin: 0;
 7659:   padding: 0;
 7660: }
 7661: 
 7662: ol#LC_PathBreadcrumbs {
 7663:   margin: 0;
 7664: }
 7665: 
 7666: ol.LC_primary_menu li {
 7667:   color: RGB(80, 80, 80);
 7668:   vertical-align: middle;
 7669:   text-align: left;
 7670:   list-style: none;
 7671:   position: relative;
 7672:   float: left;
 7673:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
 7674:   line-height: 1.5em;
 7675: }
 7676: 
 7677: ol.LC_primary_menu li a, 
 7678: ol.LC_primary_menu li p {
 7679:   display: block;
 7680:   margin: 0;
 7681:   padding: 0 5px 0 10px;
 7682:   text-decoration: none;
 7683: }
 7684: 
 7685: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
 7686:   display: inline-block;
 7687:   width: 95%;
 7688:   text-align: left;
 7689: }
 7690: 
 7691: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
 7692:   display: inline-block;
 7693:   width: 5%;
 7694:   float: right;
 7695:   text-align: right;
 7696:   font-size: 70%;
 7697: }
 7698: 
 7699: ol.LC_primary_menu ul {
 7700:   display: none;
 7701:   width: 15em;
 7702:   background-color: $data_table_light;
 7703:   position: absolute;
 7704:   top: 100%;
 7705: }
 7706: 
 7707: ol.LC_primary_menu ul ul {
 7708:   left: 100%;
 7709:   top: 0;
 7710: }
 7711: 
 7712: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
 7713:   display: block;
 7714:   position: absolute;
 7715:   margin: 0;
 7716:   padding: 0;
 7717:   z-index: 2;
 7718: }
 7719: 
 7720: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 7721: /* First Submenu -> size should be smaller than the menu title of the whole menu */
 7722:   font-size: 90%;
 7723:   vertical-align: top;
 7724:   float: none;
 7725:   border-left: 1px solid black;
 7726:   border-right: 1px solid black;
 7727: /* A dark bottom border to visualize different menu options;
 7728: overwritten in the create_submenu routine for the last border-bottom of the menu */
 7729:   border-bottom: 1px solid $data_table_dark;
 7730: }
 7731: 
 7732: ol.LC_primary_menu li li p:hover {
 7733:   color:$button_hover;
 7734:   text-decoration:none;
 7735:   background-color:$data_table_dark;
 7736: }
 7737: 
 7738: ol.LC_primary_menu li li a:hover {
 7739:    color:$button_hover;
 7740:    background-color:$data_table_dark;
 7741: }
 7742: 
 7743: /* Font-size equal to the size of the predecessors*/
 7744: ol.LC_primary_menu li:hover li li {
 7745:   font-size: 100%;
 7746: }
 7747: 
 7748: ol.LC_primary_menu li img {
 7749:   vertical-align: bottom;
 7750:   height: 1.1em;
 7751:   margin: 0.2em 0 0 0;
 7752: }
 7753: 
 7754: ol.LC_primary_menu a {
 7755:   color: RGB(80, 80, 80);
 7756:   text-decoration: none;
 7757: }
 7758: 
 7759: ol.LC_primary_menu a.LC_new_message {
 7760:   font-weight:bold;
 7761:   color: darkred;
 7762: }
 7763: 
 7764: ol.LC_docs_parameters {
 7765:   margin-left: 0;
 7766:   padding: 0;
 7767:   list-style: none;
 7768: }
 7769: 
 7770: ol.LC_docs_parameters li {
 7771:   margin: 0;
 7772:   padding-right: 20px;
 7773:   display: inline;
 7774: }
 7775: 
 7776: ol.LC_docs_parameters li:before {
 7777:   content: "\\002022 \\0020";
 7778: }
 7779: 
 7780: li.LC_docs_parameters_title {
 7781:   font-weight: bold;
 7782: }
 7783: 
 7784: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 7785:   content: "";
 7786: }
 7787: 
 7788: ul#LC_secondary_menu {
 7789:   clear: right;
 7790:   color: $fontmenu;
 7791:   background: $tabbg;
 7792:   list-style: none;
 7793:   padding: 0;
 7794:   margin: 0;
 7795:   width: 100%;
 7796:   text-align: left;
 7797:   float: left;
 7798: }
 7799: 
 7800: ul#LC_secondary_menu li {
 7801:   font-weight: bold;
 7802:   line-height: 1.8em;
 7803:   border-right: 1px solid black;
 7804:   float: left;
 7805: }
 7806: 
 7807: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 7808:   background-color: $data_table_light;
 7809: }
 7810: 
 7811: ul#LC_secondary_menu li a {
 7812:   padding: 0 0.8em;
 7813: }
 7814: 
 7815: ul#LC_secondary_menu li ul {
 7816:   display: none;
 7817: }
 7818: 
 7819: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 7820:   display: block;
 7821:   position: absolute;
 7822:   margin: 0;
 7823:   padding: 0;
 7824:   list-style:none;
 7825:   float: none;
 7826:   background-color: $data_table_light;
 7827:   z-index: 2;
 7828:   margin-left: -1px;
 7829: }
 7830: 
 7831: ul#LC_secondary_menu li ul li {
 7832:   font-size: 90%;
 7833:   vertical-align: top;
 7834:   border-left: 1px solid black;
 7835:   border-right: 1px solid black;
 7836:   background-color: $data_table_light;
 7837:   list-style:none;
 7838:   float: none;
 7839: }
 7840: 
 7841: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 7842:   background-color: $data_table_dark;
 7843: }
 7844: 
 7845: ul.LC_TabContent {
 7846:   display:block;
 7847:   background: $sidebg;
 7848:   border-bottom: solid 1px $lg_border_color;
 7849:   list-style:none;
 7850:   margin: -1px -10px 0 -10px;
 7851:   padding: 0;
 7852: }
 7853: 
 7854: ul.LC_TabContent li,
 7855: ul.LC_TabContentBigger li {
 7856:   float:left;
 7857: }
 7858: 
 7859: ul#LC_secondary_menu li a {
 7860:   color: $fontmenu;
 7861:   text-decoration: none;
 7862: }
 7863: 
 7864: ul.LC_TabContent {
 7865:   min-height:20px;
 7866: }
 7867: 
 7868: ul.LC_TabContent li {
 7869:   vertical-align:middle;
 7870:   padding: 0 16px 0 10px;
 7871:   background-color:$tabbg;
 7872:   border-bottom:solid 1px $lg_border_color;
 7873:   border-left: solid 1px $font;
 7874: }
 7875: 
 7876: ul.LC_TabContent .right {
 7877:   float:right;
 7878: }
 7879: 
 7880: ul.LC_TabContent li a,
 7881: ul.LC_TabContent li {
 7882:   color:rgb(47,47,47);
 7883:   text-decoration:none;
 7884:   font-size:95%;
 7885:   font-weight:bold;
 7886:   min-height:20px;
 7887: }
 7888: 
 7889: ul.LC_TabContent li a:hover,
 7890: ul.LC_TabContent li a:focus {
 7891:   color: $button_hover;
 7892:   background:none;
 7893:   outline:none;
 7894: }
 7895: 
 7896: ul.LC_TabContent li:hover {
 7897:   color: $button_hover;
 7898:   cursor:pointer;
 7899: }
 7900: 
 7901: ul.LC_TabContent li.active {
 7902:   color: $font;
 7903:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 7904:   border-bottom:solid 1px #FFFFFF;
 7905:   cursor: default;
 7906: }
 7907: 
 7908: ul.LC_TabContent li.active a {
 7909:   color:$font;
 7910:   background:#FFFFFF;
 7911:   outline: none;
 7912: }
 7913: 
 7914: ul.LC_TabContent li.goback {
 7915:   float: left;
 7916:   border-left: none;
 7917: }
 7918: 
 7919: #maincoursedoc {
 7920:   clear:both;
 7921: }
 7922: 
 7923: ul.LC_TabContentBigger {
 7924:   display:block;
 7925:   list-style:none;
 7926:   padding: 0;
 7927: }
 7928: 
 7929: ul.LC_TabContentBigger li {
 7930:   vertical-align:bottom;
 7931:   height: 30px;
 7932:   font-size:110%;
 7933:   font-weight:bold;
 7934:   color: #737373;
 7935: }
 7936: 
 7937: ul.LC_TabContentBigger li.active {
 7938:   position: relative;
 7939:   top: 1px;
 7940: }
 7941: 
 7942: ul.LC_TabContentBigger li a {
 7943:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 7944:   height: 30px;
 7945:   line-height: 30px;
 7946:   text-align: center;
 7947:   display: block;
 7948:   text-decoration: none;
 7949:   outline: none;  
 7950: }
 7951: 
 7952: ul.LC_TabContentBigger li.active a {
 7953:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 7954:   color:$font;
 7955: }
 7956: 
 7957: ul.LC_TabContentBigger li b {
 7958:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 7959:   display: block;
 7960:   float: left;
 7961:   padding: 0 30px;
 7962:   border-bottom: 1px solid $lg_border_color;
 7963: }
 7964: 
 7965: ul.LC_TabContentBigger li:hover b {
 7966:   color:$button_hover;
 7967: }
 7968: 
 7969: ul.LC_TabContentBigger li.active b {
 7970:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 7971:   color:$font;
 7972:   border: 0;
 7973: }
 7974: 
 7975: 
 7976: ul.LC_CourseBreadcrumbs {
 7977:   background: $sidebg;
 7978:   height: 2em;
 7979:   padding-left: 10px;
 7980:   margin: 0;
 7981:   list-style-position: inside;
 7982: }
 7983: 
 7984: ol#LC_MenuBreadcrumbs,
 7985: ol#LC_PathBreadcrumbs {
 7986:   padding-left: 10px;
 7987:   margin: 0;
 7988:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 7989: }
 7990: 
 7991: ol#LC_MenuBreadcrumbs li,
 7992: ol#LC_PathBreadcrumbs li,
 7993: ul.LC_CourseBreadcrumbs li {
 7994:   display: inline;
 7995:   white-space: normal;  
 7996: }
 7997: 
 7998: ol#LC_MenuBreadcrumbs li a,
 7999: ul.LC_CourseBreadcrumbs li a {
 8000:   text-decoration: none;
 8001:   font-size:90%;
 8002: }
 8003: 
 8004: ol#LC_MenuBreadcrumbs h1 {
 8005:   display: inline;
 8006:   font-size: 90%;
 8007:   line-height: 2.5em;
 8008:   margin: 0;
 8009:   padding: 0;
 8010: }
 8011: 
 8012: ol#LC_PathBreadcrumbs li a {
 8013:   text-decoration:none;
 8014:   font-size:100%;
 8015:   font-weight:bold;
 8016: }
 8017: 
 8018: .LC_Box {
 8019:   border: solid 1px $lg_border_color;
 8020:   padding: 0 10px 10px 10px;
 8021: }
 8022: 
 8023: .LC_DocsBox {
 8024:   border: solid 1px $lg_border_color;
 8025:   padding: 0 0 10px 10px;
 8026: }
 8027: 
 8028: .LC_AboutMe_Image {
 8029:   float:left;
 8030:   margin-right:10px;
 8031: }
 8032: 
 8033: .LC_Clear_AboutMe_Image {
 8034:   clear:left;
 8035: }
 8036: 
 8037: dl.LC_ListStyleClean dt {
 8038:   padding-right: 5px;
 8039:   display: table-header-group;
 8040: }
 8041: 
 8042: dl.LC_ListStyleClean dd {
 8043:   display: table-row;
 8044: }
 8045: 
 8046: .LC_ListStyleClean,
 8047: .LC_ListStyleSimple,
 8048: .LC_ListStyleNormal,
 8049: .LC_ListStyleSpecial {
 8050:   /* display:block; */
 8051:   list-style-position: inside;
 8052:   list-style-type: none;
 8053:   overflow: hidden;
 8054:   padding: 0;
 8055: }
 8056: 
 8057: .LC_ListStyleSimple li,
 8058: .LC_ListStyleSimple dd,
 8059: .LC_ListStyleNormal li,
 8060: .LC_ListStyleNormal dd,
 8061: .LC_ListStyleSpecial li,
 8062: .LC_ListStyleSpecial dd {
 8063:   margin: 0;
 8064:   padding: 5px 5px 5px 10px;
 8065:   clear: both;
 8066: }
 8067: 
 8068: .LC_ListStyleClean li,
 8069: .LC_ListStyleClean dd {
 8070:   padding-top: 0;
 8071:   padding-bottom: 0;
 8072: }
 8073: 
 8074: .LC_ListStyleSimple dd,
 8075: .LC_ListStyleSimple li {
 8076:   border-bottom: solid 1px $lg_border_color;
 8077: }
 8078: 
 8079: .LC_ListStyleSpecial li,
 8080: .LC_ListStyleSpecial dd {
 8081:   list-style-type: none;
 8082:   background-color: RGB(220, 220, 220);
 8083:   margin-bottom: 4px;
 8084: }
 8085: 
 8086: table.LC_SimpleTable {
 8087:   margin:5px;
 8088:   border:solid 1px $lg_border_color;
 8089: }
 8090: 
 8091: table.LC_SimpleTable tr {
 8092:   padding: 0;
 8093:   border:solid 1px $lg_border_color;
 8094: }
 8095: 
 8096: table.LC_SimpleTable thead {
 8097:   background:rgb(220,220,220);
 8098: }
 8099: 
 8100: div.LC_columnSection {
 8101:   display: block;
 8102:   clear: both;
 8103:   overflow: hidden;
 8104:   margin: 0;
 8105: }
 8106: 
 8107: div.LC_columnSection>* {
 8108:   float: left;
 8109:   margin: 10px 20px 10px 0;
 8110:   overflow:hidden;
 8111: }
 8112: 
 8113: table em {
 8114:   font-weight: bold;
 8115:   font-style: normal;
 8116: }
 8117: 
 8118: table.LC_tableBrowseRes,
 8119: table.LC_tableOfContent {
 8120:   border:none;
 8121:   border-spacing: 1px;
 8122:   padding: 3px;
 8123:   background-color: #FFFFFF;
 8124:   font-size: 90%;
 8125: }
 8126: 
 8127: table.LC_tableOfContent {
 8128:   border-collapse: collapse;
 8129: }
 8130: 
 8131: table.LC_tableBrowseRes a,
 8132: table.LC_tableOfContent a {
 8133:   background-color: transparent;
 8134:   text-decoration: none;
 8135: }
 8136: 
 8137: table.LC_tableOfContent img {
 8138:   border: none;
 8139:   height: 1.3em;
 8140:   vertical-align: text-bottom;
 8141:   margin-right: 0.3em;
 8142: }
 8143: 
 8144: a#LC_content_toolbar_firsthomework {
 8145:   background-image:url(/res/adm/pages/open-first-problem.gif);
 8146: }
 8147: 
 8148: a#LC_content_toolbar_everything {
 8149:   background-image:url(/res/adm/pages/show-all.gif);
 8150: }
 8151: 
 8152: a#LC_content_toolbar_uncompleted {
 8153:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 8154: }
 8155: 
 8156: #LC_content_toolbar_clearbubbles {
 8157:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 8158: }
 8159: 
 8160: a#LC_content_toolbar_changefolder {
 8161:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 8162: }
 8163: 
 8164: a#LC_content_toolbar_changefolder_toggled {
 8165:   background-image:url(/res/adm/pages/open-all-folders.gif);
 8166: }
 8167: 
 8168: a#LC_content_toolbar_edittoplevel {
 8169:   background-image:url(/res/adm/pages/edittoplevel.gif);
 8170: }
 8171: 
 8172: a#LC_content_toolbar_printout {
 8173:   background-image:url(/res/adm/pages/printout.gif);
 8174: }
 8175: 
 8176: ul#LC_toolbar li a:hover {
 8177:   background-position: bottom center;
 8178: }
 8179: 
 8180: ul#LC_toolbar {
 8181:   padding: 0;
 8182:   margin: 2px;
 8183:   list-style:none;
 8184:   position:relative;
 8185:   background-color:white;
 8186:   overflow: auto;
 8187: }
 8188: 
 8189: ul#LC_toolbar li {
 8190:   border:1px solid white;
 8191:   padding: 0;
 8192:   margin: 0;
 8193:   float: left;
 8194:   display:inline;
 8195:   vertical-align:middle;
 8196:   white-space: nowrap;
 8197: }
 8198: 
 8199: 
 8200: a.LC_toolbarItem {
 8201:   display:block;
 8202:   padding: 0;
 8203:   margin: 0;
 8204:   height: 32px;
 8205:   width: 32px;
 8206:   color:white;
 8207:   border: none;
 8208:   background-repeat:no-repeat;
 8209:   background-color:transparent;
 8210: }
 8211: 
 8212: ul.LC_funclist {
 8213:     margin: 0;
 8214:     padding: 0.5em 1em 0.5em 0;
 8215: }
 8216: 
 8217: ul.LC_funclist > li:first-child {
 8218:     font-weight:bold; 
 8219:     margin-left:0.8em;
 8220: }
 8221: 
 8222: ul.LC_funclist + ul.LC_funclist {
 8223:     /* 
 8224:        left border as a seperator if we have more than
 8225:        one list 
 8226:     */
 8227:     border-left: 1px solid $sidebg;
 8228:     /* 
 8229:        this hides the left border behind the border of the 
 8230:        outer box if element is wrapped to the next 'line' 
 8231:     */
 8232:     margin-left: -1px;
 8233: }
 8234: 
 8235: ul.LC_funclist li {
 8236:   display: inline;
 8237:   white-space: nowrap;
 8238:   margin: 0 0 0 25px;
 8239:   line-height: 150%;
 8240: }
 8241: 
 8242: .LC_hidden {
 8243:   display: none;
 8244: }
 8245: 
 8246: .LCmodal-overlay {
 8247: 		position:fixed;
 8248: 		top:0;
 8249: 		right:0;
 8250: 		bottom:0;
 8251: 		left:0;
 8252: 		height:100%;
 8253: 		width:100%;
 8254: 		margin:0;
 8255: 		padding:0;
 8256: 		background:#999;
 8257: 		opacity:.75;
 8258: 		filter: alpha(opacity=75);
 8259: 		-moz-opacity: 0.75;
 8260: 		z-index:101;
 8261: }
 8262: 
 8263: * html .LCmodal-overlay {   
 8264: 		position: absolute;
 8265: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 8266: }
 8267: 
 8268: .LCmodal-window {
 8269: 		position:fixed;
 8270: 		top:50%;
 8271: 		left:50%;
 8272: 		margin:0;
 8273: 		padding:0;
 8274: 		z-index:102;
 8275: 	}
 8276: 
 8277: * html .LCmodal-window {
 8278: 		position:absolute;
 8279: }
 8280: 
 8281: .LCclose-window {
 8282: 		position:absolute;
 8283: 		width:32px;
 8284: 		height:32px;
 8285: 		right:8px;
 8286: 		top:8px;
 8287: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 8288: 		text-indent:-99999px;
 8289: 		overflow:hidden;
 8290: 		cursor:pointer;
 8291: }
 8292: 
 8293: .LCisDisabled {
 8294:   cursor: not-allowed;
 8295:   opacity: 0.5;
 8296: }
 8297: 
 8298: a[aria-disabled="true"] {
 8299:   color: currentColor;
 8300:   display: inline-block;  /* For IE11/ MS Edge bug */
 8301:   pointer-events: none;
 8302:   text-decoration: none;
 8303: }
 8304: 
 8305: pre.LC_wordwrap {
 8306:   white-space: pre-wrap;
 8307:   white-space: -moz-pre-wrap;
 8308:   white-space: -pre-wrap;
 8309:   white-space: -o-pre-wrap;
 8310:   word-wrap: break-word;
 8311: }
 8312: 
 8313: /*
 8314:   styles used by TTH when "Default set of options to pass to tth/m
 8315:   when converting TeX" in course settings has been set
 8316: 
 8317:   option passed: -t
 8318: 
 8319: */
 8320: 
 8321: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 8322: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 8323: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 8324: td div.norm {line-height:normal;}
 8325: 
 8326: /*
 8327:   option passed -y3
 8328: */
 8329: 
 8330: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 8331: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 8332: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 8333: 
 8334: #LC_minitab_header {
 8335:   float:left;
 8336:   width:100%;
 8337:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
 8338:   font-size:93%;
 8339:   line-height:normal;
 8340:   margin: 0.5em 0 0.5em 0;
 8341: }
 8342: #LC_minitab_header ul {
 8343:   margin:0;
 8344:   padding:10px 10px 0;
 8345:   list-style:none;
 8346: }
 8347: #LC_minitab_header li {
 8348:   float:left;
 8349:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
 8350:   margin:0;
 8351:   padding:0 0 0 9px;
 8352: }
 8353: #LC_minitab_header a {
 8354:   display:block;
 8355:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
 8356:   padding:5px 15px 4px 6px;
 8357: }
 8358: #LC_minitab_header #LC_current_minitab {
 8359:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
 8360: }
 8361: #LC_minitab_header #LC_current_minitab a {
 8362:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
 8363:   padding-bottom:5px;
 8364: }
 8365: 
 8366: 
 8367: END
 8368: }
 8369: 
 8370: =pod
 8371: 
 8372: =item * &headtag()
 8373: 
 8374: Returns a uniform footer for LON-CAPA web pages.
 8375: 
 8376: Inputs: $title - optional title for the head
 8377:         $head_extra - optional extra HTML to put inside the <head>
 8378:         $args - optional arguments
 8379:             force_register - if is true call registerurl so the remote is 
 8380:                              informed
 8381:             redirect       -> array ref of
 8382:                                    1- seconds before redirect occurs
 8383:                                    2- url to redirect to
 8384:                                    3- whether the side effect should occur
 8385:                            (side effect of setting 
 8386:                                $env{'internal.head.redirect'} to the url 
 8387:                                redirected to)
 8388:                                    4- whether the redirect target should be
 8389:                                       the opener of the current (pop-up)
 8390:                                       window (side effect of setting
 8391:                                       $env{'internal.head.to_opener'} to
 8392:                                       1, if true.
 8393:                                    5- whether encrypt check should be skipped
 8394:             domain         -> force to color decorate a page for a specific
 8395:                                domain
 8396:             function       -> force usage of a specific rolish color scheme
 8397:             bgcolor        -> override the default page bgcolor
 8398:             no_auto_mt_title
 8399:                            -> prevent &mt()ing the title arg
 8400: 
 8401: =cut
 8402: 
 8403: sub headtag {
 8404:     my ($title,$head_extra,$args) = @_;
 8405:     
 8406:     my $function = $args->{'function'} || &get_users_function();
 8407:     my $domain   = $args->{'domain'}   || &determinedomain();
 8408:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 8409:     my $httphost = $args->{'use_absolute'};
 8410:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 8411: 		   $Apache::lonnet::perlvar{'lonVersion'},
 8412: 		   #time(),
 8413: 		   $env{'environment.color.timestamp'},
 8414: 		   $function,$domain,$bgcolor);
 8415: 
 8416:     $url = '/adm/css/'.&escape($url).'.css';
 8417: 
 8418:     my $result =
 8419: 	'<head>'.
 8420: 	&font_settings($args);
 8421: 
 8422:     my $inhibitprint;
 8423:     if ($args->{'print_suppress'}) {
 8424:         $inhibitprint = &print_suppression();
 8425:     }
 8426: 
 8427:     if (!$args->{'frameset'}) {
 8428: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 8429:     }
 8430:     if ($args->{'force_register'}) {
 8431:         $result .= &Apache::lonmenu::registerurl(1);
 8432:     }
 8433:     if (!$args->{'no_nav_bar'} 
 8434: 	&& !$args->{'only_body'}
 8435: 	&& !$args->{'frameset'}) {
 8436: 	$result .= &help_menu_js($httphost);
 8437:         $result.=&modal_window();
 8438:         $result.=&togglebox_script();
 8439:         $result.=&wishlist_window();
 8440:         $result.=&LCprogressbarUpdate_script();
 8441:     } else {
 8442:         if ($args->{'add_modal'}) {
 8443:            $result.=&modal_window();
 8444:         }
 8445:         if ($args->{'add_wishlist'}) {
 8446:            $result.=&wishlist_window();
 8447:         }
 8448:         if ($args->{'add_togglebox'}) {
 8449:            $result.=&togglebox_script();
 8450:         }
 8451:         if ($args->{'add_progressbar'}) {
 8452:            $result.=&LCprogressbarUpdate_script();
 8453:         }
 8454:     }
 8455:     if (ref($args->{'redirect'})) {
 8456: 	my ($time,$url,$inhibit_continue,$to_opener,$skip_enc_check) = @{$args->{'redirect'}};
 8457:         if (!$skip_enc_check) {
 8458: 	    $url = &Apache::lonenc::check_encrypt($url);
 8459:         }
 8460: 	if (!$inhibit_continue) {
 8461: 	    $env{'internal.head.redirect'} = $url;
 8462: 	}
 8463:         $result.=<<"ADDMETA";
 8464: <meta http-equiv="pragma" content="no-cache" />
 8465: ADDMETA
 8466:         if ($to_opener) {
 8467:             $env{'internal.head.to_opener'} = 1;
 8468:             my $dest = &js_escape($url);
 8469:             my $timeout = int($time * 1000);
 8470:             $result .=<<"ENDJS";
 8471: <script type="text/javascript">
 8472: // <![CDATA[
 8473: function LC_To_Opener() {
 8474:     var dest = '$dest';
 8475:     if (dest != '') {
 8476:         if (window.opener != null && !window.opener.closed) {
 8477:             window.opener.location.href=dest;
 8478:             window.close();
 8479:         } else {
 8480:             window.location.href=dest;
 8481:         }
 8482:     }
 8483: }
 8484: \$(document).ready(function () {
 8485:     setTimeout('LC_To_Opener()',$timeout);
 8486: });
 8487: // ]]>
 8488: </script>
 8489: ENDJS
 8490:         } else {
 8491:             $result.=<<"ADDMETA";
 8492: <meta http-equiv="Refresh" content="$time; url=$url" />
 8493: ADDMETA
 8494:         }
 8495:     } else {
 8496:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
 8497:             my $requrl = $env{'request.uri'};
 8498:             if ($requrl eq '') {
 8499:                 $requrl = $ENV{'REQUEST_URI'};
 8500:                 $requrl =~ s/\?.+$//;
 8501:             }
 8502:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
 8503:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
 8504:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
 8505:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
 8506:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
 8507:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
 8508:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 8509:                     my ($offload,$offloadoth);
 8510:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
 8511:                         if ($domdefs{'offloadnow'}{$lonhost}) {
 8512:                             $offload = 1;
 8513:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
 8514:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
 8515:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
 8516:                                     $offloadoth = 1;
 8517:                                     $dom_in_use = $env{'user.domain'};
 8518:                                 }
 8519:                             }
 8520:                         }
 8521:                     }
 8522:                     unless ($offload) {
 8523:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
 8524:                             if ($domdefs{'offloadoth'}{$lonhost}) {
 8525:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
 8526:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
 8527:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
 8528:                                         $offload = 1;
 8529:                                         $offloadoth = 1;
 8530:                                         $dom_in_use = $env{'user.domain'};
 8531:                                     }
 8532:                                 }
 8533:                             }
 8534:                         }
 8535:                     }
 8536:                     if ($offload) {
 8537:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
 8538:                         if (($newserver eq '') && ($offloadoth)) {
 8539:                             my @domains = &Apache::lonnet::current_machine_domains();
 8540:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) {
 8541:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
 8542:                             }
 8543:                         }
 8544:                         if (($newserver) && ($newserver ne $lonhost)) {
 8545:                             my $numsec = 5;
 8546:                             my $timeout = $numsec * 1000;
 8547:                             my ($newurl,$locknum,%locks,$msg);
 8548:                             if ($env{'request.role.adv'}) {
 8549:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
 8550:                             }
 8551:                             my $disable_submit = 0;
 8552:                             if ($requrl =~ /$LONCAPA::assess_re/) {
 8553:                                 $disable_submit = 1;
 8554:                             }
 8555:                             if ($locknum) {
 8556:                                 my @lockinfo = sort(values(%locks));
 8557:                                 $msg = &mt('Once the following tasks are complete:')." \n".
 8558:                                        join(", ",sort(values(%locks)))."\n";
 8559:                                 if (&show_course()) {
 8560:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
 8561:                                 } else {
 8562:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
 8563:                                 }
 8564:                             } else {
 8565:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
 8566:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
 8567:                                 }
 8568:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
 8569:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
 8570:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
 8571:                                     $newurl .= '&role='.$env{'request.role'};
 8572:                                 }
 8573:                                 if ($env{'request.symb'}) {
 8574:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
 8575:                                     if ($shownsymb =~ m{^/enc/}) {
 8576:                                         my $reqdmajor = 2;
 8577:                                         my $reqdminor = 11;
 8578:                                         my $reqdsubminor = 3;
 8579:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
 8580:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
 8581:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
 8582:                                         if (($major eq '' && $minor eq '') ||
 8583:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
 8584:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
 8585:                                              ($reqdsubminor > $subminor))))) {
 8586:                                             undef($shownsymb);
 8587:                                         }
 8588:                                     }
 8589:                                     if ($shownsymb) {
 8590:                                         &js_escape(\$shownsymb);
 8591:                                         $newurl .= '&symb='.$shownsymb;
 8592:                                     }
 8593:                                 } else {
 8594:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
 8595:                                     &js_escape(\$shownurl);
 8596:                                     $newurl .= '&origurl='.$shownurl;
 8597:                                 }
 8598:                             }
 8599:                             &js_escape(\$msg);
 8600:                             $result.=<<OFFLOAD
 8601: <meta http-equiv="pragma" content="no-cache" />
 8602: <script type="text/javascript">
 8603: // <![CDATA[
 8604: function LC_Offload_Now() {
 8605:     var dest = "$newurl";
 8606:     if (dest != '') {
 8607:         window.location.href="$newurl";
 8608:     }
 8609: }
 8610: \$(document).ready(function () {
 8611:     window.alert('$msg');
 8612:     if ($disable_submit) {
 8613:         \$(".LC_hwk_submit").prop("disabled", true);
 8614:         \$( ".LC_textline" ).prop( "readonly", "readonly");
 8615:     }
 8616:     setTimeout('LC_Offload_Now()', $timeout);
 8617: });
 8618: // ]]>
 8619: </script>
 8620: OFFLOAD
 8621:                         }
 8622:                     }
 8623:                 }
 8624:             }
 8625:         }
 8626:     }
 8627:     if (!defined($title)) {
 8628: 	$title = 'The LearningOnline Network with CAPA';
 8629:     }
 8630:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 8631:     $result .= '<title> LON-CAPA '.$title.'</title>'
 8632: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
 8633:     if (!$args->{'frameset'}) {
 8634:         $result .= ' /';
 8635:     }
 8636:     $result .= '>'
 8637:         .$inhibitprint
 8638: 	.$head_extra;
 8639:     my $clientmobile;
 8640:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 8641:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
 8642:     } else {
 8643:         $clientmobile = $env{'browser.mobile'};
 8644:     }
 8645:     if ($clientmobile) {
 8646:         $result .= '
 8647: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 8648: <meta name="apple-mobile-web-app-capable" content="yes" />';
 8649:     }
 8650:     $result .= '<meta name="google" content="notranslate" />'."\n";
 8651:     return $result.'</head>';
 8652: }
 8653: 
 8654: =pod
 8655: 
 8656: =item * &font_settings()
 8657: 
 8658: Returns neccessary <meta> to set the proper encoding
 8659: 
 8660: Inputs: optional reference to HASH -- $args passed to &headtag()
 8661: 
 8662: =cut
 8663: 
 8664: sub font_settings {
 8665:     my ($args) = @_;
 8666:     my $headerstring='';
 8667:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
 8668:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
 8669: 	$headerstring.=
 8670: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
 8671:         if (!$args->{'frameset'}) {
 8672:             $headerstring.= ' /';
 8673:         }
 8674:         $headerstring .= '>'."\n";
 8675:     }
 8676:     return $headerstring;
 8677: }
 8678: 
 8679: =pod
 8680: 
 8681: =item * &print_suppression()
 8682: 
 8683: In course context returns css which causes the body to be blank when media="print",
 8684: if printout generation is unavailable for the current resource.
 8685: 
 8686: This could be because:
 8687: 
 8688: (a) printstartdate is in the future
 8689: 
 8690: (b) printenddate is in the past
 8691: 
 8692: (c) there is an active exam block with "printout"
 8693: functionality blocked
 8694: 
 8695: Users with pav, pfo or evb privileges are exempt.
 8696: 
 8697: Inputs: none
 8698: 
 8699: =cut
 8700: 
 8701: 
 8702: sub print_suppression {
 8703:     my $noprint;
 8704:     if ($env{'request.course.id'}) {
 8705:         my $scope = $env{'request.course.id'};
 8706:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8707:             (&Apache::lonnet::allowed('pfo',$scope))) {
 8708:             return;
 8709:         }
 8710:         if ($env{'request.course.sec'} ne '') {
 8711:             $scope .= "/$env{'request.course.sec'}";
 8712:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8713:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 8714:                 return;
 8715:             }
 8716:         }
 8717:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8718:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8719:         my $clientip = &Apache::lonnet::get_requestor_ip();
 8720:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
 8721:         if ($blocked) {
 8722:             my $checkrole = "cm./$cdom/$cnum";
 8723:             if ($env{'request.course.sec'} ne '') {
 8724:                 $checkrole .= "/$env{'request.course.sec'}";
 8725:             }
 8726:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 8727:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 8728:                 $noprint = 1;
 8729:             }
 8730:         }
 8731:         unless ($noprint) {
 8732:             my $symb = &Apache::lonnet::symbread();
 8733:             if ($symb ne '') {
 8734:                 my $navmap = Apache::lonnavmaps::navmap->new();
 8735:                 if (ref($navmap)) {
 8736:                     my $res = $navmap->getBySymb($symb);
 8737:                     if (ref($res)) {
 8738:                         if (!$res->resprintable()) {
 8739:                             $noprint = 1;
 8740:                         }
 8741:                     }
 8742:                 }
 8743:             }
 8744:         }
 8745:         if ($noprint) {
 8746:             return <<"ENDSTYLE";
 8747: <style type="text/css" media="print">
 8748:     body { display:none }
 8749: </style>
 8750: ENDSTYLE
 8751:         }
 8752:     }
 8753:     return;
 8754: }
 8755: 
 8756: =pod
 8757: 
 8758: =item * &xml_begin()
 8759: 
 8760: Returns the needed doctype and <html>
 8761: 
 8762: Inputs: none
 8763: 
 8764: =cut
 8765: 
 8766: sub xml_begin {
 8767:     my ($is_frameset) = @_;
 8768:     my $output='';
 8769: 
 8770:     if ($env{'browser.mathml'}) {
 8771: 	$output='<?xml version="1.0"?>'
 8772:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 8773: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 8774:             
 8775: #	    .'<!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">] >'
 8776: 	    .'<!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">'
 8777:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 8778: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 8779:     } elsif ($is_frameset) {
 8780:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
 8781:                 '<html>'."\n";
 8782:     } else {
 8783: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
 8784:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
 8785:     }
 8786:     return $output;
 8787: }
 8788: 
 8789: =pod
 8790: 
 8791: =item * &start_page()
 8792: 
 8793: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 8794: 
 8795: Inputs:
 8796: 
 8797: =over 4
 8798: 
 8799: $title - optional title for the page
 8800: 
 8801: $head_extra - optional extra HTML to incude inside the <head>
 8802: 
 8803: $args - additional optional args supported are:
 8804: 
 8805: =over 8
 8806: 
 8807:              only_body      -> is true will set &bodytag() onlybodytag
 8808:                                     arg on
 8809:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 8810:              add_entries    -> additional attributes to add to the  <body>
 8811:              domain         -> force to color decorate a page for a 
 8812:                                     specific domain
 8813:              function       -> force usage of a specific rolish color
 8814:                                     scheme
 8815:              redirect       -> see &headtag()
 8816:              bgcolor        -> override the default page bg color
 8817:              js_ready       -> return a string ready for being used in 
 8818:                                     a javascript writeln
 8819:              html_encode    -> return a string ready for being used in 
 8820:                                     a html attribute
 8821:              force_register -> if is true will turn on the &bodytag()
 8822:                                     $forcereg arg
 8823:              frameset       -> if true will start with a <frameset>
 8824:                                     rather than <body>
 8825:              skip_phases    -> hash ref of 
 8826:                                     head -> skip the <html><head> generation
 8827:                                     body -> skip all <body> generation
 8828:              no_inline_link -> if true and in remote mode, don't show the
 8829:                                     'Switch To Inline Menu' link
 8830:              no_auto_mt_title -> prevent &mt()ing the title arg
 8831:              bread_crumbs ->             Array containing breadcrumbs
 8832:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 8833:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
 8834:                                     to lonhtmlcommon::breadcrumbs
 8835:              group          -> includes the current group, if page is for a
 8836:                                specific group
 8837:              use_absolute   -> for request for external resource or syllabus, this
 8838:                                will contain https://<hostname> if server uses
 8839:                                https (as per hosts.tab), but request is for http
 8840:              hostname       -> hostname, originally from $r->hostname(), (optional).
 8841:              links_disabled -> Links in primary and secondary menus are disabled
 8842:                                (Can enable them once page has loaded - see lonroles.pm
 8843:                                for an example).
 8844:              links_target   -> Target for links, e.g., _parent (optional).
 8845: 
 8846: =back
 8847: 
 8848: =back
 8849: 
 8850: =cut
 8851: 
 8852: sub start_page {
 8853:     my ($title,$head_extra,$args) = @_;
 8854:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 8855: 
 8856:     $env{'internal.start_page'}++;
 8857:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
 8858: 
 8859:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 8860:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
 8861:     }
 8862: 
 8863:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
 8864:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
 8865:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
 8866:                 $args->{'no_primary_menu'} = 1;
 8867:             }
 8868:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
 8869:                 $args->{'no_inline_menu'} = 1;
 8870:             }
 8871:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
 8872:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
 8873:             }
 8874:         } else {
 8875:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8876:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
 8877:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
 8878:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
 8879:                     $args->{'no_primary_menu'} = 1;
 8880:                 }
 8881:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
 8882:                     $args->{'no_inline_menu'} = 1;
 8883:                 }
 8884:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
 8885:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
 8886:                 }
 8887:             }
 8888:         }
 8889:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
 8890:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
 8891:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
 8892:     } elsif ($env{'request.course.id'}) {
 8893:         my $expiretime=600;
 8894:         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
 8895:             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
 8896:         }
 8897:         my ($deeplinkmenu,$menuref);
 8898:         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
 8899:         if ($menucoll) {
 8900:             if (ref($menuref) eq 'HASH') {
 8901:                 %menu = %{$menuref};
 8902:             }
 8903:             if ($menu{'top'} eq 'n') {
 8904:                 $args->{'no_primary_menu'} = 1;
 8905:             }
 8906:             if ($menu{'inline'} eq 'n') {
 8907:                 unless (&Apache::lonnet::allowed('opa')) {
 8908:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8909:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8910:                     my $crstype = &course_type();
 8911:                     my $now = time;
 8912:                     my $ccrole;
 8913:                     if ($crstype eq 'Community') {
 8914:                         $ccrole = 'co';
 8915:                     } else {
 8916:                         $ccrole = 'cc';
 8917:                     }
 8918:                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
 8919:                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
 8920:                         if ((($start) && ($start<0)) ||
 8921:                             (($end) && ($end<$now))  ||
 8922:                             (($start) && ($now<$start))) {
 8923:                             $args->{'no_inline_menu'} = 1;
 8924:                         }
 8925:                     } else {
 8926:                         $args->{'no_inline_menu'} = 1;
 8927:                     }
 8928:                 }
 8929:             }
 8930:         }
 8931:     }
 8932: 
 8933:     my $showncrumbs;
 8934:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 8935: 	if ($args->{'frameset'}) {
 8936: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 8937: 						$args->{'add_entries'});
 8938: 	    $result .= "\n<frameset $attr_string>\n";
 8939:         } else {
 8940:             $result .=
 8941:                 &bodytag($title, 
 8942:                          $args->{'function'},       $args->{'add_entries'},
 8943:                          $args->{'only_body'},      $args->{'domain'},
 8944:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 8945:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
 8946:                          $args,                     \@advtools,
 8947:                          $ltiscope,$ltiuri,\%ltimenu,$menucoll,\%menu,\$showncrumbs);
 8948:         }
 8949:     }
 8950: 
 8951:     if ($args->{'js_ready'}) {
 8952: 		$result = &js_ready($result);
 8953:     }
 8954:     if ($args->{'html_encode'}) {
 8955: 		$result = &html_encode($result);
 8956:     }
 8957: 
 8958:     # Preparation for new and consistent functionlist at top of screen
 8959:     # if ($args->{'functionlist'}) {
 8960:     #            $result .= &build_functionlist();
 8961:     #}
 8962: 
 8963:     # Don't add anything more if only_body wanted or in const space
 8964:     return $result if    $args->{'only_body'} 
 8965:                       || $env{'request.state'} eq 'construct';
 8966: 
 8967:     #Breadcrumbs
 8968:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 8969:         unless ($showncrumbs) {
 8970: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 8971: 		#if any br links exists, add them to the breadcrumbs
 8972: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 8973: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 8974: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 8975: 			}
 8976: 		}
 8977:                 # if @advtools array contains items add then to the breadcrumbs
 8978:                 if (@advtools > 0) {
 8979:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 8980:                 }
 8981:                 my $menulink;
 8982:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
 8983:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
 8984:                     ($ltiscope eq 'map') || ($ltiscope eq 'resource')) {
 8985:                     $menulink = 0;
 8986:                 } else {
 8987:                     undef($menulink);
 8988:                 }
 8989:                 my $linkprotout;
 8990:                 if ($env{'request.deeplink.login'}) {
 8991:                     my $linkprotout = &Apache::lonmenu::linkprot_exit();
 8992:                     if ($linkprotout) {
 8993:                         &Apache::lonhtmlcommon::add_breadcrumb_tool('tools',$linkprotout);
 8994:                     }
 8995:                 }
 8996: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 8997: 		if(exists($args->{'bread_crumbs_component'})){
 8998: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
 8999: 		} else {
 9000: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
 9001: 		}
 9002:         }
 9003:     } elsif (($env{'environment.remote'} eq 'on') &&
 9004:              ($env{'form.inhibitmenu'} ne 'yes') &&
 9005:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
 9006:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
 9007:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
 9008:     }
 9009:     return $result;
 9010: }
 9011: 
 9012: sub end_page {
 9013:     my ($args) = @_;
 9014:     $env{'internal.end_page'}++;
 9015:     my $result;
 9016:     if ($args->{'discussion'}) {
 9017: 	my ($target,$parser);
 9018: 	if (ref($args->{'discussion'})) {
 9019: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 9020: 				$args->{'discussion'}{'parser'});
 9021: 	}
 9022: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 9023:     }
 9024:     if ($args->{'frameset'}) {
 9025: 	$result .= '</frameset>';
 9026:     } else {
 9027: 	$result .= &endbodytag($args);
 9028:     }
 9029:     unless ($args->{'notbody'}) {
 9030:         $result .= "\n</html>";
 9031:     }
 9032: 
 9033:     if ($args->{'js_ready'}) {
 9034: 	$result = &js_ready($result);
 9035:     }
 9036: 
 9037:     if ($args->{'html_encode'}) {
 9038: 	$result = &html_encode($result);
 9039:     }
 9040: 
 9041:     return $result;
 9042: }
 9043: 
 9044: sub menucoll_in_effect {
 9045:     my ($menucoll,$deeplinkmenu,%menu);
 9046:     if ($env{'request.course.id'}) {
 9047:         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
 9048:         if ($env{'request.deeplink.login'}) {
 9049:             my ($deeplink_symb,$deeplink,$check_login_symb);
 9050:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9051:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9052:             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
 9053:                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
 9054:                     my $navmap = Apache::lonnavmaps::navmap->new();
 9055:                     if (ref($navmap)) {
 9056:                         $deeplink = $navmap->get_mapparam(undef,
 9057:                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
 9058:                                                           '0.deeplink');
 9059:                     } else {
 9060:                         $check_login_symb = 1;
 9061:                     }
 9062:                 } else {
 9063:                     my $symb=&Apache::lonnet::symbread();
 9064:                     if ($symb) {
 9065:                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
 9066:                     } else {
 9067:                         $check_login_symb = 1;
 9068:                     }
 9069:                 }
 9070:             } else {
 9071:                 $check_login_symb = 1;
 9072:             }
 9073:             if ($check_login_symb) {
 9074:                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
 9075:                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
 9076:                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
 9077:                     my $navmap = Apache::lonnavmaps::navmap->new();
 9078:                     if (ref($navmap)) {
 9079:                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
 9080:                     }
 9081:                 } else {
 9082:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
 9083:                 }
 9084:             }
 9085:             if ($deeplink ne '') {
 9086:                 my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
 9087:                 if ($display =~ /^\d+$/) {
 9088:                     $deeplinkmenu = 1;
 9089:                     $menucoll = $display;
 9090:                 }
 9091:             }
 9092:         }
 9093:         if ($menucoll) {
 9094:             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
 9095:         }
 9096:     }
 9097:     return ($menucoll,$deeplinkmenu,\%menu);
 9098: }
 9099: 
 9100: sub deeplink_login_symb {
 9101:     my ($cnum,$cdom) = @_;
 9102:     my $login_symb;
 9103:     if ($env{'request.deeplink.login'}) {
 9104:         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
 9105:     }
 9106:     return $login_symb;
 9107: }
 9108: 
 9109: sub symb_from_tinyurl {
 9110:     my ($url,$cnum,$cdom) = @_;
 9111:     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
 9112:         my $key = $1;
 9113:         my ($tinyurl,$login);
 9114:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
 9115:         if (defined($cached)) {
 9116:             $tinyurl = $result;
 9117:         } else {
 9118:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
 9119:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
 9120:             if ($currtiny{$key} ne '') {
 9121:                 $tinyurl = $currtiny{$key};
 9122:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
 9123:             }
 9124:         }
 9125:         if ($tinyurl ne '') {
 9126:             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
 9127:             if (wantarray) {
 9128:                 return ($cnumreq,$symb);
 9129:             } elsif ($cnumreq eq $cnum) {
 9130:                 return $symb;
 9131:             }
 9132:         }
 9133:     }
 9134:     if (wantarray) {
 9135:         return ();
 9136:     } else {
 9137:         return;
 9138:     }
 9139: }
 9140: 
 9141: sub wishlist_window {
 9142:     return(<<'ENDWISHLIST');
 9143: <script type="text/javascript">
 9144: // <![CDATA[
 9145: // <!-- BEGIN LON-CAPA Internal
 9146: function set_wishlistlink(title, path) {
 9147:     if (!title) {
 9148:         title = document.title;
 9149:         title = title.replace(/^LON-CAPA /,'');
 9150:     }
 9151:     title = encodeURIComponent(title);
 9152:     title = title.replace("'","\\\'");
 9153:     if (!path) {
 9154:         path = location.pathname;
 9155:     }
 9156:     path = encodeURIComponent(path);
 9157:     path = path.replace("'","\\\'");
 9158:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 9159:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 9160: }
 9161: // END LON-CAPA Internal -->
 9162: // ]]>
 9163: </script>
 9164: ENDWISHLIST
 9165: }
 9166: 
 9167: sub modal_window {
 9168:     return(<<'ENDMODAL');
 9169: <script type="text/javascript">
 9170: // <![CDATA[
 9171: // <!-- BEGIN LON-CAPA Internal
 9172: var modalWindow = {
 9173: 	parent:"body",
 9174: 	windowId:null,
 9175: 	content:null,
 9176: 	width:null,
 9177: 	height:null,
 9178: 	close:function()
 9179: 	{
 9180: 	        $(".LCmodal-window").remove();
 9181: 	        $(".LCmodal-overlay").remove();
 9182: 	},
 9183: 	open:function()
 9184: 	{
 9185: 		var modal = "";
 9186: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 9187: 		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;\">";
 9188: 		modal += this.content;
 9189: 		modal += "</div>";	
 9190: 
 9191: 		$(this.parent).append(modal);
 9192: 
 9193: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 9194: 		$(".LCclose-window").click(function(){modalWindow.close();});
 9195: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 9196: 	}
 9197: };
 9198: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
 9199: 	{
 9200:                 source = source.replace(/'/g,"&#39;");
 9201: 		modalWindow.windowId = "myModal";
 9202: 		modalWindow.width = width;
 9203: 		modalWindow.height = height;
 9204: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
 9205: 		modalWindow.open();
 9206: 	};
 9207: // END LON-CAPA Internal -->
 9208: // ]]>
 9209: </script>
 9210: ENDMODAL
 9211: }
 9212: 
 9213: sub modal_link {
 9214:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
 9215:     unless ($width) { $width=480; }
 9216:     unless ($height) { $height=400; }
 9217:     unless ($scrolling) { $scrolling='yes'; }
 9218:     unless ($transparency) { $transparency='true'; }
 9219: 
 9220:     my $target_attr;
 9221:     if (defined($target)) {
 9222:         $target_attr = 'target="'.$target.'"';
 9223:     }
 9224:     return <<"ENDLINK";
 9225: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
 9226: ENDLINK
 9227: }
 9228: 
 9229: sub modal_adhoc_script {
 9230:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
 9231:     my $mathjax;
 9232:     if ($possmathjax) {
 9233:         $mathjax = <<'ENDJAX';
 9234:                if (typeof MathJax == 'object') {
 9235:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
 9236:                }
 9237: ENDJAX
 9238:     }
 9239:     return (<<ENDADHOC);
 9240: <script type="text/javascript">
 9241: // <![CDATA[
 9242:         var $funcname = function()
 9243:         {
 9244:                 modalWindow.windowId = "myModal";
 9245:                 modalWindow.width = $width;
 9246:                 modalWindow.height = $height;
 9247:                 modalWindow.content = '$content';
 9248:                 modalWindow.open();
 9249:                 $mathjax
 9250:         };  
 9251: // ]]>
 9252: </script>
 9253: ENDADHOC
 9254: }
 9255: 
 9256: sub modal_adhoc_inner {
 9257:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
 9258:     my $innerwidth=$width-20;
 9259:     $content=&js_ready(
 9260:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 9261:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
 9262:                  $content.
 9263:                  &end_scrollbox().
 9264:                  &end_page()
 9265:              );
 9266:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
 9267: }
 9268: 
 9269: sub modal_adhoc_window {
 9270:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
 9271:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
 9272:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 9273: }
 9274: 
 9275: sub modal_adhoc_launch {
 9276:     my ($funcname,$width,$height,$content)=@_;
 9277:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 9278: <script type="text/javascript">
 9279: // <![CDATA[
 9280: $funcname();
 9281: // ]]>
 9282: </script>
 9283: ENDLAUNCH
 9284: }
 9285: 
 9286: sub modal_adhoc_close {
 9287:     return (<<ENDCLOSE);
 9288: <script type="text/javascript">
 9289: // <![CDATA[
 9290: modalWindow.close();
 9291: // ]]>
 9292: </script>
 9293: ENDCLOSE
 9294: }
 9295: 
 9296: sub togglebox_script {
 9297:    return(<<ENDTOGGLE);
 9298: <script type="text/javascript"> 
 9299: // <![CDATA[
 9300: function LCtoggleDisplay(id,hidetext,showtext) {
 9301:    link = document.getElementById(id + "link").childNodes[0];
 9302:    with (document.getElementById(id).style) {
 9303:       if (display == "none" ) {
 9304:           display = "inline";
 9305:           link.nodeValue = hidetext;
 9306:         } else {
 9307:           display = "none";
 9308:           link.nodeValue = showtext;
 9309:        }
 9310:    }
 9311: }
 9312: // ]]>
 9313: </script>
 9314: ENDTOGGLE
 9315: }
 9316: 
 9317: sub start_togglebox {
 9318:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 9319:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 9320:     unless ($showtext) { $showtext=&mt('show'); }
 9321:     unless ($hidetext) { $hidetext=&mt('hide'); }
 9322:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 9323:     return &start_data_table().
 9324:            &start_data_table_header_row().
 9325:            '<td bgcolor="'.$headerbg.'">'.$heading.
 9326:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 9327:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 9328:            &end_data_table_header_row().
 9329:            '<tr id="'.$id.'" style="display:none""><td>';
 9330: }
 9331: 
 9332: sub end_togglebox {
 9333:     return '</td></tr>'.&end_data_table();
 9334: }
 9335: 
 9336: sub LCprogressbar_script {
 9337:    my ($id,$number_to_do)=@_;
 9338:    if ($number_to_do) {
 9339:        return(<<ENDPROGRESS);
 9340: <script type="text/javascript">
 9341: // <![CDATA[
 9342: \$('#progressbar$id').progressbar({
 9343:   value: 0,
 9344:   change: function(event, ui) {
 9345:     var newVal = \$(this).progressbar('option', 'value');
 9346:     \$('.pblabel', this).text(LCprogressTxt);
 9347:   }
 9348: });
 9349: // ]]>
 9350: </script>
 9351: ENDPROGRESS
 9352:    } else {
 9353:        return(<<ENDPROGRESS);
 9354: <script type="text/javascript">
 9355: // <![CDATA[
 9356: \$('#progressbar$id').progressbar({
 9357:   value: false,
 9358:   create: function(event, ui) {
 9359:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
 9360:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
 9361:   }
 9362: });
 9363: // ]]>
 9364: </script>
 9365: ENDPROGRESS
 9366:    }
 9367: }
 9368: 
 9369: sub LCprogressbarUpdate_script {
 9370:    return(<<ENDPROGRESSUPDATE);
 9371: <style type="text/css">
 9372: .ui-progressbar { position:relative; }
 9373: .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%; }
 9374: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 9375: </style>
 9376: <script type="text/javascript">
 9377: // <![CDATA[
 9378: var LCprogressTxt='---';
 9379: 
 9380: function LCupdateProgress(percent,progresstext,id,maxnum) {
 9381:    LCprogressTxt=progresstext;
 9382:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
 9383:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
 9384:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
 9385:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
 9386:    } else {
 9387:        \$('#progressbar'+id).progressbar('value',percent);
 9388:    }
 9389: }
 9390: // ]]>
 9391: </script>
 9392: ENDPROGRESSUPDATE
 9393: }
 9394: 
 9395: my $LClastpercent;
 9396: my $LCidcnt;
 9397: my $LCcurrentid;
 9398: 
 9399: sub LCprogressbar {
 9400:     my ($r,$number_to_do,$preamble)=@_;
 9401:     $LClastpercent=0;
 9402:     $LCidcnt++;
 9403:     $LCcurrentid=$$.'_'.$LCidcnt;
 9404:     my ($starting,$content);
 9405:     if ($number_to_do) {
 9406:         $starting=&mt('Starting');
 9407:         $content=(<<ENDPROGBAR);
 9408: $preamble
 9409:   <div id="progressbar$LCcurrentid">
 9410:     <span class="pblabel">$starting</span>
 9411:   </div>
 9412: ENDPROGBAR
 9413:     } else {
 9414:         $starting=&mt('Loading...');
 9415:         $LClastpercent='false';
 9416:         $content=(<<ENDPROGBAR);
 9417: $preamble
 9418:   <div id="progressbar$LCcurrentid">
 9419:       <div class="progress-label">$starting</div>
 9420:   </div>
 9421: ENDPROGBAR
 9422:     }
 9423:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
 9424: }
 9425: 
 9426: sub LCprogressbarUpdate {
 9427:     my ($r,$val,$text,$number_to_do)=@_;
 9428:     if ($number_to_do) {
 9429:         unless ($val) { 
 9430:             if ($LClastpercent) {
 9431:                 $val=$LClastpercent;
 9432:             } else {
 9433:                 $val=0;
 9434:             }
 9435:         }
 9436:         if ($val<0) { $val=0; }
 9437:         if ($val>100) { $val=0; }
 9438:         $LClastpercent=$val;
 9439:         unless ($text) { $text=$val.'%'; }
 9440:     } else {
 9441:         $val = 'false';
 9442:     }
 9443:     $text=&js_ready($text);
 9444:     &r_print($r,<<ENDUPDATE);
 9445: <script type="text/javascript">
 9446: // <![CDATA[
 9447: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
 9448: // ]]>
 9449: </script>
 9450: ENDUPDATE
 9451: }
 9452: 
 9453: sub LCprogressbarClose {
 9454:     my ($r)=@_;
 9455:     $LClastpercent=0;
 9456:     &r_print($r,<<ENDCLOSE);
 9457: <script type="text/javascript">
 9458: // <![CDATA[
 9459: \$("#progressbar$LCcurrentid").hide('slow'); 
 9460: // ]]>
 9461: </script>
 9462: ENDCLOSE
 9463: }
 9464: 
 9465: sub r_print {
 9466:     my ($r,$to_print)=@_;
 9467:     if ($r) {
 9468:       $r->print($to_print);
 9469:       $r->rflush();
 9470:     } else {
 9471:       print($to_print);
 9472:     }
 9473: }
 9474: 
 9475: sub html_encode {
 9476:     my ($result) = @_;
 9477: 
 9478:     $result = &HTML::Entities::encode($result,'<>&"');
 9479:     
 9480:     return $result;
 9481: }
 9482: 
 9483: sub js_ready {
 9484:     my ($result) = @_;
 9485: 
 9486:     $result =~ s/[\n\r]/ /xmsg;
 9487:     $result =~ s/\\/\\\\/xmsg;
 9488:     $result =~ s/'/\\'/xmsg;
 9489:     $result =~ s{</}{<\\/}xmsg;
 9490:     
 9491:     return $result;
 9492: }
 9493: 
 9494: sub validate_page {
 9495:     if (  exists($env{'internal.start_page'})
 9496: 	  &&     $env{'internal.start_page'} > 1) {
 9497: 	&Apache::lonnet::logthis('start_page called multiple times '.
 9498: 				 $env{'internal.start_page'}.' '.
 9499: 				 $ENV{'request.filename'});
 9500:     }
 9501:     if (  exists($env{'internal.end_page'})
 9502: 	  &&     $env{'internal.end_page'} > 1) {
 9503: 	&Apache::lonnet::logthis('end_page called multiple times '.
 9504: 				 $env{'internal.end_page'}.' '.
 9505: 				 $env{'request.filename'});
 9506:     }
 9507:     if (     exists($env{'internal.start_page'})
 9508: 	&& ! exists($env{'internal.end_page'})) {
 9509: 	&Apache::lonnet::logthis('start_page called without end_page '.
 9510: 				 $env{'request.filename'});
 9511:     }
 9512:     if (   ! exists($env{'internal.start_page'})
 9513: 	&&   exists($env{'internal.end_page'})) {
 9514: 	&Apache::lonnet::logthis('end_page called without start_page'.
 9515: 				 $env{'request.filename'});
 9516:     }
 9517: }
 9518: 
 9519: 
 9520: sub start_scrollbox {
 9521:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
 9522:     unless ($outerwidth) { $outerwidth='520px'; }
 9523:     unless ($width) { $width='500px'; }
 9524:     unless ($height) { $height='200px'; }
 9525:     my ($table_id,$div_id,$tdcol);
 9526:     if ($id ne '') {
 9527:         $table_id = ' id="table_'.$id.'"';
 9528:         $div_id = ' id="div_'.$id.'"';
 9529:     }
 9530:     if ($bgcolor ne '') {
 9531:         $tdcol = "background-color: $bgcolor;";
 9532:     }
 9533:     my $nicescroll_js;
 9534:     if ($env{'browser.mobile'}) {
 9535:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
 9536:     }
 9537:     return <<"END";
 9538: $nicescroll_js
 9539: 
 9540: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
 9541: <div style="overflow:auto; width:$width; height:$height;"$div_id>
 9542: END
 9543: }
 9544: 
 9545: sub end_scrollbox {
 9546:     return '</div></td></tr></table>';
 9547: }
 9548: 
 9549: sub nicescroll_javascript {
 9550:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
 9551:     my %options;
 9552:     if (ref($cursor) eq 'HASH') {
 9553:         %options = %{$cursor};
 9554:     }
 9555:     unless ($options{'railalign'} =~ /^left|right$/) {
 9556:         $options{'railalign'} = 'left';
 9557:     }
 9558:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 9559:         my $function  = &get_users_function();
 9560:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
 9561:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 9562:             $options{'cursorcolor'} = '#00F';
 9563:         }
 9564:     }
 9565:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
 9566:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
 9567:             $options{'cursoropacity'}='1.0';
 9568:         }
 9569:     } else {
 9570:         $options{'cursoropacity'}='1.0';
 9571:     }
 9572:     if ($options{'cursorfixedheight'} eq 'none') {
 9573:         delete($options{'cursorfixedheight'});
 9574:     } else {
 9575:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
 9576:     }
 9577:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
 9578:         delete($options{'railoffset'});
 9579:     }
 9580:     my @niceoptions;
 9581:     while (my($key,$value) = each(%options)) {
 9582:         if ($value =~ /^\{.+\}$/) {
 9583:             push(@niceoptions,$key.':'.$value);
 9584:         } else {
 9585:             push(@niceoptions,$key.':"'.$value.'"');
 9586:         }
 9587:     }
 9588:     my $nicescroll_js = '
 9589: $(document).ready(
 9590:       function() {
 9591:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
 9592:       }
 9593: );
 9594: ';
 9595:     if ($framecheck) {
 9596:         $nicescroll_js .= '
 9597: function expand_div(caller) {
 9598:     if (top === self) {
 9599:         document.getElementById("'.$id.'").style.width = "auto";
 9600:         document.getElementById("'.$id.'").style.height = "auto";
 9601:     } else {
 9602:         try {
 9603:             if (parent.frames) {
 9604:                 if (parent.frames.length > 1) {
 9605:                     var framesrc = parent.frames[1].location.href;
 9606:                     var currsrc = framesrc.replace(/\#.*$/,"");
 9607:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
 9608:                         document.getElementById("'.$id.'").style.width = "auto";
 9609:                         document.getElementById("'.$id.'").style.height = "auto";
 9610:                     }
 9611:                 }
 9612:             }
 9613:         } catch (e) {
 9614:             return;
 9615:         }
 9616:     }
 9617:     return;
 9618: }
 9619: ';
 9620:     }
 9621:     if ($needjsready) {
 9622:         $nicescroll_js = '
 9623: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
 9624:     } else {
 9625:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
 9626:     }
 9627:     return $nicescroll_js;
 9628: }
 9629: 
 9630: sub simple_error_page {
 9631:     my ($r,$title,$msg,$args) = @_;
 9632:     my %displayargs;
 9633:     if (ref($args) eq 'HASH') {
 9634:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
 9635:         if ($args->{'only_body'}) {
 9636:             $displayargs{'only_body'} = 1;
 9637:         }
 9638:         if ($args->{'no_nav_bar'}) {
 9639:             $displayargs{'no_nav_bar'} = 1;
 9640:         }
 9641:     } else {
 9642:         $msg = &mt($msg);
 9643:     }
 9644: 
 9645:     my $page =
 9646: 	&Apache::loncommon::start_page($title,'',\%displayargs).
 9647: 	'<p class="LC_error">'.$msg.'</p>'.
 9648: 	&Apache::loncommon::end_page();
 9649:     if (ref($r)) {
 9650: 	$r->print($page);
 9651: 	return;
 9652:     }
 9653:     return $page;
 9654: }
 9655: 
 9656: {
 9657:     my @row_count;
 9658: 
 9659:     sub start_data_table_count {
 9660:         unshift(@row_count, 0);
 9661:         return;
 9662:     }
 9663: 
 9664:     sub end_data_table_count {
 9665:         shift(@row_count);
 9666:         return;
 9667:     }
 9668: 
 9669:     sub start_data_table {
 9670: 	my ($add_class,$id) = @_;
 9671: 	my $css_class = (join(' ','LC_data_table',$add_class));
 9672:         my $table_id;
 9673:         if (defined($id)) {
 9674:             $table_id = ' id="'.$id.'"';
 9675:         }
 9676: 	&start_data_table_count();
 9677: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 9678:     }
 9679: 
 9680:     sub end_data_table {
 9681: 	&end_data_table_count();
 9682: 	return '</table>'."\n";;
 9683:     }
 9684: 
 9685:     sub start_data_table_row {
 9686: 	my ($add_class, $id) = @_;
 9687: 	$row_count[0]++;
 9688: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 9689: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 9690:         $id = (' id="'.$id.'"') unless ($id eq '');
 9691:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 9692:     }
 9693:     
 9694:     sub continue_data_table_row {
 9695: 	my ($add_class, $id) = @_;
 9696: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 9697: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 9698:         $id = (' id="'.$id.'"') unless ($id eq '');
 9699:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 9700:     }
 9701: 
 9702:     sub end_data_table_row {
 9703: 	return '</tr>'."\n";;
 9704:     }
 9705: 
 9706:     sub start_data_table_empty_row {
 9707: #	$row_count[0]++;
 9708: 	return  '<tr class="LC_empty_row" >'."\n";;
 9709:     }
 9710: 
 9711:     sub end_data_table_empty_row {
 9712: 	return '</tr>'."\n";;
 9713:     }
 9714: 
 9715:     sub start_data_table_header_row {
 9716: 	return  '<tr class="LC_header_row">'."\n";;
 9717:     }
 9718: 
 9719:     sub end_data_table_header_row {
 9720: 	return '</tr>'."\n";;
 9721:     }
 9722: 
 9723:     sub data_table_caption {
 9724:         my $caption = shift;
 9725:         return "<caption class=\"LC_caption\">$caption</caption>";
 9726:     }
 9727: }
 9728: 
 9729: =pod
 9730: 
 9731: =item * &inhibit_menu_check($arg)
 9732: 
 9733: Checks for a inhibitmenu state and generates output to preserve it
 9734: 
 9735: Inputs:         $arg - can be any of
 9736:                      - undef - in which case the return value is a string 
 9737:                                to add  into arguments list of a uri
 9738:                      - 'input' - in which case the return value is a HTML
 9739:                                  <form> <input> field of type hidden to
 9740:                                  preserve the value
 9741:                      - a url - in which case the return value is the url with
 9742:                                the neccesary cgi args added to preserve the
 9743:                                inhibitmenu state
 9744:                      - a ref to a url - no return value, but the string is
 9745:                                         updated to include the neccessary cgi
 9746:                                         args to preserve the inhibitmenu state
 9747: 
 9748: =cut
 9749: 
 9750: sub inhibit_menu_check {
 9751:     my ($arg) = @_;
 9752:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 9753:     if ($arg eq 'input') {
 9754: 	if ($env{'form.inhibitmenu'}) {
 9755: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 9756: 	} else {
 9757: 	    return
 9758: 	}
 9759:     }
 9760:     if ($env{'form.inhibitmenu'}) {
 9761: 	if (ref($arg)) {
 9762: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 9763: 	} elsif ($arg eq '') {
 9764: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 9765: 	} else {
 9766: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 9767: 	}
 9768:     }
 9769:     if (!ref($arg)) {
 9770: 	return $arg;
 9771:     }
 9772: }
 9773: 
 9774: ###############################################
 9775: 
 9776: =pod
 9777: 
 9778: =back
 9779: 
 9780: =head1 User Information Routines
 9781: 
 9782: =over 4
 9783: 
 9784: =item * &get_users_function()
 9785: 
 9786: Used by &bodytag to determine the current users primary role.
 9787: Returns either 'student','coordinator','admin', or 'author'.
 9788: 
 9789: =cut
 9790: 
 9791: ###############################################
 9792: sub get_users_function {
 9793:     my $function = 'norole';
 9794:     if ($env{'request.role'}=~/^(st)/) {
 9795:         $function='student';
 9796:     }
 9797:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 9798:         $function='coordinator';
 9799:     }
 9800:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 9801:         $function='admin';
 9802:     }
 9803:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 9804:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 9805:         $function='author';
 9806:     }
 9807:     return $function;
 9808: }
 9809: 
 9810: ###############################################
 9811: 
 9812: =pod
 9813: 
 9814: =item * &show_course()
 9815: 
 9816: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 9817: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 9818: 
 9819: Inputs:
 9820: None
 9821: 
 9822: Outputs:
 9823: Scalar: 1 if 'Course' to be used, 0 otherwise.
 9824: 
 9825: =cut
 9826: 
 9827: ###############################################
 9828: sub show_course {
 9829:     my $course = !$env{'user.adv'};
 9830:     if (!$env{'user.adv'}) {
 9831:         foreach my $env (keys(%env)) {
 9832:             next if ($env !~ m/^user\.priv\./);
 9833:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 9834:                 $course = 0;
 9835:                 last;
 9836:             }
 9837:         }
 9838:     }
 9839:     return $course;
 9840: }
 9841: 
 9842: ###############################################
 9843: 
 9844: =pod
 9845: 
 9846: =item * &check_user_status()
 9847: 
 9848: Determines current status of supplied role for a
 9849: specific user. Roles can be active, previous or future.
 9850: 
 9851: Inputs: 
 9852: user's domain, user's username, course's domain,
 9853: course's number, optional section ID.
 9854: 
 9855: Outputs:
 9856: role status: active, previous or future. 
 9857: 
 9858: =cut
 9859: 
 9860: sub check_user_status {
 9861:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 9862:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 9863:     my @uroles = keys(%userinfo);
 9864:     my $srchstr;
 9865:     my $active_chk = 'none';
 9866:     my $now = time;
 9867:     if (@uroles > 0) {
 9868:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 9869:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 9870:         } else {
 9871:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 9872:         }
 9873:         if (grep/^\Q$srchstr\E$/,@uroles) {
 9874:             my $role_end = 0;
 9875:             my $role_start = 0;
 9876:             $active_chk = 'active';
 9877:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 9878:                 $role_end = $1;
 9879:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 9880:                     $role_start = $1;
 9881:                 }
 9882:             }
 9883:             if ($role_start > 0) {
 9884:                 if ($now < $role_start) {
 9885:                     $active_chk = 'future';
 9886:                 }
 9887:             }
 9888:             if ($role_end > 0) {
 9889:                 if ($now > $role_end) {
 9890:                     $active_chk = 'previous';
 9891:                 }
 9892:             }
 9893:         }
 9894:     }
 9895:     return $active_chk;
 9896: }
 9897: 
 9898: ###############################################
 9899: 
 9900: =pod
 9901: 
 9902: =item * &get_sections()
 9903: 
 9904: Determines all the sections for a course including
 9905: sections with students and sections containing other roles.
 9906: Incoming parameters: 
 9907: 
 9908: 1. domain
 9909: 2. course number 
 9910: 3. reference to array containing roles for which sections should 
 9911: be gathered (optional).
 9912: 4. reference to array containing status types for which sections 
 9913: should be gathered (optional).
 9914: 
 9915: If the third argument is undefined, sections are gathered for any role. 
 9916: If the fourth argument is undefined, sections are gathered for any status.
 9917: Permissible values are 'active' or 'future' or 'previous'.
 9918:  
 9919: Returns section hash (keys are section IDs, values are
 9920: number of users in each section), subject to the
 9921: optional roles filter, optional status filter 
 9922: 
 9923: =cut
 9924: 
 9925: ###############################################
 9926: sub get_sections {
 9927:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 9928:     if (!defined($cdom) || !defined($cnum)) {
 9929:         my $cid =  $env{'request.course.id'};
 9930: 
 9931: 	return if (!defined($cid));
 9932: 
 9933:         $cdom = $env{'course.'.$cid.'.domain'};
 9934:         $cnum = $env{'course.'.$cid.'.num'};
 9935:     }
 9936: 
 9937:     my %sectioncount;
 9938:     my $now = time;
 9939: 
 9940:     my $check_students = 1;
 9941:     my $only_students = 0;
 9942:     if (ref($possible_roles) eq 'ARRAY') {
 9943:         if (grep(/^st$/,@{$possible_roles})) {
 9944:             if (@{$possible_roles} == 1) {
 9945:                 $only_students = 1;
 9946:             }
 9947:         } else {
 9948:             $check_students = 0;
 9949:         }
 9950:     }
 9951: 
 9952:     if ($check_students) {
 9953: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 9954: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 9955: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 9956:         my $start_index = &Apache::loncoursedata::CL_START();
 9957:         my $end_index = &Apache::loncoursedata::CL_END();
 9958:         my $status;
 9959: 	while (my ($student,$data) = each(%$classlist)) {
 9960: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 9961: 				                     $data->[$status_index],
 9962:                                                      $data->[$start_index],
 9963:                                                      $data->[$end_index]);
 9964:             if ($stu_status eq 'Active') {
 9965:                 $status = 'active';
 9966:             } elsif ($end < $now) {
 9967:                 $status = 'previous';
 9968:             } elsif ($start > $now) {
 9969:                 $status = 'future';
 9970:             } 
 9971: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 9972:                 if ((!defined($possible_status)) || (($status ne '') && 
 9973:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 9974: 		    $sectioncount{$section}++;
 9975:                 }
 9976: 	    }
 9977: 	}
 9978:     }
 9979:     if ($only_students) {
 9980:         return %sectioncount;
 9981:     }
 9982:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9983:     foreach my $user (sort(keys(%courseroles))) {
 9984: 	if ($user !~ /^(\w{2})/) { next; }
 9985: 	my ($role) = ($user =~ /^(\w{2})/);
 9986: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 9987: 	my ($section,$status);
 9988: 	if ($role eq 'cr' &&
 9989: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 9990: 	    $section=$1;
 9991: 	}
 9992: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 9993: 	if (!defined($section) || $section eq '-1') { next; }
 9994:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 9995:         if ($end == -1 && $start == -1) {
 9996:             next; #deleted role
 9997:         }
 9998:         if (!defined($possible_status)) { 
 9999:             $sectioncount{$section}++;
10000:         } else {
10001:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
10002:                 $status = 'active';
10003:             } elsif ($end < $now) {
10004:                 $status = 'future';
10005:             } elsif ($start > $now) {
10006:                 $status = 'previous';
10007:             }
10008:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
10009:                 $sectioncount{$section}++;
10010:             }
10011:         }
10012:     }
10013:     return %sectioncount;
10014: }
10015: 
10016: ###############################################
10017: 
10018: =pod
10019: 
10020: =item * &get_course_users()
10021: 
10022: Retrieves usernames:domains for users in the specified course
10023: with specific role(s), and access status. 
10024: 
10025: Incoming parameters:
10026: 1. course domain
10027: 2. course number
10028: 3. access status: users must have - either active, 
10029: previous, future, or all.
10030: 4. reference to array of permissible roles
10031: 5. reference to array of section restrictions (optional)
10032: 6. reference to results object (hash of hashes).
10033: 7. reference to optional userdata hash
10034: 8. reference to optional statushash
10035: 9. flag if privileged users (except those set to unhide in
10036:    course settings) should be excluded    
10037: Keys of top level results hash are roles.
10038: Keys of inner hashes are username:domain, with 
10039: values set to access type.
10040: Optional userdata hash returns an array with arguments in the 
10041: same order as loncoursedata::get_classlist() for student data.
10042: 
10043: Optional statushash returns
10044: 
10045: Entries for end, start, section and status are blank because
10046: of the possibility of multiple values for non-student roles.
10047: 
10048: =cut
10049: 
10050: ###############################################
10051: 
10052: sub get_course_users {
10053:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
10054:     my %idx = ();
10055:     my %seclists;
10056: 
10057:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
10058:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
10059:     $idx{end} = &Apache::loncoursedata::CL_END();
10060:     $idx{start} = &Apache::loncoursedata::CL_START();
10061:     $idx{id} = &Apache::loncoursedata::CL_ID();
10062:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
10063:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
10064:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
10065: 
10066:     if (grep(/^st$/,@{$roles})) {
10067:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
10068:         my $now = time;
10069:         foreach my $student (keys(%{$classlist})) {
10070:             my $match = 0;
10071:             my $secmatch = 0;
10072:             my $section = $$classlist{$student}[$idx{section}];
10073:             my $status = $$classlist{$student}[$idx{status}];
10074:             if ($section eq '') {
10075:                 $section = 'none';
10076:             }
10077:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
10078:                 if (grep(/^all$/,@{$sections})) {
10079:                     $secmatch = 1;
10080:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
10081:                     if (grep(/^none$/,@{$sections})) {
10082:                         $secmatch = 1;
10083:                     }
10084:                 } else {  
10085: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
10086: 		        $secmatch = 1;
10087:                     }
10088: 		}
10089:                 if (!$secmatch) {
10090:                     next;
10091:                 }
10092:             }
10093:             if (defined($$types{'active'})) {
10094:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
10095:                     push(@{$$users{st}{$student}},'active');
10096:                     $match = 1;
10097:                 }
10098:             }
10099:             if (defined($$types{'previous'})) {
10100:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
10101:                     push(@{$$users{st}{$student}},'previous');
10102:                     $match = 1;
10103:                 }
10104:             }
10105:             if (defined($$types{'future'})) {
10106:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
10107:                     push(@{$$users{st}{$student}},'future');
10108:                     $match = 1;
10109:                 }
10110:             }
10111:             if ($match) {
10112:                 push(@{$seclists{$student}},$section);
10113:                 if (ref($userdata) eq 'HASH') {
10114:                     $$userdata{$student} = $$classlist{$student};
10115:                 }
10116:                 if (ref($statushash) eq 'HASH') {
10117:                     $statushash->{$student}{'st'}{$section} = $status;
10118:                 }
10119:             }
10120:         }
10121:     }
10122:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
10123:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10124:         my $now = time;
10125:         my %displaystatus = ( previous => 'Expired',
10126:                               active   => 'Active',
10127:                               future   => 'Future',
10128:                             );
10129:         my (%nothide,@possdoms);
10130:         if ($hidepriv) {
10131:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
10132:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
10133:                 if ($user !~ /:/) {
10134:                     $nothide{join(':',split(/[\@]/,$user))}=1;
10135:                 } else {
10136:                     $nothide{$user} = 1;
10137:                 }
10138:             }
10139:             my @possdoms = ($cdom);
10140:             if ($coursehash{'checkforpriv'}) {
10141:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
10142:             }
10143:         }
10144:         foreach my $person (sort(keys(%coursepersonnel))) {
10145:             my $match = 0;
10146:             my $secmatch = 0;
10147:             my $status;
10148:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
10149:             $user =~ s/:$//;
10150:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
10151:             if ($end == -1 || $start == -1) {
10152:                 next;
10153:             }
10154:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
10155:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
10156:                 my ($uname,$udom) = split(/:/,$user);
10157:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
10158:                     if (grep(/^all$/,@{$sections})) {
10159:                         $secmatch = 1;
10160:                     } elsif ($usec eq '') {
10161:                         if (grep(/^none$/,@{$sections})) {
10162:                             $secmatch = 1;
10163:                         }
10164:                     } else {
10165:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
10166:                             $secmatch = 1;
10167:                         }
10168:                     }
10169:                     if (!$secmatch) {
10170:                         next;
10171:                     }
10172:                 }
10173:                 if ($usec eq '') {
10174:                     $usec = 'none';
10175:                 }
10176:                 if ($uname ne '' && $udom ne '') {
10177:                     if ($hidepriv) {
10178:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
10179:                             (!$nothide{$uname.':'.$udom})) {
10180:                             next;
10181:                         }
10182:                     }
10183:                     if ($end > 0 && $end < $now) {
10184:                         $status = 'previous';
10185:                     } elsif ($start > $now) {
10186:                         $status = 'future';
10187:                     } else {
10188:                         $status = 'active';
10189:                     }
10190:                     foreach my $type (keys(%{$types})) { 
10191:                         if ($status eq $type) {
10192:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
10193:                                 push(@{$$users{$role}{$user}},$type);
10194:                             }
10195:                             $match = 1;
10196:                         }
10197:                     }
10198:                     if (($match) && (ref($userdata) eq 'HASH')) {
10199:                         if (!exists($$userdata{$uname.':'.$udom})) {
10200: 			    &get_user_info($udom,$uname,\%idx,$userdata);
10201:                         }
10202:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
10203:                             push(@{$seclists{$uname.':'.$udom}},$usec);
10204:                         }
10205:                         if (ref($statushash) eq 'HASH') {
10206:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
10207:                         }
10208:                     }
10209:                 }
10210:             }
10211:         }
10212:         if (grep(/^ow$/,@{$roles})) {
10213:             if ((defined($cdom)) && (defined($cnum))) {
10214:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
10215:                 if ( defined($csettings{'internal.courseowner'}) ) {
10216:                     my $owner = $csettings{'internal.courseowner'};
10217:                     next if ($owner eq '');
10218:                     my ($ownername,$ownerdom);
10219:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
10220:                         $ownername = $1;
10221:                         $ownerdom = $2;
10222:                     } else {
10223:                         $ownername = $owner;
10224:                         $ownerdom = $cdom;
10225:                         $owner = $ownername.':'.$ownerdom;
10226:                     }
10227:                     @{$$users{'ow'}{$owner}} = 'any';
10228:                     if (defined($userdata) && 
10229: 			!exists($$userdata{$owner})) {
10230: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
10231:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
10232:                             push(@{$seclists{$owner}},'none');
10233:                         }
10234:                         if (ref($statushash) eq 'HASH') {
10235:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
10236:                         }
10237: 		    }
10238:                 }
10239:             }
10240:         }
10241:         foreach my $user (keys(%seclists)) {
10242:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
10243:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
10244:         }
10245:     }
10246:     return;
10247: }
10248: 
10249: sub get_user_info {
10250:     my ($udom,$uname,$idx,$userdata) = @_;
10251:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
10252: 	&plainname($uname,$udom,'lastname');
10253:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
10254:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
10255:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
10256:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
10257:     return;
10258: }
10259: 
10260: ###############################################
10261: 
10262: =pod
10263: 
10264: =item * &get_user_quota()
10265: 
10266: Retrieves quota assigned for storage of user files.
10267: Default is to report quota for portfolio files.
10268: 
10269: Incoming parameters:
10270: 1. user's username
10271: 2. user's domain
10272: 3. quota name - portfolio, author, or course
10273:    (if no quota name provided, defaults to portfolio).
10274: 4. crstype - official, unofficial, textbook or community, if quota name is
10275:    course
10276: 
10277: Returns:
10278: 1. Disk quota (in MB) assigned to student.
10279: 2. (Optional) Type of setting: custom or default
10280:    (individually assigned or default for user's 
10281:    institutional status).
10282: 3. (Optional) - User's institutional status (e.g., faculty, staff
10283:    or student - types as defined in localenroll::inst_usertypes 
10284:    for user's domain, which determines default quota for user.
10285: 4. (Optional) - Default quota which would apply to the user.
10286: 
10287: If a value has been stored in the user's environment, 
10288: it will return that, otherwise it returns the maximal default
10289: defined for the user's institutional status(es) in the domain.
10290: 
10291: =cut
10292: 
10293: ###############################################
10294: 
10295: 
10296: sub get_user_quota {
10297:     my ($uname,$udom,$quotaname,$crstype) = @_;
10298:     my ($quota,$quotatype,$settingstatus,$defquota);
10299:     if (!defined($udom)) {
10300:         $udom = $env{'user.domain'};
10301:     }
10302:     if (!defined($uname)) {
10303:         $uname = $env{'user.name'};
10304:     }
10305:     if (($udom eq '' || $uname eq '') ||
10306:         ($udom eq 'public') && ($uname eq 'public')) {
10307:         $quota = 0;
10308:         $quotatype = 'default';
10309:         $defquota = 0; 
10310:     } else {
10311:         my $inststatus;
10312:         if ($quotaname eq 'course') {
10313:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
10314:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
10315:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
10316:             } else {
10317:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
10318:                 $quota = $cenv{'internal.uploadquota'};
10319:             }
10320:         } else {
10321:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
10322:                 if ($quotaname eq 'author') {
10323:                     $quota = $env{'environment.authorquota'};
10324:                 } else {
10325:                     $quota = $env{'environment.portfolioquota'};
10326:                 }
10327:                 $inststatus = $env{'environment.inststatus'};
10328:             } else {
10329:                 my %userenv = 
10330:                     &Apache::lonnet::get('environment',['portfolioquota',
10331:                                          'authorquota','inststatus'],$udom,$uname);
10332:                 my ($tmp) = keys(%userenv);
10333:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10334:                     if ($quotaname eq 'author') {
10335:                         $quota = $userenv{'authorquota'};
10336:                     } else {
10337:                         $quota = $userenv{'portfolioquota'};
10338:                     }
10339:                     $inststatus = $userenv{'inststatus'};
10340:                 } else {
10341:                     undef(%userenv);
10342:                 }
10343:             }
10344:         }
10345:         if ($quota eq '' || wantarray) {
10346:             if ($quotaname eq 'course') {
10347:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
10348:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
10349:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
10350:                     $defquota = $domdefs{$crstype.'quota'};
10351:                 }
10352:                 if ($defquota eq '') {
10353:                     $defquota = 500;
10354:                 }
10355:             } else {
10356:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
10357:             }
10358:             if ($quota eq '') {
10359:                 $quota = $defquota;
10360:                 $quotatype = 'default';
10361:             } else {
10362:                 $quotatype = 'custom';
10363:             }
10364:         }
10365:     }
10366:     if (wantarray) {
10367:         return ($quota,$quotatype,$settingstatus,$defquota);
10368:     } else {
10369:         return $quota;
10370:     }
10371: }
10372: 
10373: ###############################################
10374: 
10375: =pod
10376: 
10377: =item * &default_quota()
10378: 
10379: Retrieves default quota assigned for storage of user portfolio files,
10380: given an (optional) user's institutional status.
10381: 
10382: Incoming parameters:
10383: 
10384: 1. domain
10385: 2. (Optional) institutional status(es).  This is a : separated list of 
10386:    status types (e.g., faculty, staff, student etc.)
10387:    which apply to the user for whom the default is being retrieved.
10388:    If the institutional status string in undefined, the domain
10389:    default quota will be returned.
10390: 3.  quota name - portfolio, author, or course
10391:    (if no quota name provided, defaults to portfolio).
10392: 
10393: Returns:
10394: 
10395: 1. Default disk quota (in MB) for user portfolios in the domain.
10396: 2. (Optional) institutional type which determined the value of the
10397:    default quota.
10398: 
10399: If a value has been stored in the domain's configuration db,
10400: it will return that, otherwise it returns 20 (for backwards 
10401: compatibility with domains which have not set up a configuration
10402: db file; the original statically defined portfolio quota was 20 MB). 
10403: 
10404: If the user's status includes multiple types (e.g., staff and student),
10405: the largest default quota which applies to the user determines the
10406: default quota returned.
10407: 
10408: =cut
10409: 
10410: ###############################################
10411: 
10412: 
10413: sub default_quota {
10414:     my ($udom,$inststatus,$quotaname) = @_;
10415:     my ($defquota,$settingstatus);
10416:     my %quotahash = &Apache::lonnet::get_dom('configuration',
10417:                                             ['quotas'],$udom);
10418:     my $key = 'defaultquota';
10419:     if ($quotaname eq 'author') {
10420:         $key = 'authorquota';
10421:     }
10422:     if (ref($quotahash{'quotas'}) eq 'HASH') {
10423:         if ($inststatus ne '') {
10424:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
10425:             foreach my $item (@statuses) {
10426:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
10427:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
10428:                         if ($defquota eq '') {
10429:                             $defquota = $quotahash{'quotas'}{$key}{$item};
10430:                             $settingstatus = $item;
10431:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
10432:                             $defquota = $quotahash{'quotas'}{$key}{$item};
10433:                             $settingstatus = $item;
10434:                         }
10435:                     }
10436:                 } elsif ($key eq 'defaultquota') {
10437:                     if ($quotahash{'quotas'}{$item} ne '') {
10438:                         if ($defquota eq '') {
10439:                             $defquota = $quotahash{'quotas'}{$item};
10440:                             $settingstatus = $item;
10441:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
10442:                             $defquota = $quotahash{'quotas'}{$item};
10443:                             $settingstatus = $item;
10444:                         }
10445:                     }
10446:                 }
10447:             }
10448:         }
10449:         if ($defquota eq '') {
10450:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
10451:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
10452:             } elsif ($key eq 'defaultquota') {
10453:                 $defquota = $quotahash{'quotas'}{'default'};
10454:             }
10455:             $settingstatus = 'default';
10456:             if ($defquota eq '') {
10457:                 if ($quotaname eq 'author') {
10458:                     $defquota = 500;
10459:                 }
10460:             }
10461:         }
10462:     } else {
10463:         $settingstatus = 'default';
10464:         if ($quotaname eq 'author') {
10465:             $defquota = 500;
10466:         } else {
10467:             $defquota = 20;
10468:         }
10469:     }
10470:     if (wantarray) {
10471:         return ($defquota,$settingstatus);
10472:     } else {
10473:         return $defquota;
10474:     }
10475: }
10476: 
10477: ###############################################
10478: 
10479: =pod
10480: 
10481: =item * &excess_filesize_warning()
10482: 
10483: Returns warning message if upload of file to authoring space, or copying
10484: of existing file within authoring space will cause quota for the authoring
10485: space to be exceeded.
10486: 
10487: Same, if upload of a file directly to a course/community via Course Editor
10488: will cause quota for uploaded content for the course to be exceeded.
10489: 
10490: Inputs: 7 
10491: 1. username or coursenum
10492: 2. domain
10493: 3. context ('author' or 'course')
10494: 4. filename of file for which action is being requested
10495: 5. filesize (kB) of file
10496: 6. action being taken: copy or upload.
10497: 7. quotatype (in course context -- official, unofficial, community or textbook).
10498: 
10499: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
10500:          otherwise return null.
10501: 
10502: =back
10503: 
10504: =cut
10505: 
10506: sub excess_filesize_warning {
10507:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
10508:     my $current_disk_usage = 0;
10509:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
10510:     if ($context eq 'author') {
10511:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
10512:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
10513:     } else {
10514:         foreach my $subdir ('docs','supplemental') {
10515:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
10516:         }
10517:     }
10518:     $disk_quota = int($disk_quota * 1000);
10519:     if (($current_disk_usage + $filesize) > $disk_quota) {
10520:         return '<p class="LC_warning">'.
10521:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
10522:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
10523:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
10524:                             $disk_quota,$current_disk_usage).
10525:                '</p>';
10526:     }
10527:     return;
10528: }
10529: 
10530: ###############################################
10531: 
10532: 
10533: sub get_secgrprole_info {
10534:     my ($cdom,$cnum,$needroles,$type)  = @_;
10535:     my %sections_count = &get_sections($cdom,$cnum);
10536:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
10537:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
10538:     my @groups = sort(keys(%curr_groups));
10539:     my $allroles = [];
10540:     my $rolehash;
10541:     my $accesshash = {
10542:                      active => 'Currently has access',
10543:                      future => 'Will have future access',
10544:                      previous => 'Previously had access',
10545:                   };
10546:     if ($needroles) {
10547:         $rolehash = {'all' => 'all'};
10548:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10549: 	if (&Apache::lonnet::error(%user_roles)) {
10550: 	    undef(%user_roles);
10551: 	}
10552:         foreach my $item (keys(%user_roles)) {
10553:             my ($role)=split(/\:/,$item,2);
10554:             if ($role eq 'cr') { next; }
10555:             if ($role =~ /^cr/) {
10556:                 $$rolehash{$role} = (split('/',$role))[3];
10557:             } else {
10558:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
10559:             }
10560:         }
10561:         foreach my $key (sort(keys(%{$rolehash}))) {
10562:             push(@{$allroles},$key);
10563:         }
10564:         push (@{$allroles},'st');
10565:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
10566:     }
10567:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
10568: }
10569: 
10570: sub user_picker {
10571:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
10572:     my $currdom = $dom;
10573:     my @alldoms = &Apache::lonnet::all_domains();
10574:     if (@alldoms == 1) {
10575:         my %domsrch = &Apache::lonnet::get_dom('configuration',
10576:                                                ['directorysrch'],$alldoms[0]);
10577:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
10578:         my $showdom = $domdesc;
10579:         if ($showdom eq '') {
10580:             $showdom = $dom;
10581:         }
10582:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
10583:             if ((!$domsrch{'directorysrch'}{'available'}) &&
10584:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
10585:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
10586:             }
10587:         }
10588:     }
10589:     my %curr_selected = (
10590:                         srchin => 'dom',
10591:                         srchby => 'lastname',
10592:                       );
10593:     my $srchterm;
10594:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
10595:         if ($srch->{'srchby'} ne '') {
10596:             $curr_selected{'srchby'} = $srch->{'srchby'};
10597:         }
10598:         if ($srch->{'srchin'} ne '') {
10599:             $curr_selected{'srchin'} = $srch->{'srchin'};
10600:         }
10601:         if ($srch->{'srchtype'} ne '') {
10602:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
10603:         }
10604:         if ($srch->{'srchdomain'} ne '') {
10605:             $currdom = $srch->{'srchdomain'};
10606:         }
10607:         $srchterm = $srch->{'srchterm'};
10608:     }
10609:     my %html_lt=&Apache::lonlocal::texthash(
10610:                     'usr'       => 'Search criteria',
10611:                     'doma'      => 'Domain/institution to search',
10612:                     'uname'     => 'username',
10613:                     'lastname'  => 'last name',
10614:                     'lastfirst' => 'last name, first name',
10615:                     'crs'       => 'in this course',
10616:                     'dom'       => 'in selected LON-CAPA domain', 
10617:                     'alc'       => 'all LON-CAPA',
10618:                     'instd'     => 'in institutional directory for selected domain',
10619:                     'exact'     => 'is',
10620:                     'contains'  => 'contains',
10621:                     'begins'    => 'begins with',
10622:                                        );
10623:     my %js_lt=&Apache::lonlocal::texthash(
10624:                     'youm'      => "You must include some text to search for.",
10625:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
10626:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
10627:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
10628:                     'ymcd'      => "You must choose a domain when using a domain search.",
10629:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
10630:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
10631:                      'thfo'     => "The following need to be corrected before the search can be run:",
10632:                                        );
10633:     &html_escape(\%html_lt);
10634:     &js_escape(\%js_lt);
10635:     my $domform;
10636:     my $allow_blank = 1;
10637:     if ($fixeddom) {
10638:         $allow_blank = 0;
10639:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
10640:     } else {
10641:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1);
10642:     }
10643:     my $srchinsel = ' <select name="srchin">';
10644: 
10645:     my @srchins = ('crs','dom','alc','instd');
10646: 
10647:     foreach my $option (@srchins) {
10648:         # FIXME 'alc' option unavailable until 
10649:         #       loncreateuser::print_user_query_page()
10650:         #       has been completed.
10651:         next if ($option eq 'alc');
10652:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
10653:         next if ($option eq 'crs' && !$env{'request.course.id'});
10654:         next if (($option eq 'instd') && ($noinstd));
10655:         if ($curr_selected{'srchin'} eq $option) {
10656:             $srchinsel .= ' 
10657:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10658:         } else {
10659:             $srchinsel .= '
10660:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10661:         }
10662:     }
10663:     $srchinsel .= "\n  </select>\n";
10664: 
10665:     my $srchbysel =  ' <select name="srchby">';
10666:     foreach my $option ('lastname','lastfirst','uname') {
10667:         if ($curr_selected{'srchby'} eq $option) {
10668:             $srchbysel .= '
10669:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10670:         } else {
10671:             $srchbysel .= '
10672:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10673:          }
10674:     }
10675:     $srchbysel .= "\n  </select>\n";
10676: 
10677:     my $srchtypesel = ' <select name="srchtype">';
10678:     foreach my $option ('begins','contains','exact') {
10679:         if ($curr_selected{'srchtype'} eq $option) {
10680:             $srchtypesel .= '
10681:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10682:         } else {
10683:             $srchtypesel .= '
10684:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10685:         }
10686:     }
10687:     $srchtypesel .= "\n  </select>\n";
10688: 
10689:     my ($newuserscript,$new_user_create);
10690:     my $context_dom = $env{'request.role.domain'};
10691:     if ($context eq 'requestcrs') {
10692:         if ($env{'form.coursedom'} ne '') { 
10693:             $context_dom = $env{'form.coursedom'};
10694:         }
10695:     }
10696:     if ($forcenewuser) {
10697:         if (ref($srch) eq 'HASH') {
10698:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
10699:                 if ($cancreate) {
10700:                     $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>';
10701:                 } else {
10702:                     my $helplink = 'javascript:helpMenu('."'display'".')';
10703:                     my %usertypetext = (
10704:                         official   => 'institutional',
10705:                         unofficial => 'non-institutional',
10706:                     );
10707:                     $new_user_create = '<p class="LC_warning">'
10708:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
10709:                                       .' '
10710:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
10711:                                           ,'<a href="'.$helplink.'">','</a>')
10712:                                       .'</p><br />';
10713:                 }
10714:             }
10715:         }
10716: 
10717:         $newuserscript = <<"ENDSCRIPT";
10718: 
10719: function setSearch(createnew,callingForm) {
10720:     if (createnew == 1) {
10721:         for (var i=0; i<callingForm.srchby.length; i++) {
10722:             if (callingForm.srchby.options[i].value == 'uname') {
10723:                 callingForm.srchby.selectedIndex = i;
10724:             }
10725:         }
10726:         for (var i=0; i<callingForm.srchin.length; i++) {
10727:             if ( callingForm.srchin.options[i].value == 'dom') {
10728: 		callingForm.srchin.selectedIndex = i;
10729:             }
10730:         }
10731:         for (var i=0; i<callingForm.srchtype.length; i++) {
10732:             if (callingForm.srchtype.options[i].value == 'exact') {
10733:                 callingForm.srchtype.selectedIndex = i;
10734:             }
10735:         }
10736:         for (var i=0; i<callingForm.srchdomain.length; i++) {
10737:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
10738:                 callingForm.srchdomain.selectedIndex = i;
10739:             }
10740:         }
10741:     }
10742: }
10743: ENDSCRIPT
10744: 
10745:     }
10746: 
10747:     my $output = <<"END_BLOCK";
10748: <script type="text/javascript">
10749: // <![CDATA[
10750: function validateEntry(callingForm) {
10751: 
10752:     var checkok = 1;
10753:     var srchin;
10754:     for (var i=0; i<callingForm.srchin.length; i++) {
10755: 	if ( callingForm.srchin[i].checked ) {
10756: 	    srchin = callingForm.srchin[i].value;
10757: 	}
10758:     }
10759: 
10760:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
10761:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
10762:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
10763:     var srchterm =  callingForm.srchterm.value;
10764:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
10765:     var msg = "";
10766: 
10767:     if (srchterm == "") {
10768:         checkok = 0;
10769:         msg += "$js_lt{'youm'}\\n";
10770:     }
10771: 
10772:     if (srchtype== 'begins') {
10773:         if (srchterm.length < 2) {
10774:             checkok = 0;
10775:             msg += "$js_lt{'thte'}\\n";
10776:         }
10777:     }
10778: 
10779:     if (srchtype== 'contains') {
10780:         if (srchterm.length < 3) {
10781:             checkok = 0;
10782:             msg += "$js_lt{'thet'}\\n";
10783:         }
10784:     }
10785:     if (srchin == 'instd') {
10786:         if (srchdomain == '') {
10787:             checkok = 0;
10788:             msg += "$js_lt{'yomc'}\\n";
10789:         }
10790:     }
10791:     if (srchin == 'dom') {
10792:         if (srchdomain == '') {
10793:             checkok = 0;
10794:             msg += "$js_lt{'ymcd'}\\n";
10795:         }
10796:     }
10797:     if (srchby == 'lastfirst') {
10798:         if (srchterm.indexOf(",") == -1) {
10799:             checkok = 0;
10800:             msg += "$js_lt{'whus'}\\n";
10801:         }
10802:         if (srchterm.indexOf(",") == srchterm.length -1) {
10803:             checkok = 0;
10804:             msg += "$js_lt{'whse'}\\n";
10805:         }
10806:     }
10807:     if (checkok == 0) {
10808:         alert("$js_lt{'thfo'}\\n"+msg);
10809:         return;
10810:     }
10811:     if (checkok == 1) {
10812:         callingForm.submit();
10813:     }
10814: }
10815: 
10816: $newuserscript
10817: 
10818: // ]]>
10819: </script>
10820: 
10821: $new_user_create
10822: 
10823: END_BLOCK
10824: 
10825:     $output .= &Apache::lonhtmlcommon::start_pick_box().
10826:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
10827:                $domform.
10828:                &Apache::lonhtmlcommon::row_closure().
10829:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
10830:                $srchbysel.
10831:                $srchtypesel. 
10832:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
10833:                $srchinsel.
10834:                &Apache::lonhtmlcommon::row_closure(1). 
10835:                &Apache::lonhtmlcommon::end_pick_box().
10836:                '<br />';
10837:     return ($output,1);
10838: }
10839: 
10840: sub user_rule_check {
10841:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
10842:     my ($response,%inst_response);
10843:     if (ref($usershash) eq 'HASH') {
10844:         if (keys(%{$usershash}) > 1) {
10845:             my (%by_username,%by_id,%userdoms);
10846:             my $checkid;
10847:             if (ref($checks) eq 'HASH') {
10848:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
10849:                     $checkid = 1;
10850:                 }
10851:             }
10852:             foreach my $user (keys(%{$usershash})) {
10853:                 my ($uname,$udom) = split(/:/,$user);
10854:                 if ($checkid) {
10855:                     if (ref($usershash->{$user}) eq 'HASH') {
10856:                         if ($usershash->{$user}->{'id'} ne '') {
10857:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
10858:                             $userdoms{$udom} = 1;
10859:                             if (ref($inst_results) eq 'HASH') {
10860:                                 $inst_results->{$uname.':'.$udom} = {};
10861:                             }
10862:                         }
10863:                     }
10864:                 } else {
10865:                     $by_username{$udom}{$uname} = 1;
10866:                     $userdoms{$udom} = 1;
10867:                     if (ref($inst_results) eq 'HASH') {
10868:                         $inst_results->{$uname.':'.$udom} = {};
10869:                     }
10870:                 }
10871:             }
10872:             foreach my $udom (keys(%userdoms)) {
10873:                 if (!$got_rules->{$udom}) {
10874:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
10875:                                                              ['usercreation'],$udom);
10876:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
10877:                         foreach my $item ('username','id') {
10878:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10879:                                 $$curr_rules{$udom}{$item} =
10880:                                     $domconfig{'usercreation'}{$item.'_rule'};
10881:                             }
10882:                         }
10883:                     }
10884:                     $got_rules->{$udom} = 1;
10885:                 }
10886:             }
10887:             if ($checkid) {
10888:                 foreach my $udom (keys(%by_id)) {
10889:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
10890:                     if ($outcome eq 'ok') {
10891:                         foreach my $id (keys(%{$by_id{$udom}})) {
10892:                             my $uname = $by_id{$udom}{$id};
10893:                             $inst_response{$uname.':'.$udom} = $outcome;
10894:                         }
10895:                         if (ref($results) eq 'HASH') {
10896:                             foreach my $uname (keys(%{$results})) {
10897:                                 if (exists($inst_response{$uname.':'.$udom})) {
10898:                                     $inst_response{$uname.':'.$udom} = $outcome;
10899:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
10900:                                 }
10901:                             }
10902:                         }
10903:                     }
10904:                 }
10905:             } else {
10906:                 foreach my $udom (keys(%by_username)) {
10907:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
10908:                     if ($outcome eq 'ok') {
10909:                         foreach my $uname (keys(%{$by_username{$udom}})) {
10910:                             $inst_response{$uname.':'.$udom} = $outcome;
10911:                         }
10912:                         if (ref($results) eq 'HASH') {
10913:                             foreach my $uname (keys(%{$results})) {
10914:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
10915:                             }
10916:                         }
10917:                     }
10918:                 }
10919:             }
10920:         } elsif (keys(%{$usershash}) == 1) {
10921:             my $user = (keys(%{$usershash}))[0];
10922:             my ($uname,$udom) = split(/:/,$user);
10923:             if (($udom ne '') && ($uname ne '')) {
10924:                 if (ref($usershash->{$user}) eq 'HASH') {
10925:                     if (ref($checks) eq 'HASH') {
10926:                         if (defined($checks->{'username'})) {
10927:                             ($inst_response{$user},%{$inst_results->{$user}}) =
10928:                                 &Apache::lonnet::get_instuser($udom,$uname);
10929:                         } elsif (defined($checks->{'id'})) {
10930:                             if ($usershash->{$user}->{'id'} ne '') {
10931:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
10932:                                     &Apache::lonnet::get_instuser($udom,undef,
10933:                                                                   $usershash->{$user}->{'id'});
10934:                             } else {
10935:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
10936:                                     &Apache::lonnet::get_instuser($udom,$uname);
10937:                             }
10938:                         }
10939:                     } else {
10940:                        ($inst_response{$user},%{$inst_results->{$user}}) =
10941:                             &Apache::lonnet::get_instuser($udom,$uname);
10942:                        return;
10943:                     }
10944:                     if (!$got_rules->{$udom}) {
10945:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
10946:                                                                  ['usercreation'],$udom);
10947:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
10948:                             foreach my $item ('username','id') {
10949:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10950:                                    $$curr_rules{$udom}{$item} =
10951:                                        $domconfig{'usercreation'}{$item.'_rule'};
10952:                                 }
10953:                             }
10954:                         }
10955:                         $got_rules->{$udom} = 1;
10956:                     }
10957:                 }
10958:             } else {
10959:                 return;
10960:             }
10961:         } else {
10962:             return;
10963:         }
10964:         foreach my $user (keys(%{$usershash})) {
10965:             my ($uname,$udom) = split(/:/,$user);
10966:             next if (($udom eq '') || ($uname eq ''));
10967:             my $id;
10968:             if (ref($inst_results) eq 'HASH') {
10969:                 if (ref($inst_results->{$user}) eq 'HASH') {
10970:                     $id = $inst_results->{$user}->{'id'};
10971:                 }
10972:             }
10973:             if ($id eq '') {
10974:                 if (ref($usershash->{$user})) {
10975:                     $id = $usershash->{$user}->{'id'};
10976:                 }
10977:             }
10978:             foreach my $item (keys(%{$checks})) {
10979:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
10980:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
10981:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
10982:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
10983:                                                                              $$curr_rules{$udom}{$item});
10984:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
10985:                                 if ($rule_check{$rule}) {
10986:                                     $$rulematch{$user}{$item} = $rule;
10987:                                     if ($inst_response{$user} eq 'ok') {
10988:                                         if (ref($inst_results) eq 'HASH') {
10989:                                             if (ref($inst_results->{$user}) eq 'HASH') {
10990:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
10991:                                                     $$alerts{$item}{$udom}{$uname} = 1;
10992:                                                 } elsif ($item eq 'id') {
10993:                                                     if ($inst_results->{$user}->{'id'} eq '') {
10994:                                                         $$alerts{$item}{$udom}{$uname} = 1;
10995:                                                     }
10996:                                                 }
10997:                                             }
10998:                                         }
10999:                                     }
11000:                                     last;
11001:                                 }
11002:                             }
11003:                         }
11004:                     }
11005:                 }
11006:             }
11007:         }
11008:     }
11009:     return;
11010: }
11011: 
11012: sub user_rule_formats {
11013:     my ($domain,$domdesc,$curr_rules,$check) = @_;
11014:     my %text = ( 
11015:                  'username' => 'Usernames',
11016:                  'id'       => 'IDs',
11017:                );
11018:     my $output;
11019:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
11020:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
11021:         if (@{$ruleorder} > 0) {
11022:             $output = '<br />'.
11023:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
11024:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
11025:                       ' <ul>';
11026:             foreach my $rule (@{$ruleorder}) {
11027:                 if (ref($curr_rules) eq 'ARRAY') {
11028:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
11029:                         if (ref($rules->{$rule}) eq 'HASH') {
11030:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
11031:                                         $rules->{$rule}{'desc'}.'</li>';
11032:                         }
11033:                     }
11034:                 }
11035:             }
11036:             $output .= '</ul>';
11037:         }
11038:     }
11039:     return $output;
11040: }
11041: 
11042: sub instrule_disallow_msg {
11043:     my ($checkitem,$domdesc,$count,$mode) = @_;
11044:     my $response;
11045:     my %text = (
11046:                   item   => 'username',
11047:                   items  => 'usernames',
11048:                   match  => 'matches',
11049:                   do     => 'does',
11050:                   action => 'a username',
11051:                   one    => 'one',
11052:                );
11053:     if ($count > 1) {
11054:         $text{'item'} = 'usernames';
11055:         $text{'match'} ='match';
11056:         $text{'do'} = 'do';
11057:         $text{'action'} = 'usernames',
11058:         $text{'one'} = 'ones';
11059:     }
11060:     if ($checkitem eq 'id') {
11061:         $text{'items'} = 'IDs';
11062:         $text{'item'} = 'ID';
11063:         $text{'action'} = 'an ID';
11064:         if ($count > 1) {
11065:             $text{'item'} = 'IDs';
11066:             $text{'action'} = 'IDs';
11067:         }
11068:     }
11069:     $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 />';
11070:     if ($mode eq 'upload') {
11071:         if ($checkitem eq 'username') {
11072:             $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'}.");
11073:         } elsif ($checkitem eq 'id') {
11074:             $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.");
11075:         }
11076:     } elsif ($mode eq 'selfcreate') {
11077:         if ($checkitem eq 'id') {
11078:             $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.");
11079:         }
11080:     } else {
11081:         if ($checkitem eq 'username') {
11082:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
11083:         } elsif ($checkitem eq 'id') {
11084:             $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.");
11085:         }
11086:     }
11087:     return $response;
11088: }
11089: 
11090: sub personal_data_fieldtitles {
11091:     my %fieldtitles = &Apache::lonlocal::texthash (
11092:                         id => 'Student/Employee ID',
11093:                         permanentemail => 'E-mail address',
11094:                         lastname => 'Last Name',
11095:                         firstname => 'First Name',
11096:                         middlename => 'Middle Name',
11097:                         generation => 'Generation',
11098:                         gen => 'Generation',
11099:                         inststatus => 'Affiliation',
11100:                    );
11101:     return %fieldtitles;
11102: }
11103: 
11104: sub sorted_inst_types {
11105:     my ($dom) = @_;
11106:     my ($usertypes,$order);
11107:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
11108:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
11109:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
11110:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
11111:     } else {
11112:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
11113:     }
11114:     my $othertitle = &mt('All users');
11115:     if ($env{'request.course.id'}) {
11116:         $othertitle  = &mt('Any users');
11117:     }
11118:     my @types;
11119:     if (ref($order) eq 'ARRAY') {
11120:         @types = @{$order};
11121:     }
11122:     if (@types == 0) {
11123:         if (ref($usertypes) eq 'HASH') {
11124:             @types = sort(keys(%{$usertypes}));
11125:         }
11126:     }
11127:     if (keys(%{$usertypes}) > 0) {
11128:         $othertitle = &mt('Other users');
11129:     }
11130:     return ($othertitle,$usertypes,\@types);
11131: }
11132: 
11133: sub get_institutional_codes {
11134:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
11135: # Get complete list of course sections to update
11136:     my @currsections = ();
11137:     my @currxlists = ();
11138:     my (%unclutteredsec,%unclutteredlcsec);
11139:     my $coursecode = $$settings{'internal.coursecode'};
11140:     my $crskey = $crs.':'.$coursecode;
11141:     @{$unclutteredsec{$crskey}} = ();
11142:     @{$unclutteredlcsec{$crskey}} = ();
11143: 
11144:     if ($$settings{'internal.sectionnums'} ne '') {
11145:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
11146:     }
11147: 
11148:     if ($$settings{'internal.crosslistings'} ne '') {
11149:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
11150:     }
11151: 
11152:     if (@currxlists > 0) {
11153:         foreach my $xl (@currxlists) {
11154:             if ($xl =~ /^([^:]+):(\w*)$/) {
11155:                 unless (grep/^$1$/,@{$allcourses}) {
11156:                     push(@{$allcourses},$1);
11157:                     $$LC_code{$1} = $2;
11158:                 }
11159:             }
11160:         }
11161:     }
11162: 
11163:     if (@currsections > 0) {
11164:         foreach my $sec (@currsections) {
11165:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
11166:                 my $instsec = $1;
11167:                 my $lc_sec = $2;
11168:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
11169:                     push(@{$unclutteredsec{$crskey}},$instsec);
11170:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
11171:                 }
11172:             }
11173:         }
11174:     }
11175: 
11176:     if (@{$unclutteredsec{$crskey}} > 0) {
11177:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
11178:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
11179:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
11180:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
11181:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
11182:                     push(@{$allcourses},$sec);
11183:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
11184:                 }
11185:             }
11186:         }
11187:     }
11188:     return;
11189: }
11190: 
11191: sub get_standard_codeitems {
11192:     return ('Year','Semester','Department','Number','Section');
11193: }
11194: 
11195: =pod
11196: 
11197: =head1 Slot Helpers
11198: 
11199: =over 4
11200: 
11201: =item * sorted_slots()
11202: 
11203: Sorts an array of slot names in order of an optional sort key,
11204: default sort is by slot start time (earliest first). 
11205: 
11206: Inputs:
11207: 
11208: =over 4
11209: 
11210: slotsarr  - Reference to array of unsorted slot names.
11211: 
11212: slots     - Reference to hash of hash, where outer hash keys are slot names.
11213: 
11214: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
11215: 
11216: =back
11217: 
11218: Returns:
11219: 
11220: =over 4
11221: 
11222: sorted   - An array of slot names sorted by a specified sort key 
11223:            (default sort key is start time of the slot).
11224: 
11225: =back
11226: 
11227: =cut
11228: 
11229: 
11230: sub sorted_slots {
11231:     my ($slotsarr,$slots,$sortkey) = @_;
11232:     if ($sortkey eq '') {
11233:         $sortkey = 'starttime';
11234:     }
11235:     my @sorted;
11236:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
11237:         @sorted =
11238:             sort {
11239:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
11240:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
11241:                      }
11242:                      if (ref($slots->{$a})) { return -1;}
11243:                      if (ref($slots->{$b})) { return 1;}
11244:                      return 0;
11245:                  } @{$slotsarr};
11246:     }
11247:     return @sorted;
11248: }
11249: 
11250: =pod
11251: 
11252: =item * get_future_slots()
11253: 
11254: Inputs:
11255: 
11256: =over 4
11257: 
11258: cnum - course number
11259: 
11260: cdom - course domain
11261: 
11262: now - current UNIX time
11263: 
11264: symb - optional symb
11265: 
11266: =back
11267: 
11268: Returns:
11269: 
11270: =over 4
11271: 
11272: sorted_reservable - ref to array of student_schedulable slots currently 
11273:                     reservable, ordered by end date of reservation period.
11274: 
11275: reservable_now - ref to hash of student_schedulable slots currently
11276:                  reservable.
11277: 
11278:     Keys in inner hash are:
11279:     (a) symb: either blank or symb to which slot use is restricted.
11280:     (b) endreserve: end date of reservation period.
11281:     (c) uniqueperiod: start,end dates when slot is to be uniquely
11282:         selected.
11283: 
11284: sorted_future - ref to array of student_schedulable slots reservable in
11285:                 the future, ordered by start date of reservation period.
11286: 
11287: future_reservable - ref to hash of student_schedulable slots reservable
11288:                     in the future.
11289: 
11290:     Keys in inner hash are:
11291:     (a) symb: either blank or symb to which slot use is restricted.
11292:     (b) startreserve:  start date of reservation period.
11293:     (c) uniqueperiod: start,end dates when slot is to be uniquely
11294:         selected.
11295: 
11296: =back
11297: 
11298: =cut
11299: 
11300: sub get_future_slots {
11301:     my ($cnum,$cdom,$now,$symb) = @_;
11302:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
11303:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
11304:     foreach my $slot (keys(%slots)) {
11305:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
11306:         if ($symb) {
11307:             next if (($slots{$slot}->{'symb'} ne '') && 
11308:                      ($slots{$slot}->{'symb'} ne $symb));
11309:         }
11310:         if (($slots{$slot}->{'starttime'} > $now) &&
11311:             ($slots{$slot}->{'endtime'} > $now)) {
11312:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
11313:                 my $userallowed = 0;
11314:                 if ($slots{$slot}->{'allowedsections'}) {
11315:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
11316:                     if (!defined($env{'request.role.sec'})
11317:                         && grep(/^No section assigned$/,@allowed_sec)) {
11318:                         $userallowed=1;
11319:                     } else {
11320:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
11321:                             $userallowed=1;
11322:                         }
11323:                     }
11324:                     unless ($userallowed) {
11325:                         if (defined($env{'request.course.groups'})) {
11326:                             my @groups = split(/:/,$env{'request.course.groups'});
11327:                             foreach my $group (@groups) {
11328:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
11329:                                     $userallowed=1;
11330:                                     last;
11331:                                 }
11332:                             }
11333:                         }
11334:                     }
11335:                 }
11336:                 if ($slots{$slot}->{'allowedusers'}) {
11337:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
11338:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
11339:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
11340:                         $userallowed = 1;
11341:                     }
11342:                 }
11343:                 next unless($userallowed);
11344:             }
11345:             my $startreserve = $slots{$slot}->{'startreserve'};
11346:             my $endreserve = $slots{$slot}->{'endreserve'};
11347:             my $symb = $slots{$slot}->{'symb'};
11348:             my $uniqueperiod;
11349:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
11350:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
11351:             }
11352:             if (($startreserve < $now) &&
11353:                 (!$endreserve || $endreserve > $now)) {
11354:                 my $lastres = $endreserve;
11355:                 if (!$lastres) {
11356:                     $lastres = $slots{$slot}->{'starttime'};
11357:                 }
11358:                 $reservable_now{$slot} = {
11359:                                            symb       => $symb,
11360:                                            endreserve => $lastres,
11361:                                            uniqueperiod => $uniqueperiod,   
11362:                                          };
11363:             } elsif (($startreserve > $now) &&
11364:                      (!$endreserve || $endreserve > $startreserve)) {
11365:                 $future_reservable{$slot} = {
11366:                                               symb         => $symb,
11367:                                               startreserve => $startreserve,
11368:                                               uniqueperiod => $uniqueperiod,
11369:                                             };
11370:             }
11371:         }
11372:     }
11373:     my @unsorted_reservable = keys(%reservable_now);
11374:     if (@unsorted_reservable > 0) {
11375:         @sorted_reservable = 
11376:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
11377:     }
11378:     my @unsorted_future = keys(%future_reservable);
11379:     if (@unsorted_future > 0) {
11380:         @sorted_future =
11381:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
11382:     }
11383:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
11384: }
11385: 
11386: =pod
11387: 
11388: =back
11389: 
11390: =head1 HTTP Helpers
11391: 
11392: =over 4
11393: 
11394: =item * &get_unprocessed_cgi($query,$possible_names)
11395: 
11396: Modify the %env hash to contain unprocessed CGI form parameters held in
11397: $query.  The parameters listed in $possible_names (an array reference),
11398: will be set in $env{'form.name'} if they do not already exist.
11399: 
11400: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
11401: $possible_names is an ref to an array of form element names.  As an example:
11402: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
11403: will result in $env{'form.uname'} and $env{'form.udom'} being set.
11404: 
11405: =cut
11406: 
11407: sub get_unprocessed_cgi {
11408:   my ($query,$possible_names)= @_;
11409:   # $Apache::lonxml::debug=1;
11410:   foreach my $pair (split(/&/,$query)) {
11411:     my ($name, $value) = split(/=/,$pair);
11412:     $name = &unescape($name);
11413:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
11414:       $value =~ tr/+/ /;
11415:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
11416:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
11417:     }
11418:   }
11419: }
11420: 
11421: =pod
11422: 
11423: =item * &cacheheader() 
11424: 
11425: returns cache-controlling header code
11426: 
11427: =cut
11428: 
11429: sub cacheheader {
11430:     unless ($env{'request.method'} eq 'GET') { return ''; }
11431:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
11432:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
11433:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
11434:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
11435:     return $output;
11436: }
11437: 
11438: =pod
11439: 
11440: =item * &no_cache($r) 
11441: 
11442: specifies header code to not have cache
11443: 
11444: =cut
11445: 
11446: sub no_cache {
11447:     my ($r) = @_;
11448:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
11449: 	$env{'request.method'} ne 'GET') { return ''; }
11450:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
11451:     $r->no_cache(1);
11452:     $r->header_out("Expires" => $date);
11453:     $r->header_out("Pragma" => "no-cache");
11454: }
11455: 
11456: sub content_type {
11457:     my ($r,$type,$charset) = @_;
11458:     if ($r) {
11459: 	#  Note that printout.pl calls this with undef for $r.
11460: 	&no_cache($r);
11461:     }
11462:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
11463:     unless ($charset) {
11464: 	$charset=&Apache::lonlocal::current_encoding;
11465:     }
11466:     if ($charset) { $type.='; charset='.$charset; }
11467:     if ($r) {
11468: 	$r->content_type($type);
11469:     } else {
11470: 	print("Content-type: $type\n\n");
11471:     }
11472: }
11473: 
11474: =pod
11475: 
11476: =item * &add_to_env($name,$value) 
11477: 
11478: adds $name to the %env hash with value
11479: $value, if $name already exists, the entry is converted to an array
11480: reference and $value is added to the array.
11481: 
11482: =cut
11483: 
11484: sub add_to_env {
11485:   my ($name,$value)=@_;
11486:   if (defined($env{$name})) {
11487:     if (ref($env{$name})) {
11488:       #already have multiple values
11489:       push(@{ $env{$name} },$value);
11490:     } else {
11491:       #first time seeing multiple values, convert hash entry to an arrayref
11492:       my $first=$env{$name};
11493:       undef($env{$name});
11494:       push(@{ $env{$name} },$first,$value);
11495:     }
11496:   } else {
11497:     $env{$name}=$value;
11498:   }
11499: }
11500: 
11501: =pod
11502: 
11503: =item * &get_env_multiple($name) 
11504: 
11505: gets $name from the %env hash, it seemlessly handles the cases where multiple
11506: values may be defined and end up as an array ref.
11507: 
11508: returns an array of values
11509: 
11510: =cut
11511: 
11512: sub get_env_multiple {
11513:     my ($name) = @_;
11514:     my @values;
11515:     if (defined($env{$name})) {
11516:         # exists is it an array
11517:         if (ref($env{$name})) {
11518:             @values=@{ $env{$name} };
11519:         } else {
11520:             $values[0]=$env{$name};
11521:         }
11522:     }
11523:     return(@values);
11524: }
11525: 
11526: sub ask_for_embedded_content {
11527:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
11528:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
11529:         %currsubfile,%unused,$rem);
11530:     my $counter = 0;
11531:     my $numnew = 0;
11532:     my $numremref = 0;
11533:     my $numinvalid = 0;
11534:     my $numpathchg = 0;
11535:     my $numexisting = 0;
11536:     my $numunused = 0;
11537:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
11538:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
11539:     my $heading = &mt('Upload embedded files');
11540:     my $buttontext = &mt('Upload');
11541: 
11542:     if ($env{'request.course.id'}) {
11543:         if ($actionurl eq '/adm/dependencies') {
11544:             $navmap = Apache::lonnavmaps::navmap->new();
11545:         }
11546:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11547:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11548:     }
11549:     if (($actionurl eq '/adm/portfolio') ||
11550:         ($actionurl eq '/adm/coursegrp_portfolio')) {
11551:         my $current_path='/';
11552:         if ($env{'form.currentpath'}) {
11553:             $current_path = $env{'form.currentpath'};
11554:         }
11555:         if ($actionurl eq '/adm/coursegrp_portfolio') {
11556:             $udom = $cdom;
11557:             $uname = $cnum;
11558:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
11559:         } else {
11560:             $udom = $env{'user.domain'};
11561:             $uname = $env{'user.name'};
11562:             $url = '/userfiles/portfolio';
11563:         }
11564:         $toplevel = $url.'/';
11565:         $url .= $current_path;
11566:         $getpropath = 1;
11567:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
11568:              ($actionurl eq '/adm/imsimport')) { 
11569:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
11570:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
11571:         $toplevel = $url;
11572:         if ($rest ne '') {
11573:             $url .= $rest;
11574:         }
11575:     } elsif ($actionurl eq '/adm/coursedocs') {
11576:         if (ref($args) eq 'HASH') {
11577:             $url = $args->{'docs_url'};
11578:             $toplevel = $url;
11579:             if ($args->{'context'} eq 'paste') {
11580:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
11581:                 ($path) =
11582:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
11583:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
11584:                 $fileloc =~ s{^/}{};
11585:             }
11586:         }
11587:     } elsif ($actionurl eq '/adm/dependencies') {
11588:         if ($env{'request.course.id'} ne '') {
11589:             if (ref($args) eq 'HASH') {
11590:                 $url = $args->{'docs_url'};
11591:                 $title = $args->{'docs_title'};
11592:                 $toplevel = $url;
11593:                 unless ($toplevel =~ m{^/}) {
11594:                     $toplevel = "/$url";
11595:                 }
11596:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
11597:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
11598:                     $path = $1;
11599:                 } else {
11600:                     ($path) =
11601:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
11602:                 }
11603:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
11604:                     $fileloc = $toplevel;
11605:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
11606:                     my ($udom,$uname,$fname) =
11607:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
11608:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
11609:                 } else {
11610:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
11611:                 }
11612:                 $fileloc =~ s{^/}{};
11613:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
11614:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
11615:             }
11616:         }
11617:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
11618:         $udom = $cdom;
11619:         $uname = $cnum;
11620:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
11621:         $toplevel = $url;
11622:         $path = $url;
11623:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
11624:         $fileloc =~ s{^/}{};
11625:     }
11626:     foreach my $file (keys(%{$allfiles})) {
11627:         my $embed_file;
11628:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
11629:             $embed_file = $1;
11630:         } else {
11631:             $embed_file = $file;
11632:         }
11633:         my ($absolutepath,$cleaned_file);
11634:         if ($embed_file =~ m{^\w+://}) {
11635:             $cleaned_file = $embed_file;
11636:             $newfiles{$cleaned_file} = 1;
11637:             $mapping{$cleaned_file} = $embed_file;
11638:         } else {
11639:             $cleaned_file = &clean_path($embed_file);
11640:             if ($embed_file =~ m{^/}) {
11641:                 $absolutepath = $embed_file;
11642:             }
11643:             if ($cleaned_file =~ m{/}) {
11644:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
11645:                 $path = &check_for_traversal($path,$url,$toplevel);
11646:                 my $item = $fname;
11647:                 if ($path ne '') {
11648:                     $item = $path.'/'.$fname;
11649:                     $subdependencies{$path}{$fname} = 1;
11650:                 } else {
11651:                     $dependencies{$item} = 1;
11652:                 }
11653:                 if ($absolutepath) {
11654:                     $mapping{$item} = $absolutepath;
11655:                 } else {
11656:                     $mapping{$item} = $embed_file;
11657:                 }
11658:             } else {
11659:                 $dependencies{$embed_file} = 1;
11660:                 if ($absolutepath) {
11661:                     $mapping{$cleaned_file} = $absolutepath;
11662:                 } else {
11663:                     $mapping{$cleaned_file} = $embed_file;
11664:                 }
11665:             }
11666:         }
11667:     }
11668:     my $dirptr = 16384;
11669:     foreach my $path (keys(%subdependencies)) {
11670:         $currsubfile{$path} = {};
11671:         if (($actionurl eq '/adm/portfolio') ||
11672:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
11673:             my ($sublistref,$listerror) =
11674:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
11675:             if (ref($sublistref) eq 'ARRAY') {
11676:                 foreach my $line (@{$sublistref}) {
11677:                     my ($file_name,$rest) = split(/\&/,$line,2);
11678:                     $currsubfile{$path}{$file_name} = 1;
11679:                 }
11680:             }
11681:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11682:             if (opendir(my $dir,$url.'/'.$path)) {
11683:                 my @subdir_list = grep(!/^\./,readdir($dir));
11684:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
11685:             }
11686:         } elsif (($actionurl eq '/adm/dependencies') ||
11687:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11688:                   ($args->{'context'} eq 'paste')) ||
11689:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
11690:             if ($env{'request.course.id'} ne '') {
11691:                 my $dir;
11692:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
11693:                     $dir = $fileloc;
11694:                 } else {
11695:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
11696:                 }
11697:                 if ($dir ne '') {
11698:                     my ($sublistref,$listerror) =
11699:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
11700:                     if (ref($sublistref) eq 'ARRAY') {
11701:                         foreach my $line (@{$sublistref}) {
11702:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
11703:                                 undef,$mtime)=split(/\&/,$line,12);
11704:                             unless (($testdir&$dirptr) ||
11705:                                     ($file_name =~ /^\.\.?$/)) {
11706:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
11707:                             }
11708:                         }
11709:                     }
11710:                 }
11711:             }
11712:         }
11713:         foreach my $file (keys(%{$subdependencies{$path}})) {
11714:             if (exists($currsubfile{$path}{$file})) {
11715:                 my $item = $path.'/'.$file;
11716:                 unless ($mapping{$item} eq $item) {
11717:                     $pathchanges{$item} = 1;
11718:                 }
11719:                 $existing{$item} = 1;
11720:                 $numexisting ++;
11721:             } else {
11722:                 $newfiles{$path.'/'.$file} = 1;
11723:             }
11724:         }
11725:         if ($actionurl eq '/adm/dependencies') {
11726:             foreach my $path (keys(%currsubfile)) {
11727:                 if (ref($currsubfile{$path}) eq 'HASH') {
11728:                     foreach my $file (keys(%{$currsubfile{$path}})) {
11729:                          unless ($subdependencies{$path}{$file}) {
11730:                              next if (($rem ne '') &&
11731:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
11732:                                        (ref($navmap) &&
11733:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
11734:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
11735:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
11736:                              $unused{$path.'/'.$file} = 1; 
11737:                          }
11738:                     }
11739:                 }
11740:             }
11741:         }
11742:     }
11743:     my %currfile;
11744:     if (($actionurl eq '/adm/portfolio') ||
11745:         ($actionurl eq '/adm/coursegrp_portfolio')) {
11746:         my ($dirlistref,$listerror) =
11747:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
11748:         if (ref($dirlistref) eq 'ARRAY') {
11749:             foreach my $line (@{$dirlistref}) {
11750:                 my ($file_name,$rest) = split(/\&/,$line,2);
11751:                 $currfile{$file_name} = 1;
11752:             }
11753:         }
11754:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11755:         if (opendir(my $dir,$url)) {
11756:             my @dir_list = grep(!/^\./,readdir($dir));
11757:             map {$currfile{$_} = 1;} @dir_list;
11758:         }
11759:     } elsif (($actionurl eq '/adm/dependencies') ||
11760:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11761:               ($args->{'context'} eq 'paste')) ||
11762:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
11763:         if ($env{'request.course.id'} ne '') {
11764:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
11765:             if ($dir ne '') {
11766:                 my ($dirlistref,$listerror) =
11767:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
11768:                 if (ref($dirlistref) eq 'ARRAY') {
11769:                     foreach my $line (@{$dirlistref}) {
11770:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
11771:                             $size,undef,$mtime)=split(/\&/,$line,12);
11772:                         unless (($testdir&$dirptr) ||
11773:                                 ($file_name =~ /^\.\.?$/)) {
11774:                             $currfile{$file_name} = [$size,$mtime];
11775:                         }
11776:                     }
11777:                 }
11778:             }
11779:         }
11780:     }
11781:     foreach my $file (keys(%dependencies)) {
11782:         if (exists($currfile{$file})) {
11783:             unless ($mapping{$file} eq $file) {
11784:                 $pathchanges{$file} = 1;
11785:             }
11786:             $existing{$file} = 1;
11787:             $numexisting ++;
11788:         } else {
11789:             $newfiles{$file} = 1;
11790:         }
11791:     }
11792:     foreach my $file (keys(%currfile)) {
11793:         unless (($file eq $filename) ||
11794:                 ($file eq $filename.'.bak') ||
11795:                 ($dependencies{$file})) {
11796:             if ($actionurl eq '/adm/dependencies') {
11797:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
11798:                     next if (($rem ne '') &&
11799:                              (($env{"httpref.$rem".$file} ne '') ||
11800:                               (ref($navmap) &&
11801:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
11802:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
11803:                                 ($navmap->getResourceByUrl($rem.$1)))))));
11804:                 }
11805:             }
11806:             $unused{$file} = 1;
11807:         }
11808:     }
11809:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11810:         ($args->{'context'} eq 'paste')) {
11811:         $counter = scalar(keys(%existing));
11812:         $numpathchg = scalar(keys(%pathchanges));
11813:         return ($output,$counter,$numpathchg,\%existing);
11814:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
11815:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
11816:         $counter = scalar(keys(%existing));
11817:         $numpathchg = scalar(keys(%pathchanges));
11818:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
11819:     }
11820:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
11821:         if ($actionurl eq '/adm/dependencies') {
11822:             next if ($embed_file =~ m{^\w+://});
11823:         }
11824:         $upload_output .= &start_data_table_row().
11825:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
11826:                           '<span class="LC_filename">'.$embed_file.'</span>';
11827:         unless ($mapping{$embed_file} eq $embed_file) {
11828:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
11829:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
11830:         }
11831:         $upload_output .= '</td>';
11832:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
11833:             $upload_output.='<td align="right">'.
11834:                             '<span class="LC_info LC_fontsize_medium">'.
11835:                             &mt("URL points to web address").'</span>';
11836:             $numremref++;
11837:         } elsif ($args->{'error_on_invalid_names'}
11838:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
11839:             $upload_output.='<td align="right"><span class="LC_warning">'.
11840:                             &mt('Invalid characters').'</span>';
11841:             $numinvalid++;
11842:         } else {
11843:             $upload_output .= '<td>'.
11844:                               &embedded_file_element('upload_embedded',$counter,
11845:                                                      $embed_file,\%mapping,
11846:                                                      $allfiles,$codebase,'upload');
11847:             $counter ++;
11848:             $numnew ++;
11849:         }
11850:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
11851:     }
11852:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
11853:         if ($actionurl eq '/adm/dependencies') {
11854:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
11855:             $modify_output .= &start_data_table_row().
11856:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
11857:                               '<img src="'.&icon($embed_file).'" border="0" />'.
11858:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
11859:                               '<td>'.$size.'</td>'.
11860:                               '<td>'.$mtime.'</td>'.
11861:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
11862:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
11863:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
11864:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
11865:                               &embedded_file_element('upload_embedded',$counter,
11866:                                                      $embed_file,\%mapping,
11867:                                                      $allfiles,$codebase,'modify').
11868:                               '</div></td>'.
11869:                               &end_data_table_row()."\n";
11870:             $counter ++;
11871:         } else {
11872:             $upload_output .= &start_data_table_row().
11873:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
11874:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
11875:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
11876:                               &Apache::loncommon::end_data_table_row()."\n";
11877:         }
11878:     }
11879:     my $delidx = $counter;
11880:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
11881:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
11882:         $delete_output .= &start_data_table_row().
11883:                           '<td><img src="'.&icon($oldfile).'" />'.
11884:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
11885:                           '<td>'.$size.'</td>'.
11886:                           '<td>'.$mtime.'</td>'.
11887:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
11888:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
11889:                           &embedded_file_element('upload_embedded',$delidx,
11890:                                                  $oldfile,\%mapping,$allfiles,
11891:                                                  $codebase,'delete').'</td>'.
11892:                           &end_data_table_row()."\n"; 
11893:         $numunused ++;
11894:         $delidx ++;
11895:     }
11896:     if ($upload_output) {
11897:         $upload_output = &start_data_table().
11898:                          $upload_output.
11899:                          &end_data_table()."\n";
11900:     }
11901:     if ($modify_output) {
11902:         $modify_output = &start_data_table().
11903:                          &start_data_table_header_row().
11904:                          '<th>'.&mt('File').'</th>'.
11905:                          '<th>'.&mt('Size (KB)').'</th>'.
11906:                          '<th>'.&mt('Modified').'</th>'.
11907:                          '<th>'.&mt('Upload replacement?').'</th>'.
11908:                          &end_data_table_header_row().
11909:                          $modify_output.
11910:                          &end_data_table()."\n";
11911:     }
11912:     if ($delete_output) {
11913:         $delete_output = &start_data_table().
11914:                          &start_data_table_header_row().
11915:                          '<th>'.&mt('File').'</th>'.
11916:                          '<th>'.&mt('Size (KB)').'</th>'.
11917:                          '<th>'.&mt('Modified').'</th>'.
11918:                          '<th>'.&mt('Delete?').'</th>'.
11919:                          &end_data_table_header_row().
11920:                          $delete_output.
11921:                          &end_data_table()."\n";
11922:     }
11923:     my $applies = 0;
11924:     if ($numremref) {
11925:         $applies ++;
11926:     }
11927:     if ($numinvalid) {
11928:         $applies ++;
11929:     }
11930:     if ($numexisting) {
11931:         $applies ++;
11932:     }
11933:     if ($counter || $numunused) {
11934:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
11935:                   ' method="post" enctype="multipart/form-data">'."\n".
11936:                   $state.'<h3>'.$heading.'</h3>'; 
11937:         if ($actionurl eq '/adm/dependencies') {
11938:             if ($numnew) {
11939:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
11940:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
11941:                            $upload_output.'<br />'."\n";
11942:             }
11943:             if ($numexisting) {
11944:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
11945:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
11946:                            $modify_output.'<br />'."\n";
11947:                            $buttontext = &mt('Save changes');
11948:             }
11949:             if ($numunused) {
11950:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
11951:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
11952:                            $delete_output.'<br />'."\n";
11953:                            $buttontext = &mt('Save changes');
11954:             }
11955:         } else {
11956:             $output .= $upload_output.'<br />'."\n";
11957:         }
11958:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
11959:                    $counter.'" />'."\n";
11960:         if ($actionurl eq '/adm/dependencies') { 
11961:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
11962:                        $numnew.'" />'."\n";
11963:         } elsif ($actionurl eq '') {
11964:             $output .=  '<input type="hidden" name="phase" value="three" />';
11965:         }
11966:     } elsif ($applies) {
11967:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
11968:         if ($applies > 1) {
11969:             $output .=  
11970:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
11971:             if ($numremref) {
11972:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
11973:             }
11974:             if ($numinvalid) {
11975:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
11976:             }
11977:             if ($numexisting) {
11978:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
11979:             }
11980:             $output .= '</ul><br />';
11981:         } elsif ($numremref) {
11982:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
11983:         } elsif ($numinvalid) {
11984:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
11985:         } elsif ($numexisting) {
11986:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
11987:         }
11988:         $output .= $upload_output.'<br />';
11989:     }
11990:     my ($pathchange_output,$chgcount);
11991:     $chgcount = $counter;
11992:     if (keys(%pathchanges) > 0) {
11993:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
11994:             if ($counter) {
11995:                 $output .= &embedded_file_element('pathchange',$chgcount,
11996:                                                   $embed_file,\%mapping,
11997:                                                   $allfiles,$codebase,'change');
11998:             } else {
11999:                 $pathchange_output .= 
12000:                     &start_data_table_row().
12001:                     '<td><input type ="checkbox" name="namechange" value="'.
12002:                     $chgcount.'" checked="checked" /></td>'.
12003:                     '<td>'.$mapping{$embed_file}.'</td>'.
12004:                     '<td>'.$embed_file.
12005:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
12006:                                            \%mapping,$allfiles,$codebase,'change').
12007:                     '</td>'.&end_data_table_row();
12008:             }
12009:             $numpathchg ++;
12010:             $chgcount ++;
12011:         }
12012:     }
12013:     if (($counter) || ($numunused)) {
12014:         if ($numpathchg) {
12015:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
12016:                        $numpathchg.'" />'."\n";
12017:         }
12018:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
12019:             ($actionurl eq '/adm/imsimport')) {
12020:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
12021:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
12022:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
12023:         } elsif ($actionurl eq '/adm/dependencies') {
12024:             $output .= '<input type="hidden" name="action" value="process_changes" />';
12025:         }
12026:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
12027:     } elsif ($numpathchg) {
12028:         my %pathchange = ();
12029:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
12030:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
12031:             $output .= '<p>'.&mt('or').'</p>'; 
12032:         }
12033:     }
12034:     return ($output,$counter,$numpathchg);
12035: }
12036: 
12037: =pod
12038: 
12039: =item * clean_path($name)
12040: 
12041: Performs clean-up of directories, subdirectories and filename in an
12042: embedded object, referenced in an HTML file which is being uploaded
12043: to a course or portfolio, where
12044: "Upload embedded images/multimedia files if HTML file" checkbox was
12045: checked.
12046: 
12047: Clean-up is similar to replacements in lonnet::clean_filename()
12048: except each / between sub-directory and next level is preserved.
12049: 
12050: =cut
12051: 
12052: sub clean_path {
12053:     my ($embed_file) = @_;
12054:     $embed_file =~s{^/+}{};
12055:     my @contents;
12056:     if ($embed_file =~ m{/}) {
12057:         @contents = split(/\//,$embed_file);
12058:     } else {
12059:         @contents = ($embed_file);
12060:     }
12061:     my $lastidx = scalar(@contents)-1;
12062:     for (my $i=0; $i<=$lastidx; $i++) {
12063:         $contents[$i]=~s{\\}{/}g;
12064:         $contents[$i]=~s/\s+/\_/g;
12065:         $contents[$i]=~s{[^/\w\.\-]}{}g;
12066:         if ($i == $lastidx) {
12067:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
12068:         }
12069:     }
12070:     if ($lastidx > 0) {
12071:         return join('/',@contents);
12072:     } else {
12073:         return $contents[0];
12074:     }
12075: }
12076: 
12077: sub embedded_file_element {
12078:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
12079:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
12080:                    (ref($codebase) eq 'HASH'));
12081:     my $output;
12082:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
12083:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
12084:     }
12085:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
12086:                &escape($embed_file).'" />';
12087:     unless (($context eq 'upload_embedded') && 
12088:             ($mapping->{$embed_file} eq $embed_file)) {
12089:         $output .='
12090:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
12091:     }
12092:     my $attrib;
12093:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
12094:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
12095:     }
12096:     $output .=
12097:         "\n\t\t".
12098:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
12099:         $attrib.'" />';
12100:     if (exists($codebase->{$mapping->{$embed_file}})) {
12101:         $output .=
12102:             "\n\t\t".
12103:             '<input name="codebase_'.$num.'" type="hidden" value="'.
12104:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
12105:     }
12106:     return $output;
12107: }
12108: 
12109: sub get_dependency_details {
12110:     my ($currfile,$currsubfile,$embed_file) = @_;
12111:     my ($size,$mtime,$showsize,$showmtime);
12112:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
12113:         if ($embed_file =~ m{/}) {
12114:             my ($path,$fname) = split(/\//,$embed_file);
12115:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
12116:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
12117:             }
12118:         } else {
12119:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
12120:                 ($size,$mtime) = @{$currfile->{$embed_file}};
12121:             }
12122:         }
12123:         $showsize = $size/1024.0;
12124:         $showsize = sprintf("%.1f",$showsize);
12125:         if ($mtime > 0) {
12126:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
12127:         }
12128:     }
12129:     return ($showsize,$showmtime);
12130: }
12131: 
12132: sub ask_embedded_js {
12133:     return <<"END";
12134: <script type="text/javascript"">
12135: // <![CDATA[
12136: function toggleBrowse(counter) {
12137:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
12138:     var fileid = document.getElementById('embedded_item_'+counter);
12139:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
12140:     if (chkboxid.checked == true) {
12141:         uploaddivid.style.display='block';
12142:     } else {
12143:         uploaddivid.style.display='none';
12144:         fileid.value = '';
12145:     }
12146: }
12147: // ]]>
12148: </script>
12149: 
12150: END
12151: }
12152: 
12153: sub upload_embedded {
12154:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
12155:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
12156:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
12157:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
12158:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
12159:         my $orig_uploaded_filename =
12160:             $env{'form.embedded_item_'.$i.'.filename'};
12161:         foreach my $type ('orig','ref','attrib','codebase') {
12162:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
12163:                 $env{'form.embedded_'.$type.'_'.$i} =
12164:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
12165:             }
12166:         }
12167:         my ($path,$fname) =
12168:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
12169:         # no path, whole string is fname
12170:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
12171:         $fname = &Apache::lonnet::clean_filename($fname);
12172:         # See if there is anything left
12173:         next if ($fname eq '');
12174: 
12175:         # Check if file already exists as a file or directory.
12176:         my ($state,$msg);
12177:         if ($context eq 'portfolio') {
12178:             my $port_path = $dirpath;
12179:             if ($group ne '') {
12180:                 $port_path = "groups/$group/$port_path";
12181:             }
12182:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
12183:                                               $fname,$group,'embedded_item_'.$i,
12184:                                               $dir_root,$port_path,$disk_quota,
12185:                                               $current_disk_usage,$uname,$udom);
12186:             if ($state eq 'will_exceed_quota'
12187:                 || $state eq 'file_locked') {
12188:                 $output .= $msg;
12189:                 next;
12190:             }
12191:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
12192:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
12193:             if ($state eq 'exists') {
12194:                 $output .= $msg;
12195:                 next;
12196:             }
12197:         }
12198:         # Check if extension is valid
12199:         if (($fname =~ /\.(\w+)$/) &&
12200:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
12201:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
12202:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
12203:             next;
12204:         } elsif (($fname =~ /\.(\w+)$/) &&
12205:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
12206:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
12207:             next;
12208:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
12209:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
12210:             next;
12211:         }
12212:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
12213:         my $subdir = $path;
12214:         $subdir =~ s{/+$}{};
12215:         if ($context eq 'portfolio') {
12216:             my $result;
12217:             if ($state eq 'existingfile') {
12218:                 $result=
12219:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
12220:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
12221:             } else {
12222:                 $result=
12223:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
12224:                                                     $dirpath.
12225:                                                     $env{'form.currentpath'}.$subdir);
12226:                 if ($result !~ m|^/uploaded/|) {
12227:                     $output .= '<span class="LC_error">'
12228:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
12229:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
12230:                                .'</span><br />';
12231:                     next;
12232:                 } else {
12233:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
12234:                                $path.$fname.'</span>').'<br />';     
12235:                 }
12236:             }
12237:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
12238:             my $extendedsubdir = $dirpath.'/'.$subdir;
12239:             $extendedsubdir =~ s{/+$}{};
12240:             my $result =
12241:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
12242:             if ($result !~ m|^/uploaded/|) {
12243:                 $output .= '<span class="LC_error">'
12244:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
12245:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
12246:                            .'</span><br />';
12247:                     next;
12248:             } else {
12249:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
12250:                            $path.$fname.'</span>').'<br />';
12251:                 if ($context eq 'syllabus') {
12252:                     &Apache::lonnet::make_public_indefinitely($result);
12253:                 }
12254:             }
12255:         } else {
12256: # Save the file
12257:             my $target = $env{'form.embedded_item_'.$i};
12258:             my $fullpath = $dir_root.$dirpath.'/'.$path;
12259:             my $dest = $fullpath.$fname;
12260:             my $url = $url_root.$dirpath.'/'.$path.$fname;
12261:             my @parts=split(/\//,"$dirpath/$path");
12262:             my $count;
12263:             my $filepath = $dir_root;
12264:             foreach my $subdir (@parts) {
12265:                 $filepath .= "/$subdir";
12266:                 if (!-e $filepath) {
12267:                     mkdir($filepath,0770);
12268:                 }
12269:             }
12270:             my $fh;
12271:             if (!open($fh,'>'.$dest)) {
12272:                 &Apache::lonnet::logthis('Failed to create '.$dest);
12273:                 $output .= '<span class="LC_error">'.
12274:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
12275:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
12276:                            '</span><br />';
12277:             } else {
12278:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
12279:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
12280:                     $output .= '<span class="LC_error">'.
12281:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
12282:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
12283:                               '</span><br />';
12284:                 } else {
12285:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
12286:                                $url.'</span>').'<br />';
12287:                     unless ($context eq 'testbank') {
12288:                         $footer .= &mt('View embedded file: [_1]',
12289:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
12290:                     }
12291:                 }
12292:                 close($fh);
12293:             }
12294:         }
12295:         if ($env{'form.embedded_ref_'.$i}) {
12296:             $pathchange{$i} = 1;
12297:         }
12298:     }
12299:     if ($output) {
12300:         $output = '<p>'.$output.'</p>';
12301:     }
12302:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
12303:     $returnflag = 'ok';
12304:     my $numpathchgs = scalar(keys(%pathchange));
12305:     if ($numpathchgs > 0) {
12306:         if ($context eq 'portfolio') {
12307:             $output .= '<p>'.&mt('or').'</p>';
12308:         } elsif ($context eq 'testbank') {
12309:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
12310:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
12311:             $returnflag = 'modify_orightml';
12312:         }
12313:     }
12314:     return ($output.$footer,$returnflag,$numpathchgs);
12315: }
12316: 
12317: sub modify_html_form {
12318:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
12319:     my $end = 0;
12320:     my $modifyform;
12321:     if ($context eq 'upload_embedded') {
12322:         return unless (ref($pathchange) eq 'HASH');
12323:         if ($env{'form.number_embedded_items'}) {
12324:             $end += $env{'form.number_embedded_items'};
12325:         }
12326:         if ($env{'form.number_pathchange_items'}) {
12327:             $end += $env{'form.number_pathchange_items'};
12328:         }
12329:         if ($end) {
12330:             for (my $i=0; $i<$end; $i++) {
12331:                 if ($i < $env{'form.number_embedded_items'}) {
12332:                     next unless($pathchange->{$i});
12333:                 }
12334:                 $modifyform .=
12335:                     &start_data_table_row().
12336:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
12337:                     'checked="checked" /></td>'.
12338:                     '<td>'.$env{'form.embedded_ref_'.$i}.
12339:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
12340:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
12341:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
12342:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
12343:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
12344:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
12345:                     '<td>'.$env{'form.embedded_orig_'.$i}.
12346:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
12347:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
12348:                     &end_data_table_row();
12349:             }
12350:         }
12351:     } else {
12352:         $modifyform = $pathchgtable;
12353:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12354:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
12355:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
12356:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
12357:         }
12358:     }
12359:     if ($modifyform) {
12360:         if ($actionurl eq '/adm/dependencies') {
12361:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
12362:         }
12363:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
12364:                '<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".
12365:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
12366:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
12367:                '</ol></p>'."\n".'<p>'.
12368:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
12369:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
12370:                &start_data_table()."\n".
12371:                &start_data_table_header_row().
12372:                '<th>'.&mt('Change?').'</th>'.
12373:                '<th>'.&mt('Current reference').'</th>'.
12374:                '<th>'.&mt('Required reference').'</th>'.
12375:                &end_data_table_header_row()."\n".
12376:                $modifyform.
12377:                &end_data_table().'<br />'."\n".$hiddenstate.
12378:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
12379:                '</form>'."\n";
12380:     }
12381:     return;
12382: }
12383: 
12384: sub modify_html_refs {
12385:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
12386:     my $container;
12387:     if ($context eq 'portfolio') {
12388:         $container = $env{'form.container'};
12389:     } elsif ($context eq 'coursedoc') {
12390:         $container = $env{'form.primaryurl'};
12391:     } elsif ($context eq 'manage_dependencies') {
12392:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
12393:         $container = "/$container";
12394:     } elsif ($context eq 'syllabus') {
12395:         $container = $url;
12396:     } else {
12397:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
12398:     }
12399:     my (%allfiles,%codebase,$output,$content);
12400:     my @changes = &get_env_multiple('form.namechange');
12401:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
12402:         if (wantarray) {
12403:             return ('',0,0); 
12404:         } else {
12405:             return;
12406:         }
12407:     }
12408:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
12409:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
12410:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
12411:             if (wantarray) {
12412:                 return ('',0,0);
12413:             } else {
12414:                 return;
12415:             }
12416:         } 
12417:         $content = &Apache::lonnet::getfile($container);
12418:         if ($content eq '-1') {
12419:             if (wantarray) {
12420:                 return ('',0,0);
12421:             } else {
12422:                 return;
12423:             }
12424:         }
12425:     } else {
12426:         unless ($container =~ /^\Q$dir_root\E/) {
12427:             if (wantarray) {
12428:                 return ('',0,0);
12429:             } else {
12430:                 return;
12431:             }
12432:         } 
12433:         if (open(my $fh,'<',$container)) {
12434:             $content = join('', <$fh>);
12435:             close($fh);
12436:         } else {
12437:             if (wantarray) {
12438:                 return ('',0,0);
12439:             } else {
12440:                 return;
12441:             }
12442:         }
12443:     }
12444:     my ($count,$codebasecount) = (0,0);
12445:     my $mm = new File::MMagic;
12446:     my $mime_type = $mm->checktype_contents($content);
12447:     if ($mime_type eq 'text/html') {
12448:         my $parse_result = 
12449:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
12450:                                                     \%codebase,\$content);
12451:         if ($parse_result eq 'ok') {
12452:             foreach my $i (@changes) {
12453:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
12454:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
12455:                 if ($allfiles{$ref}) {
12456:                     my $newname =  $orig;
12457:                     my ($attrib_regexp,$codebase);
12458:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
12459:                     if ($attrib_regexp =~ /:/) {
12460:                         $attrib_regexp =~ s/\:/|/g;
12461:                     }
12462:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
12463:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
12464:                         $count += $numchg;
12465:                         $allfiles{$newname} = $allfiles{$ref};
12466:                         delete($allfiles{$ref});
12467:                     }
12468:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
12469:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
12470:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
12471:                         $codebasecount ++;
12472:                     }
12473:                 }
12474:             }
12475:             my $skiprewrites;
12476:             if ($count || $codebasecount) {
12477:                 my $saveresult;
12478:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
12479:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
12480:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
12481:                     if ($url eq $container) {
12482:                         my ($fname) = ($container =~ m{/([^/]+)$});
12483:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
12484:                                             $count,'<span class="LC_filename">'.
12485:                                             $fname.'</span>').'</p>';
12486:                     } else {
12487:                          $output = '<p class="LC_error">'.
12488:                                    &mt('Error: update failed for: [_1].',
12489:                                    '<span class="LC_filename">'.
12490:                                    $container.'</span>').'</p>';
12491:                     }
12492:                     if ($context eq 'syllabus') {
12493:                         unless ($saveresult eq 'ok') {
12494:                             $skiprewrites = 1;
12495:                         }
12496:                     }
12497:                 } else {
12498:                     if (open(my $fh,'>',$container)) {
12499:                         print $fh $content;
12500:                         close($fh);
12501:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
12502:                                   $count,'<span class="LC_filename">'.
12503:                                   $container.'</span>').'</p>';
12504:                     } else {
12505:                          $output = '<p class="LC_error">'.
12506:                                    &mt('Error: could not update [_1].',
12507:                                    '<span class="LC_filename">'.
12508:                                    $container.'</span>').'</p>';
12509:                     }
12510:                 }
12511:             }
12512:             if (($context eq 'syllabus') && (!$skiprewrites)) {
12513:                 my ($actionurl,$state);
12514:                 $actionurl = "/public/$udom/$uname/syllabus";
12515:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
12516:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
12517:                                               \%codebase,
12518:                                               {'context' => 'rewrites',
12519:                                                'ignore_remote_references' => 1,});
12520:                 if (ref($mapping) eq 'HASH') {
12521:                     my $rewrites = 0;
12522:                     foreach my $key (keys(%{$mapping})) {
12523:                         next if ($key =~ m{^https?://});
12524:                         my $ref = $mapping->{$key};
12525:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
12526:                         my $attrib;
12527:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
12528:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
12529:                         }
12530:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
12531:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
12532:                             $rewrites += $numchg;
12533:                         }
12534:                     }
12535:                     if ($rewrites) {
12536:                         my $saveresult;
12537:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
12538:                         if ($url eq $container) {
12539:                             my ($fname) = ($container =~ m{/([^/]+)$});
12540:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
12541:                                             $count,'<span class="LC_filename">'.
12542:                                             $fname.'</span>').'</p>';
12543:                         } else {
12544:                             $output .= '<p class="LC_error">'.
12545:                                        &mt('Error: could not update links in [_1].',
12546:                                        '<span class="LC_filename">'.
12547:                                        $container.'</span>').'</p>';
12548: 
12549:                         }
12550:                     }
12551:                 }
12552:             }
12553:         } else {
12554:             &logthis('Failed to parse '.$container.
12555:                      ' to modify references: '.$parse_result);
12556:         }
12557:     }
12558:     if (wantarray) {
12559:         return ($output,$count,$codebasecount);
12560:     } else {
12561:         return $output;
12562:     }
12563: }
12564: 
12565: sub check_for_existing {
12566:     my ($path,$fname,$element) = @_;
12567:     my ($state,$msg);
12568:     if (-d $path.'/'.$fname) {
12569:         $state = 'exists';
12570:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
12571:     } elsif (-e $path.'/'.$fname) {
12572:         $state = 'exists';
12573:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
12574:     }
12575:     if ($state eq 'exists') {
12576:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
12577:     }
12578:     return ($state,$msg);
12579: }
12580: 
12581: sub check_for_upload {
12582:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
12583:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
12584:     my $filesize = length($env{'form.'.$element});
12585:     if (!$filesize) {
12586:         my $msg = '<span class="LC_error">'.
12587:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
12588:                       '<span class="LC_filename">'.$fname.'</span>',
12589:                       $filesize).'<br />'.
12590:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
12591:                   '</span>';
12592:         return ('zero_bytes',$msg);
12593:     }
12594:     $filesize =  $filesize/1000; #express in k (1024?)
12595:     my $getpropath = 1;
12596:     my ($dirlistref,$listerror) =
12597:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
12598:     my $found_file = 0;
12599:     my $locked_file = 0;
12600:     my @lockers;
12601:     my $navmap;
12602:     if ($env{'request.course.id'}) {
12603:         $navmap = Apache::lonnavmaps::navmap->new();
12604:     }
12605:     if (ref($dirlistref) eq 'ARRAY') {
12606:         foreach my $line (@{$dirlistref}) {
12607:             my ($file_name,$rest)=split(/\&/,$line,2);
12608:             if ($file_name eq $fname){
12609:                 $file_name = $path.$file_name;
12610:                 if ($group ne '') {
12611:                     $file_name = $group.$file_name;
12612:                 }
12613:                 $found_file = 1;
12614:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
12615:                     foreach my $lock (@lockers) {
12616:                         if (ref($lock) eq 'ARRAY') {
12617:                             my ($symb,$crsid) = @{$lock};
12618:                             if ($crsid eq $env{'request.course.id'}) {
12619:                                 if (ref($navmap)) {
12620:                                     my $res = $navmap->getBySymb($symb);
12621:                                     foreach my $part (@{$res->parts()}) { 
12622:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
12623:                                         unless (($slot_status == $res->RESERVED) ||
12624:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
12625:                                             $locked_file = 1;
12626:                                         }
12627:                                     }
12628:                                 } else {
12629:                                     $locked_file = 1;
12630:                                 }
12631:                             } else {
12632:                                 $locked_file = 1;
12633:                             }
12634:                         }
12635:                    }
12636:                 } else {
12637:                     my @info = split(/\&/,$rest);
12638:                     my $currsize = $info[6]/1000;
12639:                     if ($currsize < $filesize) {
12640:                         my $extra = $filesize - $currsize;
12641:                         if (($current_disk_usage + $extra) > $disk_quota) {
12642:                             my $msg = '<p class="LC_warning">'.
12643:                                       &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.',
12644:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
12645:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
12646:                                                    $disk_quota,$current_disk_usage).'</p>';
12647:                             return ('will_exceed_quota',$msg);
12648:                         }
12649:                     }
12650:                 }
12651:             }
12652:         }
12653:     }
12654:     if (($current_disk_usage + $filesize) > $disk_quota){
12655:         my $msg = '<p class="LC_warning">'.
12656:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
12657:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
12658:         return ('will_exceed_quota',$msg);
12659:     } elsif ($found_file) {
12660:         if ($locked_file) {
12661:             my $msg = '<p class="LC_warning">';
12662:             $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>');
12663:             $msg .= '</p>';
12664:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
12665:             return ('file_locked',$msg);
12666:         } else {
12667:             my $msg = '<p class="LC_error">';
12668:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
12669:             $msg .= '</p>';
12670:             return ('existingfile',$msg);
12671:         }
12672:     }
12673: }
12674: 
12675: sub check_for_traversal {
12676:     my ($path,$url,$toplevel) = @_;
12677:     my @parts=split(/\//,$path);
12678:     my $cleanpath;
12679:     my $fullpath = $url;
12680:     for (my $i=0;$i<@parts;$i++) {
12681:         next if ($parts[$i] eq '.');
12682:         if ($parts[$i] eq '..') {
12683:             $fullpath =~ s{([^/]+/)$}{};
12684:         } else {
12685:             $fullpath .= $parts[$i].'/';
12686:         }
12687:     }
12688:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
12689:         $cleanpath = $1;
12690:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
12691:         my $curr_toprel = $1;
12692:         my @parts = split(/\//,$curr_toprel);
12693:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
12694:         my @urlparts = split(/\//,$url_toprel);
12695:         my $doubledots;
12696:         my $startdiff = -1;
12697:         for (my $i=0; $i<@urlparts; $i++) {
12698:             if ($startdiff == -1) {
12699:                 unless ($urlparts[$i] eq $parts[$i]) {
12700:                     $startdiff = $i;
12701:                     $doubledots .= '../';
12702:                 }
12703:             } else {
12704:                 $doubledots .= '../';
12705:             }
12706:         }
12707:         if ($startdiff > -1) {
12708:             $cleanpath = $doubledots;
12709:             for (my $i=$startdiff; $i<@parts; $i++) {
12710:                 $cleanpath .= $parts[$i].'/';
12711:             }
12712:         }
12713:     }
12714:     $cleanpath =~ s{(/)$}{};
12715:     return $cleanpath;
12716: }
12717: 
12718: sub is_archive_file {
12719:     my ($mimetype) = @_;
12720:     if (($mimetype eq 'application/octet-stream') ||
12721:         ($mimetype eq 'application/x-stuffit') ||
12722:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
12723:         return 1;
12724:     }
12725:     return;
12726: }
12727: 
12728: sub decompress_form {
12729:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
12730:     my %lt = &Apache::lonlocal::texthash (
12731:         this => 'This file is an archive file.',
12732:         camt => 'This file is a Camtasia archive file.',
12733:         itsc => 'Its contents are as follows:',
12734:         youm => 'You may wish to extract its contents.',
12735:         extr => 'Extract contents',
12736:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
12737:         proa => 'Process automatically?',
12738:         yes  => 'Yes',
12739:         no   => 'No',
12740:         fold => 'Title for folder containing movie',
12741:         movi => 'Title for page containing embedded movie', 
12742:     );
12743:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
12744:     my ($is_camtasia,$topdir,%toplevel,@paths);
12745:     my $info = &list_archive_contents($fileloc,\@paths);
12746:     if (@paths) {
12747:         foreach my $path (@paths) {
12748:             $path =~ s{^/}{};
12749:             if ($path =~ m{^([^/]+)/$}) {
12750:                 $topdir = $1;
12751:             }
12752:             if ($path =~ m{^([^/]+)/}) {
12753:                 $toplevel{$1} = $path;
12754:             } else {
12755:                 $toplevel{$path} = $path;
12756:             }
12757:         }
12758:     }
12759:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
12760:         my @camtasia6 = ("$topdir/","$topdir/index.html",
12761:                         "$topdir/media/",
12762:                         "$topdir/media/$topdir.mp4",
12763:                         "$topdir/media/FirstFrame.png",
12764:                         "$topdir/media/player.swf",
12765:                         "$topdir/media/swfobject.js",
12766:                         "$topdir/media/expressInstall.swf");
12767:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
12768:                          "$topdir/$topdir.mp4",
12769:                          "$topdir/$topdir\_config.xml",
12770:                          "$topdir/$topdir\_controller.swf",
12771:                          "$topdir/$topdir\_embed.css",
12772:                          "$topdir/$topdir\_First_Frame.png",
12773:                          "$topdir/$topdir\_player.html",
12774:                          "$topdir/$topdir\_Thumbnails.png",
12775:                          "$topdir/playerProductInstall.swf",
12776:                          "$topdir/scripts/",
12777:                          "$topdir/scripts/config_xml.js",
12778:                          "$topdir/scripts/handlebars.js",
12779:                          "$topdir/scripts/jquery-1.7.1.min.js",
12780:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
12781:                          "$topdir/scripts/modernizr.js",
12782:                          "$topdir/scripts/player-min.js",
12783:                          "$topdir/scripts/swfobject.js",
12784:                          "$topdir/skins/",
12785:                          "$topdir/skins/configuration_express.xml",
12786:                          "$topdir/skins/express_show/",
12787:                          "$topdir/skins/express_show/player-min.css",
12788:                          "$topdir/skins/express_show/spritesheet.png");
12789:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
12790:                          "$topdir/$topdir.mp4",
12791:                          "$topdir/$topdir\_config.xml",
12792:                          "$topdir/$topdir\_controller.swf",
12793:                          "$topdir/$topdir\_embed.css",
12794:                          "$topdir/$topdir\_First_Frame.png",
12795:                          "$topdir/$topdir\_player.html",
12796:                          "$topdir/$topdir\_Thumbnails.png",
12797:                          "$topdir/playerProductInstall.swf",
12798:                          "$topdir/scripts/",
12799:                          "$topdir/scripts/config_xml.js",
12800:                          "$topdir/scripts/techsmith-smart-player.min.js",
12801:                          "$topdir/skins/",
12802:                          "$topdir/skins/configuration_express.xml",
12803:                          "$topdir/skins/express_show/",
12804:                          "$topdir/skins/express_show/spritesheet.min.css",
12805:                          "$topdir/skins/express_show/spritesheet.png",
12806:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
12807:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
12808:         if (@diffs == 0) {
12809:             $is_camtasia = 6;
12810:         } else {
12811:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
12812:             if (@diffs == 0) {
12813:                 $is_camtasia = 8;
12814:             } else {
12815:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
12816:                 if (@diffs == 0) {
12817:                     $is_camtasia = 8;
12818:                 }
12819:             }
12820:         }
12821:     }
12822:     my $output;
12823:     if ($is_camtasia) {
12824:         $output = <<"ENDCAM";
12825: <script type="text/javascript" language="Javascript">
12826: // <![CDATA[
12827: 
12828: function camtasiaToggle() {
12829:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
12830:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
12831:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
12832:                 document.getElementById('camtasia_titles').style.display='block';
12833:             } else {
12834:                 document.getElementById('camtasia_titles').style.display='none';
12835:             }
12836:         }
12837:     }
12838:     return;
12839: }
12840: 
12841: // ]]>
12842: </script>
12843: <p>$lt{'camt'}</p>
12844: ENDCAM
12845:     } else {
12846:         $output = '<p>'.$lt{'this'};
12847:         if ($info eq '') {
12848:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
12849:         } else {
12850:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
12851:                        '<div><pre>'.$info.'</pre></div>';
12852:         }
12853:     }
12854:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
12855:     my $duplicates;
12856:     my $num = 0;
12857:     if (ref($dirlist) eq 'ARRAY') {
12858:         foreach my $item (@{$dirlist}) {
12859:             if (ref($item) eq 'ARRAY') {
12860:                 if (exists($toplevel{$item->[0]})) {
12861:                     $duplicates .= 
12862:                         &start_data_table_row().
12863:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
12864:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
12865:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
12866:                         'value="1" />'.&mt('Yes').'</label>'.
12867:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
12868:                         '<td>'.$item->[0].'</td>';
12869:                     if ($item->[2]) {
12870:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
12871:                     } else {
12872:                         $duplicates .= '<td>'.&mt('File').'</td>';
12873:                     }
12874:                     $duplicates .= '<td>'.$item->[3].'</td>'.
12875:                                    '<td>'.
12876:                                    &Apache::lonlocal::locallocaltime($item->[4]).
12877:                                    '</td>'.
12878:                                    &end_data_table_row();
12879:                     $num ++;
12880:                 }
12881:             }
12882:         }
12883:     }
12884:     my $itemcount;
12885:     if (@paths > 0) {
12886:         $itemcount = scalar(@paths);
12887:     } else {
12888:         $itemcount = 1;
12889:     }
12890:     if ($is_camtasia) {
12891:         $output .= $lt{'auto'}.'<br />'.
12892:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
12893:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
12894:                    $lt{'yes'}.'</label>&nbsp;<label>'.
12895:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
12896:                    $lt{'no'}.'</label></span><br />'.
12897:                    '<div id="camtasia_titles" style="display:block">'.
12898:                    &Apache::lonhtmlcommon::start_pick_box().
12899:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
12900:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
12901:                    &Apache::lonhtmlcommon::row_closure().
12902:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
12903:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
12904:                    &Apache::lonhtmlcommon::row_closure(1).
12905:                    &Apache::lonhtmlcommon::end_pick_box().
12906:                    '</div>';
12907:     }
12908:     $output .= 
12909:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
12910:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
12911:         "\n";
12912:     if ($duplicates ne '') {
12913:         $output .= '<p><span class="LC_warning">'.
12914:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
12915:                    &start_data_table().
12916:                    &start_data_table_header_row().
12917:                    '<th>'.&mt('Overwrite?').'</th>'.
12918:                    '<th>'.&mt('Name').'</th>'.
12919:                    '<th>'.&mt('Type').'</th>'.
12920:                    '<th>'.&mt('Size').'</th>'.
12921:                    '<th>'.&mt('Last modified').'</th>'.
12922:                    &end_data_table_header_row().
12923:                    $duplicates.
12924:                    &end_data_table().
12925:                    '</p>';
12926:     }
12927:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
12928:     if (ref($hiddenelements) eq 'HASH') {
12929:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
12930:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
12931:         }
12932:     }
12933:     $output .= <<"END";
12934: <br />
12935: <input type="submit" name="decompress" value="$lt{'extr'}" />
12936: </form>
12937: $noextract
12938: END
12939:     return $output;
12940: }
12941: 
12942: sub decompression_utility {
12943:     my ($program) = @_;
12944:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
12945:     my $location;
12946:     if (grep(/^\Q$program\E$/,@utilities)) { 
12947:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
12948:                          '/usr/sbin/') {
12949:             if (-x $dir.$program) {
12950:                 $location = $dir.$program;
12951:                 last;
12952:             }
12953:         }
12954:     }
12955:     return $location;
12956: }
12957: 
12958: sub list_archive_contents {
12959:     my ($file,$pathsref) = @_;
12960:     my (@cmd,$output);
12961:     my $needsregexp;
12962:     if ($file =~ /\.zip$/) {
12963:         @cmd = (&decompression_utility('unzip'),"-l");
12964:         $needsregexp = 1;
12965:     } elsif (($file =~ m/\.tar\.gz$/) ||
12966:              ($file =~ /\.tgz$/)) {
12967:         @cmd = (&decompression_utility('tar'),"-ztf");
12968:     } elsif ($file =~ /\.tar\.bz2$/) {
12969:         @cmd = (&decompression_utility('tar'),"-jtf");
12970:     } elsif ($file =~ m|\.tar$|) {
12971:         @cmd = (&decompression_utility('tar'),"-tf");
12972:     }
12973:     if (@cmd) {
12974:         undef($!);
12975:         undef($@);
12976:         if (open(my $fh,"-|", @cmd, $file)) {
12977:             while (my $line = <$fh>) {
12978:                 $output .= $line;
12979:                 chomp($line);
12980:                 my $item;
12981:                 if ($needsregexp) {
12982:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
12983:                 } else {
12984:                     $item = $line;
12985:                 }
12986:                 if ($item ne '') {
12987:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
12988:                         push(@{$pathsref},$item);
12989:                     } 
12990:                 }
12991:             }
12992:             close($fh);
12993:         }
12994:     }
12995:     return $output;
12996: }
12997: 
12998: sub decompress_uploaded_file {
12999:     my ($file,$dir) = @_;
13000:     &Apache::lonnet::appenv({'cgi.file' => $file});
13001:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
13002:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
13003:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
13004:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
13005:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
13006:     my $decompressed = $env{'cgi.decompressed'};
13007:     &Apache::lonnet::delenv('cgi.file');
13008:     &Apache::lonnet::delenv('cgi.dir');
13009:     &Apache::lonnet::delenv('cgi.decompressed');
13010:     return ($decompressed,$result);
13011: }
13012: 
13013: sub process_decompression {
13014:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
13015:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
13016:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13017:                &mt('Unexpected file path.').'</p>'."\n";
13018:     }
13019:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
13020:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13021:                &mt('Unexpected course context.').'</p>'."\n";
13022:     }
13023:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
13024:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13025:                &mt('Filename contained unexpected characters.').'</p>'."\n";
13026:     }
13027:     my ($dir,$error,$warning,$output);
13028:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
13029:         $error = &mt('Filename not a supported archive file type.').
13030:                  '<br />'.&mt('Filename should end with one of: [_1].',
13031:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
13032:     } else {
13033:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
13034:         if ($docuhome eq 'no_host') {
13035:             $error = &mt('Could not determine home server for course.');
13036:         } else {
13037:             my @ids=&Apache::lonnet::current_machine_ids();
13038:             my $currdir = "$dir_root/$destination";
13039:             if (grep(/^\Q$docuhome\E$/,@ids)) {
13040:                 $dir = &LONCAPA::propath($docudom,$docuname).
13041:                        "$dir_root/$destination";
13042:             } else {
13043:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
13044:                        "$dir_root/$docudom/$docuname/$destination";
13045:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
13046:                     $error = &mt('Archive file not found.');
13047:                 }
13048:             }
13049:             my (@to_overwrite,@to_skip);
13050:             if ($env{'form.archive_overwrite_total'} > 0) {
13051:                 my $total = $env{'form.archive_overwrite_total'};
13052:                 for (my $i=0; $i<$total; $i++) {
13053:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
13054:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
13055:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
13056:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
13057:                     }
13058:                 }
13059:             }
13060:             my $numskip = scalar(@to_skip);
13061:             my $numoverwrite = scalar(@to_overwrite);
13062:             if (($numskip) && (!$numoverwrite)) {
13063:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
13064:             } elsif ($dir eq '') {
13065:                 $error = &mt('Directory containing archive file unavailable.');
13066:             } elsif (!$error) {
13067:                 my ($decompressed,$display);
13068:                 if (($numskip) || ($numoverwrite)) {
13069:                     my $tempdir = time.'_'.$$.int(rand(10000));
13070:                     mkdir("$dir/$tempdir",0755);
13071:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
13072:                         ($decompressed,$display) =
13073:                             &decompress_uploaded_file($file,"$dir/$tempdir");
13074:                         foreach my $item (@to_skip) {
13075:                             if (($item ne '') && ($item !~ /\.\./)) {
13076:                                 if (-f "$dir/$tempdir/$item") {
13077:                                     unlink("$dir/$tempdir/$item");
13078:                                 } elsif (-d "$dir/$tempdir/$item") {
13079:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
13080:                                 }
13081:                             }
13082:                         }
13083:                         foreach my $item (@to_overwrite) {
13084:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
13085:                                 if (($item ne '') && ($item !~ /\.\./)) {
13086:                                     if (-f "$dir/$item") {
13087:                                         unlink("$dir/$item");
13088:                                     } elsif (-d "$dir/$item") {
13089:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
13090:                                     }
13091:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
13092:                                 }
13093:                             }
13094:                         }
13095:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
13096:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
13097:                         }
13098:                     }
13099:                 } else {
13100:                     ($decompressed,$display) = 
13101:                         &decompress_uploaded_file($file,$dir);
13102:                 }
13103:                 if ($decompressed eq 'ok') {
13104:                     $output = '<p class="LC_info">'.
13105:                               &mt('Files extracted successfully from archive.').
13106:                               '</p>'."\n";
13107:                     my ($warning,$result,@contents);
13108:                     my ($newdirlistref,$newlisterror) =
13109:                         &Apache::lonnet::dirlist($currdir,$docudom,
13110:                                                  $docuname,1);
13111:                     my (%is_dir,%changes,@newitems);
13112:                     my $dirptr = 16384;
13113:                     if (ref($newdirlistref) eq 'ARRAY') {
13114:                         foreach my $dir_line (@{$newdirlistref}) {
13115:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
13116:                             unless (($item =~ /^\.+$/) || ($item eq $file)) { 
13117:                                 push(@newitems,$item);
13118:                                 if ($dirptr&$testdir) {
13119:                                     $is_dir{$item} = 1;
13120:                                 }
13121:                                 $changes{$item} = 1;
13122:                             }
13123:                         }
13124:                     }
13125:                     if (keys(%changes) > 0) {
13126:                         foreach my $item (sort(@newitems)) {
13127:                             if ($changes{$item}) {
13128:                                 push(@contents,$item);
13129:                             }
13130:                         }
13131:                     }
13132:                     if (@contents > 0) {
13133:                         my $wantform;
13134:                         unless ($env{'form.autoextract_camtasia'}) {
13135:                             $wantform = 1;
13136:                         }
13137:                         my (%children,%parent,%dirorder,%titles);
13138:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
13139:                                                                 $currdir,\%is_dir,
13140:                                                                 \%children,\%parent,
13141:                                                                 \@contents,\%dirorder,
13142:                                                                 \%titles,$wantform);
13143:                         if ($datatable ne '') {
13144:                             $output .= &archive_options_form('decompressed',$datatable,
13145:                                                              $count,$hiddenelem);
13146:                             my $startcount = 6;
13147:                             $output .= &archive_javascript($startcount,$count,
13148:                                                            \%titles,\%children);
13149:                         }
13150:                         if ($env{'form.autoextract_camtasia'}) {
13151:                             my $version = $env{'form.autoextract_camtasia'};
13152:                             my %displayed;
13153:                             my $total = 1;
13154:                             $env{'form.archive_directory'} = [];
13155:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
13156:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
13157:                                 $path =~ s{/$}{};
13158:                                 my $item;
13159:                                 if ($path ne '') {
13160:                                     $item = "$path/$titles{$i}";
13161:                                 } else {
13162:                                     $item = $titles{$i};
13163:                                 }
13164:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
13165:                                 if ($item eq $contents[0]) {
13166:                                     push(@{$env{'form.archive_directory'}},$i);
13167:                                     $env{'form.archive_'.$i} = 'display';
13168:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
13169:                                     $displayed{'folder'} = $i;
13170:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
13171:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
13172:                                     $env{'form.archive_'.$i} = 'display';
13173:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
13174:                                     $displayed{'web'} = $i;
13175:                                 } else {
13176:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
13177:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
13178:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
13179:                                         push(@{$env{'form.archive_directory'}},$i);
13180:                                     }
13181:                                     $env{'form.archive_'.$i} = 'dependency';
13182:                                 }
13183:                                 $total ++;
13184:                             }
13185:                             for (my $i=1; $i<$total; $i++) {
13186:                                 next if ($i == $displayed{'web'});
13187:                                 next if ($i == $displayed{'folder'});
13188:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
13189:                             }
13190:                             $env{'form.phase'} = 'decompress_cleanup';
13191:                             $env{'form.archivedelete'} = 1;
13192:                             $env{'form.archive_count'} = $total-1;
13193:                             $output .=
13194:                                 &process_extracted_files('coursedocs',$docudom,
13195:                                                          $docuname,$destination,
13196:                                                          $dir_root,$hiddenelem);
13197:                         }
13198:                     } else {
13199:                         $warning = &mt('No new items extracted from archive file.');
13200:                     }
13201:                 } else {
13202:                     $output = $display;
13203:                     $error = &mt('An error occurred during extraction from the archive file.');
13204:                 }
13205:             }
13206:         }
13207:     }
13208:     if ($error) {
13209:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13210:                    $error.'</p>'."\n";
13211:     }
13212:     if ($warning) {
13213:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
13214:     }
13215:     return $output;
13216: }
13217: 
13218: sub get_extracted {
13219:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
13220:         $titles,$wantform) = @_;
13221:     my $count = 0;
13222:     my $depth = 0;
13223:     my $datatable;
13224:     my @hierarchy;
13225:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
13226:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
13227:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
13228:     foreach my $item (@{$contents}) {
13229:         $count ++;
13230:         @{$dirorder->{$count}} = @hierarchy;
13231:         $titles->{$count} = $item;
13232:         &archive_hierarchy($depth,$count,$parent,$children);
13233:         if ($wantform) {
13234:             $datatable .= &archive_row($is_dir->{$item},$item,
13235:                                        $currdir,$depth,$count);
13236:         }
13237:         if ($is_dir->{$item}) {
13238:             $depth ++;
13239:             push(@hierarchy,$count);
13240:             $parent->{$depth} = $count;
13241:             $datatable .=
13242:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
13243:                                            \$depth,\$count,\@hierarchy,$dirorder,
13244:                                            $children,$parent,$titles,$wantform);
13245:             $depth --;
13246:             pop(@hierarchy);
13247:         }
13248:     }
13249:     return ($count,$datatable);
13250: }
13251: 
13252: sub recurse_extracted_archive {
13253:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
13254:         $children,$parent,$titles,$wantform) = @_;
13255:     my $result='';
13256:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
13257:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
13258:             (ref($dirorder) eq 'HASH')) {
13259:         return $result;
13260:     }
13261:     my $dirptr = 16384;
13262:     my ($newdirlistref,$newlisterror) =
13263:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
13264:     if (ref($newdirlistref) eq 'ARRAY') {
13265:         foreach my $dir_line (@{$newdirlistref}) {
13266:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
13267:             unless ($item =~ /^\.+$/) {
13268:                 $$count ++;
13269:                 @{$dirorder->{$$count}} = @{$hierarchy};
13270:                 $titles->{$$count} = $item;
13271:                 &archive_hierarchy($$depth,$$count,$parent,$children);
13272: 
13273:                 my $is_dir;
13274:                 if ($dirptr&$testdir) {
13275:                     $is_dir = 1;
13276:                 }
13277:                 if ($wantform) {
13278:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
13279:                 }
13280:                 if ($is_dir) {
13281:                     $$depth ++;
13282:                     push(@{$hierarchy},$$count);
13283:                     $parent->{$$depth} = $$count;
13284:                     $result .=
13285:                         &recurse_extracted_archive("$currdir/$item",$docudom,
13286:                                                    $docuname,$depth,$count,
13287:                                                    $hierarchy,$dirorder,$children,
13288:                                                    $parent,$titles,$wantform);
13289:                     $$depth --;
13290:                     pop(@{$hierarchy});
13291:                 }
13292:             }
13293:         }
13294:     }
13295:     return $result;
13296: }
13297: 
13298: sub archive_hierarchy {
13299:     my ($depth,$count,$parent,$children) =@_;
13300:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
13301:         if (exists($parent->{$depth})) {
13302:              $children->{$parent->{$depth}} .= $count.':';
13303:         }
13304:     }
13305:     return;
13306: }
13307: 
13308: sub archive_row {
13309:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
13310:     my ($name) = ($item =~ m{([^/]+)$});
13311:     my %choices = &Apache::lonlocal::texthash (
13312:                                        'display'    => 'Add as file',
13313:                                        'dependency' => 'Include as dependency',
13314:                                        'discard'    => 'Discard',
13315:                                       );
13316:     if ($is_dir) {
13317:         $choices{'display'} = &mt('Add as folder'); 
13318:     }
13319:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
13320:     my $offset = 0;
13321:     foreach my $action ('display','dependency','discard') {
13322:         $offset ++;
13323:         if ($action ne 'display') {
13324:             $offset ++;
13325:         }  
13326:         $output .= '<td><span class="LC_nobreak">'.
13327:                    '<label><input type="radio" name="archive_'.$count.
13328:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
13329:         my $text = $choices{$action};
13330:         if ($is_dir) {
13331:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
13332:             if ($action eq 'display') {
13333:                 $text = &mt('Add as folder');
13334:             }
13335:         } else {
13336:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
13337: 
13338:         }
13339:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
13340:         if ($action eq 'dependency') {
13341:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
13342:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
13343:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
13344:                        '<option value=""></option>'."\n".
13345:                        '</select>'."\n".
13346:                        '</div>';
13347:         } elsif ($action eq 'display') {
13348:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
13349:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
13350:                        '</div>';
13351:         }
13352:         $output .= '</td>';
13353:     }
13354:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
13355:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
13356:     for (my $i=0; $i<$depth; $i++) {
13357:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
13358:     }
13359:     if ($is_dir) {
13360:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
13361:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
13362:     } else {
13363:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
13364:     }
13365:     $output .= '&nbsp;'.$name.'</td>'."\n".
13366:                &end_data_table_row();
13367:     return $output;
13368: }
13369: 
13370: sub archive_options_form {
13371:     my ($form,$display,$count,$hiddenelem) = @_;
13372:     my %lt = &Apache::lonlocal::texthash(
13373:                perm => 'Permanently remove archive file?',
13374:                hows => 'How should each extracted item be incorporated in the course?',
13375:                cont => 'Content actions for all',
13376:                addf => 'Add as folder/file',
13377:                incd => 'Include as dependency for a displayed file',
13378:                disc => 'Discard',
13379:                no   => 'No',
13380:                yes  => 'Yes',
13381:                save => 'Save',
13382:     );
13383:     my $output = <<"END";
13384: <form name="$form" method="post" action="">
13385: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
13386: <label>
13387:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
13388: </label>
13389: &nbsp;
13390: <label>
13391:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
13392: </span>
13393: </p>
13394: <input type="hidden" name="phase" value="decompress_cleanup" />
13395: <br />$lt{'hows'}
13396: <div class="LC_columnSection">
13397:   <fieldset>
13398:     <legend>$lt{'cont'}</legend>
13399:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
13400:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
13401:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
13402:   </fieldset>
13403: </div>
13404: END
13405:     return $output.
13406:            &start_data_table()."\n".
13407:            $display."\n".
13408:            &end_data_table()."\n".
13409:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
13410:            $hiddenelem.
13411:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
13412:            '</form>';
13413: }
13414: 
13415: sub archive_javascript {
13416:     my ($startcount,$numitems,$titles,$children) = @_;
13417:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
13418:     my $maintitle = $env{'form.comment'};
13419:     my $scripttag = <<START;
13420: <script type="text/javascript">
13421: // <![CDATA[
13422: 
13423: function checkAll(form,prefix) {
13424:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
13425:     for (var i=0; i < form.elements.length; i++) {
13426:         var id = form.elements[i].id;
13427:         if ((id != '') && (id != undefined)) {
13428:             if (idstr.test(id)) {
13429:                 if (form.elements[i].type == 'radio') {
13430:                     form.elements[i].checked = true;
13431:                     var nostart = i-$startcount;
13432:                     var offset = nostart%7;
13433:                     var count = (nostart-offset)/7;    
13434:                     dependencyCheck(form,count,offset);
13435:                 }
13436:             }
13437:         }
13438:     }
13439: }
13440: 
13441: function propagateCheck(form,count) {
13442:     if (count > 0) {
13443:         var startelement = $startcount + ((count-1) * 7);
13444:         for (var j=1; j<6; j++) {
13445:             if ((j != 2) && (j != 4)) {
13446:                 var item = startelement + j; 
13447:                 if (form.elements[item].type == 'radio') {
13448:                     if (form.elements[item].checked) {
13449:                         containerCheck(form,count,j);
13450:                         break;
13451:                     }
13452:                 }
13453:             }
13454:         }
13455:     }
13456: }
13457: 
13458: numitems = $numitems
13459: var titles = new Array(numitems);
13460: var parents = new Array(numitems);
13461: for (var i=0; i<numitems; i++) {
13462:     parents[i] = new Array;
13463: }
13464: var maintitle = '$maintitle';
13465: 
13466: START
13467: 
13468:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
13469:         my @contents = split(/:/,$children->{$container});
13470:         for (my $i=0; $i<@contents; $i ++) {
13471:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
13472:         }
13473:     }
13474: 
13475:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
13476:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
13477:     }
13478: 
13479:     $scripttag .= <<END;
13480: 
13481: function containerCheck(form,count,offset) {
13482:     if (count > 0) {
13483:         dependencyCheck(form,count,offset);
13484:         var item = (offset+$startcount)+7*(count-1);
13485:         form.elements[item].checked = true;
13486:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
13487:             if (parents[count].length > 0) {
13488:                 for (var j=0; j<parents[count].length; j++) {
13489:                     containerCheck(form,parents[count][j],offset);
13490:                 }
13491:             }
13492:         }
13493:     }
13494: }
13495: 
13496: function dependencyCheck(form,count,offset) {
13497:     if (count > 0) {
13498:         var chosen = (offset+$startcount)+7*(count-1);
13499:         var depitem = $startcount + ((count-1) * 7) + 4;
13500:         var currtype = form.elements[depitem].type;
13501:         if (form.elements[chosen].value == 'dependency') {
13502:             document.getElementById('arc_depon_'+count).style.display='block'; 
13503:             form.elements[depitem].options.length = 0;
13504:             form.elements[depitem].options[0] = new Option('Select','',true,true);
13505:             for (var i=1; i<=numitems; i++) {
13506:                 if (i == count) {
13507:                     continue;
13508:                 }
13509:                 var startelement = $startcount + (i-1) * 7;
13510:                 for (var j=1; j<6; j++) {
13511:                     if ((j != 2) && (j!= 4)) {
13512:                         var item = startelement + j;
13513:                         if (form.elements[item].type == 'radio') {
13514:                             if (form.elements[item].checked) {
13515:                                 if (form.elements[item].value == 'display') {
13516:                                     var n = form.elements[depitem].options.length;
13517:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
13518:                                 }
13519:                             }
13520:                         }
13521:                     }
13522:                 }
13523:             }
13524:         } else {
13525:             document.getElementById('arc_depon_'+count).style.display='none';
13526:             form.elements[depitem].options.length = 0;
13527:             form.elements[depitem].options[0] = new Option('Select','',true,true);
13528:         }
13529:         titleCheck(form,count,offset);
13530:     }
13531: }
13532: 
13533: function propagateSelect(form,count,offset) {
13534:     if (count > 0) {
13535:         var item = (1+offset+$startcount)+7*(count-1);
13536:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
13537:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
13538:             if (parents[count].length > 0) {
13539:                 for (var j=0; j<parents[count].length; j++) {
13540:                     containerSelect(form,parents[count][j],offset,picked);
13541:                 }
13542:             }
13543:         }
13544:     }
13545: }
13546: 
13547: function containerSelect(form,count,offset,picked) {
13548:     if (count > 0) {
13549:         var item = (offset+$startcount)+7*(count-1);
13550:         if (form.elements[item].type == 'radio') {
13551:             if (form.elements[item].value == 'dependency') {
13552:                 if (form.elements[item+1].type == 'select-one') {
13553:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
13554:                         if (form.elements[item+1].options[i].value == picked) {
13555:                             form.elements[item+1].selectedIndex = i;
13556:                             break;
13557:                         }
13558:                     }
13559:                 }
13560:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
13561:                     if (parents[count].length > 0) {
13562:                         for (var j=0; j<parents[count].length; j++) {
13563:                             containerSelect(form,parents[count][j],offset,picked);
13564:                         }
13565:                     }
13566:                 }
13567:             }
13568:         }
13569:     }
13570: }
13571: 
13572: function titleCheck(form,count,offset) {
13573:     if (count > 0) {
13574:         var chosen = (offset+$startcount)+7*(count-1);
13575:         var depitem = $startcount + ((count-1) * 7) + 2;
13576:         var currtype = form.elements[depitem].type;
13577:         if (form.elements[chosen].value == 'display') {
13578:             document.getElementById('arc_title_'+count).style.display='block';
13579:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
13580:                 document.getElementById('archive_title_'+count).value=maintitle;
13581:             }
13582:         } else {
13583:             document.getElementById('arc_title_'+count).style.display='none';
13584:             if (currtype == 'text') { 
13585:                 document.getElementById('archive_title_'+count).value='';
13586:             }
13587:         }
13588:     }
13589:     return;
13590: }
13591: 
13592: // ]]>
13593: </script>
13594: END
13595:     return $scripttag;
13596: }
13597: 
13598: sub process_extracted_files {
13599:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
13600:     my $numitems = $env{'form.archive_count'};
13601:     return if ((!$numitems) || ($numitems =~ /\D/));
13602:     my @ids=&Apache::lonnet::current_machine_ids();
13603:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
13604:         %folders,%containers,%mapinner,%prompttofetch);
13605:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
13606:     if (grep(/^\Q$docuhome\E$/,@ids)) {
13607:         $prefix = &LONCAPA::propath($docudom,$docuname);
13608:         $pathtocheck = "$dir_root/$destination";
13609:         $dir = $dir_root;
13610:         $ishome = 1;
13611:     } else {
13612:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
13613:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
13614:         $dir = "$dir_root/$docudom/$docuname";
13615:     }
13616:     my $currdir = "$dir_root/$destination";
13617:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
13618:     if ($env{'form.folderpath'}) {
13619:         my @items = split('&',$env{'form.folderpath'});
13620:         $folders{'0'} = $items[-2];
13621:         if ($env{'form.folderpath'} =~ /\:1$/) {
13622:             $containers{'0'}='page';
13623:         } else {
13624:             $containers{'0'}='sequence';
13625:         }
13626:     }
13627:     my @archdirs = &get_env_multiple('form.archive_directory');
13628:     if ($numitems) {
13629:         for (my $i=1; $i<=$numitems; $i++) {
13630:             my $path = $env{'form.archive_content_'.$i};
13631:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
13632:                 my $item = $1;
13633:                 $toplevelitems{$item} = $i;
13634:                 if (grep(/^\Q$i\E$/,@archdirs)) {
13635:                     $is_dir{$item} = 1;
13636:                 }
13637:             }
13638:         }
13639:     }
13640:     my ($output,%children,%parent,%titles,%dirorder,$result);
13641:     if (keys(%toplevelitems) > 0) {
13642:         my @contents = sort(keys(%toplevelitems));
13643:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
13644:                                            \%parent,\@contents,\%dirorder,\%titles);
13645:     }
13646:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
13647:     if ($numitems) {
13648:         for (my $i=1; $i<=$numitems; $i++) {
13649:             next if ($env{'form.archive_'.$i} eq 'dependency');
13650:             my $path = $env{'form.archive_content_'.$i};
13651:             if ($path =~ /^\Q$pathtocheck\E/) {
13652:                 if ($env{'form.archive_'.$i} eq 'discard') {
13653:                     if ($prefix ne '' && $path ne '') {
13654:                         if (-e $prefix.$path) {
13655:                             if ((@archdirs > 0) && 
13656:                                 (grep(/^\Q$i\E$/,@archdirs))) {
13657:                                 $todeletedir{$prefix.$path} = 1;
13658:                             } else {
13659:                                 $todelete{$prefix.$path} = 1;
13660:                             }
13661:                         }
13662:                     }
13663:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
13664:                     my ($docstitle,$title,$url,$outer);
13665:                     ($title) = ($path =~ m{/([^/]+)$});
13666:                     $docstitle = $env{'form.archive_title_'.$i};
13667:                     if ($docstitle eq '') {
13668:                         $docstitle = $title;
13669:                     }
13670:                     $outer = 0;
13671:                     if (ref($dirorder{$i}) eq 'ARRAY') {
13672:                         if (@{$dirorder{$i}} > 0) {
13673:                             foreach my $item (reverse(@{$dirorder{$i}})) {
13674:                                 if ($env{'form.archive_'.$item} eq 'display') {
13675:                                     $outer = $item;
13676:                                     last;
13677:                                 }
13678:                             }
13679:                         }
13680:                     }
13681:                     my ($errtext,$fatal) = 
13682:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
13683:                                                '/'.$folders{$outer}.'.'.
13684:                                                $containers{$outer});
13685:                     next if ($fatal);
13686:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
13687:                         if ($context eq 'coursedocs') {
13688:                             $mapinner{$i} = time;
13689:                             $folders{$i} = 'default_'.$mapinner{$i};
13690:                             $containers{$i} = 'sequence';
13691:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
13692:                                       $folders{$i}.'.'.$containers{$i};
13693:                             my $newidx = &LONCAPA::map::getresidx();
13694:                             $LONCAPA::map::resources[$newidx]=
13695:                                 $docstitle.':'.$url.':false:normal:res';
13696:                             push(@LONCAPA::map::order,$newidx);
13697:                             my ($outtext,$errtext) =
13698:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
13699:                                                         $docuname.'/'.$folders{$outer}.
13700:                                                         '.'.$containers{$outer},1,1);
13701:                             $newseqid{$i} = $newidx;
13702:                             unless ($errtext) {
13703:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
13704:                                                        &HTML::Entities::encode($docstitle,'<>&"'))..
13705:                                             '</li>'."\n";
13706:                             }
13707:                         }
13708:                     } else {
13709:                         if ($context eq 'coursedocs') {
13710:                             my $newidx=&LONCAPA::map::getresidx();
13711:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
13712:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
13713:                                       $title;
13714:                             if (($outer !~ /\D/) &&
13715:                                 (($mapinner{$outer} eq 'default') || ($mapinner{$outer} !~ /\D/)) &&
13716:                                 ($newidx !~ /\D/)) {
13717:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
13718:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
13719:                                 }
13720:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
13721:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
13722:                                 }
13723:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
13724:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
13725:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
13726:                                         unless ($ishome) {
13727:                                             my $fetch = "$newdest{$i}/$title";
13728:                                             $fetch =~ s/^\Q$prefix$dir\E//;
13729:                                             $prompttofetch{$fetch} = 1;
13730:                                         }
13731:                                    }
13732:                                 }
13733:                                 $LONCAPA::map::resources[$newidx]=
13734:                                     $docstitle.':'.$url.':false:normal:res';
13735:                                 push(@LONCAPA::map::order, $newidx);
13736:                                 my ($outtext,$errtext)=
13737:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
13738:                                                             $docuname.'/'.$folders{$outer}.
13739:                                                             '.'.$containers{$outer},1,1);
13740:                                 unless ($errtext) {
13741:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
13742:                                         $result .= '<li>'.&mt('File: [_1] added to course',
13743:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
13744:                                                    '</li>'."\n";
13745:                                     }
13746:                                 }
13747:                             } else {
13748:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13749:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
13750:                             }
13751:                         }
13752:                     }
13753:                 }
13754:             } else {
13755:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13756:                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
13757:             }
13758:         }
13759:         for (my $i=1; $i<=$numitems; $i++) {
13760:             next unless ($env{'form.archive_'.$i} eq 'dependency');
13761:             my $path = $env{'form.archive_content_'.$i};
13762:             if ($path =~ /^\Q$pathtocheck\E/) {
13763:                 my ($title) = ($path =~ m{/([^/]+)$});
13764:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
13765:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
13766:                     if (ref($dirorder{$i}) eq 'ARRAY') {
13767:                         my ($itemidx,$fullpath,$relpath);
13768:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
13769:                             my $container = $dirorder{$referrer{$i}}->[-1];
13770:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
13771:                                 if ($dirorder{$i}->[$j] eq $container) {
13772:                                     $itemidx = $j;
13773:                                 }
13774:                             }
13775:                         }
13776:                         if ($itemidx eq '') {
13777:                             $itemidx =  0;
13778:                         }
13779:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
13780:                             if ($mapinner{$referrer{$i}}) {
13781:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
13782:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
13783:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
13784:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
13785:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
13786:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
13787:                                             if (!-e $fullpath) {
13788:                                                 mkdir($fullpath,0755);
13789:                                             }
13790:                                         }
13791:                                     } else {
13792:                                         last;
13793:                                     }
13794:                                 }
13795:                             }
13796:                         } elsif ($newdest{$referrer{$i}}) {
13797:                             $fullpath = $newdest{$referrer{$i}};
13798:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
13799:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
13800:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
13801:                                     last;
13802:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
13803:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
13804:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
13805:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
13806:                                         if (!-e $fullpath) {
13807:                                             mkdir($fullpath,0755);
13808:                                         }
13809:                                     }
13810:                                 } else {
13811:                                     last;
13812:                                 }
13813:                             }
13814:                         }
13815:                         if ($fullpath ne '') {
13816:                             if (-e "$prefix$path") {
13817:                                 unless (rename("$prefix$path","$fullpath/$title")) {
13818:                                      $warning .= &mt('Failed to rename dependency').'<br />';
13819:                                 }
13820:                             }
13821:                             if (-e "$fullpath/$title") {
13822:                                 my $showpath;
13823:                                 if ($relpath ne '') {
13824:                                     $showpath = "$relpath/$title";
13825:                                 } else {
13826:                                     $showpath = "/$title";
13827:                                 }
13828:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
13829:                                                       &HTML::Entities::encode($showpath,'<>&"')).
13830:                                            '</li>'."\n";
13831:                                 unless ($ishome) {
13832:                                     my $fetch = "$fullpath/$title";
13833:                                     $fetch =~ s/^\Q$prefix$dir\E//;
13834:                                     $prompttofetch{$fetch} = 1;
13835:                                 }
13836:                             }
13837:                         }
13838:                     }
13839:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
13840:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
13841:                                     &HTML::Entities::encode($path,'<>&"'),
13842:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
13843:                                 '<br />';
13844:                 }
13845:             } else {
13846:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13847:                                 &HTML::Entities::encode($path)).'<br />';
13848:             }
13849:         }
13850:         if (keys(%todelete)) {
13851:             foreach my $key (keys(%todelete)) {
13852:                 unlink($key);
13853:             }
13854:         }
13855:         if (keys(%todeletedir)) {
13856:             foreach my $key (keys(%todeletedir)) {
13857:                 rmdir($key);
13858:             }
13859:         }
13860:         foreach my $dir (sort(keys(%is_dir))) {
13861:             if (($pathtocheck ne '') && ($dir ne ''))  {
13862:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
13863:             }
13864:         }
13865:         if ($result ne '') {
13866:             $output .= '<ul>'."\n".
13867:                        $result."\n".
13868:                        '</ul>';
13869:         }
13870:         unless ($ishome) {
13871:             my $replicationfail;
13872:             foreach my $item (keys(%prompttofetch)) {
13873:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
13874:                 unless ($fetchresult eq 'ok') {
13875:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
13876:                 }
13877:             }
13878:             if ($replicationfail) {
13879:                 $output .= '<p class="LC_error">'.
13880:                            &mt('Course home server failed to retrieve:').'<ul>'.
13881:                            $replicationfail.
13882:                            '</ul></p>';
13883:             }
13884:         }
13885:     } else {
13886:         $warning = &mt('No items found in archive.');
13887:     }
13888:     if ($error) {
13889:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13890:                    $error.'</p>'."\n";
13891:     }
13892:     if ($warning) {
13893:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
13894:     }
13895:     return $output;
13896: }
13897: 
13898: sub cleanup_empty_dirs {
13899:     my ($path) = @_;
13900:     if (($path ne '') && (-d $path)) {
13901:         if (opendir(my $dirh,$path)) {
13902:             my @dircontents = grep(!/^\./,readdir($dirh));
13903:             my $numitems = 0;
13904:             foreach my $item (@dircontents) {
13905:                 if (-d "$path/$item") {
13906:                     &cleanup_empty_dirs("$path/$item");
13907:                     if (-e "$path/$item") {
13908:                         $numitems ++;
13909:                     }
13910:                 } else {
13911:                     $numitems ++;
13912:                 }
13913:             }
13914:             if ($numitems == 0) {
13915:                 rmdir($path);
13916:             }
13917:             closedir($dirh);
13918:         }
13919:     }
13920:     return;
13921: }
13922: 
13923: =pod
13924: 
13925: =item * &get_folder_hierarchy()
13926: 
13927: Provides hierarchy of names of folders/sub-folders containing the current
13928: item,
13929: 
13930: Inputs: 3
13931:      - $navmap - navmaps object
13932: 
13933:      - $map - url for map (either the trigger itself, or map containing
13934:                            the resource, which is the trigger).
13935: 
13936:      - $showitem - 1 => show title for map itself; 0 => do not show.
13937: 
13938: Outputs: 1 @pathitems - array of folder/subfolder names.
13939: 
13940: =cut
13941: 
13942: sub get_folder_hierarchy {
13943:     my ($navmap,$map,$showitem) = @_;
13944:     my @pathitems;
13945:     if (ref($navmap)) {
13946:         my $mapres = $navmap->getResourceByUrl($map);
13947:         if (ref($mapres)) {
13948:             my $pcslist = $mapres->map_hierarchy();
13949:             if ($pcslist ne '') {
13950:                 my @pcs = split(/,/,$pcslist);
13951:                 foreach my $pc (@pcs) {
13952:                     if ($pc == 1) {
13953:                         push(@pathitems,&mt('Main Content'));
13954:                     } else {
13955:                         my $res = $navmap->getByMapPc($pc);
13956:                         if (ref($res)) {
13957:                             my $title = $res->compTitle();
13958:                             $title =~ s/\W+/_/g;
13959:                             if ($title ne '') {
13960:                                 push(@pathitems,$title);
13961:                             }
13962:                         }
13963:                     }
13964:                 }
13965:             }
13966:             if ($showitem) {
13967:                 if ($mapres->{ID} eq '0.0') {
13968:                     push(@pathitems,&mt('Main Content'));
13969:                 } else {
13970:                     my $maptitle = $mapres->compTitle();
13971:                     $maptitle =~ s/\W+/_/g;
13972:                     if ($maptitle ne '') {
13973:                         push(@pathitems,$maptitle);
13974:                     }
13975:                 }
13976:             }
13977:         }
13978:     }
13979:     return @pathitems;
13980: }
13981: 
13982: =pod
13983: 
13984: =item * &get_turnedin_filepath()
13985: 
13986: Determines path in a user's portfolio file for storage of files uploaded
13987: to a specific essayresponse or dropbox item.
13988: 
13989: Inputs: 3 required + 1 optional.
13990: $symb is symb for resource, $uname and $udom are for current user (required).
13991: $caller is optional (can be "submission", if routine is called when storing
13992: an upoaded file when "Submit Answer" button was pressed).
13993: 
13994: Returns array containing $path and $multiresp. 
13995: $path is path in portfolio.  $multiresp is 1 if this resource contains more
13996: than one file upload item.  Callers of routine should append partid as a 
13997: subdirectory to $path in cases where $multiresp is 1.
13998: 
13999: Called by: homework/essayresponse.pm and homework/structuretags.pm
14000: 
14001: =cut
14002: 
14003: sub get_turnedin_filepath {
14004:     my ($symb,$uname,$udom,$caller) = @_;
14005:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
14006:     my $turnindir;
14007:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
14008:     $turnindir = $userhash{'turnindir'};
14009:     my ($path,$multiresp);
14010:     if ($turnindir eq '') {
14011:         if ($caller eq 'submission') {
14012:             $turnindir = &mt('turned in');
14013:             $turnindir =~ s/\W+/_/g;
14014:             my %newhash = (
14015:                             'turnindir' => $turnindir,
14016:                           );
14017:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
14018:         }
14019:     }
14020:     if ($turnindir ne '') {
14021:         $path = '/'.$turnindir.'/';
14022:         my ($multipart,$turnin,@pathitems);
14023:         my $navmap = Apache::lonnavmaps::navmap->new();
14024:         if (defined($navmap)) {
14025:             my $mapres = $navmap->getResourceByUrl($map);
14026:             if (ref($mapres)) {
14027:                 my $pcslist = $mapres->map_hierarchy();
14028:                 if ($pcslist ne '') {
14029:                     foreach my $pc (split(/,/,$pcslist)) {
14030:                         my $res = $navmap->getByMapPc($pc);
14031:                         if (ref($res)) {
14032:                             my $title = $res->compTitle();
14033:                             $title =~ s/\W+/_/g;
14034:                             if ($title ne '') {
14035:                                 if (($pc > 1) && (length($title) > 12)) {
14036:                                     $title = substr($title,0,12);
14037:                                 }
14038:                                 push(@pathitems,$title);
14039:                             }
14040:                         }
14041:                     }
14042:                 }
14043:                 my $maptitle = $mapres->compTitle();
14044:                 $maptitle =~ s/\W+/_/g;
14045:                 if ($maptitle ne '') {
14046:                     if (length($maptitle) > 12) {
14047:                         $maptitle = substr($maptitle,0,12);
14048:                     }
14049:                     push(@pathitems,$maptitle);
14050:                 }
14051:                 unless ($env{'request.state'} eq 'construct') {
14052:                     my $res = $navmap->getBySymb($symb);
14053:                     if (ref($res)) {
14054:                         my $partlist = $res->parts();
14055:                         my $totaluploads = 0;
14056:                         if (ref($partlist) eq 'ARRAY') {
14057:                             foreach my $part (@{$partlist}) {
14058:                                 my @types = $res->responseType($part);
14059:                                 my @ids = $res->responseIds($part);
14060:                                 for (my $i=0; $i < scalar(@ids); $i++) {
14061:                                     if ($types[$i] eq 'essay') {
14062:                                         my $partid = $part.'_'.$ids[$i];
14063:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
14064:                                             $totaluploads ++;
14065:                                         }
14066:                                     }
14067:                                 }
14068:                             }
14069:                             if ($totaluploads > 1) {
14070:                                 $multiresp = 1;
14071:                             }
14072:                         }
14073:                     }
14074:                 }
14075:             } else {
14076:                 return;
14077:             }
14078:         } else {
14079:             return;
14080:         }
14081:         my $restitle=&Apache::lonnet::gettitle($symb);
14082:         $restitle =~ s/\W+/_/g;
14083:         if ($restitle eq '') {
14084:             $restitle = ($resurl =~ m{/[^/]+$});
14085:             if ($restitle eq '') {
14086:                 $restitle = time;
14087:             }
14088:         }
14089:         if (length($restitle) > 12) {
14090:             $restitle = substr($restitle,0,12);
14091:         }
14092:         push(@pathitems,$restitle);
14093:         $path .= join('/',@pathitems);
14094:     }
14095:     return ($path,$multiresp);
14096: }
14097: 
14098: =pod
14099: 
14100: =back
14101: 
14102: =head1 CSV Upload/Handling functions
14103: 
14104: =over 4
14105: 
14106: =item * &upfile_store($r)
14107: 
14108: Store uploaded file, $r should be the HTTP Request object,
14109: needs $env{'form.upfile'}
14110: returns $datatoken to be put into hidden field
14111: 
14112: =cut
14113: 
14114: sub upfile_store {
14115:     my $r=shift;
14116:     $env{'form.upfile'}=~s/\r/\n/gs;
14117:     $env{'form.upfile'}=~s/\f/\n/gs;
14118:     $env{'form.upfile'}=~s/\n+/\n/gs;
14119:     $env{'form.upfile'}=~s/\n+$//gs;
14120: 
14121:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
14122:                                      '_enroll_'.$env{'request.course.id'}.'_'.
14123:                                      time.'_'.$$);
14124:     return if ($datatoken eq '');
14125: 
14126:     {
14127:         my $datafile = $r->dir_config('lonDaemons').
14128:                            '/tmp/'.$datatoken.'.tmp';
14129:         if ( open(my $fh,'>',$datafile) ) {
14130:             print $fh $env{'form.upfile'};
14131:             close($fh);
14132:         }
14133:     }
14134:     return $datatoken;
14135: }
14136: 
14137: =pod
14138: 
14139: =item * &load_tmp_file($r,$datatoken)
14140: 
14141: Load uploaded file from tmp, $r should be the HTTP Request object,
14142: $datatoken is the name to assign to the temporary file.
14143: sets $env{'form.upfile'} to the contents of the file
14144: 
14145: =cut
14146: 
14147: sub load_tmp_file {
14148:     my ($r,$datatoken) = @_;
14149:     return if ($datatoken eq '');
14150:     my @studentdata=();
14151:     {
14152:         my $studentfile = $r->dir_config('lonDaemons').
14153:                               '/tmp/'.$datatoken.'.tmp';
14154:         if ( open(my $fh,'<',$studentfile) ) {
14155:             @studentdata=<$fh>;
14156:             close($fh);
14157:         }
14158:     }
14159:     $env{'form.upfile'}=join('',@studentdata);
14160: }
14161: 
14162: sub valid_datatoken {
14163:     my ($datatoken) = @_;
14164:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
14165:         return $datatoken;
14166:     }
14167:     return;
14168: }
14169: 
14170: =pod
14171: 
14172: =item * &upfile_record_sep()
14173: 
14174: Separate uploaded file into records
14175: returns array of records,
14176: needs $env{'form.upfile'} and $env{'form.upfiletype'}
14177: 
14178: =cut
14179: 
14180: sub upfile_record_sep {
14181:     if ($env{'form.upfiletype'} eq 'xml') {
14182:     } else {
14183: 	my @records;
14184: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
14185: 	    if ($line=~/^\s*$/) { next; }
14186: 	    push(@records,$line);
14187: 	}
14188: 	return @records;
14189:     }
14190: }
14191: 
14192: =pod
14193: 
14194: =item * &record_sep($record)
14195: 
14196: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
14197: 
14198: =cut
14199: 
14200: sub takeleft {
14201:     my $index=shift;
14202:     return substr('0000'.$index,-4,4);
14203: }
14204: 
14205: sub record_sep {
14206:     my $record=shift;
14207:     my %components=();
14208:     if ($env{'form.upfiletype'} eq 'xml') {
14209:     } elsif ($env{'form.upfiletype'} eq 'space') {
14210:         my $i=0;
14211:         foreach my $field (split(/\s+/,$record)) {
14212:             $field=~s/^(\"|\')//;
14213:             $field=~s/(\"|\')$//;
14214:             $components{&takeleft($i)}=$field;
14215:             $i++;
14216:         }
14217:     } elsif ($env{'form.upfiletype'} eq 'tab') {
14218:         my $i=0;
14219:         foreach my $field (split(/\t/,$record)) {
14220:             $field=~s/^(\"|\')//;
14221:             $field=~s/(\"|\')$//;
14222:             $components{&takeleft($i)}=$field;
14223:             $i++;
14224:         }
14225:     } else {
14226:         my $separator=',';
14227:         if ($env{'form.upfiletype'} eq 'semisv') {
14228:             $separator=';';
14229:         }
14230:         my $i=0;
14231: # the character we are looking for to indicate the end of a quote or a record 
14232:         my $looking_for=$separator;
14233: # do not add the characters to the fields
14234:         my $ignore=0;
14235: # we just encountered a separator (or the beginning of the record)
14236:         my $just_found_separator=1;
14237: # store the field we are working on here
14238:         my $field='';
14239: # work our way through all characters in record
14240:         foreach my $character ($record=~/(.)/g) {
14241:             if ($character eq $looking_for) {
14242:                if ($character ne $separator) {
14243: # Found the end of a quote, again looking for separator
14244:                   $looking_for=$separator;
14245:                   $ignore=1;
14246:                } else {
14247: # Found a separator, store away what we got
14248:                   $components{&takeleft($i)}=$field;
14249: 	          $i++;
14250:                   $just_found_separator=1;
14251:                   $ignore=0;
14252:                   $field='';
14253:                }
14254:                next;
14255:             }
14256: # single or double quotation marks after a separator indicate beginning of a quote
14257: # we are now looking for the end of the quote and need to ignore separators
14258:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
14259:                $looking_for=$character;
14260:                next;
14261:             }
14262: # ignore would be true after we reached the end of a quote
14263:             if ($ignore) { next; }
14264:             if (($just_found_separator) && ($character=~/\s/)) { next; }
14265:             $field.=$character;
14266:             $just_found_separator=0; 
14267:         }
14268: # catch the very last entry, since we never encountered the separator
14269:         $components{&takeleft($i)}=$field;
14270:     }
14271:     return %components;
14272: }
14273: 
14274: ######################################################
14275: ######################################################
14276: 
14277: =pod
14278: 
14279: =item * &upfile_select_html()
14280: 
14281: Return HTML code to select a file from the users machine and specify 
14282: the file type.
14283: 
14284: =cut
14285: 
14286: ######################################################
14287: ######################################################
14288: sub upfile_select_html {
14289:     my %Types = (
14290:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
14291:                  semisv => &mt('Semicolon separated values'),
14292:                  space => &mt('Space separated'),
14293:                  tab   => &mt('Tabulator separated'),
14294: #                 xml   => &mt('HTML/XML'),
14295:                  );
14296:     my $Str = '<input type="file" name="upfile" size="50" />'.
14297:         '<br />'.&mt('Type').': <select name="upfiletype">';
14298:     foreach my $type (sort(keys(%Types))) {
14299:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
14300:     }
14301:     $Str .= "</select>\n";
14302:     return $Str;
14303: }
14304: 
14305: sub get_samples {
14306:     my ($records,$toget) = @_;
14307:     my @samples=({});
14308:     my $got=0;
14309:     foreach my $rec (@$records) {
14310: 	my %temp = &record_sep($rec);
14311: 	if (! grep(/\S/, values(%temp))) { next; }
14312: 	if (%temp) {
14313: 	    $samples[$got]=\%temp;
14314: 	    $got++;
14315: 	    if ($got == $toget) { last; }
14316: 	}
14317:     }
14318:     return \@samples;
14319: }
14320: 
14321: ######################################################
14322: ######################################################
14323: 
14324: =pod
14325: 
14326: =item * &csv_print_samples($r,$records)
14327: 
14328: Prints a table of sample values from each column uploaded $r is an
14329: Apache Request ref, $records is an arrayref from
14330: &Apache::loncommon::upfile_record_sep
14331: 
14332: =cut
14333: 
14334: ######################################################
14335: ######################################################
14336: sub csv_print_samples {
14337:     my ($r,$records) = @_;
14338:     my $samples = &get_samples($records,5);
14339: 
14340:     $r->print(&mt('Samples').'<br />'.&start_data_table().
14341:               &start_data_table_header_row());
14342:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
14343:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
14344:     $r->print(&end_data_table_header_row());
14345:     foreach my $hash (@$samples) {
14346: 	$r->print(&start_data_table_row());
14347: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
14348: 	    $r->print('<td>');
14349: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
14350: 	    $r->print('</td>');
14351: 	}
14352: 	$r->print(&end_data_table_row());
14353:     }
14354:     $r->print(&end_data_table().'<br />'."\n");
14355: }
14356: 
14357: ######################################################
14358: ######################################################
14359: 
14360: =pod
14361: 
14362: =item * &csv_print_select_table($r,$records,$d)
14363: 
14364: Prints a table to create associations between values and table columns.
14365: 
14366: $r is an Apache Request ref,
14367: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
14368: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
14369: 
14370: =cut
14371: 
14372: ######################################################
14373: ######################################################
14374: sub csv_print_select_table {
14375:     my ($r,$records,$d) = @_;
14376:     my $i=0;
14377:     my $samples = &get_samples($records,1);
14378:     $r->print(&mt('Associate columns with student attributes.')."\n".
14379: 	      &start_data_table().&start_data_table_header_row().
14380:               '<th>'.&mt('Attribute').'</th>'.
14381:               '<th>'.&mt('Column').'</th>'.
14382:               &end_data_table_header_row()."\n");
14383:     foreach my $array_ref (@$d) {
14384: 	my ($value,$display,$defaultcol)=@{ $array_ref };
14385: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
14386: 
14387: 	$r->print('<td><select name="f'.$i.'"'.
14388: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
14389: 	$r->print('<option value="none"></option>');
14390: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
14391: 	    $r->print('<option value="'.$sample.'"'.
14392:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
14393:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
14394: 	}
14395: 	$r->print('</select></td>'.&end_data_table_row()."\n");
14396: 	$i++;
14397:     }
14398:     $r->print(&end_data_table());
14399:     $i--;
14400:     return $i;
14401: }
14402: 
14403: ######################################################
14404: ######################################################
14405: 
14406: =pod
14407: 
14408: =item * &csv_samples_select_table($r,$records,$d)
14409: 
14410: Prints a table of sample values from the upload and can make associate samples to internal names.
14411: 
14412: $r is an Apache Request ref,
14413: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
14414: $d is an array of 2 element arrays (internal name, displayed name)
14415: 
14416: =cut
14417: 
14418: ######################################################
14419: ######################################################
14420: sub csv_samples_select_table {
14421:     my ($r,$records,$d) = @_;
14422:     my $i=0;
14423:     #
14424:     my $max_samples = 5;
14425:     my $samples = &get_samples($records,$max_samples);
14426:     $r->print(&start_data_table().
14427:               &start_data_table_header_row().'<th>'.
14428:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
14429:               &end_data_table_header_row());
14430: 
14431:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
14432: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
14433: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
14434: 	foreach my $option (@$d) {
14435: 	    my ($value,$display,$defaultcol)=@{ $option };
14436: 	    $r->print('<option value="'.$value.'"'.
14437:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
14438:                       $display.'</option>');
14439: 	}
14440: 	$r->print('</select></td><td>');
14441: 	foreach my $line (0..($max_samples-1)) {
14442: 	    if (defined($samples->[$line]{$key})) { 
14443: 		$r->print($samples->[$line]{$key}."<br />\n"); 
14444: 	    }
14445: 	}
14446: 	$r->print('</td>'.&end_data_table_row());
14447: 	$i++;
14448:     }
14449:     $r->print(&end_data_table());
14450:     $i--;
14451:     return($i);
14452: }
14453: 
14454: ######################################################
14455: ######################################################
14456: 
14457: =pod
14458: 
14459: =item * &clean_excel_name($name)
14460: 
14461: Returns a replacement for $name which does not contain any illegal characters.
14462: 
14463: =cut
14464: 
14465: ######################################################
14466: ######################################################
14467: sub clean_excel_name {
14468:     my ($name) = @_;
14469:     $name =~ s/[:\*\?\/\\]//g;
14470:     if (length($name) > 31) {
14471:         $name = substr($name,0,31);
14472:     }
14473:     return $name;
14474: }
14475: 
14476: =pod
14477: 
14478: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
14479: 
14480: Returns either 1 or undef
14481: 
14482: 1 if the part is to be hidden, undef if it is to be shown
14483: 
14484: Arguments are:
14485: 
14486: $id the id of the part to be checked
14487: $symb, optional the symb of the resource to check
14488: $udom, optional the domain of the user to check for
14489: $uname, optional the username of the user to check for
14490: 
14491: =cut
14492: 
14493: sub check_if_partid_hidden {
14494:     my ($id,$symb,$udom,$uname) = @_;
14495:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
14496: 					 $symb,$udom,$uname);
14497:     my $truth=1;
14498:     #if the string starts with !, then the list is the list to show not hide
14499:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
14500:     my @hiddenlist=split(/,/,$hiddenparts);
14501:     foreach my $checkid (@hiddenlist) {
14502: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
14503:     }
14504:     return !$truth;
14505: }
14506: 
14507: 
14508: ############################################################
14509: ############################################################
14510: 
14511: =pod
14512: 
14513: =back 
14514: 
14515: =head1 cgi-bin script and graphing routines
14516: 
14517: =over 4
14518: 
14519: =item * &get_cgi_id()
14520: 
14521: Inputs: none
14522: 
14523: Returns an id which can be used to pass environment variables
14524: to various cgi-bin scripts.  These environment variables will
14525: be removed from the users environment after a given time by
14526: the routine &Apache::lonnet::transfer_profile_to_env.
14527: 
14528: =cut
14529: 
14530: ############################################################
14531: ############################################################
14532: my $uniq=0;
14533: sub get_cgi_id {
14534:     $uniq=($uniq+1)%100000;
14535:     return (time.'_'.$$.'_'.$uniq);
14536: }
14537: 
14538: ############################################################
14539: ############################################################
14540: 
14541: =pod
14542: 
14543: =item * &DrawBarGraph()
14544: 
14545: Facilitates the plotting of data in a (stacked) bar graph.
14546: Puts plot definition data into the users environment in order for 
14547: graph.png to plot it.  Returns an <img> tag for the plot.
14548: The bars on the plot are labeled '1','2',...,'n'.
14549: 
14550: Inputs:
14551: 
14552: =over 4
14553: 
14554: =item $Title: string, the title of the plot
14555: 
14556: =item $xlabel: string, text describing the X-axis of the plot
14557: 
14558: =item $ylabel: string, text describing the Y-axis of the plot
14559: 
14560: =item $Max: scalar, the maximum Y value to use in the plot
14561: If $Max is < any data point, the graph will not be rendered.
14562: 
14563: =item $colors: array ref holding the colors to be used for the data sets when
14564: they are plotted.  If undefined, default values will be used.
14565: 
14566: =item $labels: array ref holding the labels to use on the x-axis for the bars.
14567: 
14568: =item @Values: An array of array references.  Each array reference holds data
14569: to be plotted in a stacked bar chart.
14570: 
14571: =item If the final element of @Values is a hash reference the key/value
14572: pairs will be added to the graph definition.
14573: 
14574: =back
14575: 
14576: Returns:
14577: 
14578: An <img> tag which references graph.png and the appropriate identifying
14579: information for the plot.
14580: 
14581: =cut
14582: 
14583: ############################################################
14584: ############################################################
14585: sub DrawBarGraph {
14586:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
14587:     #
14588:     if (! defined($colors)) {
14589:         $colors = ['#33ff00', 
14590:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
14591:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
14592:                   ]; 
14593:     }
14594:     my $extra_settings = {};
14595:     if (ref($Values[-1]) eq 'HASH') {
14596:         $extra_settings = pop(@Values);
14597:     }
14598:     #
14599:     my $identifier = &get_cgi_id();
14600:     my $id = 'cgi.'.$identifier;        
14601:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
14602:         return '';
14603:     }
14604:     #
14605:     my @Labels;
14606:     if (defined($labels)) {
14607:         @Labels = @$labels;
14608:     } else {
14609:         for (my $i=0;$i<@{$Values[0]};$i++) {
14610:             push(@Labels,$i+1);
14611:         }
14612:     }
14613:     #
14614:     my $NumBars = scalar(@{$Values[0]});
14615:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
14616:     my %ValuesHash;
14617:     my $NumSets=1;
14618:     foreach my $array (@Values) {
14619:         next if (! ref($array));
14620:         $ValuesHash{$id.'.data.'.$NumSets++} = 
14621:             join(',',@$array);
14622:     }
14623:     #
14624:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
14625:     if ($NumBars < 3) {
14626:         $width = 120+$NumBars*32;
14627:         $xskip = 1;
14628:         $bar_width = 30;
14629:     } elsif ($NumBars < 5) {
14630:         $width = 120+$NumBars*20;
14631:         $xskip = 1;
14632:         $bar_width = 20;
14633:     } elsif ($NumBars < 10) {
14634:         $width = 120+$NumBars*15;
14635:         $xskip = 1;
14636:         $bar_width = 15;
14637:     } elsif ($NumBars <= 25) {
14638:         $width = 120+$NumBars*11;
14639:         $xskip = 5;
14640:         $bar_width = 8;
14641:     } elsif ($NumBars <= 50) {
14642:         $width = 120+$NumBars*8;
14643:         $xskip = 5;
14644:         $bar_width = 4;
14645:     } else {
14646:         $width = 120+$NumBars*8;
14647:         $xskip = 5;
14648:         $bar_width = 4;
14649:     }
14650:     #
14651:     $Max = 1 if ($Max < 1);
14652:     if ( int($Max) < $Max ) {
14653:         $Max++;
14654:         $Max = int($Max);
14655:     }
14656:     $Title  = '' if (! defined($Title));
14657:     $xlabel = '' if (! defined($xlabel));
14658:     $ylabel = '' if (! defined($ylabel));
14659:     $ValuesHash{$id.'.title'}    = &escape($Title);
14660:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
14661:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
14662:     $ValuesHash{$id.'.y_max_value'} = $Max;
14663:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
14664:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
14665:     $ValuesHash{$id.'.PlotType'} = 'bar';
14666:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14667:     $ValuesHash{$id.'.height'}   = $height;
14668:     $ValuesHash{$id.'.width'}    = $width;
14669:     $ValuesHash{$id.'.xskip'}    = $xskip;
14670:     $ValuesHash{$id.'.bar_width'} = $bar_width;
14671:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
14672:     #
14673:     # Deal with other parameters
14674:     while (my ($key,$value) = each(%$extra_settings)) {
14675:         $ValuesHash{$id.'.'.$key} = $value;
14676:     }
14677:     #
14678:     &Apache::lonnet::appenv(\%ValuesHash);
14679:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14680: }
14681: 
14682: ############################################################
14683: ############################################################
14684: 
14685: =pod
14686: 
14687: =item * &DrawXYGraph()
14688: 
14689: Facilitates the plotting of data in an XY graph.
14690: Puts plot definition data into the users environment in order for 
14691: graph.png to plot it.  Returns an <img> tag for the plot.
14692: 
14693: Inputs:
14694: 
14695: =over 4
14696: 
14697: =item $Title: string, the title of the plot
14698: 
14699: =item $xlabel: string, text describing the X-axis of the plot
14700: 
14701: =item $ylabel: string, text describing the Y-axis of the plot
14702: 
14703: =item $Max: scalar, the maximum Y value to use in the plot
14704: If $Max is < any data point, the graph will not be rendered.
14705: 
14706: =item $colors: Array ref containing the hex color codes for the data to be 
14707: plotted in.  If undefined, default values will be used.
14708: 
14709: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
14710: 
14711: =item $Ydata: Array ref containing Array refs.  
14712: Each of the contained arrays will be plotted as a separate curve.
14713: 
14714: =item %Values: hash indicating or overriding any default values which are 
14715: passed to graph.png.  
14716: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
14717: 
14718: =back
14719: 
14720: Returns:
14721: 
14722: An <img> tag which references graph.png and the appropriate identifying
14723: information for the plot.
14724: 
14725: =cut
14726: 
14727: ############################################################
14728: ############################################################
14729: sub DrawXYGraph {
14730:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
14731:     #
14732:     # Create the identifier for the graph
14733:     my $identifier = &get_cgi_id();
14734:     my $id = 'cgi.'.$identifier;
14735:     #
14736:     $Title  = '' if (! defined($Title));
14737:     $xlabel = '' if (! defined($xlabel));
14738:     $ylabel = '' if (! defined($ylabel));
14739:     my %ValuesHash = 
14740:         (
14741:          $id.'.title'  => &escape($Title),
14742:          $id.'.xlabel' => &escape($xlabel),
14743:          $id.'.ylabel' => &escape($ylabel),
14744:          $id.'.y_max_value'=> $Max,
14745:          $id.'.labels'     => join(',',@$Xlabels),
14746:          $id.'.PlotType'   => 'XY',
14747:          );
14748:     #
14749:     if (defined($colors) && ref($colors) eq 'ARRAY') {
14750:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14751:     }
14752:     #
14753:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
14754:         return '';
14755:     }
14756:     my $NumSets=1;
14757:     foreach my $array (@{$Ydata}){
14758:         next if (! ref($array));
14759:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
14760:     }
14761:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
14762:     #
14763:     # Deal with other parameters
14764:     while (my ($key,$value) = each(%Values)) {
14765:         $ValuesHash{$id.'.'.$key} = $value;
14766:     }
14767:     #
14768:     &Apache::lonnet::appenv(\%ValuesHash);
14769:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14770: }
14771: 
14772: ############################################################
14773: ############################################################
14774: 
14775: =pod
14776: 
14777: =item * &DrawXYYGraph()
14778: 
14779: Facilitates the plotting of data in an XY graph with two Y axes.
14780: Puts plot definition data into the users environment in order for 
14781: graph.png to plot it.  Returns an <img> tag for the plot.
14782: 
14783: Inputs:
14784: 
14785: =over 4
14786: 
14787: =item $Title: string, the title of the plot
14788: 
14789: =item $xlabel: string, text describing the X-axis of the plot
14790: 
14791: =item $ylabel: string, text describing the Y-axis of the plot
14792: 
14793: =item $colors: Array ref containing the hex color codes for the data to be 
14794: plotted in.  If undefined, default values will be used.
14795: 
14796: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
14797: 
14798: =item $Ydata1: The first data set
14799: 
14800: =item $Min1: The minimum value of the left Y-axis
14801: 
14802: =item $Max1: The maximum value of the left Y-axis
14803: 
14804: =item $Ydata2: The second data set
14805: 
14806: =item $Min2: The minimum value of the right Y-axis
14807: 
14808: =item $Max2: The maximum value of the left Y-axis
14809: 
14810: =item %Values: hash indicating or overriding any default values which are 
14811: passed to graph.png.  
14812: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
14813: 
14814: =back
14815: 
14816: Returns:
14817: 
14818: An <img> tag which references graph.png and the appropriate identifying
14819: information for the plot.
14820: 
14821: =cut
14822: 
14823: ############################################################
14824: ############################################################
14825: sub DrawXYYGraph {
14826:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
14827:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
14828:     #
14829:     # Create the identifier for the graph
14830:     my $identifier = &get_cgi_id();
14831:     my $id = 'cgi.'.$identifier;
14832:     #
14833:     $Title  = '' if (! defined($Title));
14834:     $xlabel = '' if (! defined($xlabel));
14835:     $ylabel = '' if (! defined($ylabel));
14836:     my %ValuesHash = 
14837:         (
14838:          $id.'.title'  => &escape($Title),
14839:          $id.'.xlabel' => &escape($xlabel),
14840:          $id.'.ylabel' => &escape($ylabel),
14841:          $id.'.labels' => join(',',@$Xlabels),
14842:          $id.'.PlotType' => 'XY',
14843:          $id.'.NumSets' => 2,
14844:          $id.'.two_axes' => 1,
14845:          $id.'.y1_max_value' => $Max1,
14846:          $id.'.y1_min_value' => $Min1,
14847:          $id.'.y2_max_value' => $Max2,
14848:          $id.'.y2_min_value' => $Min2,
14849:          );
14850:     #
14851:     if (defined($colors) && ref($colors) eq 'ARRAY') {
14852:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14853:     }
14854:     #
14855:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
14856:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
14857:         return '';
14858:     }
14859:     my $NumSets=1;
14860:     foreach my $array ($Ydata1,$Ydata2){
14861:         next if (! ref($array));
14862:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
14863:     }
14864:     #
14865:     # Deal with other parameters
14866:     while (my ($key,$value) = each(%Values)) {
14867:         $ValuesHash{$id.'.'.$key} = $value;
14868:     }
14869:     #
14870:     &Apache::lonnet::appenv(\%ValuesHash);
14871:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14872: }
14873: 
14874: ############################################################
14875: ############################################################
14876: 
14877: =pod
14878: 
14879: =back 
14880: 
14881: =head1 Statistics helper routines?  
14882: 
14883: Bad place for them but what the hell.
14884: 
14885: =over 4
14886: 
14887: =item * &chartlink()
14888: 
14889: Returns a link to the chart for a specific student.  
14890: 
14891: Inputs:
14892: 
14893: =over 4
14894: 
14895: =item $linktext: The text of the link
14896: 
14897: =item $sname: The students username
14898: 
14899: =item $sdomain: The students domain
14900: 
14901: =back
14902: 
14903: =back
14904: 
14905: =cut
14906: 
14907: ############################################################
14908: ############################################################
14909: sub chartlink {
14910:     my ($linktext, $sname, $sdomain) = @_;
14911:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
14912:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
14913:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
14914:        '">'.$linktext.'</a>';
14915: }
14916: 
14917: #######################################################
14918: #######################################################
14919: 
14920: =pod
14921: 
14922: =head1 Course Environment Routines
14923: 
14924: =over 4
14925: 
14926: =item * &restore_course_settings()
14927: 
14928: =item * &store_course_settings()
14929: 
14930: Restores/Store indicated form parameters from the course environment.
14931: Will not overwrite existing values of the form parameters.
14932: 
14933: Inputs: 
14934: a scalar describing the data (e.g. 'chart', 'problem_analysis')
14935: 
14936: a hash ref describing the data to be stored.  For example:
14937:    
14938: %Save_Parameters = ('Status' => 'scalar',
14939:     'chartoutputmode' => 'scalar',
14940:     'chartoutputdata' => 'scalar',
14941:     'Section' => 'array',
14942:     'Group' => 'array',
14943:     'StudentData' => 'array',
14944:     'Maps' => 'array');
14945: 
14946: Returns: both routines return nothing
14947: 
14948: =back
14949: 
14950: =cut
14951: 
14952: #######################################################
14953: #######################################################
14954: sub store_course_settings {
14955:     return &store_settings($env{'request.course.id'},@_);
14956: }
14957: 
14958: sub store_settings {
14959:     # save to the environment
14960:     # appenv the same items, just to be safe
14961:     my $udom  = $env{'user.domain'};
14962:     my $uname = $env{'user.name'};
14963:     my ($context,$prefix,$Settings) = @_;
14964:     my %SaveHash;
14965:     my %AppHash;
14966:     while (my ($setting,$type) = each(%$Settings)) {
14967:         my $basename = join('.','internal',$context,$prefix,$setting);
14968:         my $envname = 'environment.'.$basename;
14969:         if (exists($env{'form.'.$setting})) {
14970:             # Save this value away
14971:             if ($type eq 'scalar' &&
14972:                 (! exists($env{$envname}) || 
14973:                  $env{$envname} ne $env{'form.'.$setting})) {
14974:                 $SaveHash{$basename} = $env{'form.'.$setting};
14975:                 $AppHash{$envname}   = $env{'form.'.$setting};
14976:             } elsif ($type eq 'array') {
14977:                 my $stored_form;
14978:                 if (ref($env{'form.'.$setting})) {
14979:                     $stored_form = join(',',
14980:                                         map {
14981:                                             &escape($_);
14982:                                         } sort(@{$env{'form.'.$setting}}));
14983:                 } else {
14984:                     $stored_form = 
14985:                         &escape($env{'form.'.$setting});
14986:                 }
14987:                 # Determine if the array contents are the same.
14988:                 if ($stored_form ne $env{$envname}) {
14989:                     $SaveHash{$basename} = $stored_form;
14990:                     $AppHash{$envname}   = $stored_form;
14991:                 }
14992:             }
14993:         }
14994:     }
14995:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
14996:                                           $udom,$uname);
14997:     if ($put_result !~ /^(ok|delayed)/) {
14998:         &Apache::lonnet::logthis('unable to save form parameters, '.
14999:                                  'got error:'.$put_result);
15000:     }
15001:     # Make sure these settings stick around in this session, too
15002:     &Apache::lonnet::appenv(\%AppHash);
15003:     return;
15004: }
15005: 
15006: sub restore_course_settings {
15007:     return &restore_settings($env{'request.course.id'},@_);
15008: }
15009: 
15010: sub restore_settings {
15011:     my ($context,$prefix,$Settings) = @_;
15012:     while (my ($setting,$type) = each(%$Settings)) {
15013:         next if (exists($env{'form.'.$setting}));
15014:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
15015:             '.'.$setting;
15016:         if (exists($env{$envname})) {
15017:             if ($type eq 'scalar') {
15018:                 $env{'form.'.$setting} = $env{$envname};
15019:             } elsif ($type eq 'array') {
15020:                 $env{'form.'.$setting} = [ 
15021:                                            map { 
15022:                                                &unescape($_); 
15023:                                            } split(',',$env{$envname})
15024:                                            ];
15025:             }
15026:         }
15027:     }
15028: }
15029: 
15030: #######################################################
15031: #######################################################
15032: 
15033: =pod
15034: 
15035: =head1 Domain E-mail Routines  
15036: 
15037: =over 4
15038: 
15039: =item * &build_recipient_list()
15040: 
15041: Build recipient lists for following types of e-mail:
15042: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
15043: (d) Help requests, (e) Course requests needing approval, (f) loncapa
15044: module change checking, student/employee ID conflict checks, as
15045: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
15046: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
15047: 
15048: Inputs:
15049: defmail (scalar - email address of default recipient),
15050: mailing type (scalar: errormail, packagesmail, helpdeskmail,
15051: requestsmail, updatesmail, or idconflictsmail).
15052: 
15053: defdom (domain for which to retrieve configuration settings),
15054: 
15055: origmail (scalar - email address of recipient from loncapa.conf,
15056: i.e., predates configuration by DC via domainprefs.pm
15057: 
15058: $requname username of requester (if mailing type is helpdeskmail)
15059: 
15060: $requdom domain of requester (if mailing type is helpdeskmail)
15061: 
15062: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
15063: 
15064: Returns: comma separated list of addresses to which to send e-mail.
15065: 
15066: =back
15067: 
15068: =cut
15069: 
15070: ############################################################
15071: ############################################################
15072: sub build_recipient_list {
15073:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
15074:     my @recipients;
15075:     my ($otheremails,$lastresort,$allbcc,$addtext);
15076:     my %domconfig =
15077:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
15078:     if (ref($domconfig{'contacts'}) eq 'HASH') {
15079:         if (exists($domconfig{'contacts'}{$mailing})) {
15080:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
15081:                 my @contacts = ('adminemail','supportemail');
15082:                 foreach my $item (@contacts) {
15083:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
15084:                         my $addr = $domconfig{'contacts'}{$item}; 
15085:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
15086:                             push(@recipients,$addr);
15087:                         }
15088:                     }
15089:                 }
15090:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
15091:                 if ($mailing eq 'helpdeskmail') {
15092:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
15093:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
15094:                         my @ok_bccs;
15095:                         foreach my $bcc (@bccs) {
15096:                             $bcc =~ s/^\s+//g;
15097:                             $bcc =~ s/\s+$//g;
15098:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15099:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15100:                                     push(@ok_bccs,$bcc);
15101:                                 }
15102:                             }
15103:                         }
15104:                         if (@ok_bccs > 0) {
15105:                             $allbcc = join(', ',@ok_bccs);
15106:                         }
15107:                     }
15108:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
15109:                 }
15110:             }
15111:         } elsif ($origmail ne '') {
15112:             $lastresort = $origmail;
15113:         }
15114:         if ($mailing eq 'helpdeskmail') {
15115:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
15116:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
15117:                 my ($inststatus,$inststatus_checked);
15118:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
15119:                     ($env{'user.domain'} ne 'public')) {
15120:                     $inststatus_checked = 1;
15121:                     $inststatus = $env{'environment.inststatus'};
15122:                 }
15123:                 unless ($inststatus_checked) {
15124:                     if (($requname ne '') && ($requdom ne '')) {
15125:                         if (($requname =~ /^$match_username$/) &&
15126:                             ($requdom =~ /^$match_domain$/) &&
15127:                             (&Apache::lonnet::domain($requdom))) {
15128:                             my $requhome = &Apache::lonnet::homeserver($requname,
15129:                                                                       $requdom);
15130:                             unless ($requhome eq 'no_host') {
15131:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
15132:                                 $inststatus = $userenv{'inststatus'};
15133:                                 $inststatus_checked = 1;
15134:                             }
15135:                         }
15136:                     }
15137:                 }
15138:                 unless ($inststatus_checked) {
15139:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
15140:                         my %srch = (srchby     => 'email',
15141:                                     srchdomain => $defdom,
15142:                                     srchterm   => $reqemail,
15143:                                     srchtype   => 'exact');
15144:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
15145:                         foreach my $uname (keys(%srch_results)) {
15146:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
15147:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
15148:                                 $inststatus_checked = 1;
15149:                                 last;
15150:                             }
15151:                         }
15152:                         unless ($inststatus_checked) {
15153:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
15154:                             if ($dirsrchres eq 'ok') {
15155:                                 foreach my $uname (keys(%srch_results)) {
15156:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
15157:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
15158:                                         $inststatus_checked = 1;
15159:                                         last;
15160:                                     }
15161:                                 }
15162:                             }
15163:                         }
15164:                     }
15165:                 }
15166:                 if ($inststatus ne '') {
15167:                     foreach my $status (split(/\:/,$inststatus)) {
15168:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
15169:                             my @contacts = ('adminemail','supportemail');
15170:                             foreach my $item (@contacts) {
15171:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
15172:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
15173:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
15174:                                         push(@recipients,$addr);
15175:                                     }
15176:                                 }
15177:                             }
15178:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
15179:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
15180:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
15181:                                 my @ok_bccs;
15182:                                 foreach my $bcc (@bccs) {
15183:                                     $bcc =~ s/^\s+//g;
15184:                                     $bcc =~ s/\s+$//g;
15185:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15186:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15187:                                             push(@ok_bccs,$bcc);
15188:                                         }
15189:                                     }
15190:                                 }
15191:                                 if (@ok_bccs > 0) {
15192:                                     $allbcc = join(', ',@ok_bccs);
15193:                                 }
15194:                             }
15195:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
15196:                             last;
15197:                         }
15198:                     }
15199:                 }
15200:             }
15201:         }
15202:     } elsif ($origmail ne '') {
15203:         $lastresort = $origmail;
15204:     }
15205:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
15206:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
15207:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
15208:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
15209:             my %what = (
15210:                           perlvar => 1,
15211:                        );
15212:             my $primary = &Apache::lonnet::domain($defdom,'primary');
15213:             if ($primary) {
15214:                 my $gotaddr;
15215:                 my ($result,$returnhash) =
15216:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
15217:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
15218:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
15219:                         $lastresort = $returnhash->{'lonSupportEMail'};
15220:                         $gotaddr = 1;
15221:                     }
15222:                 }
15223:                 unless ($gotaddr) {
15224:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
15225:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
15226:                     unless ($uintdom eq $intdom) {
15227:                         my %domconfig =
15228:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
15229:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
15230:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
15231:                                 my @contacts = ('adminemail','supportemail');
15232:                                 foreach my $item (@contacts) {
15233:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
15234:                                         my $addr = $domconfig{'contacts'}{$item};
15235:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
15236:                                             push(@recipients,$addr);
15237:                                         }
15238:                                     }
15239:                                 }
15240:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
15241:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
15242:                                 }
15243:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
15244:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
15245:                                     my @ok_bccs;
15246:                                     foreach my $bcc (@bccs) {
15247:                                         $bcc =~ s/^\s+//g;
15248:                                         $bcc =~ s/\s+$//g;
15249:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15250:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15251:                                                 push(@ok_bccs,$bcc);
15252:                                             }
15253:                                         }
15254:                                     }
15255:                                     if (@ok_bccs > 0) {
15256:                                         $allbcc = join(', ',@ok_bccs);
15257:                                     }
15258:                                 }
15259:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
15260:                             }
15261:                         }
15262:                     }
15263:                 }
15264:             }
15265:         }
15266:     }
15267:     if (defined($defmail)) {
15268:         if ($defmail ne '') {
15269:             push(@recipients,$defmail);
15270:         }
15271:     }
15272:     if ($otheremails) {
15273:         my @others;
15274:         if ($otheremails =~ /,/) {
15275:             @others = split(/,/,$otheremails);
15276:         } else {
15277:             push(@others,$otheremails);
15278:         }
15279:         foreach my $addr (@others) {
15280:             if (!grep(/^\Q$addr\E$/,@recipients)) {
15281:                 push(@recipients,$addr);
15282:             }
15283:         }
15284:     }
15285:     if ($mailing eq 'helpdeskmail') {
15286:         if ((!@recipients) && ($lastresort ne '')) {
15287:             push(@recipients,$lastresort);
15288:         }
15289:     } elsif ($lastresort ne '') {
15290:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
15291:             push(@recipients,$lastresort);
15292:         }
15293:     }
15294:     my $recipientlist = join(',',@recipients);
15295:     if (wantarray) {
15296:         return ($recipientlist,$allbcc,$addtext);
15297:     } else {
15298:         return $recipientlist;
15299:     }
15300: }
15301: 
15302: ############################################################
15303: ############################################################
15304: 
15305: =pod
15306: 
15307: =head1 Course Catalog Routines
15308: 
15309: =over 4
15310: 
15311: =item * &gather_categories()
15312: 
15313: Converts category definitions - keys of categories hash stored in  
15314: coursecategories in configuration.db on the primary library server in a 
15315: domain - to an array.  Also generates javascript and idx hash used to 
15316: generate Domain Coordinator interface for editing Course Categories.
15317: 
15318: Inputs:
15319: 
15320: categories (reference to hash of category definitions).
15321: 
15322: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15323:       categories and subcategories).
15324: 
15325: idx (reference to hash of counters used in Domain Coordinator interface for 
15326:       editing Course Categories).
15327: 
15328: jsarray (reference to array of categories used to create Javascript arrays for
15329:          Domain Coordinator interface for editing Course Categories).
15330: 
15331: Returns: nothing
15332: 
15333: Side effects: populates cats, idx and jsarray. 
15334: 
15335: =cut
15336: 
15337: sub gather_categories {
15338:     my ($categories,$cats,$idx,$jsarray) = @_;
15339:     my %counters;
15340:     my $num = 0;
15341:     foreach my $item (keys(%{$categories})) {
15342:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
15343:         if ($container eq '' && $depth == 0) {
15344:             $cats->[$depth][$categories->{$item}] = $cat;
15345:         } else {
15346:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
15347:         }
15348:         my ($escitem,$tail) = split(/:/,$item,2);
15349:         if ($counters{$tail} eq '') {
15350:             $counters{$tail} = $num;
15351:             $num ++;
15352:         }
15353:         if (ref($idx) eq 'HASH') {
15354:             $idx->{$item} = $counters{$tail};
15355:         }
15356:         if (ref($jsarray) eq 'ARRAY') {
15357:             push(@{$jsarray->[$counters{$tail}]},$item);
15358:         }
15359:     }
15360:     return;
15361: }
15362: 
15363: =pod
15364: 
15365: =item * &extract_categories()
15366: 
15367: Used to generate breadcrumb trails for course categories.
15368: 
15369: Inputs:
15370: 
15371: categories (reference to hash of category definitions).
15372: 
15373: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15374:       categories and subcategories).
15375: 
15376: trails (reference to array of breacrumb trails for each category).
15377: 
15378: allitems (reference to hash - key is category key 
15379:          (format: escaped(name):escaped(parent category):depth in hierarchy).
15380: 
15381: idx (reference to hash of counters used in Domain Coordinator interface for
15382:       editing Course Categories).
15383: 
15384: jsarray (reference to array of categories used to create Javascript arrays for
15385:          Domain Coordinator interface for editing Course Categories).
15386: 
15387: subcats (reference to hash of arrays containing all subcategories within each 
15388:          category, -recursive)
15389: 
15390: maxd (reference to hash used to hold max depth for all top-level categories).
15391: 
15392: Returns: nothing
15393: 
15394: Side effects: populates trails and allitems hash references.
15395: 
15396: =cut
15397: 
15398: sub extract_categories {
15399:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
15400:     if (ref($categories) eq 'HASH') {
15401:         &gather_categories($categories,$cats,$idx,$jsarray);
15402:         if (ref($cats->[0]) eq 'ARRAY') {
15403:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
15404:                 my $name = $cats->[0][$i];
15405:                 my $item = &escape($name).'::0';
15406:                 my $trailstr;
15407:                 if ($name eq 'instcode') {
15408:                     $trailstr = &mt('Official courses (with institutional codes)');
15409:                 } elsif ($name eq 'communities') {
15410:                     $trailstr = &mt('Communities');
15411:                 } else {
15412:                     $trailstr = $name;
15413:                 }
15414:                 if ($allitems->{$item} eq '') {
15415:                     push(@{$trails},$trailstr);
15416:                     $allitems->{$item} = scalar(@{$trails})-1;
15417:                 }
15418:                 my @parents = ($name);
15419:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
15420:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
15421:                         my $category = $cats->[1]{$name}[$j];
15422:                         if (ref($subcats) eq 'HASH') {
15423:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
15424:                         }
15425:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
15426:                     }
15427:                 } else {
15428:                     if (ref($subcats) eq 'HASH') {
15429:                         $subcats->{$item} = [];
15430:                     }
15431:                     if (ref($maxd) eq 'HASH') {
15432:                         $maxd->{$name} = 1;
15433:                     }
15434:                 }
15435:             }
15436:         }
15437:     }
15438:     return;
15439: }
15440: 
15441: =pod
15442: 
15443: =item * &recurse_categories()
15444: 
15445: Recursively used to generate breadcrumb trails for course categories.
15446: 
15447: Inputs:
15448: 
15449: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15450:       categories and subcategories).
15451: 
15452: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
15453: 
15454: category (current course category, for which breadcrumb trail is being generated).
15455: 
15456: trails (reference to array of breadcrumb trails for each category).
15457: 
15458: allitems (reference to hash - key is category key
15459:          (format: escaped(name):escaped(parent category):depth in hierarchy).
15460: 
15461: parents (array containing containers directories for current category, 
15462:          back to top level). 
15463: 
15464: Returns: nothing
15465: 
15466: Side effects: populates trails and allitems hash references
15467: 
15468: =cut
15469: 
15470: sub recurse_categories {
15471:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
15472:     my $shallower = $depth - 1;
15473:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
15474:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
15475:             my $name = $cats->[$depth]{$category}[$k];
15476:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
15477:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
15478:             if ($allitems->{$item} eq '') {
15479:                 push(@{$trails},$trailstr);
15480:                 $allitems->{$item} = scalar(@{$trails})-1;
15481:             }
15482:             my $deeper = $depth+1;
15483:             push(@{$parents},$category);
15484:             if (ref($subcats) eq 'HASH') {
15485:                 my $subcat = &escape($name).':'.$category.':'.$depth;
15486:                 for (my $j=@{$parents}; $j>=0; $j--) {
15487:                     my $higher;
15488:                     if ($j > 0) {
15489:                         $higher = &escape($parents->[$j]).':'.
15490:                                   &escape($parents->[$j-1]).':'.$j;
15491:                     } else {
15492:                         $higher = &escape($parents->[$j]).'::'.$j;
15493:                     }
15494:                     push(@{$subcats->{$higher}},$subcat);
15495:                 }
15496:             }
15497:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
15498:                                 $subcats,$maxd);
15499:             pop(@{$parents});
15500:         }
15501:     } else {
15502:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
15503:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
15504:         if ($allitems->{$item} eq '') {
15505:             push(@{$trails},$trailstr);
15506:             $allitems->{$item} = scalar(@{$trails})-1;
15507:         }
15508:         if (ref($maxd) eq 'HASH') {
15509:             if ($depth > $maxd->{$parents->[0]}) {
15510:                 $maxd->{$parents->[0]} = $depth;
15511:             }
15512:         }
15513:     }
15514:     return;
15515: }
15516: 
15517: =pod
15518: 
15519: =item * &assign_categories_table()
15520: 
15521: Create a datatable for display of hierarchical categories in a domain,
15522: with checkboxes to allow a course to be categorized. 
15523: 
15524: Inputs:
15525: 
15526: cathash - reference to hash of categories defined for the domain (from
15527:           configuration.db)
15528: 
15529: currcat - scalar with an & separated list of categories assigned to a course. 
15530: 
15531: type    - scalar contains course type (Course or Community).
15532: 
15533: disabled - scalar (optional) contains disabled="disabled" if input elements are
15534:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
15535: 
15536: Returns: $output (markup to be displayed) 
15537: 
15538: =cut
15539: 
15540: sub assign_categories_table {
15541:     my ($cathash,$currcat,$type,$disabled) = @_;
15542:     my $output;
15543:     if (ref($cathash) eq 'HASH') {
15544:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
15545:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
15546:         $maxdepth = scalar(@cats);
15547:         if (@cats > 0) {
15548:             my $itemcount = 0;
15549:             if (ref($cats[0]) eq 'ARRAY') {
15550:                 my @currcategories;
15551:                 if ($currcat ne '') {
15552:                     @currcategories = split('&',$currcat);
15553:                 }
15554:                 my $table;
15555:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
15556:                     my $parent = $cats[0][$i];
15557:                     next if ($parent eq 'instcode');
15558:                     if ($type eq 'Community') {
15559:                         next unless ($parent eq 'communities');
15560:                     } else {
15561:                         next if ($parent eq 'communities');
15562:                     }
15563:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
15564:                     my $item = &escape($parent).'::0';
15565:                     my $checked = '';
15566:                     if (@currcategories > 0) {
15567:                         if (grep(/^\Q$item\E$/,@currcategories)) {
15568:                             $checked = ' checked="checked"';
15569:                         }
15570:                     }
15571:                     my $parent_title = $parent;
15572:                     if ($parent eq 'communities') {
15573:                         $parent_title = &mt('Communities');
15574:                     }
15575:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
15576:                               '<input type="checkbox" name="usecategory" value="'.
15577:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
15578:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
15579:                     my $depth = 1;
15580:                     push(@path,$parent);
15581:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
15582:                     pop(@path);
15583:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
15584:                     $itemcount ++;
15585:                 }
15586:                 if ($itemcount) {
15587:                     $output = &Apache::loncommon::start_data_table().
15588:                               $table.
15589:                               &Apache::loncommon::end_data_table();
15590:                 }
15591:             }
15592:         }
15593:     }
15594:     return $output;
15595: }
15596: 
15597: =pod
15598: 
15599: =item * &assign_category_rows()
15600: 
15601: Create a datatable row for display of nested categories in a domain,
15602: with checkboxes to allow a course to be categorized,called recursively.
15603: 
15604: Inputs:
15605: 
15606: itemcount - track row number for alternating colors
15607: 
15608: cats - reference to array of arrays/hashes which encapsulates hierarchy of
15609:       categories and subcategories.
15610: 
15611: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
15612: 
15613: parent - parent of current category item
15614: 
15615: path - Array containing all categories back up through the hierarchy from the
15616:        current category to the top level.
15617: 
15618: currcategories - reference to array of current categories assigned to the course
15619: 
15620: disabled - scalar (optional) contains disabled="disabled" if input elements are
15621:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
15622: 
15623: Returns: $output (markup to be displayed).
15624: 
15625: =cut
15626: 
15627: sub assign_category_rows {
15628:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
15629:     my ($text,$name,$item,$chgstr);
15630:     if (ref($cats) eq 'ARRAY') {
15631:         my $maxdepth = scalar(@{$cats});
15632:         if (ref($cats->[$depth]) eq 'HASH') {
15633:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
15634:                 my $numchildren = @{$cats->[$depth]{$parent}};
15635:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
15636:                 $text .= '<td><table class="LC_data_table">';
15637:                 for (my $j=0; $j<$numchildren; $j++) {
15638:                     $name = $cats->[$depth]{$parent}[$j];
15639:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
15640:                     my $deeper = $depth+1;
15641:                     my $checked = '';
15642:                     if (ref($currcategories) eq 'ARRAY') {
15643:                         if (@{$currcategories} > 0) {
15644:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
15645:                                 $checked = ' checked="checked"';
15646:                             }
15647:                         }
15648:                     }
15649:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
15650:                              '<input type="checkbox" name="usecategory" value="'.
15651:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
15652:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
15653:                              '</td><td>';
15654:                     if (ref($path) eq 'ARRAY') {
15655:                         push(@{$path},$name);
15656:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
15657:                         pop(@{$path});
15658:                     }
15659:                     $text .= '</td></tr>';
15660:                 }
15661:                 $text .= '</table></td>';
15662:             }
15663:         }
15664:     }
15665:     return $text;
15666: }
15667: 
15668: =pod
15669: 
15670: =back
15671: 
15672: =cut
15673: 
15674: ############################################################
15675: ############################################################
15676: 
15677: 
15678: sub commit_customrole {
15679:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
15680:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
15681:                          ($start?', '.&mt('starting').' '.localtime($start):'').
15682:                          ($end?', ending '.localtime($end):'').': <b>'.
15683:               &Apache::lonnet::assigncustomrole(
15684:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
15685:                  '</b><br />';
15686:     return $output;
15687: }
15688: 
15689: sub commit_standardrole {
15690:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
15691:     my ($output,$logmsg,$linefeed);
15692:     if ($context eq 'auto') {
15693:         $linefeed = "\n";
15694:     } else {
15695:         $linefeed = "<br />\n";
15696:     }  
15697:     if ($three eq 'st') {
15698:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
15699:                                          $one,$two,$sec,$context,$credits);
15700:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
15701:             ($result eq 'unknown_course') || ($result eq 'refused')) {
15702:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
15703:         } else {
15704:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
15705:                ($start?', '.&mt('starting').' '.localtime($start):'').
15706:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
15707:             if ($context eq 'auto') {
15708:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
15709:             } else {
15710:                $output .= '<b>'.$result.'</b>'.$linefeed.
15711:                &mt('Add to classlist').': <b>ok</b>';
15712:             }
15713:             $output .= $linefeed;
15714:         }
15715:     } else {
15716:         $output = &mt('Assigning').' '.$three.' in '.$url.
15717:                ($start?', '.&mt('starting').' '.localtime($start):'').
15718:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
15719:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
15720:         if ($context eq 'auto') {
15721:             $output .= $result.$linefeed;
15722:         } else {
15723:             $output .= '<b>'.$result.'</b>'.$linefeed;
15724:         }
15725:     }
15726:     return $output;
15727: }
15728: 
15729: sub commit_studentrole {
15730:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
15731:         $credits) = @_;
15732:     my ($result,$linefeed,$oldsecurl,$newsecurl);
15733:     if ($context eq 'auto') {
15734:         $linefeed = "\n";
15735:     } else {
15736:         $linefeed = '<br />'."\n";
15737:     }
15738:     if (defined($one) && defined($two)) {
15739:         my $cid=$one.'_'.$two;
15740:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
15741:         my $secchange = 0;
15742:         my $expire_role_result;
15743:         my $modify_section_result;
15744:         if ($oldsec ne '-1') { 
15745:             if ($oldsec ne $sec) {
15746:                 $secchange = 1;
15747:                 my $now = time;
15748:                 my $uurl='/'.$cid;
15749:                 $uurl=~s/\_/\//g;
15750:                 if ($oldsec) {
15751:                     $uurl.='/'.$oldsec;
15752:                 }
15753:                 $oldsecurl = $uurl;
15754:                 $expire_role_result = 
15755:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','','',$context);
15756:                 if ($env{'request.course.sec'} ne '') { 
15757:                     if ($expire_role_result eq 'refused') {
15758:                         my @roles = ('st');
15759:                         my @statuses = ('previous');
15760:                         my @roledoms = ($one);
15761:                         my $withsec = 1;
15762:                         my %roleshash = 
15763:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
15764:                                               \@statuses,\@roles,\@roledoms,$withsec);
15765:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
15766:                             my ($oldstart,$oldend) = 
15767:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
15768:                             if ($oldend > 0 && $oldend <= $now) {
15769:                                 $expire_role_result = 'ok';
15770:                             }
15771:                         }
15772:                     }
15773:                 }
15774:                 $result = $expire_role_result;
15775:             }
15776:         }
15777:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
15778:             $modify_section_result = 
15779:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
15780:                                                            undef,undef,undef,$sec,
15781:                                                            $end,$start,'','',$cid,
15782:                                                            '',$context,$credits);
15783:             if ($modify_section_result =~ /^ok/) {
15784:                 if ($secchange == 1) {
15785:                     if ($sec eq '') {
15786:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
15787:                     } else {
15788:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
15789:                     }
15790:                 } elsif ($oldsec eq '-1') {
15791:                     if ($sec eq '') {
15792:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
15793:                     } else {
15794:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
15795:                     }
15796:                 } else {
15797:                     if ($sec eq '') {
15798:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
15799:                     } else {
15800:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
15801:                     }
15802:                 }
15803:             } else {
15804:                 if ($secchange) {       
15805:                     $$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;
15806:                 } else {
15807:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
15808:                 }
15809:             }
15810:             $result = $modify_section_result;
15811:         } elsif ($secchange == 1) {
15812:             if ($oldsec eq '') {
15813:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
15814:             } else {
15815:                 $$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;
15816:             }
15817:             if ($expire_role_result eq 'refused') {
15818:                 my $newsecurl = '/'.$cid;
15819:                 $newsecurl =~ s/\_/\//g;
15820:                 if ($sec ne '') {
15821:                     $newsecurl.='/'.$sec;
15822:                 }
15823:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
15824:                     if ($sec eq '') {
15825:                         $$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;
15826:                     } else {
15827:                         $$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;
15828:                     }
15829:                 }
15830:             }
15831:         }
15832:     } else {
15833:         $$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;
15834:         $result = "error: incomplete course id\n";
15835:     }
15836:     return $result;
15837: }
15838: 
15839: sub show_role_extent {
15840:     my ($scope,$context,$role) = @_;
15841:     $scope =~ s{^/}{};
15842:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
15843:     push(@courseroles,'co');
15844:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
15845:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
15846:         $scope =~ s{/}{_};
15847:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
15848:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
15849:         my ($audom,$auname) = split(/\//,$scope);
15850:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
15851:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
15852:     } else {
15853:         $scope =~ s{/$}{};
15854:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
15855:                    &Apache::lonnet::domain($scope,'description').'</span>');
15856:     }
15857: }
15858: 
15859: ############################################################
15860: ############################################################
15861: 
15862: sub check_clone {
15863:     my ($args,$linefeed) = @_;
15864:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
15865:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
15866:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
15867:     my $clonetitle;
15868:     my @clonemsg;
15869:     my $can_clone = 0;
15870:     my $lctype = lc($args->{'crstype'});
15871:     if ($lctype ne 'community') {
15872:         $lctype = 'course';
15873:     }
15874:     if ($clonehome eq 'no_host') {
15875:         if ($args->{'crstype'} eq 'Community') {
15876:             push(@clonemsg,({
15877:                               mt => 'No new community created.',
15878:                               args => [],
15879:                             },
15880:                             {
15881:                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
15882:                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
15883:                             }));
15884:         } else {
15885:             push(@clonemsg,({
15886:                               mt => 'No new course created.',
15887:                               args => [],
15888:                             },
15889:                             {
15890:                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
15891:                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
15892:                             }));
15893:         }
15894:     } else {
15895: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
15896:         $clonetitle = $clonedesc{'description'};
15897:         if ($args->{'crstype'} eq 'Community') {
15898:             if ($clonedesc{'type'} ne 'Community') {
15899:                 push(@clonemsg,({
15900:                                   mt => 'No new community created.',
15901:                                   args => [],
15902:                                 },
15903:                                 {
15904:                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
15905:                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
15906:                                 }));
15907:                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
15908:             }
15909:         }
15910: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
15911:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
15912: 	    $can_clone = 1;
15913: 	} else {
15914: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
15915: 						 $args->{'clonedomain'},$args->{'clonecourse'});
15916:             if ($clonehash{'cloners'} eq '') {
15917:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
15918:                 if ($domdefs{'canclone'}) {
15919:                     unless ($domdefs{'canclone'} eq 'none') {
15920:                         if ($domdefs{'canclone'} eq 'domain') {
15921:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
15922:                                 $can_clone = 1;
15923:                             }
15924:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
15925:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
15926:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
15927:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
15928:                                 $can_clone = 1;
15929:                             }
15930:                         }
15931:                     }
15932:                 }
15933:             } else {
15934: 	        my @cloners = split(/,/,$clonehash{'cloners'});
15935:                 if (grep(/^\*$/,@cloners)) {
15936:                     $can_clone = 1;
15937:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
15938:                     $can_clone = 1;
15939:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
15940:                     $can_clone = 1;
15941:                 }
15942:                 unless ($can_clone) {
15943:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
15944:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
15945:                         my (%gotdomdefaults,%gotcodedefaults);
15946:                         foreach my $cloner (@cloners) {
15947:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
15948:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
15949:                                 my (%codedefaults,@code_order);
15950:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
15951:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
15952:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
15953:                                     }
15954:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
15955:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
15956:                                     }
15957:                                 } else {
15958:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
15959:                                                                             \%codedefaults,
15960:                                                                             \@code_order);
15961:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
15962:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
15963:                                 }
15964:                                 if (@code_order > 0) {
15965:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
15966:                                                                                 $cloner,$clonehash{'internal.coursecode'},
15967:                                                                                 $args->{'crscode'})) {
15968:                                         $can_clone = 1;
15969:                                         last;
15970:                                     }
15971:                                 }
15972:                             }
15973:                         }
15974:                     }
15975:                 }
15976:             }
15977:             unless ($can_clone) {
15978:                 my $ccrole = 'cc';
15979:                 if ($args->{'crstype'} eq 'Community') {
15980:                     $ccrole = 'co';
15981:                 }
15982:                 my %roleshash =
15983:                     &Apache::lonnet::get_my_roles($args->{'ccuname'},
15984:                                                   $args->{'ccdomain'},
15985:                                                   'userroles',['active'],[$ccrole],
15986:                                                   [$args->{'clonedomain'}]);
15987:                 if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
15988:                     $can_clone = 1;
15989:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
15990:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
15991:                     $can_clone = 1;
15992:                 }
15993:             }
15994:             unless ($can_clone) {
15995:                 if ($args->{'crstype'} eq 'Community') {
15996:                     push(@clonemsg,({
15997:                                       mt => 'No new community created.',
15998:                                       args => [],
15999:                                     },
16000:                                     {
16001:                                       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]).',
16002:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
16003:                                     }));
16004:                 } else {
16005:                     push(@clonemsg,({
16006:                                       mt => 'No new course created.',
16007:                                       args => [],
16008:                                     },
16009:                                     {
16010:                                       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]).',
16011:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
16012:                                     }));
16013: 	        }
16014: 	    }
16015:         }
16016:     }
16017:     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
16018: }
16019: 
16020: sub construct_course {
16021:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
16022:         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
16023:     my ($outcome,$msgref,$clonemsgref);
16024:     my $linefeed =  '<br />'."\n";
16025:     if ($context eq 'auto') {
16026:         $linefeed = "\n";
16027:     }
16028: 
16029: #
16030: # Are we cloning?
16031: #
16032:     my ($can_clone,$cloneid,$clonehome,$clonetitle);
16033:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
16034: 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
16035:         if (!$can_clone) {
16036: 	    return (0,$outcome,$clonemsgref);
16037: 	}
16038:     }
16039: 
16040: #
16041: # Open course
16042: #
16043:     my $crstype = lc($args->{'crstype'});
16044:     my %cenv=();
16045:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
16046:                                              $args->{'cdescr'},
16047:                                              $args->{'curl'},
16048:                                              $args->{'course_home'},
16049:                                              $args->{'nonstandard'},
16050:                                              $args->{'crscode'},
16051:                                              $args->{'ccuname'}.':'.
16052:                                              $args->{'ccdomain'},
16053:                                              $args->{'crstype'},
16054:                                              $cnum,$context,$category,
16055:                                              $callercontext);
16056: 
16057:     # Note: The testing routines depend on this being output; see 
16058:     # Utils::Course. This needs to at least be output as a comment
16059:     # if anyone ever decides to not show this, and Utils::Course::new
16060:     # will need to be suitably modified.
16061:     if (($callercontext eq 'auto') && ($user_lh ne '')) {
16062:         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
16063:     } else {
16064:         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
16065:     }
16066:     if ($$courseid =~ /^error:/) {
16067:         return (0,$outcome,$clonemsgref);
16068:     }
16069: 
16070: #
16071: # Check if created correctly
16072: #
16073:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
16074:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
16075:     if ($crsuhome eq 'no_host') {
16076:         if (($callercontext eq 'auto') && ($user_lh ne '')) {
16077:             $outcome .= &mt_user($user_lh,
16078:                             'Course creation failed, unrecognized course home server.');
16079:         } else {
16080:             $outcome .= &mt('Course creation failed, unrecognized course home server.');
16081:         }
16082:         $outcome .= $linefeed;
16083:         return (0,$outcome,$clonemsgref);
16084:     }
16085:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
16086: 
16087: #
16088: # Do the cloning
16089: #
16090:     my @clonemsg;
16091:     if ($can_clone && $cloneid) {
16092:         push(@clonemsg,
16093:                       {
16094:                           mt => 'Created [_1] by cloning from [_2]',
16095:                           args => [$crstype,$clonetitle],
16096:                       });
16097: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
16098: # Copy all files
16099:         my @info =
16100:             &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
16101:                                                      $args->{'dateshift'},$args->{'crscode'},
16102:                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
16103:                                                      $args->{'tinyurls'});
16104:         if (@info) {
16105:             push(@clonemsg,@info);
16106:         }
16107: # Restore URL
16108: 	$cenv{'url'}=$oldcenv{'url'};
16109: # Restore title
16110: 	$cenv{'description'}=$oldcenv{'description'};
16111: # Restore creation date, creator and creation context.
16112:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
16113:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
16114:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
16115: # Mark as cloned
16116: 	$cenv{'clonedfrom'}=$cloneid;
16117: # Need to clone grading mode
16118:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
16119:         $cenv{'grading'}=$newenv{'grading'};
16120: # Do not clone these environment entries
16121:         &Apache::lonnet::del('environment',
16122:                   ['default_enrollment_start_date',
16123:                    'default_enrollment_end_date',
16124:                    'question.email',
16125:                    'policy.email',
16126:                    'comment.email',
16127:                    'pch.users.denied',
16128:                    'plc.users.denied',
16129:                    'hidefromcat',
16130:                    'checkforpriv',
16131:                    'categories'],
16132:                    $$crsudom,$$crsunum);
16133:         if ($args->{'textbook'}) {
16134:             $cenv{'internal.textbook'} = $args->{'textbook'};
16135:         }
16136:     }
16137: 
16138: #
16139: # Set environment (will override cloned, if existing)
16140: #
16141:     my @sections = ();
16142:     my @xlists = ();
16143:     if ($args->{'crstype'}) {
16144:         $cenv{'type'}=$args->{'crstype'};
16145:     }
16146:     if ($args->{'crsid'}) {
16147:         $cenv{'courseid'}=$args->{'crsid'};
16148:     }
16149:     if ($args->{'crscode'}) {
16150:         $cenv{'internal.coursecode'}=$args->{'crscode'};
16151:     }
16152:     if ($args->{'crsquota'} ne '') {
16153:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
16154:     } else {
16155:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
16156:     }
16157:     if ($args->{'ccuname'}) {
16158:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
16159:                                         ':'.$args->{'ccdomain'};
16160:     } else {
16161:         $cenv{'internal.courseowner'} = $args->{'curruser'};
16162:     }
16163:     if ($args->{'defaultcredits'}) {
16164:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
16165:     }
16166:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
16167:     if ($args->{'crssections'}) {
16168:         $cenv{'internal.sectionnums'} = '';
16169:         if ($args->{'crssections'} =~ m/,/) {
16170:             @sections = split/,/,$args->{'crssections'};
16171:         } else {
16172:             $sections[0] = $args->{'crssections'};
16173:         }
16174:         if (@sections > 0) {
16175:             foreach my $item (@sections) {
16176:                 my ($sec,$gp) = split/:/,$item;
16177:                 my $class = $args->{'crscode'}.$sec;
16178:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
16179:                 $cenv{'internal.sectionnums'} .= $item.',';
16180:                 unless ($addcheck eq 'ok') {
16181:                     push(@badclasses,$class);
16182:                 }
16183:             }
16184:             $cenv{'internal.sectionnums'} =~ s/,$//;
16185:         }
16186:     }
16187: # do not hide course coordinator from staff listing, 
16188: # even if privileged
16189:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16190: # add course coordinator's domain to domains to check for privileged users
16191: # if different to course domain
16192:     if ($$crsudom ne $args->{'ccdomain'}) {
16193:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
16194:     }
16195: # add crosslistings
16196:     if ($args->{'crsxlist'}) {
16197:         $cenv{'internal.crosslistings'}='';
16198:         if ($args->{'crsxlist'} =~ m/,/) {
16199:             @xlists = split/,/,$args->{'crsxlist'};
16200:         } else {
16201:             $xlists[0] = $args->{'crsxlist'};
16202:         }
16203:         if (@xlists > 0) {
16204:             foreach my $item (@xlists) {
16205:                 my ($xl,$gp) = split/:/,$item;
16206:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
16207:                 $cenv{'internal.crosslistings'} .= $item.',';
16208:                 unless ($addcheck eq 'ok') {
16209:                     push(@badclasses,$xl);
16210:                 }
16211:             }
16212:             $cenv{'internal.crosslistings'} =~ s/,$//;
16213:         }
16214:     }
16215:     if ($args->{'autoadds'}) {
16216:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
16217:     }
16218:     if ($args->{'autodrops'}) {
16219:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
16220:     }
16221: # check for notification of enrollment changes
16222:     my @notified = ();
16223:     if ($args->{'notify_owner'}) {
16224:         if ($args->{'ccuname'} ne '') {
16225:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
16226:         }
16227:     }
16228:     if ($args->{'notify_dc'}) {
16229:         if ($uname ne '') { 
16230:             push(@notified,$uname.':'.$udom);
16231:         }
16232:     }
16233:     if (@notified > 0) {
16234:         my $notifylist;
16235:         if (@notified > 1) {
16236:             $notifylist = join(',',@notified);
16237:         } else {
16238:             $notifylist = $notified[0];
16239:         }
16240:         $cenv{'internal.notifylist'} = $notifylist;
16241:     }
16242:     if (@badclasses > 0) {
16243:         my %lt=&Apache::lonlocal::texthash(
16244:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
16245:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
16246:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
16247:         );
16248:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
16249:                            &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'};
16250:         if ($context eq 'auto') {
16251:             $outcome .= $badclass_msg.$linefeed;
16252:         } else {
16253:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
16254:         }
16255:         foreach my $item (@badclasses) {
16256:             if ($context eq 'auto') {
16257:                 $outcome .= " - $item\n";
16258:             } else {
16259:                 $outcome .= "<li>$item</li>\n";
16260:             }
16261:         }
16262:         if ($context eq 'auto') {
16263:             $outcome .= $linefeed;
16264:         } else {
16265:             $outcome .= "</ul><br /><br /></div>\n";
16266:         }
16267:     }
16268:     if ($args->{'no_end_date'}) {
16269:         $args->{'endaccess'} = 0;
16270:     }
16271:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
16272:     $cenv{'internal.autoend'}=$args->{'enrollend'};
16273:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
16274:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
16275:     if ($args->{'showphotos'}) {
16276:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
16277:     }
16278:     $cenv{'internal.authtype'} = $args->{'authtype'};
16279:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
16280:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
16281:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
16282:             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'); 
16283:             if ($context eq 'auto') {
16284:                 $outcome .= $krb_msg;
16285:             } else {
16286:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
16287:             }
16288:             $outcome .= $linefeed;
16289:         }
16290:     }
16291:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
16292:        if ($args->{'setpolicy'}) {
16293:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16294:        }
16295:        if ($args->{'setcontent'}) {
16296:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16297:        }
16298:        if ($args->{'setcomment'}) {
16299:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16300:        }
16301:     }
16302:     if ($args->{'reshome'}) {
16303: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
16304: 	$cenv{'reshome'}=~s/\/+$/\//;
16305:     }
16306: #
16307: # course has keyed access
16308: #
16309:     if ($args->{'setkeys'}) {
16310:        $cenv{'keyaccess'}='yes';
16311:     }
16312: # if specified, key authority is not course, but user
16313: # only active if keyaccess is yes
16314:     if ($args->{'keyauth'}) {
16315: 	my ($user,$domain) = split(':',$args->{'keyauth'});
16316: 	$user = &LONCAPA::clean_username($user);
16317: 	$domain = &LONCAPA::clean_username($domain);
16318: 	if ($user ne '' && $domain ne '') {
16319: 	    $cenv{'keyauth'}=$user.':'.$domain;
16320: 	}
16321:     }
16322: 
16323: #
16324: #  generate and store uniquecode (available to course requester), if course should have one.
16325: #
16326:     if ($args->{'uniquecode'}) {
16327:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
16328:         if ($code) {
16329:             $cenv{'internal.uniquecode'} = $code;
16330:             my %crsinfo =
16331:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
16332:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
16333:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
16334:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
16335:             }
16336:             if (ref($coderef)) {
16337:                 $$coderef = $code;
16338:             }
16339:         }
16340:     }
16341: 
16342:     if ($args->{'disresdis'}) {
16343:         $cenv{'pch.roles.denied'}='st';
16344:     }
16345:     if ($args->{'disablechat'}) {
16346:         $cenv{'plc.roles.denied'}='st';
16347:     }
16348: 
16349:     # Record we've not yet viewed the Course Initialization Helper for this 
16350:     # course
16351:     $cenv{'course.helper.not.run'} = 1;
16352:     #
16353:     # Use new Randomseed
16354:     #
16355:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
16356:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
16357:     #
16358:     # The encryption code and receipt prefix for this course
16359:     #
16360:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
16361:     $cenv{'internal.encpref'}=100+int(9*rand(99));
16362:     #
16363:     # By default, use standard grading
16364:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
16365: 
16366:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
16367:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
16368: #
16369: # Open all assignments
16370: #
16371:     if ($args->{'openall'}) {
16372:        my $opendate = time;
16373:        if ($args->{'openallfrom'} =~ /^\d+$/) {
16374:            $opendate = $args->{'openallfrom'};
16375:        }
16376:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
16377:        my %storecontent = ($storeunder         => $opendate,
16378:                            $storeunder.'.type' => 'date_start');
16379:        $outcome .= &mt('All assignments open starting [_1]',
16380:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
16381:                    &Apache::lonnet::cput
16382:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
16383:    }
16384: #
16385: # Set first page
16386: #
16387:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
16388: 	    || ($cloneid)) {
16389: 	$outcome .= &mt('Setting first resource').': ';
16390: 
16391: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
16392:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
16393: 
16394:         $outcome .= ($fatal?$errtext:'read ok').' - ';
16395:         my $title; my $url;
16396:         if ($args->{'firstres'} eq 'syl') {
16397: 	    $title=&mt('Syllabus');
16398:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
16399:         } else {
16400:             $title=&mt('Table of Contents');
16401:             $url='/adm/navmaps';
16402:         }
16403: 
16404:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
16405: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
16406: 
16407: 	if ($errtext) { $fatal=2; }
16408:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
16409:     }
16410: 
16411:     return (1,$outcome,\@clonemsg);
16412: }
16413: 
16414: sub make_unique_code {
16415:     my ($cdom,$cnum) = @_;
16416:     # get lock on uniquecodes db
16417:     my $lockhash = {
16418:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
16419:                                                   ':'.$env{'user.domain'},
16420:                    };
16421:     my $tries = 0;
16422:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
16423:     my ($code,$error);
16424: 
16425:     while (($gotlock ne 'ok') && ($tries<3)) {
16426:         $tries ++;
16427:         sleep 1;
16428:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
16429:     }
16430:     if ($gotlock eq 'ok') {
16431:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
16432:         my $gotcode;
16433:         my $attempts = 0;
16434:         while ((!$gotcode) && ($attempts < 100)) {
16435:             $code = &generate_code();
16436:             if (!exists($currcodes{$code})) {
16437:                 $gotcode = 1;
16438:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
16439:                     $error = 'nostore';
16440:                 }
16441:             }
16442:             $attempts ++;
16443:         }
16444:         my @del_lock = ($cnum."\0".'uniquecodes');
16445:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
16446:     } else {
16447:         $error = 'nolock';
16448:     }
16449:     return ($code,$error);
16450: }
16451: 
16452: sub generate_code {
16453:     my $code;
16454:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
16455:     for (my $i=0; $i<6; $i++) {
16456:         my $lettnum = int (rand 2);
16457:         my $item = '';
16458:         if ($lettnum) {
16459:             $item = $letts[int( rand(18) )];
16460:         } else {
16461:             $item = 1+int( rand(8) );
16462:         }
16463:         $code .= $item;
16464:     }
16465:     return $code;
16466: }
16467: 
16468: ############################################################
16469: ############################################################
16470: 
16471: #SD
16472: # only Community and Course, or anything else?
16473: sub course_type {
16474:     my ($cid) = @_;
16475:     if (!defined($cid)) {
16476:         $cid = $env{'request.course.id'};
16477:     }
16478:     if (defined($env{'course.'.$cid.'.type'})) {
16479:         return $env{'course.'.$cid.'.type'};
16480:     } else {
16481:         return 'Course';
16482:     }
16483: }
16484: 
16485: sub group_term {
16486:     my $crstype = &course_type();
16487:     my %names = (
16488:                   'Course' => 'group',
16489:                   'Community' => 'group',
16490:                 );
16491:     return $names{$crstype};
16492: }
16493: 
16494: sub course_types {
16495:     my @types = ('official','unofficial','community','textbook');
16496:     my %typename = (
16497:                          official   => 'Official course',
16498:                          unofficial => 'Unofficial course',
16499:                          community  => 'Community',
16500:                          textbook   => 'Textbook course',
16501:                    );
16502:     return (\@types,\%typename);
16503: }
16504: 
16505: sub icon {
16506:     my ($file)=@_;
16507:     my $curfext = lc((split(/\./,$file))[-1]);
16508:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
16509:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
16510:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
16511: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
16512: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
16513: 	            $curfext.".gif") {
16514: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
16515: 		$curfext.".gif";
16516: 	}
16517:     }
16518:     return &lonhttpdurl($iconname);
16519: } 
16520: 
16521: sub lonhttpdurl {
16522: #
16523: # Had been used for "small fry" static images on separate port 8080.
16524: # Modify here if lightweight http functionality desired again.
16525: # Currently eliminated due to increasing firewall issues.
16526: #
16527:     my ($url)=@_;
16528:     return $url;
16529: }
16530: 
16531: sub connection_aborted {
16532:     my ($r)=@_;
16533:     $r->print(" ");$r->rflush();
16534:     my $c = $r->connection;
16535:     return $c->aborted();
16536: }
16537: 
16538: #    Escapes strings that may have embedded 's that will be put into
16539: #    strings as 'strings'.
16540: sub escape_single {
16541:     my ($input) = @_;
16542:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
16543:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
16544:     return $input;
16545: }
16546: 
16547: #  Same as escape_single, but escape's "'s  This 
16548: #  can be used for  "strings"
16549: sub escape_double {
16550:     my ($input) = @_;
16551:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
16552:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
16553:     return $input;
16554: }
16555:  
16556: #   Escapes the last element of a full URL.
16557: sub escape_url {
16558:     my ($url)   = @_;
16559:     my @urlslices = split(/\//, $url,-1);
16560:     my $lastitem = &escape(pop(@urlslices));
16561:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
16562: }
16563: 
16564: sub compare_arrays {
16565:     my ($arrayref1,$arrayref2) = @_;
16566:     my (@difference,%count);
16567:     @difference = ();
16568:     %count = ();
16569:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
16570:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
16571:         foreach my $element (keys(%count)) {
16572:             if ($count{$element} == 1) {
16573:                 push(@difference,$element);
16574:             }
16575:         }
16576:     }
16577:     return @difference;
16578: }
16579: 
16580: sub lon_status_items {
16581:     my %defaults = (
16582:                      E         => 100,
16583:                      W         => 4,
16584:                      N         => 1,
16585:                      U         => 5,
16586:                      threshold => 200,
16587:                      sysmail   => 2500,
16588:                    );
16589:     my %names = (
16590:                    E => 'Errors',
16591:                    W => 'Warnings',
16592:                    N => 'Notices',
16593:                    U => 'Unsent',
16594:                 );
16595:     return (\%defaults,\%names);
16596: }
16597: 
16598: # -------------------------------------------------------- Initialize user login
16599: sub init_user_environment {
16600:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
16601:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
16602: 
16603:     my $public=($username eq 'public' && $domain eq 'public');
16604: 
16605: # See if old ID present, if so, remove
16606: 
16607:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
16608:     my $now=time;
16609: 
16610:     if ($public) {
16611: 	my $max_public=100;
16612: 	my $oldest;
16613: 	my $oldest_time=0;
16614: 	for(my $next=1;$next<=$max_public;$next++) {
16615: 	    if (-e $lonids."/publicuser_$next.id") {
16616: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
16617: 		if ($mtime<$oldest_time || !$oldest_time) {
16618: 		    $oldest_time=$mtime;
16619: 		    $oldest=$next;
16620: 		}
16621: 	    } else {
16622: 		$cookie="publicuser_$next";
16623: 		last;
16624: 	    }
16625: 	}
16626: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
16627:     } else {
16628: 	# if this isn't a robot, kill any existing non-robot sessions
16629: 	if (!$args->{'robot'}) {
16630: 	    opendir(DIR,$lonids);
16631: 	    while ($filename=readdir(DIR)) {
16632: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
16633:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
16634:                             &GDBM_READER(),0640)) {
16635:                         my $linkedfile;
16636:                         if (exists($oldenv{'user.linkedenv'})) {
16637:                             $linkedfile = $oldenv{'user.linkedenv'};
16638:                         }
16639:                         untie(%oldenv);
16640:                         if (unlink("$lonids/$filename")) {
16641:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
16642:                                 if (-l "$lonids/$linkedfile.id") {
16643:                                     unlink("$lonids/$linkedfile.id");
16644:                                 }
16645:                             }
16646:                         }
16647:                     } else {
16648:                         unlink($lonids.'/'.$filename);
16649:                     }
16650: 		}
16651: 	    }
16652: 	    closedir(DIR);
16653: # If there is a undeleted lockfile for the user's paste buffer remove it.
16654:             my $namespace = 'nohist_courseeditor';
16655:             my $lockingkey = 'paste'."\0".'locked_num';
16656:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
16657:                                                 $domain,$username);
16658:             if (exists($lockhash{$lockingkey})) {
16659:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
16660:                 unless ($delresult eq 'ok') {
16661:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
16662:                 }
16663:             }
16664: 	}
16665: # Give them a new cookie
16666: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
16667: 		                   : $now.$$.int(rand(10000)));
16668: 	$cookie="$username\_$id\_$domain\_$authhost";
16669:     
16670: # Initialize roles
16671: 
16672: 	($userroles,$firstaccenv,$timerintenv) = 
16673:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
16674:     }
16675: # ------------------------------------ Check browser type and MathML capability
16676: 
16677:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
16678:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
16679: 
16680: # ------------------------------------------------------------- Get environment
16681: 
16682:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
16683:     my ($tmp) = keys(%userenv);
16684:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
16685:     } else {
16686: 	undef(%userenv);
16687:     }
16688:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
16689: 	$form->{'interface'}=$userenv{'interface'};
16690:     }
16691:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
16692: 
16693: # --------------- Do not trust query string to be put directly into environment
16694:     foreach my $option ('interface','localpath','localres') {
16695:         $form->{$option}=~s/[\n\r\=]//gs;
16696:     }
16697: # --------------------------------------------------------- Write first profile
16698: 
16699:     {
16700:         my $ip = &Apache::lonnet::get_requestor_ip();
16701: 	my %initial_env = 
16702: 	    ("user.name"          => $username,
16703: 	     "user.domain"        => $domain,
16704: 	     "user.home"          => $authhost,
16705: 	     "browser.type"       => $clientbrowser,
16706: 	     "browser.version"    => $clientversion,
16707: 	     "browser.mathml"     => $clientmathml,
16708: 	     "browser.unicode"    => $clientunicode,
16709: 	     "browser.os"         => $clientos,
16710:              "browser.mobile"     => $clientmobile,
16711:              "browser.info"       => $clientinfo,
16712:              "browser.osversion"  => $clientosversion,
16713: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
16714: 	     "request.course.fn"  => '',
16715: 	     "request.course.uri" => '',
16716: 	     "request.course.sec" => '',
16717: 	     "request.role"       => 'cm',
16718: 	     "request.role.adv"   => $env{'user.adv'},
16719: 	     "request.host"       => $ip,);
16720: 
16721:         if ($form->{'localpath'}) {
16722: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
16723: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
16724:         }
16725: 	
16726: 	if ($form->{'interface'}) {
16727: 	    $form->{'interface'}=~s/\W//gs;
16728: 	    $initial_env{"browser.interface"} = $form->{'interface'};
16729: 	    $env{'browser.interface'}=$form->{'interface'};
16730: 	}
16731: 
16732:         if ($form->{'iptoken'}) {
16733:             my $lonhost = $r->dir_config('lonHostID');
16734:             $initial_env{"user.noloadbalance"} = $lonhost;
16735:             $env{'user.noloadbalance'} = $lonhost;
16736:         }
16737: 
16738:         if ($form->{'noloadbalance'}) {
16739:             my @hosts = &Apache::lonnet::current_machine_ids();
16740:             my $hosthere = $form->{'noloadbalance'};
16741:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
16742:                 $initial_env{"user.noloadbalance"} = $hosthere;
16743:                 $env{'user.noloadbalance'} = $hosthere;
16744:             }
16745:         }
16746: 
16747:         unless ($domain eq 'public') {
16748:             my %is_adv = ( is_adv => $env{'user.adv'} );
16749:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
16750: 
16751:             foreach my $tool ('aboutme','blog','webdav','portfolio','timezone') {
16752:                 $userenv{'availabletools.'.$tool} = 
16753:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
16754:                                                       undef,\%userenv,\%domdef,\%is_adv);
16755:             }
16756: 
16757:             foreach my $crstype ('official','unofficial','community','textbook') {
16758:                 $userenv{'canrequest.'.$crstype} =
16759:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
16760:                                                       'reload','requestcourses',
16761:                                                       \%userenv,\%domdef,\%is_adv);
16762:             }
16763: 
16764:             $userenv{'canrequest.author'} =
16765:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
16766:                                                   'reload','requestauthor',
16767:                                                   \%userenv,\%domdef,\%is_adv);
16768:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
16769:                                                  $domain,$username);
16770:             my $reqstatus = $reqauthor{'author_status'};
16771:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
16772:                 if (ref($reqauthor{'author'}) eq 'HASH') {
16773:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
16774:                                                       $reqauthor{'author'}{'timestamp'};
16775:                 }
16776:             }
16777:         }
16778: 
16779: 	$env{'user.environment'} = "$lonids/$cookie.id";
16780: 
16781: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
16782: 		 &GDBM_WRCREAT(),0640)) {
16783: 	    &_add_to_env(\%disk_env,\%initial_env);
16784: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
16785: 	    &_add_to_env(\%disk_env,$userroles);
16786:             if (ref($firstaccenv) eq 'HASH') {
16787:                 &_add_to_env(\%disk_env,$firstaccenv);
16788:             }
16789:             if (ref($timerintenv) eq 'HASH') {
16790:                 &_add_to_env(\%disk_env,$timerintenv);
16791:             }
16792: 	    if (ref($args->{'extra_env'})) {
16793: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
16794: 	    }
16795: 	    untie(%disk_env);
16796: 	} else {
16797: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
16798: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
16799: 	    return 'error: '.$!;
16800: 	}
16801:     }
16802:     $env{'request.role'}='cm';
16803:     $env{'request.role.adv'}=$env{'user.adv'};
16804:     $env{'browser.type'}=$clientbrowser;
16805: 
16806:     return $cookie;
16807: 
16808: }
16809: 
16810: sub _add_to_env {
16811:     my ($idf,$env_data,$prefix) = @_;
16812:     if (ref($env_data) eq 'HASH') {
16813:         while (my ($key,$value) = each(%$env_data)) {
16814: 	    $idf->{$prefix.$key} = $value;
16815: 	    $env{$prefix.$key}   = $value;
16816:         }
16817:     }
16818: }
16819: 
16820: # --- Get the symbolic name of a problem and the url
16821: sub get_symb {
16822:     my ($request,$silent) = @_;
16823:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
16824:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
16825:     if ($symb eq '') {
16826:         if (!$silent) {
16827:             if (ref($request)) { 
16828:                 $request->print("Unable to handle ambiguous references:$url:.");
16829:             }
16830:             return ();
16831:         }
16832:     }
16833:     &Apache::lonenc::check_decrypt(\$symb);
16834:     return ($symb);
16835: }
16836: 
16837: # --------------------------------------------------------------Get annotation
16838: 
16839: sub get_annotation {
16840:     my ($symb,$enc) = @_;
16841: 
16842:     my $key = $symb;
16843:     if (!$enc) {
16844:         $key =
16845:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
16846:     }
16847:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
16848:     return $annotation{$key};
16849: }
16850: 
16851: sub clean_symb {
16852:     my ($symb,$delete_enc) = @_;
16853: 
16854:     &Apache::lonenc::check_decrypt(\$symb);
16855:     my $enc = $env{'request.enc'};
16856:     if ($delete_enc) {
16857:         delete($env{'request.enc'});
16858:     }
16859: 
16860:     return ($symb,$enc);
16861: }
16862: 
16863: ############################################################
16864: ############################################################
16865: 
16866: =pod
16867: 
16868: =head1 Routines for building display used to search for courses
16869: 
16870: 
16871: =over 4
16872: 
16873: =item * &build_filters()
16874: 
16875: Create markup for a table used to set filters to use when selecting
16876: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
16877: and quotacheck.pl
16878: 
16879: 
16880: Inputs:
16881: 
16882: filterlist - anonymous array of fields to include as potential filters
16883: 
16884: crstype - course type
16885: 
16886: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
16887:               to pop-open a course selector (will contain "extra element").
16888: 
16889: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
16890: 
16891: filter - anonymous hash of criteria and their values
16892: 
16893: action - form action
16894: 
16895: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
16896: 
16897: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
16898: 
16899: cloneruname - username of owner of new course who wants to clone
16900: 
16901: clonerudom - domain of owner of new course who wants to clone
16902: 
16903: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
16904: 
16905: codetitlesref - reference to array of titles of components in institutional codes (official courses)
16906: 
16907: codedom - domain
16908: 
16909: formname - value of form element named "form".
16910: 
16911: fixeddom - domain, if fixed.
16912: 
16913: prevphase - value to assign to form element named "phase" when going back to the previous screen
16914: 
16915: cnameelement - name of form element in form on opener page which will receive title of selected course
16916: 
16917: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
16918: 
16919: cdomelement - name of form element in form on opener page which will receive domain of selected course
16920: 
16921: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
16922: 
16923: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
16924: 
16925: clonewarning - warning message about missing information for intended course owner when DC creates a course
16926: 
16927: 
16928: Returns: $output - HTML for display of search criteria, and hidden form elements.
16929: 
16930: 
16931: Side Effects: None
16932: 
16933: =cut
16934: 
16935: # ---------------------------------------------- search for courses based on last activity etc.
16936: 
16937: sub build_filters {
16938:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
16939:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
16940:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
16941:         $cnameelement,$cnumelement,$cdomelement,$setroles,
16942:         $clonetext,$clonewarning) = @_;
16943:     my ($list,$jscript);
16944:     my $onchange = 'javascript:updateFilters(this)';
16945:     my ($domainselectform,$sincefilterform,$createdfilterform,
16946:         $ownerdomselectform,$persondomselectform,$instcodeform,
16947:         $typeselectform,$instcodetitle);
16948:     if ($formname eq '') {
16949:         $formname = $caller;
16950:     }
16951:     foreach my $item (@{$filterlist}) {
16952:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
16953:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
16954:             if ($item eq 'domainfilter') {
16955:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
16956:             } elsif ($item eq 'coursefilter') {
16957:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
16958:             } elsif ($item eq 'ownerfilter') {
16959:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
16960:             } elsif ($item eq 'ownerdomfilter') {
16961:                 $filter->{'ownerdomfilter'} =
16962:                     &LONCAPA::clean_domain($filter->{$item});
16963:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
16964:                                                        'ownerdomfilter',1);
16965:             } elsif ($item eq 'personfilter') {
16966:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
16967:             } elsif ($item eq 'persondomfilter') {
16968:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
16969:                                                         'persondomfilter',1);
16970:             } else {
16971:                 $filter->{$item} =~ s/\W//g;
16972:             }
16973:             if (!$filter->{$item}) {
16974:                 $filter->{$item} = '';
16975:             }
16976:         }
16977:         if ($item eq 'domainfilter') {
16978:             my $allow_blank = 1;
16979:             if ($formname eq 'portform') {
16980:                 $allow_blank=0;
16981:             } elsif ($formname eq 'studentform') {
16982:                 $allow_blank=0;
16983:             }
16984:             if ($fixeddom) {
16985:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
16986:                                     ' value="'.$codedom.'" />'.
16987:                                     &Apache::lonnet::domain($codedom,'description');
16988:             } else {
16989:                 $domainselectform = &select_dom_form($filter->{$item},
16990:                                                      'domainfilter',
16991:                                                       $allow_blank,'',$onchange);
16992:             }
16993:         } else {
16994:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
16995:         }
16996:     }
16997: 
16998:     # last course activity filter and selection
16999:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
17000: 
17001:     # course created filter and selection
17002:     if (exists($filter->{'createdfilter'})) {
17003:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
17004:     }
17005: 
17006:     my %lt = &Apache::lonlocal::texthash(
17007:                 'cac' => "$crstype Activity",
17008:                 'ccr' => "$crstype Created",
17009:                 'cde' => "$crstype Title",
17010:                 'cdo' => "$crstype Domain",
17011:                 'ins' => 'Institutional Code',
17012:                 'inc' => 'Institutional Categorization',
17013:                 'cow' => "$crstype Owner/Co-owner",
17014:                 'cop' => "$crstype Personnel Includes",
17015:                 'cog' => 'Type',
17016:              );
17017: 
17018:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
17019:         my $typeval = 'Course';
17020:         if ($crstype eq 'Community') {
17021:             $typeval = 'Community';
17022:         }
17023:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
17024:     } else {
17025:         $typeselectform =  '<select name="type" size="1"';
17026:         if ($onchange) {
17027:             $typeselectform .= ' onchange="'.$onchange.'"';
17028:         }
17029:         $typeselectform .= '>'."\n";
17030:         foreach my $posstype ('Course','Community') {
17031:             $typeselectform.='<option value="'.$posstype.'"'.
17032:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
17033:         }
17034:         $typeselectform.="</select>";
17035:     }
17036: 
17037:     my ($cloneableonlyform,$cloneabletitle);
17038:     if (exists($filter->{'cloneableonly'})) {
17039:         my $cloneableon = '';
17040:         my $cloneableoff = ' checked="checked"';
17041:         if ($filter->{'cloneableonly'}) {
17042:             $cloneableon = $cloneableoff;
17043:             $cloneableoff = '';
17044:         }
17045:         $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>';
17046:         if ($formname eq 'ccrs') {
17047:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
17048:         } else {
17049:             $cloneabletitle = &mt('Cloneable by you');
17050:         }
17051:     }
17052:     my $officialjs;
17053:     if ($crstype eq 'Course') {
17054:         if (exists($filter->{'instcodefilter'})) {
17055: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
17056: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
17057:             if ($codedom) {
17058:                 $officialjs = 1;
17059:                 ($instcodeform,$jscript,$$numtitlesref) =
17060:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
17061:                                                                   $officialjs,$codetitlesref);
17062:                 if ($jscript) {
17063:                     $jscript = '<script type="text/javascript">'."\n".
17064:                                '// <![CDATA['."\n".
17065:                                $jscript."\n".
17066:                                '// ]]>'."\n".
17067:                                '</script>'."\n";
17068:                 }
17069:             }
17070:             if ($instcodeform eq '') {
17071:                 $instcodeform =
17072:                     '<input type="text" name="instcodefilter" size="10" value="'.
17073:                     $list->{'instcodefilter'}.'" />';
17074:                 $instcodetitle = $lt{'ins'};
17075:             } else {
17076:                 $instcodetitle = $lt{'inc'};
17077:             }
17078:             if ($fixeddom) {
17079:                 $instcodetitle .= '<br />('.$codedom.')';
17080:             }
17081:         }
17082:     }
17083:     my $output = qq|
17084: <form method="post" name="filterpicker" action="$action">
17085: <input type="hidden" name="form" value="$formname" />
17086: |;
17087:     if ($formname eq 'modifycourse') {
17088:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
17089:                    '<input type="hidden" name="prevphase" value="'.
17090:                    $prevphase.'" />'."\n";
17091:     } elsif ($formname eq 'quotacheck') {
17092:         $output .= qq|
17093: <input type="hidden" name="sortby" value="" />
17094: <input type="hidden" name="sortorder" value="" />
17095: |;
17096:     } else {
17097:         my $name_input;
17098:         if ($cnameelement ne '') {
17099:             $name_input = '<input type="hidden" name="cnameelement" value="'.
17100:                           $cnameelement.'" />';
17101:         }
17102:         $output .= qq|
17103: <input type="hidden" name="cnumelement" value="$cnumelement" />
17104: <input type="hidden" name="cdomelement" value="$cdomelement" />
17105: $name_input
17106: $roleelement
17107: $multelement
17108: $typeelement
17109: |;
17110:         if ($formname eq 'portform') {
17111:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
17112:         }
17113:     }
17114:     if ($fixeddom) {
17115:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
17116:     }
17117:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
17118:     if ($sincefilterform) {
17119:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
17120:                   .$sincefilterform
17121:                   .&Apache::lonhtmlcommon::row_closure();
17122:     }
17123:     if ($createdfilterform) {
17124:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
17125:                   .$createdfilterform
17126:                   .&Apache::lonhtmlcommon::row_closure();
17127:     }
17128:     if ($domainselectform) {
17129:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
17130:                   .$domainselectform
17131:                   .&Apache::lonhtmlcommon::row_closure();
17132:     }
17133:     if ($typeselectform) {
17134:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
17135:             $output .= $typeselectform;
17136:         } else {
17137:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
17138:                       .$typeselectform
17139:                       .&Apache::lonhtmlcommon::row_closure();
17140:         }
17141:     }
17142:     if ($instcodeform) {
17143:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
17144:                   .$instcodeform
17145:                   .&Apache::lonhtmlcommon::row_closure();
17146:     }
17147:     if (exists($filter->{'ownerfilter'})) {
17148:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
17149:                    '<table><tr><td>'.&mt('Username').'<br />'.
17150:                    '<input type="text" name="ownerfilter" size="20" value="'.
17151:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
17152:                    $ownerdomselectform.'</td></tr></table>'.
17153:                    &Apache::lonhtmlcommon::row_closure();
17154:     }
17155:     if (exists($filter->{'personfilter'})) {
17156:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
17157:                    '<table><tr><td>'.&mt('Username').'<br />'.
17158:                    '<input type="text" name="personfilter" size="20" value="'.
17159:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
17160:                    $persondomselectform.'</td></tr></table>'.
17161:                    &Apache::lonhtmlcommon::row_closure();
17162:     }
17163:     if (exists($filter->{'coursefilter'})) {
17164:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
17165:                   .'<input type="text" name="coursefilter" size="25" value="'
17166:                   .$list->{'coursefilter'}.'" />'
17167:                   .&Apache::lonhtmlcommon::row_closure();
17168:     }
17169:     if ($cloneableonlyform) {
17170:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
17171:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
17172:     }
17173:     if (exists($filter->{'descriptfilter'})) {
17174:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
17175:                   .'<input type="text" name="descriptfilter" size="40" value="'
17176:                   .$list->{'descriptfilter'}.'" />'
17177:                   .&Apache::lonhtmlcommon::row_closure(1);
17178:     }
17179:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
17180:                '<input type="hidden" name="updater" value="" />'."\n".
17181:                '<input type="submit" name="gosearch" value="'.
17182:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
17183:     return $jscript.$clonewarning.$output;
17184: }
17185: 
17186: =pod
17187: 
17188: =item * &timebased_select_form()
17189: 
17190: Create markup for a dropdown list used to select a time-based
17191: filter e.g., Course Activity, Course Created, when searching for courses
17192: or communities
17193: 
17194: Inputs:
17195: 
17196: item - name of form element (sincefilter or createdfilter)
17197: 
17198: filter - anonymous hash of criteria and their values
17199: 
17200: Returns: HTML for a select box contained a blank, then six time selections,
17201:          with value set in incoming form variables currently selected.
17202: 
17203: Side Effects: None
17204: 
17205: =cut
17206: 
17207: sub timebased_select_form {
17208:     my ($item,$filter) = @_;
17209:     if (ref($filter) eq 'HASH') {
17210:         $filter->{$item} =~ s/[^\d-]//g;
17211:         if (!$filter->{$item}) { $filter->{$item}=-1; }
17212:         return &select_form(
17213:                             $filter->{$item},
17214:                             $item,
17215:                             {      '-1' => '',
17216:                                 '86400' => &mt('today'),
17217:                                '604800' => &mt('last week'),
17218:                               '2592000' => &mt('last month'),
17219:                               '7776000' => &mt('last three months'),
17220:                              '15552000' => &mt('last six months'),
17221:                              '31104000' => &mt('last year'),
17222:                     'select_form_order' =>
17223:                            ['-1','86400','604800','2592000','7776000',
17224:                             '15552000','31104000']});
17225:     }
17226: }
17227: 
17228: =pod
17229: 
17230: =item * &js_changer()
17231: 
17232: Create script tag containing Javascript used to submit course search form
17233: when course type or domain is changed, and also to hide 'Searching ...' on
17234: page load completion for page showing search result.
17235: 
17236: Inputs: None
17237: 
17238: Returns: markup containing updateFilters() and hideSearching() javascript functions.
17239: 
17240: Side Effects: None
17241: 
17242: =cut
17243: 
17244: sub js_changer {
17245:     return <<ENDJS;
17246: <script type="text/javascript">
17247: // <![CDATA[
17248: function updateFilters(caller) {
17249:     if (typeof(caller) != "undefined") {
17250:         document.filterpicker.updater.value = caller.name;
17251:     }
17252:     document.filterpicker.submit();
17253: }
17254: 
17255: function hideSearching() {
17256:     if (document.getElementById('searching')) {
17257:         document.getElementById('searching').style.display = 'none';
17258:     }
17259:     return;
17260: }
17261: 
17262: // ]]>
17263: </script>
17264: 
17265: ENDJS
17266: }
17267: 
17268: =pod
17269: 
17270: =item * &search_courses()
17271: 
17272: Process selected filters form course search form and pass to lonnet::courseiddump
17273: to retrieve a hash for which keys are courseIDs which match the selected filters.
17274: 
17275: Inputs:
17276: 
17277: dom - domain being searched
17278: 
17279: type - course type ('Course' or 'Community' or '.' if any).
17280: 
17281: filter - anonymous hash of criteria and their values
17282: 
17283: numtitles - for institutional codes - number of categories
17284: 
17285: cloneruname - optional username of new course owner
17286: 
17287: clonerudom - optional domain of new course owner
17288: 
17289: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
17290:             (used when DC is using course creation form)
17291: 
17292: codetitles - reference to array of titles of components in institutional codes (official courses).
17293: 
17294: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
17295:            (and so can clone automatically)
17296: 
17297: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
17298: 
17299: reqinstcode - institutional code of new course, where search_courses is used to identify potential
17300:               courses to clone
17301: 
17302: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
17303: 
17304: 
17305: Side Effects: None
17306: 
17307: =cut
17308: 
17309: 
17310: sub search_courses {
17311:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
17312:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
17313:     my (%courses,%showcourses,$cloner);
17314:     if (($filter->{'ownerfilter'} ne '') ||
17315:         ($filter->{'ownerdomfilter'} ne '')) {
17316:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
17317:                                        $filter->{'ownerdomfilter'};
17318:     }
17319:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
17320:         if (!$filter->{$item}) {
17321:             $filter->{$item}='.';
17322:         }
17323:     }
17324:     my $now = time;
17325:     my $timefilter =
17326:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
17327:     my ($createdbefore,$createdafter);
17328:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
17329:         $createdbefore = $now;
17330:         $createdafter = $now-$filter->{'createdfilter'};
17331:     }
17332:     my ($instcodefilter,$regexpok);
17333:     if ($numtitles) {
17334:         if ($env{'form.official'} eq 'on') {
17335:             $instcodefilter =
17336:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
17337:             $regexpok = 1;
17338:         } elsif ($env{'form.official'} eq 'off') {
17339:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
17340:             unless ($instcodefilter eq '') {
17341:                 $regexpok = -1;
17342:             }
17343:         }
17344:     } else {
17345:         $instcodefilter = $filter->{'instcodefilter'};
17346:     }
17347:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
17348:     if ($type eq '') { $type = '.'; }
17349: 
17350:     if (($clonerudom ne '') && ($cloneruname ne '')) {
17351:         $cloner = $cloneruname.':'.$clonerudom;
17352:     }
17353:     %courses = &Apache::lonnet::courseiddump($dom,
17354:                                              $filter->{'descriptfilter'},
17355:                                              $timefilter,
17356:                                              $instcodefilter,
17357:                                              $filter->{'combownerfilter'},
17358:                                              $filter->{'coursefilter'},
17359:                                              undef,undef,$type,$regexpok,undef,undef,
17360:                                              undef,undef,$cloner,$cc_clone,
17361:                                              $filter->{'cloneableonly'},
17362:                                              $createdbefore,$createdafter,undef,
17363:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
17364:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
17365:         my $ccrole;
17366:         if ($type eq 'Community') {
17367:             $ccrole = 'co';
17368:         } else {
17369:             $ccrole = 'cc';
17370:         }
17371:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
17372:                                                      $filter->{'persondomfilter'},
17373:                                                      'userroles',undef,
17374:                                                      [$ccrole,'in','ad','ep','ta','cr'],
17375:                                                      $dom);
17376:         foreach my $role (keys(%rolehash)) {
17377:             my ($cnum,$cdom,$courserole) = split(':',$role);
17378:             my $cid = $cdom.'_'.$cnum;
17379:             if (exists($courses{$cid})) {
17380:                 if (ref($courses{$cid}) eq 'HASH') {
17381:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
17382:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
17383:                             push(@{$courses{$cid}{roles}},$courserole);
17384:                         }
17385:                     } else {
17386:                         $courses{$cid}{roles} = [$courserole];
17387:                     }
17388:                     $showcourses{$cid} = $courses{$cid};
17389:                 }
17390:             }
17391:         }
17392:         %courses = %showcourses;
17393:     }
17394:     return %courses;
17395: }
17396: 
17397: =pod
17398: 
17399: =back
17400: 
17401: =head1 Routines for version requirements for current course.
17402: 
17403: =over 4
17404: 
17405: =item * &check_release_required()
17406: 
17407: Compares required LON-CAPA version with version on server, and
17408: if required version is newer looks for a server with the required version.
17409: 
17410: Looks first at servers in user's owen domain; if none suitable, looks at
17411: servers in course's domain are permitted to host sessions for user's domain.
17412: 
17413: Inputs:
17414: 
17415: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
17416: 
17417: $courseid - Course ID of current course
17418: 
17419: $rolecode - User's current role in course (for switchserver query string).
17420: 
17421: $required - LON-CAPA version needed by course (format: Major.Minor).
17422: 
17423: 
17424: Returns:
17425: 
17426: $switchserver - query string tp append to /adm/switchserver call (if
17427:                 current server's LON-CAPA version is too old.
17428: 
17429: $warning - Message is displayed if no suitable server could be found.
17430: 
17431: =cut
17432: 
17433: sub check_release_required {
17434:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
17435:     my ($switchserver,$warning);
17436:     if ($required ne '') {
17437:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
17438:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
17439:         if ($reqdmajor ne '' && $reqdminor ne '') {
17440:             my $otherserver;
17441:             if (($major eq '' && $minor eq '') ||
17442:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
17443:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
17444:                 my $switchlcrev =
17445:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
17446:                                                            $userdomserver);
17447:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
17448:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
17449:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
17450:                     my $cdom = $env{'course.'.$courseid.'.domain'};
17451:                     if ($cdom ne $env{'user.domain'}) {
17452:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
17453:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
17454:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
17455:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
17456:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
17457:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
17458:                         my $canhost =
17459:                             &Apache::lonnet::can_host_session($env{'user.domain'},
17460:                                                               $coursedomserver,
17461:                                                               $remoterev,
17462:                                                               $udomdefaults{'remotesessions'},
17463:                                                               $defdomdefaults{'hostedsessions'});
17464: 
17465:                         if ($canhost) {
17466:                             $otherserver = $coursedomserver;
17467:                         } else {
17468:                             $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.");
17469:                         }
17470:                     } else {
17471:                         $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).");
17472:                     }
17473:                 } else {
17474:                     $otherserver = $userdomserver;
17475:                 }
17476:             }
17477:             if ($otherserver ne '') {
17478:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
17479:             }
17480:         }
17481:     }
17482:     return ($switchserver,$warning);
17483: }
17484: 
17485: =pod
17486: 
17487: =item * &check_release_result()
17488: 
17489: Inputs:
17490: 
17491: $switchwarning - Warning message if no suitable server found to host session.
17492: 
17493: $switchserver - query string to append to /adm/switchserver containing lonHostID
17494:                 and current role.
17495: 
17496: Returns: HTML to display with information about requirement to switch server.
17497:          Either displaying warning with link to Roles/Courses screen or
17498:          display link to switchserver.
17499: 
17500: =cut
17501: 
17502: sub check_release_result {
17503:     my ($switchwarning,$switchserver) = @_;
17504:     my $output = &start_page('Selected course unavailable on this server').
17505:                  '<p class="LC_warning">';
17506:     if ($switchwarning) {
17507:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
17508:         if (&show_course()) {
17509:             $output .= &mt('Display courses');
17510:         } else {
17511:             $output .= &mt('Display roles');
17512:         }
17513:         $output .= '</a>';
17514:     } elsif ($switchserver) {
17515:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
17516:                    '<br />'.
17517:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
17518:                    &mt('Switch Server').
17519:                    '</a>';
17520:     }
17521:     $output .= '</p>'.&end_page();
17522:     return $output;
17523: }
17524: 
17525: =pod
17526: 
17527: =item * &needs_coursereinit()
17528: 
17529: Determine if course contents stored for user's session needs to be
17530: refreshed, because content has changed since "Big Hash" last tied.
17531: 
17532: Check for change is made if time last checked is more than 10 minutes ago
17533: (by default).
17534: 
17535: Inputs:
17536: 
17537: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
17538: 
17539: $interval (optional) - Time which may elapse (in s) between last check for content
17540:                        change in current course. (default: 600 s).
17541: 
17542: Returns: an array; first element is:
17543: 
17544: =over 4
17545: 
17546: 'switch' - if content updates mean user's session
17547:            needs to be switched to a server running a newer LON-CAPA version
17548: 
17549: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
17550:            on current server hosting user's session
17551: 
17552: ''       - if no action required.
17553: 
17554: =back
17555: 
17556: If first item element is 'switch':
17557: 
17558: second item is $switchwarning - Warning message if no suitable server found to host session.
17559: 
17560: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
17561:                               and current role.
17562: 
17563: otherwise: no other elements returned.
17564: 
17565: =back
17566: 
17567: =cut
17568: 
17569: sub needs_coursereinit {
17570:     my ($loncaparev,$interval) = @_;
17571:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
17572:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
17573:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
17574:     my $now = time;
17575:     if ($interval eq '') {
17576:         $interval = 600;
17577:     }
17578:     if (($now-$env{'request.course.timechecked'})>$interval) {
17579:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
17580:         my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
17581:         if ($blocked) {
17582:             return ();
17583:         }
17584:         my $update;
17585:         my $lastmainchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
17586:         my $lastsuppchange = &Apache::lonnet::get_suppchange($cdom,$cnum);
17587:         if ($lastmainchange > $env{'request.course.tied'}) {
17588:             my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
17589:             if ($needswitch) {
17590:                 return ('switch',$switchwarning,$switchserver);
17591:             }
17592:             $update = 'main';
17593:         }
17594:         if ($lastsuppchange > $env{'request.course.suppupdated'}) {
17595:             if ($update) {
17596:                 $update = 'both';
17597:             } else {
17598:                 my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
17599:                 if ($needswitch) {
17600:                     return ('switch',$switchwarning,$switchserver);
17601:                 } else {
17602:                     $update = 'supp';
17603:                 }
17604:             }
17605:             return ($update);
17606:         }
17607:     }
17608:     return ();
17609: }
17610: 
17611: sub switch_for_update {
17612:     my ($loncaparev,$cdom,$cnum) = @_;
17613:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
17614:     if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
17615:         my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
17616:         if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
17617:             &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
17618:                                     $curr_reqd_hash{'internal.releaserequired'}});
17619:             my ($switchserver,$switchwarning) =
17620:                 &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
17621:                                         $curr_reqd_hash{'internal.releaserequired'});
17622:             if ($switchwarning ne '' || $switchserver ne '') {
17623:                 return ('switch',$switchwarning,$switchserver);
17624:             }
17625:         }
17626:     }
17627:     return ();
17628: }
17629: 
17630: sub update_content_constraints {
17631:     my ($cdom,$cnum,$chome,$cid) = @_;
17632:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
17633:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
17634:     my %checkresponsetypes;
17635:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
17636:         my ($item,$name,$value) = split(/:/,$key);
17637:         if ($item eq 'resourcetag') {
17638:             if ($name eq 'responsetype') {
17639:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
17640:             }
17641:         }
17642:     }
17643:     my $navmap = Apache::lonnavmaps::navmap->new();
17644:     if (defined($navmap)) {
17645:         my %allresponses;
17646:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
17647:             my %responses = $res->responseTypes();
17648:             foreach my $key (keys(%responses)) {
17649:                 next unless(exists($checkresponsetypes{$key}));
17650:                 $allresponses{$key} += $responses{$key};
17651:             }
17652:         }
17653:         foreach my $key (keys(%allresponses)) {
17654:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
17655:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
17656:                 ($reqdmajor,$reqdminor) = ($major,$minor);
17657:             }
17658:         }
17659:         undef($navmap);
17660:     }
17661:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
17662:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
17663:     }
17664:     return;
17665: }
17666: 
17667: sub allmaps_incourse {
17668:     my ($cdom,$cnum,$chome,$cid) = @_;
17669:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
17670:         $cid = $env{'request.course.id'};
17671:         $cdom = $env{'course.'.$cid.'.domain'};
17672:         $cnum = $env{'course.'.$cid.'.num'};
17673:         $chome = $env{'course.'.$cid.'.home'};
17674:     }
17675:     my %allmaps = ();
17676:     my $lastchange =
17677:         &Apache::lonnet::get_coursechange($cdom,$cnum);
17678:     if ($lastchange > $env{'request.course.tied'}) {
17679:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
17680:         unless ($ferr) {
17681:             &update_content_constraints($cdom,$cnum,$chome,$cid);
17682:         }
17683:     }
17684:     my $navmap = Apache::lonnavmaps::navmap->new();
17685:     if (defined($navmap)) {
17686:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
17687:             $allmaps{$res->src()} = 1;
17688:         }
17689:     }
17690:     return \%allmaps;
17691: }
17692: 
17693: sub parse_supplemental_title {
17694:     my ($title) = @_;
17695: 
17696:     my ($foldertitle,$renametitle);
17697:     if ($title =~ /&amp;&amp;&amp;/) {
17698:         $title = &HTML::Entites::decode($title);
17699:     }
17700:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
17701:         $renametitle=$4;
17702:         my ($time,$uname,$udom) = ($1,$2,$3);
17703:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
17704:         my $name =  &plainname($uname,$udom);
17705:         $name = &HTML::Entities::encode($name,'"<>&\'');
17706:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
17707:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.$name;
17708:         if ($foldertitle ne '') {
17709:             $title .= ': <br />'.$foldertitle;
17710:         }
17711:     }
17712:     if (wantarray) {
17713:         return ($title,$foldertitle,$renametitle);
17714:     }
17715:     return $title;
17716: }
17717: 
17718: sub get_supplemental {
17719:     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
17720:     my $hashid=$cnum.':'.$cdom;
17721:     my ($supplemental,$cached,$set_httprefs);
17722:     unless ($ignorecache) {
17723:         ($supplemental,$cached) = &Apache::lonnet::is_cached_new('supplemental',$hashid);
17724:     }
17725:     unless (defined($cached)) {
17726:         my $chome=&Apache::lonnet::homeserver($cnum,$cdom);
17727:         unless ($chome eq 'no_host') {
17728:             my @order = @LONCAPA::map::order;
17729:             my @resources = @LONCAPA::map::resources;
17730:             my @resparms = @LONCAPA::map::resparms;
17731:             my @zombies = @LONCAPA::map::zombies;
17732:             my ($errors,%ids,%hidden);
17733:             $errors =
17734:                 &recurse_supplemental($cnum,$cdom,'supplemental.sequence',
17735:                                       $errors,$possdel,\%ids,\%hidden);
17736:             @LONCAPA::map::order = @order;
17737:             @LONCAPA::map::resources = @resources;
17738:             @LONCAPA::map::resparms = @resparms;
17739:             @LONCAPA::map::zombies = @zombies;
17740:             $set_httprefs = 1;
17741:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
17742:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
17743:             }
17744:             $supplemental = {
17745:                                ids => \%ids,
17746:                                hidden => \%hidden,
17747:                             };
17748:             &Apache::lonnet::do_cache_new('supplemental',$hashid,$supplemental,600);
17749:         }
17750:     }
17751:     return ($supplemental,$set_httprefs);
17752: }
17753: 
17754: sub recurse_supplemental {
17755:     my ($cnum,$cdom,$suppmap,$errors,$possdel,$suppids,$hiddensupp,$hidden) = @_;
17756:     if (($suppmap) && (ref($suppids) eq 'HASH') && (ref($hiddensupp) eq 'HASH')) {
17757:         my $mapnum;
17758:         if ($suppmap eq 'supplemental.sequence') {
17759:             $mapnum = 0;
17760:         } else {
17761:             ($mapnum) = ($suppmap =~ /^supplemental_(\d+)\.sequence$/);
17762:         }
17763:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
17764:         if ($fatal) {
17765:             $errors ++;
17766:         } else {
17767:             my @order = @LONCAPA::map::order;
17768:             if (@order > 0) {
17769:                 my @resources = @LONCAPA::map::resources;
17770:                 my @resparms = @LONCAPA::map::resparms;
17771:                 foreach my $idx (@order) {
17772:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$resources[$idx]);
17773:                     if (($src ne '') && ($status eq 'res')) {
17774:                         my $id = $mapnum.':'.$idx;
17775:                         push(@{$suppids->{$src}},$id);
17776:                         if (($hidden) || (&get_supp_parameter($resparms[$idx],'parameter_hiddenresource') =~ /^yes/i)) {
17777:                             $hiddensupp->{$id} = 1;
17778:                         }
17779:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
17780:                             $errors = &recurse_supplemental($cnum,$cdom,$1,$errors,$possdel,$suppids,
17781:                                                             $hiddensupp,$hiddensupp->{$id});
17782:                         } else {
17783:                             my $allowed;
17784:                             if (($env{'request.role.adv'}) || (!$hiddensupp->{$id})) {
17785:                                 $allowed = 1;
17786:                             } elsif ($possdel) {
17787:                                 foreach my $item (@{$suppids->{$src}}) {
17788:                                     next if ($item eq $id);
17789:                                     unless ($hiddensupp->{$item}) {
17790:                                        $allowed = 1;
17791:                                        last;
17792:                                     }
17793:                                 }
17794:                                 if ((!$allowed) && (exists($env{'httpref.'.$src}))) {
17795:                                     &Apache::lonnet::delenv('httpref.'.$src);
17796:                                 }
17797:                             }
17798:                             if ($allowed && (!exists($env{'httpref.'.$src}))) {
17799:                                 &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
17800:                             }
17801:                         }
17802:                     }
17803:                 }
17804:             }
17805:         }
17806:     }
17807:     return $errors;
17808: }
17809: 
17810: sub set_supp_httprefs {
17811:     my ($cnum,$cdom,$supplemental,$possdel) = @_;
17812:     if (ref($supplemental) eq 'HASH') {
17813:         if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
17814:             foreach my $src (keys(%{$supplemental->{'ids'}})) {
17815:                 next if ($src =~ /\.sequence$/);
17816:                 if (ref($supplemental->{'ids'}->{$src}) eq 'ARRAY') {
17817:                     my $allowed;
17818:                     if ($env{'request.role.adv'}) {
17819:                         $allowed = 1;
17820:                     } else {
17821:                         foreach my $id (@{$supplemental->{'ids'}->{$src}}) {
17822:                             unless ($supplemental->{'hidden'}->{$id}) {
17823:                                 $allowed = 1;
17824:                                 last;
17825:                             }
17826:                         }
17827:                     }
17828:                     if (exists($env{'httpref.'.$src})) {
17829:                         if ($possdel) {
17830:                             unless ($allowed) {
17831:                                 &Apache::lonnet::delenv('httpref.'.$src);
17832:                             }
17833:                         }
17834:                     } elsif ($allowed) {
17835:                         &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
17836:                     }
17837:                 }
17838:             }
17839:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
17840:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
17841:             }
17842:         }
17843:     }
17844: }
17845: 
17846: sub get_supp_parameter {
17847:     my ($resparm,$name)=@_;
17848:     return if ($resparm eq '');
17849:     my $value=undef;
17850:     my $ptype=undef;
17851:     foreach (split('&&&',$resparm)) {
17852:         my ($thistype,$thisname,$thisvalue)=split('___',$_);
17853:         if ($thisname eq $name) {
17854:             $value=$thisvalue;
17855:             $ptype=$thistype;
17856:         }
17857:     }
17858:     return $value;
17859: }
17860: 
17861: sub symb_to_docspath {
17862:     my ($symb,$navmapref) = @_;
17863:     return unless ($symb && ref($navmapref));
17864:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
17865:     if ($resurl=~/\.(sequence|page)$/) {
17866:         $mapurl=$resurl;
17867:     } elsif ($resurl eq 'adm/navmaps') {
17868:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
17869:     }
17870:     my $mapresobj;
17871:     unless (ref($$navmapref)) {
17872:         $$navmapref = Apache::lonnavmaps::navmap->new();
17873:     }
17874:     if (ref($$navmapref)) {
17875:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
17876:     }
17877:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
17878:     my $type=$2;
17879:     my $path;
17880:     if (ref($mapresobj)) {
17881:         my $pcslist = $mapresobj->map_hierarchy();
17882:         if ($pcslist ne '') {
17883:             foreach my $pc (split(/,/,$pcslist)) {
17884:                 next if ($pc <= 1);
17885:                 my $res = $$navmapref->getByMapPc($pc);
17886:                 if (ref($res)) {
17887:                     my $thisurl = $res->src();
17888:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
17889:                     my $thistitle = $res->title();
17890:                     $path .= '&'.
17891:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
17892:                              &escape($thistitle).
17893:                              ':'.$res->randompick().
17894:                              ':'.$res->randomout().
17895:                              ':'.$res->encrypted().
17896:                              ':'.$res->randomorder().
17897:                              ':'.$res->is_page();
17898:                 }
17899:             }
17900:         }
17901:         $path =~ s/^\&//;
17902:         my $maptitle = $mapresobj->title();
17903:         if ($mapurl eq 'default') {
17904:             $maptitle = 'Main Content';
17905:         }
17906:         $path .= (($path ne '')? '&' : '').
17907:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
17908:                  &escape($maptitle).
17909:                  ':'.$mapresobj->randompick().
17910:                  ':'.$mapresobj->randomout().
17911:                  ':'.$mapresobj->encrypted().
17912:                  ':'.$mapresobj->randomorder().
17913:                  ':'.$mapresobj->is_page();
17914:     } else {
17915:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
17916:         my $ispage = (($type eq 'page')? 1 : '');
17917:         if ($mapurl eq 'default') {
17918:             $maptitle = 'Main Content';
17919:         }
17920:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
17921:                 &escape($maptitle).':::::'.$ispage;
17922:     }
17923:     unless ($mapurl eq 'default') {
17924:         $path = 'default&'.
17925:                 &escape('Main Content').
17926:                 ':::::&'.$path;
17927:     }
17928:     return $path;
17929: }
17930: 
17931: sub validate_folderpath {
17932:     my ($supplementalflag,$allowed,$coursenum,$coursedom) = @_;
17933:     if ($env{'form.folderpath'} ne '') {
17934:         my @items = split(/\&/,$env{'form.folderpath'});
17935:         my ($badpath,$changed,$got_supp,$supppath,%supphidden,%suppids);
17936:         for (my $i=0; $i<@items; $i++) {
17937:             my $odd = $i%2;
17938:             if (($odd) && (!$supplementalflag) && ($items[$i] !~ /^[^:]*:(|\d+):(|1):(|1):(|1):(|1)$/)) {
17939:                 $badpath = 1;
17940:             } elsif ($odd && $supplementalflag) {
17941:                 my $idx = $i-1;
17942:                 if ($items[$i] =~ /^([^:]*)::(|1):::$/) {
17943:                     my $esc_name = $1;
17944:                     if ((!$allowed) || ($items[$idx] eq 'supplemental')) {
17945:                         $supppath .= '&'.$esc_name;
17946:                         $changed = 1;
17947:                     } else {
17948:                         $supppath .= '&'.$items[$i];
17949:                     }
17950:                 } elsif (($allowed) && ($items[$idx] ne 'supplemental')) {
17951:                     $changed = 1;
17952:                     my $is_hidden;
17953:                     unless ($got_supp) {
17954:                         my ($supplemental) = &get_supplemental($coursenum,$coursedom);
17955:                         if (ref($supplemental) eq 'HASH') {
17956:                             if (ref($supplemental->{'hidden'}) eq 'HASH') {
17957:                                 %supphidden = %{$supplemental->{'hidden'}};
17958:                             }
17959:                             if (ref($supplemental->{'ids'}) eq 'HASH') {
17960:                                 %suppids = %{$supplemental->{'ids'}};
17961:                             }
17962:                         }
17963:                         $got_supp = 1;
17964:                     }
17965:                     if (ref($suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}) eq 'ARRAY') {
17966:                         my $mapid = $suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}->[0];
17967:                         if ($supphidden{$mapid}) {
17968:                             $is_hidden = 1;
17969:                         }
17970:                     }
17971:                     $supppath .= '&'.$items[$i].'::'.$is_hidden.':::';
17972:                 } else {
17973:                     $supppath .= '&'.$items[$i];
17974:                 }
17975:             } elsif ((!$odd) && ($items[$i] !~ /^(default|supplemental)(|_\d+)$/)) {
17976:                 $badpath = 1;
17977:             } elsif ($supplementalflag) {
17978:                 $supppath .= '&'.$items[$i];
17979:             }
17980:             last if ($badpath);
17981:         }
17982:         if ($badpath) {
17983:             delete($env{'form.folderpath'});
17984:         } elsif ($changed && $supplementalflag) {
17985:             $supppath =~ s/^\&//;
17986:             $env{'form.folderpath'} = $supppath;
17987:         }
17988:     }
17989:     return;
17990: }
17991: 
17992: sub captcha_display {
17993:     my ($context,$lonhost,$defdom) = @_;
17994:     my ($output,$error);
17995:     my ($captcha,$pubkey,$privkey,$version) =
17996:         &get_captcha_config($context,$lonhost,$defdom);
17997:     if ($captcha eq 'original') {
17998:         $output = &create_captcha();
17999:         unless ($output) {
18000:             $error = 'captcha';
18001:         }
18002:     } elsif ($captcha eq 'recaptcha') {
18003:         $output = &create_recaptcha($pubkey,$version);
18004:         unless ($output) {
18005:             $error = 'recaptcha';
18006:         }
18007:     }
18008:     return ($output,$error,$captcha,$version);
18009: }
18010: 
18011: sub captcha_response {
18012:     my ($context,$lonhost,$defdom) = @_;
18013:     my ($captcha_chk,$captcha_error);
18014:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
18015:     if ($captcha eq 'original') {
18016:         ($captcha_chk,$captcha_error) = &check_captcha();
18017:     } elsif ($captcha eq 'recaptcha') {
18018:         $captcha_chk = &check_recaptcha($privkey,$version);
18019:     } else {
18020:         $captcha_chk = 1;
18021:     }
18022:     return ($captcha_chk,$captcha_error);
18023: }
18024: 
18025: sub get_captcha_config {
18026:     my ($context,$lonhost,$dom_in_effect) = @_;
18027:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
18028:     my $hostname = &Apache::lonnet::hostname($lonhost);
18029:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
18030:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
18031:     if ($context eq 'usercreation') {
18032:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
18033:         if (ref($domconfig{$context}) eq 'HASH') {
18034:             $hashtocheck = $domconfig{$context}{'cancreate'};
18035:             if (ref($hashtocheck) eq 'HASH') {
18036:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
18037:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
18038:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
18039:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
18040:                     }
18041:                     if ($privkey && $pubkey) {
18042:                         $captcha = 'recaptcha';
18043:                         $version = $hashtocheck->{'recaptchaversion'};
18044:                         if ($version ne '2') {
18045:                             $version = 1;
18046:                         }
18047:                     } else {
18048:                         $captcha = 'original';
18049:                     }
18050:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
18051:                     $captcha = 'original';
18052:                 }
18053:             }
18054:         } else {
18055:             $captcha = 'captcha';
18056:         }
18057:     } elsif ($context eq 'login') {
18058:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
18059:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
18060:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
18061:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
18062:             if ($privkey && $pubkey) {
18063:                 $captcha = 'recaptcha';
18064:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
18065:                 if ($version ne '2') {
18066:                     $version = 1;
18067:                 }
18068:             } else {
18069:                 $captcha = 'original';
18070:             }
18071:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
18072:             $captcha = 'original';
18073:         }
18074:     } elsif ($context eq 'passwords') {
18075:         if ($dom_in_effect) {
18076:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
18077:             if ($passwdconf{'captcha'} eq 'recaptcha') {
18078:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
18079:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
18080:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
18081:                 }
18082:                 if ($privkey && $pubkey) {
18083:                     $captcha = 'recaptcha';
18084:                     $version = $passwdconf{'recaptchaversion'};
18085:                     if ($version ne '2') {
18086:                         $version = 1;
18087:                     }
18088:                 } else {
18089:                     $captcha = 'original';
18090:                 }
18091:             } elsif ($passwdconf{'captcha'} ne 'notused') {
18092:                 $captcha = 'original';
18093:             }
18094:         }
18095:     }
18096:     return ($captcha,$pubkey,$privkey,$version);
18097: }
18098: 
18099: sub create_captcha {
18100:     my %captcha_params = &captcha_settings();
18101:     my ($output,$maxtries,$tries) = ('',10,0);
18102:     while ($tries < $maxtries) {
18103:         $tries ++;
18104:         my $captcha = Authen::Captcha->new (
18105:                                            output_folder => $captcha_params{'output_dir'},
18106:                                            data_folder   => $captcha_params{'db_dir'},
18107:                                           );
18108:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
18109: 
18110:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
18111:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
18112:                       '<span class="LC_nobreak">'.
18113:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
18114:                       '<input type="text" size="5" name="code" value="" autocomplete="new-password" />'.
18115:                       '</span><br />'.
18116:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
18117:             last;
18118:         }
18119:     }
18120:     if ($output eq '') {
18121:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
18122:     }
18123:     return $output;
18124: }
18125: 
18126: sub captcha_settings {
18127:     my %captcha_params = (
18128:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
18129:                            www_output_dir => "/captchaspool",
18130:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
18131:                            numchars       => '5',
18132:                          );
18133:     return %captcha_params;
18134: }
18135: 
18136: sub check_captcha {
18137:     my ($captcha_chk,$captcha_error);
18138:     my $code = $env{'form.code'};
18139:     my $md5sum = $env{'form.crypt'};
18140:     my %captcha_params = &captcha_settings();
18141:     my $captcha = Authen::Captcha->new(
18142:                       output_folder => $captcha_params{'output_dir'},
18143:                       data_folder   => $captcha_params{'db_dir'},
18144:                   );
18145:     $captcha_chk = $captcha->check_code($code,$md5sum);
18146:     my %captcha_hash = (
18147:                         0       => 'Code not checked (file error)',
18148:                        -1      => 'Failed: code expired',
18149:                        -2      => 'Failed: invalid code (not in database)',
18150:                        -3      => 'Failed: invalid code (code does not match crypt)',
18151:     );
18152:     if ($captcha_chk != 1) {
18153:         $captcha_error = $captcha_hash{$captcha_chk}
18154:     }
18155:     return ($captcha_chk,$captcha_error);
18156: }
18157: 
18158: sub create_recaptcha {
18159:     my ($pubkey,$version) = @_;
18160:     if ($version >= 2) {
18161:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
18162:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
18163:     } else {
18164:         my $use_ssl;
18165:         if ($ENV{'SERVER_PORT'} == 443) {
18166:             $use_ssl = 1;
18167:         }
18168:         my $captcha = Captcha::reCAPTCHA->new;
18169:         return $captcha->get_options_setter({theme => 'white'})."\n".
18170:                $captcha->get_html($pubkey,undef,$use_ssl).
18171:                &mt('If the text is hard to read, [_1] will replace them.',
18172:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
18173:                '<br /><br />';
18174:      }
18175: }
18176: 
18177: sub check_recaptcha {
18178:     my ($privkey,$version) = @_;
18179:     my $captcha_chk;
18180:     my $ip = &Apache::lonnet::get_requestor_ip(); 
18181:     if ($version >= 2) {
18182:         my $ua = LWP::UserAgent->new;
18183:         $ua->timeout(10);
18184:         my %info = (
18185:                      secret   => $privkey,
18186:                      response => $env{'form.g-recaptcha-response'},
18187:                      remoteip => $ip,
18188:                    );
18189:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
18190:         if ($response->is_success)  {
18191:             my $data = JSON::DWIW->from_json($response->decoded_content);
18192:             if (ref($data) eq 'HASH') {
18193:                 if ($data->{'success'}) {
18194:                     $captcha_chk = 1;
18195:                 }
18196:             }
18197:         }
18198:     } else {
18199:         my $captcha = Captcha::reCAPTCHA->new;
18200:         my $captcha_result =
18201:             $captcha->check_answer(
18202:                                     $privkey,
18203:                                     $ip,
18204:                                     $env{'form.recaptcha_challenge_field'},
18205:                                     $env{'form.recaptcha_response_field'},
18206:                                   );
18207:         if ($captcha_result->{is_valid}) {
18208:             $captcha_chk = 1;
18209:         }
18210:     }
18211:     return $captcha_chk;
18212: }
18213: 
18214: sub emailusername_info {
18215:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
18216:     my %titles = &Apache::lonlocal::texthash (
18217:                      lastname      => 'Last Name',
18218:                      firstname     => 'First Name',
18219:                      institution   => 'School/college/university',
18220:                      location      => "School's city, state/province, country",
18221:                      web           => "School's web address",
18222:                      officialemail => 'E-mail address at institution (if different)',
18223:                      id            => 'Student/Employee ID',
18224:                  );
18225:     return (\@fields,\%titles);
18226: }
18227: 
18228: sub cleanup_html {
18229:     my ($incoming) = @_;
18230:     my $outgoing;
18231:     if ($incoming ne '') {
18232:         $outgoing = $incoming;
18233:         $outgoing =~ s/;/&#059;/g;
18234:         $outgoing =~ s/\#/&#035;/g;
18235:         $outgoing =~ s/\&/&#038;/g;
18236:         $outgoing =~ s/</&#060;/g;
18237:         $outgoing =~ s/>/&#062;/g;
18238:         $outgoing =~ s/\(/&#040/g;
18239:         $outgoing =~ s/\)/&#041;/g;
18240:         $outgoing =~ s/"/&#034;/g;
18241:         $outgoing =~ s/'/&#039;/g;
18242:         $outgoing =~ s/\$/&#036;/g;
18243:         $outgoing =~ s{/}{&#047;}g;
18244:         $outgoing =~ s/=/&#061;/g;
18245:         $outgoing =~ s/\\/&#092;/g
18246:     }
18247:     return $outgoing;
18248: }
18249: 
18250: # Checks for critical messages and returns a redirect url if one exists.
18251: # $interval indicates how often to check for messages.
18252: # $context is the calling context -- roles, grades, contents, menu or flip.
18253: sub critical_redirect {
18254:     my ($interval,$context) = @_;
18255:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
18256:         return ();
18257:     }
18258:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
18259:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
18260:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
18261:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
18262:             my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
18263:             if ($blocked) {
18264:                 my $checkrole = "cm./$cdom/$cnum";
18265:                 if ($env{'request.course.sec'} ne '') {
18266:                     $checkrole .= "/$env{'request.course.sec'}";
18267:                 }
18268:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
18269:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
18270:                     return;
18271:                 }
18272:             }
18273:         }
18274:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
18275:                                         $env{'user.name'});
18276:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
18277:         my $redirecturl;
18278:         if ($what[0]) {
18279:             if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
18280:                 $redirecturl='/adm/email?critical=display';
18281:                 my $url=&Apache::lonnet::absolute_url().$redirecturl;
18282:                 return (1, $url);
18283:             }
18284:         }
18285:     }
18286:     return ();
18287: }
18288: 
18289: # Use:
18290: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
18291: #
18292: ##################################################
18293: #          password associated functions         #
18294: ##################################################
18295: sub des_keys {
18296:     # Make a new key for DES encryption.
18297:     # Each key has two parts which are returned separately.
18298:     # Please note:  Each key must be passed through the &hex function
18299:     # before it is output to the web browser.  The hex versions cannot
18300:     # be used to decrypt.
18301:     my @hexstr=('0','1','2','3','4','5','6','7',
18302:                 '8','9','a','b','c','d','e','f');
18303:     my $lkey='';
18304:     for (0..7) {
18305:         $lkey.=$hexstr[rand(15)];
18306:     }
18307:     my $ukey='';
18308:     for (0..7) {
18309:         $ukey.=$hexstr[rand(15)];
18310:     }
18311:     return ($lkey,$ukey);
18312: }
18313: 
18314: sub des_decrypt {
18315:     my ($key,$cyphertext) = @_;
18316:     my $keybin=pack("H16",$key);
18317:     my $cypher;
18318:     if ($Crypt::DES::VERSION>=2.03) {
18319:         $cypher=new Crypt::DES $keybin;
18320:     } else {
18321:         $cypher=new DES $keybin;
18322:     }
18323:     my $plaintext='';
18324:     my $cypherlength = length($cyphertext);
18325:     my $numchunks = int($cypherlength/32);
18326:     for (my $j=0; $j<$numchunks; $j++) {
18327:         my $start = $j*32;
18328:         my $cypherblock = substr($cyphertext,$start,32);
18329:         my $chunk =
18330:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
18331:         $chunk .=
18332:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
18333:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
18334:         $plaintext .= $chunk;
18335:     }
18336:     return $plaintext;
18337: }
18338: 
18339: sub get_requested_shorturls {
18340:     my ($cdom,$cnum,$navmap) = @_;
18341:     return unless (ref($navmap));
18342:     my ($numnew,$errors);
18343:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
18344:     if (@toshorten) {
18345:         my (%maps,%resources,%titles);
18346:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
18347:                                                                'shorturls',$cdom,$cnum);
18348:         if (keys(%resources)) {
18349:             my %tocreate;
18350:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
18351:                 my $symb = $resources{$item};
18352:                 if ($symb) {
18353:                     $tocreate{$cnum.'&'.$symb} = 1;
18354:                 }
18355:             }
18356:             if (keys(%tocreate)) {
18357:                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
18358:                                                       \%tocreate);
18359:             }
18360:         }
18361:     }
18362:     return ($numnew,$errors);
18363: }
18364: 
18365: sub make_short_symbs {
18366:     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
18367:     my ($numnew,@errors);
18368:     if (ref($tocreateref) eq 'HASH') {
18369:         my %tocreate = %{$tocreateref};
18370:         if (keys(%tocreate)) {
18371:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
18372:             my $su = Short::URL->new(no_vowels => 1);
18373:             my $init = '';
18374:             my (%newunique,%addcourse,%courseonly,%failed);
18375:             # get lock on tiny db
18376:             my $now = time;
18377:             if ($lockuser eq '') {
18378:                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
18379:             }
18380:             my $lockhash = {
18381:                                 "lock\0$now" => $lockuser,
18382:                             };
18383:             my $tries = 0;
18384:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
18385:             my ($code,$error);
18386:             while (($gotlock ne 'ok') && ($tries<3)) {
18387:                 $tries ++;
18388:                 sleep 1;
18389:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
18390:             }
18391:             if ($gotlock eq 'ok') {
18392:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
18393:                                        \%addcourse,\%courseonly,\%failed);
18394:                 if (keys(%failed)) {
18395:                     my $numfailed = scalar(keys(%failed));
18396:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
18397:                 }
18398:                 if (keys(%newunique)) {
18399:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
18400:                     if ($putres eq 'ok') {
18401:                         $numnew = scalar(keys(%newunique));
18402:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
18403:                         unless ($newputres eq 'ok') {
18404:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
18405:                         }
18406:                     } else {
18407:                         push(@errors,&mt('error: could not store unique six character URLs'));
18408:                     }
18409:                 }
18410:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
18411:                 unless ($dellockres eq 'ok') {
18412:                     push(@errors,&mt('error: could not release lockfile'));
18413:                 }
18414:             } else {
18415:                 push(@errors,&mt('error: could not obtain lockfile'));
18416:             }
18417:             if (keys(%courseonly)) {
18418:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
18419:                 if ($result ne 'ok') {
18420:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
18421:                 }
18422:             }
18423:         }
18424:     }
18425:     return ($numnew,\@errors);
18426: }
18427: 
18428: sub shorten_symbs {
18429:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
18430:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
18431:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
18432:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
18433:     my (%possibles,%collisions);
18434:     foreach my $key (keys(%{$tocreate})) {
18435:         my $num = String::CRC32::crc32($key);
18436:         my $tiny = $su->encode($num,$init);
18437:         if ($tiny) {
18438:             $possibles{$tiny} = $key;
18439:         }
18440:     }
18441:     if (!$init) {
18442:         $init = 1;
18443:     } else {
18444:         $init ++;
18445:     }
18446:     if (keys(%possibles)) {
18447:         my @posstiny = keys(%possibles);
18448:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
18449:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
18450:         if (keys(%currtiny)) {
18451:             foreach my $key (keys(%currtiny)) {
18452:                 next if ($currtiny{$key} eq '');
18453:                 if ($currtiny{$key} eq $possibles{$key}) {
18454:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
18455:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
18456:                         $courseonly->{$tsymb} = $key;
18457:                     }
18458:                 } else {
18459:                     $collisions{$possibles{$key}} = 1;
18460:                 }
18461:                 delete($possibles{$key});
18462:             }
18463:         }
18464:         foreach my $key (keys(%possibles)) {
18465:             $newunique->{$key} = $possibles{$key};
18466:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
18467:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
18468:                 $addcourse->{$tsymb} = $key;
18469:             }
18470:         }
18471:     }
18472:     if (keys(%collisions)) {
18473:         if ($init <5) {
18474:             if (!$init) {
18475:                 $init = 1;
18476:             } else {
18477:                 $init ++;
18478:             }
18479:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
18480:                                    $newunique,$addcourse,$courseonly,$failed);
18481:         } else {
18482:             foreach my $key (keys(%collisions)) {
18483:                 $failed->{$key} = 1;
18484:                 $failed->{$key} = 1;
18485:             }
18486:         }
18487:     }
18488:     return $init;
18489: }
18490: 
18491: sub is_nonframeable {
18492:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
18493:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
18494:     return if (($remprotocol eq '') || ($remhost eq ''));
18495: 
18496:     $remprotocol = lc($remprotocol);
18497:     $remhost = lc($remhost);
18498:     my $remport = 80;
18499:     if ($remprotocol eq 'https') {
18500:         $remport = 443;
18501:     }
18502:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
18503:     if ($cached) {
18504:         unless ($nocache) {
18505:             if ($result) {
18506:                 return 1;
18507:             } else {
18508:                 return 0;
18509:             }
18510:         }
18511:     }
18512:     my $uselink;
18513:     my $request = new HTTP::Request('HEAD',$url);
18514:     my $ua = LWP::UserAgent->new;
18515:     $ua->timeout(5);
18516:     my $response=$ua->request($request);
18517:     if ($response->is_success()) {
18518:         my $secpolicy = lc($response->header('content-security-policy'));
18519:         my $xframeop = lc($response->header('x-frame-options'));
18520:         $secpolicy =~ s/^\s+|\s+$//g;
18521:         $xframeop =~ s/^\s+|\s+$//g;
18522:         if (($secpolicy ne '') || ($xframeop ne '')) {
18523:             my $remotehost = $remprotocol.'://'.$remhost;
18524:             my ($origin,$protocol,$port);
18525:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
18526:                 $port = $ENV{'SERVER_PORT'};
18527:             } else {
18528:                 $port = 80;
18529:             }
18530:             if ($absolute eq '') {
18531:                 $protocol = 'http:';
18532:                 if ($port == 443) {
18533:                     $protocol = 'https:';
18534:                 }
18535:                 $origin = $protocol.'//'.lc($hostname);
18536:             } else {
18537:                 $origin = lc($absolute);
18538:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
18539:             }
18540:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
18541:                 my $framepolicy = $1;
18542:                 $framepolicy =~ s/^\s+|\s+$//g;
18543:                 my @policies = split(/\s+/,$framepolicy);
18544:                 if (@policies) {
18545:                     if (grep(/^\Q'none'\E$/,@policies)) {
18546:                         $uselink = 1;
18547:                     } else {
18548:                         $uselink = 1;
18549:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
18550:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
18551:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
18552:                             undef($uselink);
18553:                         }
18554:                         if ($uselink) {
18555:                             if (grep(/^\Q'self'\E$/,@policies)) {
18556:                                 if (($origin ne '') && ($remotehost eq $origin)) {
18557:                                     undef($uselink);
18558:                                 }
18559:                             }
18560:                         }
18561:                         if ($uselink) {
18562:                             my @possok;
18563:                             if ($ip ne '') {
18564:                                 push(@possok,$ip);
18565:                             }
18566:                             my $hoststr = '';
18567:                             foreach my $part (reverse(split(/\./,$hostname))) {
18568:                                 if ($hoststr eq '') {
18569:                                     $hoststr = $part;
18570:                                 } else {
18571:                                     $hoststr = "$part.$hoststr";
18572:                                 }
18573:                                 if ($hoststr eq $hostname) {
18574:                                     push(@possok,$hostname);
18575:                                 } else {
18576:                                     push(@possok,"*.$hoststr");
18577:                                 }
18578:                             }
18579:                             if (@possok) {
18580:                                 foreach my $poss (@possok) {
18581:                                     last if (!$uselink);
18582:                                     foreach my $policy (@policies) {
18583:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
18584:                                             undef($uselink);
18585:                                             last;
18586:                                         }
18587:                                     }
18588:                                 }
18589:                             }
18590:                         }
18591:                     }
18592:                 }
18593:             } elsif ($xframeop ne '') {
18594:                 $uselink = 1;
18595:                 my @policies = split(/\s*,\s*/,$xframeop);
18596:                 if (@policies) {
18597:                     unless (grep(/^deny$/,@policies)) {
18598:                         if ($origin ne '') {
18599:                             if (grep(/^sameorigin$/,@policies)) {
18600:                                 if ($remotehost eq $origin) {
18601:                                     undef($uselink);
18602:                                 }
18603:                             }
18604:                             if ($uselink) {
18605:                                 foreach my $policy (@policies) {
18606:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
18607:                                         my $allowfrom = $1;
18608:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
18609:                                             undef($uselink);
18610:                                             last;
18611:                                         }
18612:                                     }
18613:                                 }
18614:                             }
18615:                         }
18616:                     }
18617:                 }
18618:             }
18619:         }
18620:     }
18621:     if ($nocache) {
18622:         if ($cached) {
18623:             my $devalidate;
18624:             if ($uselink && !$result) {
18625:                 $devalidate = 1;
18626:             } elsif (!$uselink && $result) {
18627:                 $devalidate = 1;
18628:             }
18629:             if ($devalidate) {
18630:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
18631:             }
18632:         }
18633:     } else {
18634:         if ($uselink) {
18635:             $result = 1;
18636:         } else {
18637:             $result = 0;
18638:         }
18639:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
18640:     }
18641:     return $uselink;
18642: }
18643: 
18644: sub page_menu {
18645:     my ($menucolls,$menunum) = @_;
18646:     my %menu;
18647:     foreach my $item (split(/;/,$menucolls)) {
18648:         my ($num,$value) = split(/\%/,$item);
18649:         if ($num eq $menunum) {
18650:             my @entries = split(/\&/,$value);
18651:             foreach my $entry (@entries) {
18652:                 my ($name,$fields) = split(/=/,$entry);
18653:                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
18654:                     $menu{$name} = $fields;
18655:                 } else {
18656:                     my @shown;
18657:                     if ($fields =~ /,/) {
18658:                         @shown = split(/,/,$fields);
18659:                     } else {
18660:                         @shown = ($fields);
18661:                     }
18662:                     if (@shown) {
18663:                         foreach my $field (@shown) {
18664:                             next if ($field eq '');
18665:                             $menu{$field} = 1;
18666:                         }
18667:                     }
18668:                 }
18669:             }
18670:         }
18671:     }
18672:     return %menu;
18673: }
18674: 
18675: 1;
18676: __END__;
18677: 

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