File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1408: download - view: text, annotated - select for diffs
Tue Jun 20 14:03:52 2023 UTC (11 months, 1 week ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Support case where assignment of roles in a different domain is queued
  pending acceptance of the role by the role recipient.
  - A user can also choose to decline the role.
  - Domain configuration can be set for domain roles, co-author roles,
    course roles and community roles.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1408 2023/06/20 14:03:52 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::LWPReq;
   75: use LONCAPA::map();
   76: use HTTP::Request;
   77: use DateTime::TimeZone;
   78: use DateTime::Locale;
   79: use Encode();
   80: use Text::Aspell;
   81: use Authen::Captcha;
   82: use Captcha::reCAPTCHA;
   83: use JSON::DWIW;
   84: use Crypt::DES;
   85: use DynaLoader; # for Crypt::DES version
   86: use MIME::Lite;
   87: use MIME::Types;
   88: use File::Copy();
   89: use File::Path();
   90: use String::CRC32();
   91: use Short::URL();
   92: 
   93: # ---------------------------------------------- Designs
   94: use vars qw(%defaultdesign);
   95: 
   96: my $readit;
   97: 
   98: 
   99: ##
  100: ## Global Variables
  101: ##
  102: 
  103: 
  104: # ----------------------------------------------- SSI with retries:
  105: #
  106: 
  107: =pod
  108: 
  109: =head1 Server Side include with retries:
  110: 
  111: =over 4
  112: 
  113: =item * &ssi_with_retries(resource,retries form)
  114: 
  115: Performs an ssi with some number of retries.  Retries continue either
  116: until the result is ok or until the retry count supplied by the
  117: caller is exhausted.  
  118: 
  119: Inputs:
  120: 
  121: =over 4
  122: 
  123: resource   - Identifies the resource to insert.
  124: 
  125: retries    - Count of the number of retries allowed.
  126: 
  127: form       - Hash that identifies the rendering options.
  128: 
  129: =back
  130: 
  131: Returns:
  132: 
  133: =over 4
  134: 
  135: content    - The content of the response.  If retries were exhausted this is empty.
  136: 
  137: response   - The response from the last attempt (which may or may not have been successful.
  138: 
  139: =back
  140: 
  141: =back
  142: 
  143: =cut
  144: 
  145: sub ssi_with_retries {
  146:     my ($resource, $retries, %form) = @_;
  147: 
  148: 
  149:     my $ok = 0;			# True if we got a good response.
  150:     my $content;
  151:     my $response;
  152: 
  153:     # Try to get the ssi done. within the retries count:
  154: 
  155:     do {
  156: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  157: 	$ok      = $response->is_success;
  158:         if (!$ok) {
  159:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  160:         }
  161: 	$retries--;
  162:     } while (!$ok && ($retries > 0));
  163: 
  164:     if (!$ok) {
  165: 	$content = '';		# On error return an empty content.
  166:     }
  167:     return ($content, $response);
  168: 
  169: }
  170: 
  171: 
  172: 
  173: # ----------------------------------------------- Filetypes/Languages/Copyright
  174: my %language;
  175: my %supported_language;
  176: my %supported_codes;
  177: my %latex_language;		# For choosing hyphenation in <transl..>
  178: my %latex_language_bykey;	# for choosing hyphenation from metadata
  179: my %cprtag;
  180: my %scprtag;
  181: my %fe; my %fd; my %fm;
  182: my %category_extensions;
  183: 
  184: # ---------------------------------------------- Thesaurus variables
  185: #
  186: # %Keywords:
  187: #      A hash used by &keyword to determine if a word is considered a keyword.
  188: # $thesaurus_db_file 
  189: #      Scalar containing the full path to the thesaurus database.
  190: 
  191: my %Keywords;
  192: my $thesaurus_db_file;
  193: 
  194: #
  195: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  196: # thesaurus.tab, and filecategories.tab.
  197: #
  198: BEGIN {
  199:     # Variable initialization
  200:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  201:     #
  202:     unless ($readit) {
  203: # ------------------------------------------------------------------- languages
  204:     {
  205:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  206:                                    '/language.tab';
  207:         if ( open(my $fh,'<',$langtabfile) ) {
  208:             while (my $line = <$fh>) {
  209:                 next if ($line=~/^\#/);
  210:                 chomp($line);
  211:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  212:                 $language{$key}=$val.' - '.$enc;
  213:                 if ($sup) {
  214:                     $supported_language{$key}=$sup;
  215: 		    $supported_codes{$key}   = $code;
  216:                 }
  217: 		if ($latex) {
  218: 		    $latex_language_bykey{$key} = $latex;
  219: 		    $latex_language{$code} = $latex;
  220: 		}
  221:             }
  222:             close($fh);
  223:         }
  224:     }
  225: # ------------------------------------------------------------------ copyrights
  226:     {
  227:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  228:                                   '/copyright.tab';
  229:         if ( open (my $fh,'<',$copyrightfile) ) {
  230:             while (my $line = <$fh>) {
  231:                 next if ($line=~/^\#/);
  232:                 chomp($line);
  233:                 my ($key,$val)=(split(/\s+/,$line,2));
  234:                 $cprtag{$key}=$val;
  235:             }
  236:             close($fh);
  237:         }
  238:     }
  239: # ----------------------------------------------------------- source copyrights
  240:     {
  241:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  242:                                   '/source_copyright.tab';
  243:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
  244:             while (my $line = <$fh>) {
  245:                 next if ($line =~ /^\#/);
  246:                 chomp($line);
  247:                 my ($key,$val)=(split(/\s+/,$line,2));
  248:                 $scprtag{$key}=$val;
  249:             }
  250:             close($fh);
  251:         }
  252:     }
  253: 
  254: # -------------------------------------------------------------- default domain designs
  255:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  256:     my $designfile = $designdir.'/default.tab';
  257:     if ( open (my $fh,'<',$designfile) ) {
  258:         while (my $line = <$fh>) {
  259:             next if ($line =~ /^\#/);
  260:             chomp($line);
  261:             my ($key,$val)=(split(/\=/,$line));
  262:             if ($val) { $defaultdesign{$key}=$val; }
  263:         }
  264:         close($fh);
  265:     }
  266: 
  267: # ------------------------------------------------------------- file categories
  268:     {
  269:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  270:                                   '/filecategories.tab';
  271:         if ( open (my $fh,'<',$categoryfile) ) {
  272: 	    while (my $line = <$fh>) {
  273: 		next if ($line =~ /^\#/);
  274: 		chomp($line);
  275:                 my ($extension,$category)=(split(/\s+/,$line,2));
  276:                 push(@{$category_extensions{lc($category)}},$extension);
  277:             }
  278:             close($fh);
  279:         }
  280: 
  281:     }
  282: # ------------------------------------------------------------------ file types
  283:     {
  284:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  285:                '/filetypes.tab';
  286:         if ( open (my $fh,'<',$typesfile) ) {
  287:             while (my $line = <$fh>) {
  288: 		next if ($line =~ /^\#/);
  289: 		chomp($line);
  290:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  291:                 if ($descr ne '') {
  292:                     $fe{$ending}=lc($emb);
  293:                     $fd{$ending}=$descr;
  294:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  295:                 }
  296:             }
  297:             close($fh);
  298:         }
  299:     }
  300:     &Apache::lonnet::logthis(
  301:              "<span style='color:yellow;'>INFO: Read file types</span>");
  302:     $readit=1;
  303:     }  # end of unless($readit) 
  304:     
  305: }
  306: 
  307: ###############################################################
  308: ##           HTML and Javascript Helper Functions            ##
  309: ###############################################################
  310: 
  311: =pod 
  312: 
  313: =head1 HTML and Javascript Functions
  314: 
  315: =over 4
  316: 
  317: =item * &browser_and_searcher_javascript()
  318: 
  319: X<browsing, javascript>X<searching, javascript>Returns a string
  320: containing javascript with two functions, C<openbrowser> and
  321: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  322: tags.
  323: 
  324: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  325: 
  326: inputs: formname, elementname, only, omit
  327: 
  328: formname and elementname indicate the name of the html form and name of
  329: the element that the results of the browsing selection are to be placed in. 
  330: 
  331: Specifying 'only' will restrict the browser to displaying only files
  332: with the given extension.  Can be a comma separated list.
  333: 
  334: Specifying 'omit' will restrict the browser to NOT displaying files
  335: with the given extension.  Can be a comma separated list.
  336: 
  337: =item * &opensearcher(formname,elementname) [javascript]
  338: 
  339: Inputs: formname, elementname
  340: 
  341: formname and elementname specify the name of the html form and the name
  342: of the element the selection from the search results will be placed in.
  343: 
  344: =cut
  345: 
  346: sub browser_and_searcher_javascript {
  347:     my ($mode)=@_;
  348:     if (!defined($mode)) { $mode='edit'; }
  349:     my $resurl=&escape_single(&lastresurl());
  350:     return <<END;
  351: // <!-- BEGIN LON-CAPA Internal
  352:     var editbrowser = null;
  353:     function openbrowser(formname,elementname,only,omit,titleelement) {
  354:         var url = '$resurl/?';
  355:         if (editbrowser == null) {
  356:             url += 'launch=1&';
  357:         }
  358:         url += 'catalogmode=interactive&';
  359:         url += 'mode=$mode&';
  360:         url += 'inhibitmenu=yes&';
  361:         url += 'form=' + formname + '&';
  362:         if (only != null) {
  363:             url += 'only=' + only + '&';
  364:         } else {
  365:             url += 'only=&';
  366: 	}
  367:         if (omit != null) {
  368:             url += 'omit=' + omit + '&';
  369:         } else {
  370:             url += 'omit=&';
  371: 	}
  372:         if (titleelement != null) {
  373:             url += 'titleelement=' + titleelement + '&';
  374:         } else {
  375: 	    url += 'titleelement=&';
  376: 	}
  377:         url += 'element=' + elementname + '';
  378:         var title = 'Browser';
  379:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  380:         options += ',width=700,height=600';
  381:         editbrowser = open(url,title,options,'1');
  382:         editbrowser.focus();
  383:     }
  384:     var editsearcher;
  385:     function opensearcher(formname,elementname,titleelement) {
  386:         var url = '/adm/searchcat?';
  387:         if (editsearcher == null) {
  388:             url += 'launch=1&';
  389:         }
  390:         url += 'catalogmode=interactive&';
  391:         url += 'mode=$mode&';
  392:         url += 'form=' + formname + '&';
  393:         if (titleelement != null) {
  394:             url += 'titleelement=' + titleelement + '&';
  395:         } else {
  396: 	    url += 'titleelement=&';
  397: 	}
  398:         url += 'element=' + elementname + '';
  399:         var title = 'Search';
  400:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  401:         options += ',width=700,height=600';
  402:         editsearcher = open(url,title,options,'1');
  403:         editsearcher.focus();
  404:     }
  405: // END LON-CAPA Internal -->
  406: END
  407: }
  408: 
  409: sub lastresurl {
  410:     if ($env{'environment.lastresurl'}) {
  411: 	return $env{'environment.lastresurl'}
  412:     } else {
  413: 	return '/res';
  414:     }
  415: }
  416: 
  417: sub storeresurl {
  418:     my $resurl=&Apache::lonnet::clutter(shift);
  419:     unless ($resurl=~/^\/res/) { return 0; }
  420:     $resurl=~s/\/$//;
  421:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  422:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  423:     return 1;
  424: }
  425: 
  426: sub studentbrowser_javascript {
  427:    unless (
  428:             (($env{'request.course.id'}) && 
  429:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  430: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  431: 					  '/'.$env{'request.course.sec'})
  432: 	      ))
  433:          || ($env{'request.role'}=~/^(au|dc|su)/)
  434:           ) { return ''; }  
  435:    return (<<'ENDSTDBRW');
  436: <script type="text/javascript" language="Javascript">
  437: // <![CDATA[
  438:     var stdeditbrowser;
  439:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv) {
  440:         var url = '/adm/pickstudent?';
  441:         var filter;
  442: 	if (!ignorefilter) {
  443: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  444: 	}
  445:         if (filter != null) {
  446:            if (filter != '') {
  447:                url += 'filter='+filter+'&';
  448: 	   }
  449:         }
  450:         url += 'form=' + formname + '&unameelement='+uname+
  451:                                     '&udomelement='+udom+
  452:                                     '&clicker='+clicker;
  453: 	if (roleflag) { url+="&roles=1"; }
  454:         if (courseadv == 'condition') {
  455:             if (document.getElementById('courseadv')) {
  456:                 courseadv = document.getElementById('courseadv').value;
  457:             }
  458:         }
  459:         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
  460:         var title = 'Student_Browser';
  461:         var options = 'scrollbars=1,resizable=1,menubar=0';
  462:         options += ',width=700,height=600';
  463:         stdeditbrowser = open(url,title,options,'1');
  464:         stdeditbrowser.focus();
  465:     }
  466: // ]]>
  467: </script>
  468: ENDSTDBRW
  469: }
  470: 
  471: sub resourcebrowser_javascript {
  472:    unless ($env{'request.course.id'}) { return ''; }
  473:    return (<<'ENDRESBRW');
  474: <script type="text/javascript" language="Javascript">
  475: // <![CDATA[
  476:     var reseditbrowser;
  477:     function openresbrowser(formname,reslink) {
  478:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  479:         var title = 'Resource_Browser';
  480:         var options = 'scrollbars=1,resizable=1,menubar=0';
  481:         options += ',width=700,height=500';
  482:         reseditbrowser = open(url,title,options,'1');
  483:         reseditbrowser.focus();
  484:     }
  485: // ]]>
  486: </script>
  487: ENDRESBRW
  488: }
  489: 
  490: sub selectstudent_link {
  491:    my ($form,$unameele,$udomele,$courseadv,$clickerid)=@_;
  492:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  493:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  494:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  495:    if ($env{'request.course.id'}) {  
  496:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  497: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  498: 					'/'.$env{'request.course.sec'})) {
  499: 	   return '';
  500:        }
  501:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  502:        if ($courseadv eq 'only') {
  503:            $callargs .= ",'',1,'$courseadv'";
  504:        } elsif ($courseadv eq 'none') {
  505:            $callargs .= ",'','','$courseadv'";
  506:        } elsif ($courseadv eq 'condition') {
  507:            $callargs .= ",'','','$courseadv'";
  508:        }
  509:        return '<span class="LC_nobreak">'.
  510:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  511:               &mt('Select User').'</a></span>';
  512:    }
  513:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  514:        $callargs .= ",'',1"; 
  515:        return '<span class="LC_nobreak">'.
  516:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  517:               &mt('Select User').'</a></span>';
  518:    }
  519:    return '';
  520: }
  521: 
  522: sub selectresource_link {
  523:    my ($form,$reslink,$arg)=@_;
  524:    
  525:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  526:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  527:    unless ($env{'request.course.id'}) { return $arg; }
  528:    return '<span class="LC_nobreak">'.
  529:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  530:               $arg.'</a></span>';
  531: }
  532: 
  533: 
  534: 
  535: sub authorbrowser_javascript {
  536:     return <<"ENDAUTHORBRW";
  537: <script type="text/javascript" language="JavaScript">
  538: // <![CDATA[
  539: var stdeditbrowser;
  540: 
  541: function openauthorbrowser(formname,udom) {
  542:     var url = '/adm/pickauthor?';
  543:     url += 'form='+formname+'&roledom='+udom;
  544:     var title = 'Author_Browser';
  545:     var options = 'scrollbars=1,resizable=1,menubar=0';
  546:     options += ',width=700,height=600';
  547:     stdeditbrowser = open(url,title,options,'1');
  548:     stdeditbrowser.focus();
  549: }
  550: 
  551: // ]]>
  552: </script>
  553: ENDAUTHORBRW
  554: }
  555: 
  556: sub coursebrowser_javascript {
  557:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
  558:         $credits_element,$instcode) = @_;
  559:     my $wintitle = 'Course_Browser';
  560:     if ($crstype eq 'Community') {
  561:         $wintitle = 'Community_Browser';
  562:     }
  563:     my $id_functions = &javascript_index_functions();
  564:     my $output = '
  565: <script type="text/javascript" language="JavaScript">
  566: // <![CDATA[
  567:     var stdeditbrowser;'."\n";
  568: 
  569:     $output .= <<"ENDSTDBRW";
  570:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  571:         var url = '/adm/pickcourse?';
  572:         var formid = getFormIdByName(formname);
  573:         var domainfilter = getDomainFromSelectbox(formname,udom);
  574:         if (domainfilter != null) {
  575:            if (domainfilter != '') {
  576:                url += 'domainfilter='+domainfilter+'&';
  577: 	   }
  578:         }
  579:         url += 'form=' + formname + '&cnumelement='+uname+
  580: 	                            '&cdomelement='+udom+
  581:                                     '&cnameelement='+desc;
  582:         if (extra_element !=null && extra_element != '') {
  583:             if (formname == 'rolechoice' || formname == 'studentform') {
  584:                 url += '&roleelement='+extra_element;
  585:                 if (domainfilter == null || domainfilter == '') {
  586:                     url += '&domainfilter='+extra_element;
  587:                 }
  588:             }
  589:             else {
  590:                 if (formname == 'portform') {
  591:                     url += '&setroles='+extra_element;
  592:                 } else {
  593:                     if (formname == 'rules') {
  594:                         url += '&fixeddom='+extra_element; 
  595:                     }
  596:                 }
  597:             }     
  598:         }
  599:         if (type != null && type != '') {
  600:             url += '&type='+type;
  601:         }
  602:         if (type_elem != null && type_elem != '') {
  603:             url += '&typeelement='+type_elem;
  604:         }
  605:         if (formname == 'ccrs') {
  606:             var ownername = document.forms[formid].ccuname.value;
  607:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  608:             url += '&cloner='+ownername+':'+ownerdom;
  609:             if (type == 'Course') {
  610:                 url += '&crscode='+document.forms[formid].crscode.value;
  611:             }
  612:         }
  613:         if (formname == 'requestcrs') {
  614:             url += '&crsdom=$domainfilter&crscode=$instcode';
  615:         }
  616:         if (multflag !=null && multflag != '') {
  617:             url += '&multiple='+multflag;
  618:         }
  619:         var title = '$wintitle';
  620:         var options = 'scrollbars=1,resizable=1,menubar=0';
  621:         options += ',width=700,height=600';
  622:         stdeditbrowser = open(url,title,options,'1');
  623:         stdeditbrowser.focus();
  624:     }
  625: $id_functions
  626: ENDSTDBRW
  627:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
  628:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
  629:                                       $credits_element);
  630:     }
  631:     $output .= '
  632: // ]]>
  633: </script>';
  634:     return $output;
  635: }
  636: 
  637: sub javascript_index_functions {
  638:     return <<"ENDJS";
  639: 
  640: function getFormIdByName(formname) {
  641:     for (var i=0;i<document.forms.length;i++) {
  642:         if (document.forms[i].name == formname) {
  643:             return i;
  644:         }
  645:     }
  646:     return -1;
  647: }
  648: 
  649: function getIndexByName(formid,item) {
  650:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  651:         if (document.forms[formid].elements[i].name == item) {
  652:             return i;
  653:         }
  654:     }
  655:     return -1;
  656: }
  657: 
  658: function getDomainFromSelectbox(formname,udom) {
  659:     var userdom;
  660:     var formid = getFormIdByName(formname);
  661:     if (formid > -1) {
  662:         var domid = getIndexByName(formid,udom);
  663:         if (domid > -1) {
  664:             if (document.forms[formid].elements[domid].type == 'select-one') {
  665:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  666:             }
  667:             if (document.forms[formid].elements[domid].type == 'hidden') {
  668:                 userdom=document.forms[formid].elements[domid].value;
  669:             }
  670:         }
  671:     }
  672:     return userdom;
  673: }
  674: 
  675: ENDJS
  676: 
  677: }
  678: 
  679: sub javascript_array_indexof {
  680:     return <<ENDJS;
  681: <script type="text/javascript" language="JavaScript">
  682: // <![CDATA[
  683: 
  684: if (!Array.prototype.indexOf) {
  685:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  686:         "use strict";
  687:         if (this === void 0 || this === null) {
  688:             throw new TypeError();
  689:         }
  690:         var t = Object(this);
  691:         var len = t.length >>> 0;
  692:         if (len === 0) {
  693:             return -1;
  694:         }
  695:         var n = 0;
  696:         if (arguments.length > 0) {
  697:             n = Number(arguments[1]);
  698:             if (n !== n) { // shortcut for verifying if it is NaN
  699:                 n = 0;
  700:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  701:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  702:             }
  703:         }
  704:         if (n >= len) {
  705:             return -1;
  706:         }
  707:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  708:         for (; k < len; k++) {
  709:             if (k in t && t[k] === searchElement) {
  710:                 return k;
  711:             }
  712:         }
  713:         return -1;
  714:     }
  715: }
  716: 
  717: // ]]>
  718: </script>
  719: 
  720: ENDJS
  721: 
  722: }
  723: 
  724: sub userbrowser_javascript {
  725:     my $id_functions = &javascript_index_functions();
  726:     return <<"ENDUSERBRW";
  727: 
  728: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  729:     var url = '/adm/pickuser?';
  730:     var userdom = getDomainFromSelectbox(formname,udom);
  731:     if (userdom != null) {
  732:        if (userdom != '') {
  733:            url += 'srchdom='+userdom+'&';
  734:        }
  735:     }
  736:     url += 'form=' + formname + '&unameelement='+uname+
  737:                                 '&udomelement='+udom+
  738:                                 '&ulastelement='+ulast+
  739:                                 '&ufirstelement='+ufirst+
  740:                                 '&uemailelement='+uemail+
  741:                                 '&hideudomelement='+hideudom+
  742:                                 '&coursedom='+crsdom;
  743:     if ((caller != null) && (caller != undefined)) {
  744:         url += '&caller='+caller;
  745:     }
  746:     var title = 'User_Browser';
  747:     var options = 'scrollbars=1,resizable=1,menubar=0';
  748:     options += ',width=700,height=600';
  749:     var stdeditbrowser = open(url,title,options,'1');
  750:     stdeditbrowser.focus();
  751: }
  752: 
  753: function fix_domain (formname,udom,origdom,uname) {
  754:     var formid = getFormIdByName(formname);
  755:     if (formid > -1) {
  756:         var unameid = getIndexByName(formid,uname);
  757:         var domid = getIndexByName(formid,udom);
  758:         var hidedomid = getIndexByName(formid,origdom);
  759:         if (hidedomid > -1) {
  760:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  761:             var unameval = document.forms[formid].elements[unameid].value;
  762:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  763:                 if (domid > -1) {
  764:                     var slct = document.forms[formid].elements[domid];
  765:                     if (slct.type == 'select-one') {
  766:                         var i;
  767:                         for (i=0;i<slct.length;i++) {
  768:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  769:                         }
  770:                     }
  771:                     if (slct.type == 'hidden') {
  772:                         slct.value = fixeddom;
  773:                     }
  774:                 }
  775:             }
  776:         }
  777:     }
  778:     return;
  779: }
  780: 
  781: $id_functions
  782: ENDUSERBRW
  783: }
  784: 
  785: sub setsec_javascript {
  786:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
  787:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  788:         $communityrolestr);
  789:     if ($role_element ne '') {
  790:         my @allroles = ('st','ta','ep','in','ad');
  791:         foreach my $crstype ('Course','Community') {
  792:             if ($crstype eq 'Community') {
  793:                 foreach my $role (@allroles) {
  794:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  795:                 }
  796:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  797:             } else {
  798:                 foreach my $role (@allroles) {
  799:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  800:                 }
  801:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  802:             }
  803:         }
  804:         $rolestr = '"'.join('","',@allroles).'"';
  805:         $courserolestr = '"'.join('","',@courserolenames).'"';
  806:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  807:     }
  808:     my $setsections = qq|
  809: function setSect(sectionlist) {
  810:     var sectionsArray = new Array();
  811:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  812:         sectionsArray = sectionlist.split(",");
  813:     }
  814:     var numSections = sectionsArray.length;
  815:     document.$formname.$sec_element.length = 0;
  816:     if (numSections == 0) {
  817:         document.$formname.$sec_element.multiple=false;
  818:         document.$formname.$sec_element.size=1;
  819:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  820:     } else {
  821:         if (numSections == 1) {
  822:             document.$formname.$sec_element.multiple=false;
  823:             document.$formname.$sec_element.size=1;
  824:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  825:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  826:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  827:         } else {
  828:             for (var i=0; i<numSections; i++) {
  829:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  830:             }
  831:             document.$formname.$sec_element.multiple=true
  832:             if (numSections < 3) {
  833:                 document.$formname.$sec_element.size=numSections;
  834:             } else {
  835:                 document.$formname.$sec_element.size=3;
  836:             }
  837:             document.$formname.$sec_element.options[0].selected = false
  838:         }
  839:     }
  840: }
  841: 
  842: function setRole(crstype) {
  843: |;
  844:     if ($role_element eq '') {
  845:         $setsections .= '    return;
  846: }
  847: ';
  848:     } else {
  849:         $setsections .= qq|
  850:     var elementLength = document.$formname.$role_element.length;
  851:     var allroles = Array($rolestr);
  852:     var courserolenames = Array($courserolestr);
  853:     var communityrolenames = Array($communityrolestr);
  854:     if (elementLength != undefined) {
  855:         if (document.$formname.$role_element.options[5].value == 'cc') {
  856:             if (crstype == 'Course') {
  857:                 return;
  858:             } else {
  859:                 allroles[5] = 'co';
  860:                 for (var i=0; i<6; i++) {
  861:                     document.$formname.$role_element.options[i].value = allroles[i];
  862:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  863:                 }
  864:             }
  865:         } else {
  866:             if (crstype == 'Community') {
  867:                 return;
  868:             } else {
  869:                 allroles[5] = 'cc';
  870:                 for (var i=0; i<6; i++) {
  871:                     document.$formname.$role_element.options[i].value = allroles[i];
  872:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  873:                 }
  874:             }
  875:         }
  876:     }
  877:     return;
  878: }
  879: |;
  880:     }
  881:     if ($credits_element) {
  882:         $setsections .= qq|
  883: function setCredits(defaultcredits) {
  884:     document.$formname.$credits_element.value = defaultcredits;
  885:     return;
  886: }
  887: |;
  888:     }
  889:     return $setsections;
  890: }
  891: 
  892: sub selectcourse_link {
  893:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  894:        $typeelement) = @_;
  895:    my $type = $selecttype;
  896:    my $linktext = &mt('Select Course');
  897:    if ($selecttype eq 'Community') {
  898:        $linktext = &mt('Select Community');
  899:    } elsif ($selecttype eq 'Placement') {
  900:        $linktext = &mt('Select Placement Test'); 
  901:    } elsif ($selecttype eq 'Course/Community') {
  902:        $linktext = &mt('Select Course/Community');
  903:        $type = '';
  904:    } elsif ($selecttype eq 'Select') {
  905:        $linktext = &mt('Select');
  906:        $type = '';
  907:    }
  908:    return '<span class="LC_nobreak">'
  909:          ."<a href='"
  910:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  911:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  912:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  913:          ."'>".$linktext.'</a>'
  914:          .'</span>';
  915: }
  916: 
  917: sub selectauthor_link {
  918:    my ($form,$udom)=@_;
  919:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  920:           &mt('Select Author').'</a>';
  921: }
  922: 
  923: sub selectuser_link {
  924:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  925:         $coursedom,$linktext,$caller) = @_;
  926:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  927:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  928:            ');">'.$linktext.'</a>';
  929: }
  930: 
  931: sub check_uncheck_jscript {
  932:     my $jscript = <<"ENDSCRT";
  933: function checkAll(field) {
  934:     if (field.length > 0) {
  935:         for (i = 0; i < field.length; i++) {
  936:             if (!field[i].disabled) { 
  937:                 field[i].checked = true;
  938:             }
  939:         }
  940:     } else {
  941:         if (!field.disabled) { 
  942:             field.checked = true;
  943:         }
  944:     }
  945: }
  946:  
  947: function uncheckAll(field) {
  948:     if (field.length > 0) {
  949:         for (i = 0; i < field.length; i++) {
  950:             field[i].checked = false ;
  951:         }
  952:     } else {
  953:         field.checked = false ;
  954:     }
  955: }
  956: ENDSCRT
  957:     return $jscript;
  958: }
  959: 
  960: sub select_timezone {
  961:    my ($name,$selected,$onchange,$includeempty,$id,$disabled)=@_;
  962:    my $output='<select name="'.$name.'" '.$id.$onchange.$disabled.'>'."\n";
  963:    if ($includeempty) {
  964:        $output .= '<option value=""';
  965:        if (($selected eq '') || ($selected eq 'local')) {
  966:            $output .= ' selected="selected" ';
  967:        }
  968:        $output .= '> </option>';
  969:    }
  970:    my @timezones = DateTime::TimeZone->all_names;
  971:    foreach my $tzone (@timezones) {
  972:        $output.= '<option value="'.$tzone.'"';
  973:        if ($tzone eq $selected) {
  974:            $output.=' selected="selected"';
  975:        }
  976:        $output.=">$tzone</option>\n";
  977:    }
  978:    $output.="</select>";
  979:    return $output;
  980: }
  981: 
  982: sub select_datelocale {
  983:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  984:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  985:     if ($includeempty) {
  986:         $output .= '<option value=""';
  987:         if ($selected eq '') {
  988:             $output .= ' selected="selected" ';
  989:         }
  990:         $output .= '> </option>';
  991:     }
  992:     my @languages = &Apache::lonlocal::preferred_languages();
  993:     my (@possibles,%locale_names);
  994:     my @locales = DateTime::Locale->ids();
  995:     foreach my $id (@locales) {
  996:         if ($id ne '') {
  997:             my ($en_terr,$native_terr);
  998:             my $loc = DateTime::Locale->load($id);
  999:             if (ref($loc)) {
 1000:                 $en_terr = $loc->name();
 1001:                 $native_terr = $loc->native_name();
 1002:                 if (grep(/^en$/,@languages) || !@languages) {
 1003:                     if ($en_terr ne '') {
 1004:                         $locale_names{$id} = '('.$en_terr.')';
 1005:                     } elsif ($native_terr ne '') {
 1006:                         $locale_names{$id} = $native_terr;
 1007:                     }
 1008:                 } else {
 1009:                     if ($native_terr ne '') {
 1010:                         $locale_names{$id} = $native_terr.' ';
 1011:                     } elsif ($en_terr ne '') {
 1012:                         $locale_names{$id} = '('.$en_terr.')';
 1013:                     }
 1014:                 }
 1015:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
 1016:                 push(@possibles,$id);
 1017:             } 
 1018:         }
 1019:     }
 1020:     foreach my $item (sort(@possibles)) {
 1021:         $output.= '<option value="'.$item.'"';
 1022:         if ($item eq $selected) {
 1023:             $output.=' selected="selected"';
 1024:         }
 1025:         $output.=">$item";
 1026:         if ($locale_names{$item} ne '') {
 1027:             $output.='  '.$locale_names{$item};
 1028:         }
 1029:         $output.="</option>\n";
 1030:     }
 1031:     $output.="</select>";
 1032:     return $output;
 1033: }
 1034: 
 1035: sub select_language {
 1036:     my ($name,$selected,$includeempty,$noedit) = @_;
 1037:     my %langchoices;
 1038:     if ($includeempty) {
 1039:         %langchoices = ('' => 'No language preference');
 1040:     }
 1041:     foreach my $id (&languageids()) {
 1042:         my $code = &supportedlanguagecode($id);
 1043:         if ($code) {
 1044:             $langchoices{$code} = &plainlanguagedescription($id);
 1045:         }
 1046:     }
 1047:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
 1048:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
 1049: }
 1050: 
 1051: =pod
 1052: 
 1053: 
 1054: =item * &list_languages()
 1055: 
 1056: Returns an array reference that is suitable for use in language prompters.
 1057: Each array element is itself a two element array.  The first element
 1058: is the language code.  The second element a descsriptiuon of the 
 1059: language itself.  This is suitable for use in e.g.
 1060: &Apache::edit::select_arg (once dereferenced that is).
 1061: 
 1062: =cut 
 1063: 
 1064: sub list_languages {
 1065:     my @lang_choices;
 1066: 
 1067:     foreach my $id (&languageids()) {
 1068: 	my $code = &supportedlanguagecode($id);
 1069: 	if ($code) {
 1070: 	    my $selector    = $supported_codes{$id};
 1071: 	    my $description = &plainlanguagedescription($id);
 1072: 	    push(@lang_choices, [$selector, $description]);
 1073: 	}
 1074:     }
 1075:     return \@lang_choices;
 1076: }
 1077: 
 1078: =pod
 1079: 
 1080: =item * &linked_select_forms(...)
 1081: 
 1082: linked_select_forms returns a string containing a <script></script> block
 1083: and html for two <select> menus.  The select menus will be linked in that
 1084: changing the value of the first menu will result in new values being placed
 1085: in the second menu.  The values in the select menu will appear in alphabetical
 1086: order unless a defined order is provided.
 1087: 
 1088: linked_select_forms takes the following ordered inputs:
 1089: 
 1090: =over 4
 1091: 
 1092: =item * $formname, the name of the <form> tag
 1093: 
 1094: =item * $middletext, the text which appears between the <select> tags
 1095: 
 1096: =item * $firstdefault, the default value for the first menu
 1097: 
 1098: =item * $firstselectname, the name of the first <select> tag
 1099: 
 1100: =item * $secondselectname, the name of the second <select> tag
 1101: 
 1102: =item * $hashref, a reference to a hash containing the data for the menus.
 1103: 
 1104: =item * $menuorder, the order of values in the first menu
 1105: 
 1106: =item * $onchangefirst, additional javascript call to execute for an onchange
 1107:         event for the first <select> tag
 1108: 
 1109: =item * $onchangesecond, additional javascript call to execute for an onchange
 1110:         event for the second <select> tag
 1111: 
 1112: =item * $suffix, to differentiate separate uses of select2data javascript
 1113:         objects in a page.
 1114: 
 1115: =back 
 1116: 
 1117: Below is an example of such a hash.  Only the 'text', 'default', and 
 1118: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1119: values for the first select menu.  The text that coincides with the 
 1120: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1121: and text for the second menu are given in the hash pointed to by 
 1122: $menu{$choice1}->{'select2'}.  
 1123: 
 1124:  my %menu = ( A1 => { text =>"Choice A1" ,
 1125:                        default => "B3",
 1126:                        select2 => { 
 1127:                            B1 => "Choice B1",
 1128:                            B2 => "Choice B2",
 1129:                            B3 => "Choice B3",
 1130:                            B4 => "Choice B4"
 1131:                            },
 1132:                        order => ['B4','B3','B1','B2'],
 1133:                    },
 1134:                A2 => { text =>"Choice A2" ,
 1135:                        default => "C2",
 1136:                        select2 => { 
 1137:                            C1 => "Choice C1",
 1138:                            C2 => "Choice C2",
 1139:                            C3 => "Choice C3"
 1140:                            },
 1141:                        order => ['C2','C1','C3'],
 1142:                    },
 1143:                A3 => { text =>"Choice A3" ,
 1144:                        default => "D6",
 1145:                        select2 => { 
 1146:                            D1 => "Choice D1",
 1147:                            D2 => "Choice D2",
 1148:                            D3 => "Choice D3",
 1149:                            D4 => "Choice D4",
 1150:                            D5 => "Choice D5",
 1151:                            D6 => "Choice D6",
 1152:                            D7 => "Choice D7"
 1153:                            },
 1154:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1155:                    }
 1156:                );
 1157: 
 1158: =cut
 1159: 
 1160: sub linked_select_forms {
 1161:     my ($formname,
 1162:         $middletext,
 1163:         $firstdefault,
 1164:         $firstselectname,
 1165:         $secondselectname, 
 1166:         $hashref,
 1167:         $menuorder,
 1168:         $onchangefirst,
 1169:         $onchangesecond,
 1170:         $suffix
 1171:         ) = @_;
 1172:     my $second = "document.$formname.$secondselectname";
 1173:     my $first = "document.$formname.$firstselectname";
 1174:     # output the javascript to do the changing
 1175:     my $result = '';
 1176:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1177:     $result.="// <![CDATA[\n";
 1178:     $result.="var select2data${suffix} = new Object();\n";
 1179:     $" = '","';
 1180:     my $debug = '';
 1181:     foreach my $s1 (sort(keys(%$hashref))) {
 1182:         $result.="select2data${suffix}['d_$s1'] = new Object();\n";        
 1183:         $result.="select2data${suffix}['d_$s1'].def = new String('".
 1184:             $hashref->{$s1}->{'default'}."');\n";
 1185:         $result.="select2data${suffix}['d_$s1'].values = new Array(";
 1186:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1187:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1188:             @s2values = @{$hashref->{$s1}->{'order'}};
 1189:         }
 1190:         $result.="\"@s2values\");\n";
 1191:         $result.="select2data${suffix}['d_$s1'].texts = new Array(";        
 1192:         my @s2texts;
 1193:         foreach my $value (@s2values) {
 1194:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
 1195:         }
 1196:         $result.="\"@s2texts\");\n";
 1197:     }
 1198:     $"=' ';
 1199:     $result.= <<"END";
 1200: 
 1201: function select1${suffix}_changed() {
 1202:     // Determine new choice
 1203:     var newvalue = "d_" + $first.options[$first.selectedIndex].value;
 1204:     // update select2
 1205:     var values     = select2data${suffix}[newvalue].values;
 1206:     var texts      = select2data${suffix}[newvalue].texts;
 1207:     var select2def = select2data${suffix}[newvalue].def;
 1208:     var i;
 1209:     // out with the old
 1210:     $second.options.length = 0;
 1211:     // in with the new
 1212:     for (i=0;i<values.length; i++) {
 1213:         $second.options[i] = new Option(values[i]);
 1214:         $second.options[i].value = values[i];
 1215:         $second.options[i].text = texts[i];
 1216:         if (values[i] == select2def) {
 1217:             $second.options[i].selected = true;
 1218:         }
 1219:     }
 1220: }
 1221: // ]]>
 1222: </script>
 1223: END
 1224:     # output the initial values for the selection lists
 1225:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
 1226:     my @order = sort(keys(%{$hashref}));
 1227:     if (ref($menuorder) eq 'ARRAY') {
 1228:         @order = @{$menuorder};
 1229:     }
 1230:     foreach my $value (@order) {
 1231:         $result.="    <option value=\"$value\" ";
 1232:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1233:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1234:     }
 1235:     $result .= "</select>\n";
 1236:     my %select2;
 1237:     if (ref($hashref->{$firstdefault}) eq 'HASH') {
 1238:         if (ref($hashref->{$firstdefault}->{'select2'}) eq 'HASH') {
 1239:             %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1240:         }
 1241:     }
 1242:     $result .= $middletext;
 1243:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
 1244:     if ($onchangesecond) {
 1245:         $result .= ' onchange="'.$onchangesecond.'"';
 1246:     }
 1247:     $result .= ">\n";
 1248:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1249:     
 1250:     my @secondorder = sort(keys(%select2));
 1251:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1252:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1253:     }
 1254:     foreach my $value (@secondorder) {
 1255:         $result.="    <option value=\"$value\" ";        
 1256:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1257:         $result.=">".&mt($select2{$value})."</option>\n";
 1258:     }
 1259:     $result .= "</select>\n";
 1260:     #    return $debug;
 1261:     return $result;
 1262: }   #  end of sub linked_select_forms {
 1263: 
 1264: =pod
 1265: 
 1266: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid,$links_target)
 1267: 
 1268: Returns a string corresponding to an HTML link to the given help
 1269: $topic, where $topic corresponds to the name of a .tex file in
 1270: /home/httpd/html/adm/help/tex, with underscores replaced by
 1271: spaces. 
 1272: 
 1273: $text will optionally be linked to the same topic, allowing you to
 1274: link text in addition to the graphic. If you do not want to link
 1275: text, but wish to specify one of the later parameters, pass an
 1276: empty string. 
 1277: 
 1278: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1279: the link will not open a new window. If false, the link will open
 1280: a new window using Javascript. (Default is false.) 
 1281: 
 1282: $width and $height are optional numerical parameters that will
 1283: override the width and height of the popped up window, which may
 1284: be useful for certain help topics with big pictures included.
 1285: 
 1286: $imgid is the id of the img tag used for the help icon. This may be
 1287: used in a javascript call to switch the image src.  See 
 1288: lonhtmlcommon::htmlareaselectactive() for an example.
 1289: 
 1290: $links_target will optionally be set to a target (_top, _parent or _self).
 1291: 
 1292: =cut
 1293: 
 1294: sub help_open_topic {
 1295:     my ($topic, $text, $stayOnPage, $width, $height, $imgid, $links_target) = @_;
 1296:     $text = "" if (not defined $text);
 1297:     $stayOnPage = 0 if (not defined $stayOnPage);
 1298:     $width = 500 if (not defined $width);
 1299:     $height = 400 if (not defined $height);
 1300:     my $filename = $topic;
 1301:     $filename =~ s/ /_/g;
 1302: 
 1303:     my $template = "";
 1304:     my $link;
 1305:     
 1306:     $topic=~s/\W/\_/g;
 1307: 
 1308:     if (!$stayOnPage) {
 1309: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1310:     } elsif ($stayOnPage eq 'popup') {
 1311:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1312:     } else {
 1313: 	$link = "/adm/help/${filename}.hlp";
 1314:     }
 1315: 
 1316:     # Add the text
 1317:     my $target = ' target="_top"';
 1318:     if ($links_target) {
 1319:         $target = ' target="'.$links_target.'"';
 1320:     } elsif ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
 1321:              (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
 1322:         $target = '';
 1323:     }
 1324:     if ($text ne "") {
 1325: 	$template.='<span class="LC_help_open_topic">'
 1326:                   .'<a'.$target.' href="'.$link.'">'
 1327:                   .$text.'</a>';
 1328:     }
 1329: 
 1330:     # (Always) Add the graphic
 1331:     my $title = &mt('Online Help');
 1332:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1333:     if ($imgid ne '') {
 1334:         $imgid = ' id="'.$imgid.'"';
 1335:     }
 1336:     $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
 1337:               .'<img src="'.$helpicon.'" border="0"'
 1338:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1339:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1340:               .' /></a>';
 1341:     if ($text ne "") {	
 1342:         $template.='</span>';
 1343:     }
 1344:     return $template;
 1345: 
 1346: }
 1347: 
 1348: # This is a quicky function for Latex cheatsheet editing, since it 
 1349: # appears in at least four places
 1350: sub helpLatexCheatsheet {
 1351:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1352:     my $out;
 1353:     my $addOther = '';
 1354:     if ($topic) {
 1355: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1356:     }
 1357:     $out = '<span>' # Start cheatsheet
 1358: 	  .$addOther
 1359:           .'<span>'
 1360: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1361: 	  .'</span> <span>'
 1362: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1363: 	  .'</span>';
 1364:     unless ($not_author) {
 1365:         $out .= '<span>'
 1366:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1367:                .'</span> <span>'
 1368:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
 1369: 	       .'</span>';
 1370:     }
 1371:     $out .= '</span>'; # End cheatsheet
 1372:     return $out;
 1373: }
 1374: 
 1375: sub general_help {
 1376:     my $helptopic='Student_Intro';
 1377:     if ($env{'request.role'}=~/^(ca|au)/) {
 1378: 	$helptopic='Authoring_Intro';
 1379:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1380: 	$helptopic='Course_Coordination_Intro';
 1381:     } elsif ($env{'request.role'}=~/^dc/) {
 1382:         $helptopic='Domain_Coordination_Intro';
 1383:     }
 1384:     return $helptopic;
 1385: }
 1386: 
 1387: sub update_help_link {
 1388:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1389:     my $origurl = $ENV{'REQUEST_URI'};
 1390:     $origurl=~s|^/~|/priv/|;
 1391:     my $timestamp = time;
 1392:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1393:         $$datum = &escape($$datum);
 1394:     }
 1395: 
 1396:     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";
 1397:     my $output .= <<"ENDOUTPUT";
 1398: <script type="text/javascript">
 1399: // <![CDATA[
 1400: banner_link = '$banner_link';
 1401: // ]]>
 1402: </script>
 1403: ENDOUTPUT
 1404:     return $output;
 1405: }
 1406: 
 1407: # now just updates the help link and generates a blue icon
 1408: sub help_open_menu {
 1409:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text,$links_target) 
 1410: 	= @_;    
 1411:     $stayOnPage = 1;
 1412:     my $output;
 1413:     if ($component_help) {
 1414: 	if (!$text) {
 1415: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1416: 				       $width,$height,'',$links_target);
 1417: 	} else {
 1418: 	    my $help_text;
 1419: 	    $help_text=&unescape($topic);
 1420: 	    $output='<table><tr><td>'.
 1421: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1422: 				 $width,$height,'',$links_target).'</td></tr></table>';
 1423: 	}
 1424:     }
 1425:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1426:     return $output.$banner_link;
 1427: }
 1428: 
 1429: sub top_nav_help {
 1430:     my ($text,$linkattr) = @_;
 1431:     $text = &mt($text);
 1432:     my $stay_on_page = 1;
 1433: 
 1434:     my ($link,$banner_link);
 1435:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
 1436:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1437: 	                         : "javascript:helpMenu('open')";
 1438:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1439:     }
 1440:     my $title = &mt('Get help');
 1441:     if ($link) {
 1442:         return <<"END";
 1443: $banner_link
 1444: <a href="$link" title="$title" $linkattr>$text</a>
 1445: END
 1446:     } else {
 1447:         return '&nbsp;'.$text.'&nbsp;';
 1448:     }
 1449: }
 1450: 
 1451: sub help_menu_js {
 1452:     my ($httphost) = @_;
 1453:     my $stayOnPage = 1;
 1454:     my $width = 620;
 1455:     my $height = 600;
 1456:     my $helptopic=&general_help();
 1457:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
 1458:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1459:     my $start_page =
 1460:         &Apache::loncommon::start_page('Help Menu', undef,
 1461: 				       {'frameset'    => 1,
 1462: 					'js_ready'    => 1,
 1463:                                         'use_absolute' => $httphost,
 1464: 					'add_entries' => {
 1465: 					    'border' => '0', 
 1466: 					    'rows'   => "110,*",},});
 1467:     my $end_page =
 1468:         &Apache::loncommon::end_page({'frameset' => 1,
 1469: 				      'js_ready' => 1,});
 1470: 
 1471:     my $template .= <<"ENDTEMPLATE";
 1472: <script type="text/javascript">
 1473: // <![CDATA[
 1474: // <!-- BEGIN LON-CAPA Internal
 1475: var banner_link = '';
 1476: function helpMenu(target) {
 1477:     var caller = this;
 1478:     if (target == 'open') {
 1479:         var newWindow = null;
 1480:         try {
 1481:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1482:         }
 1483:         catch(error) {
 1484:             writeHelp(caller);
 1485:             return;
 1486:         }
 1487:         if (newWindow) {
 1488:             caller = newWindow;
 1489:         }
 1490:     }
 1491:     writeHelp(caller);
 1492:     return;
 1493: }
 1494: function writeHelp(caller) {
 1495:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
 1496:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
 1497:     caller.document.close();
 1498:     caller.focus();
 1499: }
 1500: // END LON-CAPA Internal -->
 1501: // ]]>
 1502: </script>
 1503: ENDTEMPLATE
 1504:     return $template;
 1505: }
 1506: 
 1507: sub help_open_bug {
 1508:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1509:     unless ($env{'user.adv'}) { return ''; }
 1510:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1511:     $text = "" if (not defined $text);
 1512: 	$stayOnPage=1;
 1513:     $width = 600 if (not defined $width);
 1514:     $height = 600 if (not defined $height);
 1515: 
 1516:     $topic=~s/\W+/\+/g;
 1517:     my $link='';
 1518:     my $template='';
 1519:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1520: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1521:     if (!$stayOnPage)
 1522:     {
 1523: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1524:     }
 1525:     else
 1526:     {
 1527: 	$link = $url;
 1528:     }
 1529: 
 1530:     my $target = '_top';
 1531:     if ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
 1532:         (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
 1533:         $target = '_blank';
 1534:     }
 1535: 
 1536:     # Add the text
 1537:     if ($text ne "")
 1538:     {
 1539: 	$template .= 
 1540:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1541:   "<td bgcolor='#FF5555'><a target=\"$target\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1542:     }
 1543: 
 1544:     # Add the graphic
 1545:     my $title = &mt('Report a Bug');
 1546:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1547:     $template .= <<"ENDTEMPLATE";
 1548:  <a target="$target" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1549: ENDTEMPLATE
 1550:     if ($text ne '') { $template.='</td></tr></table>' };
 1551:     return $template;
 1552: 
 1553: }
 1554: 
 1555: sub help_open_faq {
 1556:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1557:     unless ($env{'user.adv'}) { return ''; }
 1558:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1559:     $text = "" if (not defined $text);
 1560: 	$stayOnPage=1;
 1561:     $width = 350 if (not defined $width);
 1562:     $height = 400 if (not defined $height);
 1563: 
 1564:     $topic=~s/\W+/\+/g;
 1565:     my $link='';
 1566:     my $template='';
 1567:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1568:     if (!$stayOnPage)
 1569:     {
 1570: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1571:     }
 1572:     else
 1573:     {
 1574: 	$link = $url;
 1575:     }
 1576: 
 1577:     # Add the text
 1578:     if ($text ne "")
 1579:     {
 1580: 	$template .= 
 1581:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1582:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1583:     }
 1584: 
 1585:     # Add the graphic
 1586:     my $title = &mt('View the FAQ');
 1587:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1588:     $template .= <<"ENDTEMPLATE";
 1589:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1590: ENDTEMPLATE
 1591:     if ($text ne '') { $template.='</td></tr></table>' };
 1592:     return $template;
 1593: 
 1594: }
 1595: 
 1596: ###############################################################
 1597: ###############################################################
 1598: 
 1599: =pod
 1600: 
 1601: =item * &change_content_javascript():
 1602: 
 1603: This and the next function allow you to create small sections of an
 1604: otherwise static HTML page that you can update on the fly with
 1605: Javascript, even in Netscape 4.
 1606: 
 1607: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1608: must be written to the HTML page once. It will prove the Javascript
 1609: function "change(name, content)". Calling the change function with the
 1610: name of the section 
 1611: you want to update, matching the name passed to C<changable_area>, and
 1612: the new content you want to put in there, will put the content into
 1613: that area.
 1614: 
 1615: B<Note>: Netscape 4 only reserves enough space for the changable area
 1616: to contain room for the original contents. You need to "make space"
 1617: for whatever changes you wish to make, and be B<sure> to check your
 1618: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1619: it's adequate for updating a one-line status display, but little more.
 1620: This script will set the space to 100% width, so you only need to
 1621: worry about height in Netscape 4.
 1622: 
 1623: Modern browsers are much less limiting, and if you can commit to the
 1624: user not using Netscape 4, this feature may be used freely with
 1625: pretty much any HTML.
 1626: 
 1627: =cut
 1628: 
 1629: sub change_content_javascript {
 1630:     # If we're on Netscape 4, we need to use Layer-based code
 1631:     if ($env{'browser.type'} eq 'netscape' &&
 1632: 	$env{'browser.version'} =~ /^4\./) {
 1633: 	return (<<NETSCAPE4);
 1634: 	function change(name, content) {
 1635: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1636: 	    doc.open();
 1637: 	    doc.write(content);
 1638: 	    doc.close();
 1639: 	}
 1640: NETSCAPE4
 1641:     } else {
 1642: 	# Otherwise, we need to use semi-standards-compliant code
 1643: 	# (technically, "innerHTML" isn't standard but the equivalent
 1644: 	# is really scary, and every useful browser supports it
 1645: 	return (<<DOMBASED);
 1646: 	function change(name, content) {
 1647: 	    element = document.getElementById(name);
 1648: 	    element.innerHTML = content;
 1649: 	}
 1650: DOMBASED
 1651:     }
 1652: }
 1653: 
 1654: =pod
 1655: 
 1656: =item * &changable_area($name,$origContent):
 1657: 
 1658: This provides a "changable area" that can be modified on the fly via
 1659: the Javascript code provided in C<change_content_javascript>. $name is
 1660: the name you will use to reference the area later; do not repeat the
 1661: same name on a given HTML page more then once. $origContent is what
 1662: the area will originally contain, which can be left blank.
 1663: 
 1664: =cut
 1665: 
 1666: sub changable_area {
 1667:     my ($name, $origContent) = @_;
 1668: 
 1669:     if ($env{'browser.type'} eq 'netscape' &&
 1670: 	$env{'browser.version'} =~ /^4\./) {
 1671: 	# If this is netscape 4, we need to use the Layer tag
 1672: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1673:     } else {
 1674: 	return "<span id='$name'>$origContent</span>";
 1675:     }
 1676: }
 1677: 
 1678: =pod
 1679: 
 1680: =item * &viewport_geometry_js 
 1681: 
 1682: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1683: 
 1684: =cut
 1685: 
 1686: 
 1687: sub viewport_geometry_js { 
 1688:     return <<"GEOMETRY";
 1689: var Geometry = {};
 1690: function init_geometry() {
 1691:     if (Geometry.init) { return };
 1692:     Geometry.init=1;
 1693:     if (window.innerHeight) {
 1694:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1695:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1696:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1697:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1698:     }
 1699:     else if (document.documentElement && document.documentElement.clientHeight) {
 1700:         Geometry.getViewportHeight =
 1701:             function() { return document.documentElement.clientHeight; };
 1702:         Geometry.getViewportWidth =
 1703:             function() { return document.documentElement.clientWidth; };
 1704: 
 1705:         Geometry.getHorizontalScroll =
 1706:             function() { return document.documentElement.scrollLeft; };
 1707:         Geometry.getVerticalScroll =
 1708:             function() { return document.documentElement.scrollTop; };
 1709:     }
 1710:     else if (document.body.clientHeight) {
 1711:         Geometry.getViewportHeight =
 1712:             function() { return document.body.clientHeight; };
 1713:         Geometry.getViewportWidth =
 1714:             function() { return document.body.clientWidth; };
 1715:         Geometry.getHorizontalScroll =
 1716:             function() { return document.body.scrollLeft; };
 1717:         Geometry.getVerticalScroll =
 1718:             function() { return document.body.scrollTop; };
 1719:     }
 1720: }
 1721: 
 1722: GEOMETRY
 1723: }
 1724: 
 1725: =pod
 1726: 
 1727: =item * &viewport_size_js()
 1728: 
 1729: 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. 
 1730: 
 1731: =cut
 1732: 
 1733: sub viewport_size_js {
 1734:     my $geometry = &viewport_geometry_js();
 1735:     return <<"DIMS";
 1736: 
 1737: $geometry
 1738: 
 1739: function getViewportDims(width,height) {
 1740:     init_geometry();
 1741:     width.value = Geometry.getViewportWidth();
 1742:     height.value = Geometry.getViewportHeight();
 1743:     return;
 1744: }
 1745: 
 1746: DIMS
 1747: }
 1748: 
 1749: =pod
 1750: 
 1751: =item * &resize_textarea_js()
 1752: 
 1753: emits the needed javascript to resize a textarea to be as big as possible
 1754: 
 1755: creates a function resize_textrea that takes two IDs first should be
 1756: the id of the element to resize, second should be the id of a div that
 1757: surrounds everything that comes after the textarea, this routine needs
 1758: to be attached to the <body> for the onload and onresize events.
 1759: 
 1760: =back
 1761: 
 1762: =cut
 1763: 
 1764: sub resize_textarea_js {
 1765:     my $geometry = &viewport_geometry_js();
 1766:     return <<"RESIZE";
 1767:     <script type="text/javascript">
 1768: // <![CDATA[
 1769: $geometry
 1770: 
 1771: function getX(element) {
 1772:     var x = 0;
 1773:     while (element) {
 1774: 	x += element.offsetLeft;
 1775: 	element = element.offsetParent;
 1776:     }
 1777:     return x;
 1778: }
 1779: function getY(element) {
 1780:     var y = 0;
 1781:     while (element) {
 1782: 	y += element.offsetTop;
 1783: 	element = element.offsetParent;
 1784:     }
 1785:     return y;
 1786: }
 1787: 
 1788: 
 1789: function resize_textarea(textarea_id,bottom_id) {
 1790:     init_geometry();
 1791:     var textarea        = document.getElementById(textarea_id);
 1792:     //alert(textarea);
 1793: 
 1794:     var textarea_top    = getY(textarea);
 1795:     var textarea_height = textarea.offsetHeight;
 1796:     var bottom          = document.getElementById(bottom_id);
 1797:     var bottom_top      = getY(bottom);
 1798:     var bottom_height   = bottom.offsetHeight;
 1799:     var window_height   = Geometry.getViewportHeight();
 1800:     var fudge           = 23;
 1801:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1802:     if (new_height < 300) {
 1803: 	new_height = 300;
 1804:     }
 1805:     textarea.style.height=new_height+'px';
 1806: }
 1807: // ]]>
 1808: </script>
 1809: RESIZE
 1810: 
 1811: }
 1812: 
 1813: sub colorfuleditor_js {
 1814:     my $browse_or_search;
 1815:     my $respath;
 1816:     my ($cnum,$cdom) = &crsauthor_url();
 1817:     if ($cnum) {
 1818:         $respath = "/res/$cdom/$cnum/";
 1819:         my %js_lt = &Apache::lonlocal::texthash(
 1820:             sunm => 'Sub-directory name',
 1821:             save => 'Save page to make this permanent',
 1822:         );
 1823:         &js_escape(\%js_lt);
 1824:         my $showfile_js = &show_crsfiles_js();
 1825:         $browse_or_search = <<"END";
 1826: 
 1827:     $showfile_js
 1828: 
 1829:     function toggleChooser(form,element,titleid,only,search) {
 1830:         var disp = 'none';
 1831:         if (document.getElementById('chooser_'+element)) {
 1832:             var curr = document.getElementById('chooser_'+element).style.display;
 1833:             if (curr == 'none') {
 1834:                 disp='inline';
 1835:                 if (form.elements['chooser_'+element].length) {
 1836:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
 1837:                         form.elements['chooser_'+element][i].checked = false;
 1838:                     }
 1839:                 }
 1840:                 toggleResImport(form,element);
 1841:             }
 1842:             document.getElementById('chooser_'+element).style.display = disp;
 1843:             var dirsel = '';
 1844:             var filesel = '';
 1845:             if (document.getElementById('chooser_'+element+'_crsres')) {
 1846:                 var currcrsres = document.getElementById('chooser_'+element+'_crsres').style.display;
 1847:                 if (currcrsres == 'none') {
 1848:                     dirsel = 'coursepath_'+element;
 1849:                     var filesel = 'coursefile_'+element;
 1850:                     var include;
 1851:                     if (document.getElementById('crsres_include_'+element)) {
 1852:                         include = document.getElementById('crsres_include_'+element).value;
 1853:                     }
 1854:                     populateCrsSelects(form,dirsel,filesel,1,include,1,0,1,1,0);
 1855:                 }
 1856:             }
 1857:             if (document.getElementById('chooser_'+element+'_upload')) {
 1858:                 var currcrsupload = document.getElementById('chooser_'+element+'_upload').style.display;
 1859:                 if (currcrsupload == 'none') {
 1860:                     dirsel = 'crsauthorpath_'+element;
 1861:                     filesel = '';
 1862:                     populateCrsSelects(form,dirsel,filesel,0,'',1,0,1,0,1);
 1863:                 }
 1864:             }
 1865:         }
 1866:     }
 1867: 
 1868:     function toggleCrsFile(form,element) {
 1869:         if (document.getElementById('chooser_'+element+'_crsres')) {
 1870:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
 1871:             if (curr == 'none') {
 1872:                 if (document.getElementById('coursepath_'+element)) {
 1873:                     var numdirs;
 1874:                     if (document.getElementById('coursepath_'+element).length) {
 1875:                         numdirs = document.getElementById('coursepath_'+element).length;
 1876:                     }
 1877:                     if ((document.getElementById('hascrsres_'+element)) &&
 1878:                         (document.getElementById('nocrsres_'+element))) {
 1879:                         if (numdirs) {
 1880:                             document.getElementById('hascrsres_'+element).style.display='inline-block';
 1881:                             document.getElementById('nocrsres_'+element).style.display='none';
 1882:                         } else {
 1883:                             document.getElementById('hascrsres_'+element).style.display='none';
 1884:                             document.getElementById('nocrsres_'+element).style.display='inline-block';
 1885:                         }
 1886:                     }
 1887:                     form.elements['coursepath_'+element].selectedIndex = 0;
 1888:                     if (numdirs > 1) {
 1889:                         var selelem = form.elements['coursefile_'+element];
 1890:                         var i, len = selelem.options.length -1;
 1891:                         if (len >=0) {
 1892:                             for (i = len; i >= 0; i--) {
 1893:                                 selelem.remove(i);
 1894:                             }
 1895:                             selelem.options[0] = new Option('','');
 1896:                         }
 1897:                     }
 1898:                 }
 1899:             }
 1900:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
 1901:         }
 1902:         if (document.getElementById('chooser_'+element+'_upload')) {
 1903:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
 1904:             if (document.getElementById('uploadcrsres_'+element)) {
 1905:                 document.getElementById('uploadcrsres_'+element).value = '';
 1906:             }
 1907:         }
 1908:         return;
 1909:     }
 1910: 
 1911:     function toggleCrsUpload(form,element) {
 1912:         if (document.getElementById('chooser_'+element+'_crsres')) {
 1913:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
 1914:         }
 1915:         if (document.getElementById('chooser_'+element+'_upload')) {
 1916:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
 1917:             if (curr == 'none') {
 1918:                 form.elements['newsubdir_'+element][0].checked = true;
 1919:                 toggleNewsubdir(form,element);
 1920:                 document.getElementById('chooser_'+element+'_upload').style.display = 'block';
 1921:                 if (document.getElementById('uploadcrsres_'+element)) {
 1922:                     document.getElementById('uploadcrsres_'+element).value = '';
 1923:                 }
 1924:             }
 1925:         }
 1926:         return;
 1927:     }
 1928: 
 1929:     function toggleResImport(form,element) {
 1930:         var choices = new Array('crsres','upload');
 1931:         for (var i=0; i<choices.length; i++) {
 1932:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
 1933:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
 1934:             }
 1935:         }
 1936:     }
 1937: 
 1938:     function toggleNewsubdir(form,element) {
 1939:         var newsub = form.elements['newsubdir_'+element];
 1940:         if (newsub) {
 1941:             if (newsub.length) {
 1942:                 for (var j=0; j<newsub.length; j++) {
 1943:                     if (newsub[j].checked) {
 1944:                         if (document.getElementById('newsubdirname_'+element)) {
 1945:                             if (newsub[j].value == '1') {
 1946:                                 document.getElementById('newsubdirname_'+element).type = "text";
 1947:                                 if (document.getElementById('newsubdir_'+element)) {
 1948:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
 1949:                                 }
 1950:                             } else {
 1951:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
 1952:                                 document.getElementById('newsubdirname_'+element).value = "";
 1953:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
 1954:                             }
 1955:                         }
 1956:                         break; 
 1957:                     }
 1958:                 }
 1959:             }
 1960:         }
 1961:     }
 1962: 
 1963:     function updateCrsFile(form,element) {
 1964:         var directory = form.elements['coursepath_'+element];
 1965:         var filename = form.elements['coursefile_'+element];
 1966:         var path = directory.options[directory.selectedIndex].value;
 1967:         var file = filename.options[filename.selectedIndex].value;
 1968:         if (file != '') {
 1969:             form.elements[element].value = '$respath';
 1970:             if (path == '/') {
 1971:                 form.elements[element].value += file;
 1972:             } else {
 1973:                 form.elements[element].value += path+'/'+file;
 1974:             }
 1975:             unClean();
 1976:             if (document.getElementById('previewimg_'+element)) {
 1977:                 document.getElementById('previewimg_'+element).src = form.elements[element].value;
 1978:                 var newsrc = document.getElementById('previewimg_'+element).src; 
 1979:             }
 1980:             if (document.getElementById('showimg_'+element)) {
 1981:                 document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
 1982:             }
 1983:         }
 1984:         toggleChooser(form,element);
 1985:         return;
 1986:     }
 1987: 
 1988:     function uploadDone(suffix,name) {
 1989:         if (name) {
 1990: 	    document.forms["lonhomework"].elements[suffix].value = name;
 1991:             unClean();
 1992:             toggleChooser(document.forms["lonhomework"],suffix);
 1993:         }
 1994:     }
 1995: 
 1996: \$(document).ready(function(){
 1997: 
 1998:     \$(document).delegate('form :submit', 'click', function( event ) {
 1999:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
 2000:             var buttonId = this.id;
 2001:             var suffix = buttonId.toString();
 2002:             suffix = suffix.replace(/^crsupload_/,'');
 2003:             event.preventDefault();
 2004:             document.lonhomework.target = 'crsupload_target_'+suffix;
 2005:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
 2006:             \$(this.form).submit();
 2007:             document.lonhomework.target = '';
 2008:             if (document.getElementById('crsuploadto_'+suffix)) {
 2009:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
 2010:             }
 2011:             return false;
 2012:         }
 2013:     });
 2014: });
 2015: END
 2016:     }
 2017:     return <<"COLORFULEDIT"
 2018: <script type="text/javascript">
 2019: // <![CDATA[>
 2020:     function fold_box(curDepth, lastresource){
 2021: 
 2022:     // we need a list because there can be several blocks you need to fold in one tag
 2023:         var block = document.getElementsByName('foldblock_'+curDepth);
 2024:     // but there is only one folding button per tag
 2025:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
 2026: 
 2027:         if(block.item(0).style.display == 'none'){
 2028: 
 2029:             foldbutton.value = '@{[&mt("Hide")]}';
 2030:             for (i = 0; i < block.length; i++){
 2031:                 block.item(i).style.display = '';
 2032:             }
 2033:         }else{
 2034: 
 2035:             foldbutton.value = '@{[&mt("Show")]}';
 2036:             for (i = 0; i < block.length; i++){
 2037:                 // block.item(i).style.visibility = 'collapse';
 2038:                 block.item(i).style.display = 'none';
 2039:             }
 2040:         };
 2041:         saveState(lastresource);
 2042:     }
 2043: 
 2044:     function saveState (lastresource) {
 2045: 
 2046:         var tag_list = getTagList();
 2047:         if(tag_list != null){
 2048:             var timestamp = new Date().getTime();
 2049:             var key = lastresource;
 2050: 
 2051:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
 2052:             // starting with timestamp
 2053:             var value = timestamp+';';
 2054: 
 2055:             // building the list of key-value pairs
 2056:             for(var i = 0; i < tag_list.length; i++){
 2057:                 value += tag_list[i]+',';
 2058:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
 2059:             }
 2060: 
 2061:             // only iterate whole storage if nothing to override
 2062:             if(localStorage.getItem(key) == null){        
 2063: 
 2064:                 // prevent storage from growing large
 2065:                 if(localStorage.length > 50){
 2066:                     var regex_getTimestamp = /^(?:\d)+;/;
 2067:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
 2068:                     var oldest_key;
 2069:                     
 2070:                     for(var i = 1; i < localStorage.length; i++){
 2071:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
 2072:                             oldest_key = localStorage.key(i);
 2073:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
 2074:                         }
 2075:                     }
 2076:                     localStorage.removeItem(oldest_key);
 2077:                 }
 2078:             }
 2079:             localStorage.setItem(key,value);
 2080:         }
 2081:     }
 2082: 
 2083:     // restore folding status of blocks (on page load)
 2084:     function restoreState (lastresource) {
 2085:         if(localStorage.getItem(lastresource) != null){
 2086:             var key = lastresource;
 2087:             var value = localStorage.getItem(key);
 2088:             var regex_delTimestamp = /^\d+;/;
 2089: 
 2090:             value.replace(regex_delTimestamp, '');
 2091: 
 2092:             var valueArr = value.split(';');
 2093:             var pairs;
 2094:             var elements;
 2095:             for (var i = 0; i < valueArr.length; i++){
 2096:                 pairs = valueArr[i].split(',');
 2097:                 elements = document.getElementsByName(pairs[0]);
 2098: 
 2099:                 for (var j = 0; j < elements.length; j++){  
 2100:                     elements[j].style.display = pairs[1];
 2101:                     if (pairs[1] == "none"){
 2102:                         var regex_id = /([_\\d]+)\$/;
 2103:                         regex_id.exec(pairs[0]);
 2104:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
 2105:                     }
 2106:                 }
 2107:             }
 2108:         }
 2109:     }
 2110: 
 2111:     function getTagList () {
 2112:         
 2113:         var stringToSearch = document.lonhomework.innerHTML;
 2114: 
 2115:         var ret = new Array();
 2116:         var regex_findBlock = /(foldblock_.*?)"/g;
 2117:         var tag_list = stringToSearch.match(regex_findBlock);
 2118: 
 2119:         if(tag_list != null){
 2120:             for(var i = 0; i < tag_list.length; i++){            
 2121:                 ret.push(tag_list[i].replace(/"/, ''));
 2122:             }
 2123:         }
 2124:         return ret;
 2125:     }
 2126: 
 2127:     function saveScrollPosition (resource) {
 2128:         var tag_list = getTagList();
 2129: 
 2130:         // we dont always want to jump to the first block
 2131:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
 2132:         if(\$(window).scrollTop() > 170){
 2133:             if(tag_list != null){
 2134:                 var result;
 2135:                 for(var i = 0; i < tag_list.length; i++){
 2136:                     if(isElementInViewport(tag_list[i])){
 2137:                         result += tag_list[i]+';';
 2138:                     }
 2139:                 }
 2140:                 sessionStorage.setItem('anchor_'+resource, result);
 2141:             }
 2142:         } else {
 2143:             // we dont need to save zero, just delete the item to leave everything tidy
 2144:             sessionStorage.removeItem('anchor_'+resource);
 2145:         }
 2146:     }
 2147: 
 2148:     function restoreScrollPosition(resource){
 2149: 
 2150:         var elem = sessionStorage.getItem('anchor_'+resource);
 2151:         if(elem != null){
 2152:             var tag_list = elem.split(';');
 2153:             var elem_list;
 2154: 
 2155:             for(var i = 0; i < tag_list.length; i++){
 2156:                 elem_list = document.getElementsByName(tag_list[i]);
 2157:                 
 2158:                 if(elem_list.length > 0){
 2159:                     elem = elem_list[0];
 2160:                     break;
 2161:                 }
 2162:             }
 2163:             elem.scrollIntoView();
 2164:         }
 2165:     }
 2166: 
 2167:     function isElementInViewport(el) {
 2168: 
 2169:         // change to last element instead of first
 2170:         var elem = document.getElementsByName(el);
 2171:         var rect = elem[0].getBoundingClientRect();
 2172: 
 2173:         return (
 2174:             rect.top >= 0 &&
 2175:             rect.left >= 0 &&
 2176:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
 2177:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
 2178:         );
 2179:     }
 2180:     
 2181:     function autosize(depth){
 2182:         var cmInst = window['cm'+depth];
 2183:         var fitsizeButton = document.getElementById('fitsize'+depth);
 2184: 
 2185:         // is fixed size, switching to dynamic
 2186:         if (sessionStorage.getItem("autosized_"+depth) == null) {
 2187:             cmInst.setSize("","auto");
 2188:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
 2189:             sessionStorage.setItem("autosized_"+depth, "yes");
 2190: 
 2191:         // is dynamic size, switching to fixed
 2192:         } else {
 2193:             cmInst.setSize("","300px");
 2194:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
 2195:             sessionStorage.removeItem("autosized_"+depth);
 2196:         }
 2197:     }
 2198: 
 2199: $browse_or_search
 2200: 
 2201: // ]]>
 2202: </script>
 2203: COLORFULEDIT
 2204: }
 2205: 
 2206: sub xmleditor_js {
 2207:     return <<XMLEDIT
 2208: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
 2209: <script type="text/javascript">
 2210: // <![CDATA[>
 2211: 
 2212:     function saveScrollPosition (resource) {
 2213: 
 2214:         var scrollPos = \$(window).scrollTop();
 2215:         sessionStorage.setItem(resource,scrollPos);
 2216:     }
 2217: 
 2218:     function restoreScrollPosition(resource){
 2219: 
 2220:         var scrollPos = sessionStorage.getItem(resource);
 2221:         \$(window).scrollTop(scrollPos);
 2222:     }
 2223: 
 2224:     // unless internet explorer
 2225:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
 2226: 
 2227:         \$(document).ready(function() {
 2228:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
 2229:         });
 2230:     }
 2231: 
 2232:     // inserts text at cursor position into codemirror (xml editor only)
 2233:     function insertText(text){
 2234:         cm.focus();
 2235:         var curPos = cm.getCursor();
 2236:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
 2237:     }
 2238: // ]]>
 2239: </script>
 2240: XMLEDIT
 2241: }
 2242: 
 2243: sub insert_folding_button {
 2244:     my $curDepth = $Apache::lonxml::curdepth;
 2245:     my $lastresource = $env{'request.ambiguous'};
 2246: 
 2247:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
 2248:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
 2249: }
 2250: 
 2251: sub crsauthor_url {
 2252:     my ($url) = @_;
 2253:     if ($url eq '') {
 2254:         $url = $ENV{'REQUEST_URI'};
 2255:     }
 2256:     my ($cnum,$cdom);
 2257:     if ($env{'request.course.id'}) {
 2258:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
 2259:         if ($audom ne '' && $auname ne '') {
 2260:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
 2261:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
 2262:                 $cnum = $auname;
 2263:                 $cdom = $audom;
 2264:             }
 2265:         }
 2266:     }
 2267:     return ($cnum,$cdom);
 2268: }
 2269: 
 2270: sub import_crsauthor_form {
 2271:     my ($firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
 2272:     return (0) unless ($env{'request.course.id'});
 2273:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2274:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2275:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
 2276:     return (0) unless (($cnum ne '') && ($cdom ne ''));
 2277:     my @ids=&Apache::lonnet::current_machine_ids();
 2278:     my ($output,$is_home,$toppath,%subdirs,%files,%selimport_menus,$include,$exclude);
 2279: 
 2280:     if (grep(/^\Q$crshome\E$/,@ids)) {
 2281:         $is_home = 1;
 2282:     }
 2283:     $toppath = "/priv/$cdom/$cnum";
 2284:     my $nonemptydir = 1;
 2285:     my $js_only;
 2286:     if ($only) {
 2287:         map { $include->{$_} = 1; } split(/\s*,\s*/,$only);
 2288:         $js_only = join(',',map { &js_escape($_); } sort(keys(%{$include})));
 2289:     }
 2290:     $exclude = &Apache::lonnet::priv_exclude();
 2291:     &Apache::lonnet::recursedirs($is_home,1,$include,$exclude,1,0,$toppath,'',\%subdirs,\%files);
 2292:     my $numdirs = scalar(keys(%files));
 2293:     my %lt = &Apache::lonlocal::texthash (
 2294:         fnam => 'Filename',
 2295:         dire => 'Directory',
 2296:         se   => 'Select',
 2297:     );
 2298:     $output = $lt{'dire'}.':&nbsp;'.
 2299:               '<select id="'.$firstselectname.'" name="'.$firstselectname.'" '.
 2300:               'onchange="populateCrsSelects(this.form,'."'$firstselectname','$secondselectname',1,'$js_only',0,1,0,0,0".');">'.
 2301:               '<option value="" selected="selected">'.$lt{'se'}.'</option>';
 2302:     if ($files{'/'}) {
 2303:         $output .= '<option value="/">/</option>'."\n";
 2304:     }
 2305:     foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
 2306:         next if ($key eq '/');
 2307:         $output .= '<option value="'.$key.'">'.$key.'</option>'."\n";
 2308:     }
 2309:     $output .= '</select><br />'."\n".
 2310:                $lt{'fnam'}.':&nbsp;<select id="'.$secondselectname.'" name="'.$secondselectname.'">'."\n".
 2311:                '<option value="" selected="selected"></option>'."\n".
 2312:                '</select>'."\n".
 2313:                '<input type="hidden" id="crsres_include_'.$suffix.'" value="'.$only.'" />';
 2314:     return ($numdirs,$output);
 2315: }
 2316: 
 2317: sub show_crsfiles_js {
 2318:     my $excluderef = &Apache::lonnet::priv_exclude();
 2319:     my $se = &js_escape(&mt('Select'));
 2320:     my $exclude;
 2321:     if (ref($excluderef) eq 'HASH') {
 2322:         $exclude = join(',', map { &js_escape($_); } sort(keys(%{$excluderef})));
 2323:     }
 2324:     my $js = <<"END";
 2325: 
 2326: 
 2327:     function populateCrsSelects (form,dirsel,filesel,exc,include,setdir,setfile,recurse,nonemptydir,addtopdir) {
 2328:         var relpath = '';
 2329:         if ((setfile) && (dirsel != null) && (dirsel != 'undefined') && (dirsel != '')) {
 2330:             var currdir = form.elements[dirsel].options[form.elements[dirsel].selectedIndex].value;
 2331:             if (currdir == '') {
 2332:                 if ((filesel != null) && (filesel != 'undefined') && (filesel != '')) {
 2333:                     selelem = form.elements[filesel];
 2334:                     var j, numfiles = selelem.options.length -1;
 2335:                     if (numfiles >=0) {
 2336:                         for (j = numfiles; j >= 0; j--) {
 2337:                             selelem.remove(j);
 2338:                         }
 2339:                     }
 2340:                     if (selelem.options.length == 0) {
 2341:                         selelem.options[selelem.options.length] = new Option('','');
 2342:                         selelem.selectedIndex = 0;
 2343:                     }
 2344:                 }
 2345:                 return;
 2346:             } else {
 2347:                 relpath = encodeURIComponent(form.elements[dirsel].options[form.elements[dirsel].selectedIndex].value);
 2348:             }
 2349:         }
 2350:         var http = new XMLHttpRequest();
 2351:         var url = "/adm/courseauthor";
 2352:         var crsrole = "$env{'request.role'}";
 2353:         var exclude = '';
 2354:         if (exc) {
 2355:             exclude = '$exclude';
 2356:         }
 2357:         var params = "role=course&files=1&rec="+recurse+"&nonempty="+nonemptydir+"&exc="+exclude+"&inc="+include+"&addtop="+addtopdir+"&path="+relpath;
 2358:         http.open("POST", url, true);
 2359:         http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 2360:         http.onreadystatechange = function() {
 2361:             if (http.readyState == 4 && http.status == 200) {
 2362:                 var data = JSON.parse(http.responseText);
 2363:                 var selelem;
 2364:                 if ((setdir) && (dirsel != null) && (dirsel != 'undefined') && (dirsel != '')) {
 2365:                     if (Array.isArray(data.dirs)) {
 2366:                         selelem = form.elements[dirsel];
 2367:                         var i, numdirs = selelem.options.length -1;
 2368:                         if (numdirs >=0) {
 2369:                             for (i = numdirs; i >= 0; i--) {
 2370:                                 selelem.remove(i);
 2371:                             }
 2372:                         }
 2373:                         var len = data.dirs.length;
 2374:                         if (len) {
 2375:                             selelem.options[selelem.options.length] = new Option('$se','');
 2376:                             var j;
 2377:                             for (j = 0; j < len; j++) {
 2378:                                 selelem.options[selelem.options.length] = new Option(data.dirs[j],data.dirs[j]);
 2379:                             }
 2380:                             selelem.selectedIndex = 0;
 2381:                         }
 2382:                         if (!setfile) {
 2383:                             if ((filesel != null) && (filesel != 'undefined') && (filesel != '')) {
 2384:                                 selelem = form.elements[filesel];
 2385:                                 var j, numfiles = selelem.options.length -1;
 2386:                                 if (numfiles >=0) {
 2387:                                     for (j = numfiles; j >= 0; j--) {
 2388:                                         selelem.remove(j);
 2389:                                     }
 2390:                                 }
 2391:                                 if (selelem.options.length == 0) {
 2392:                                     selelem.options[selelem.options.length] = new Option('','');
 2393:                                     selelem.selectedIndex = 0;
 2394:                                 }
 2395:                             }
 2396:                         }
 2397:                     }
 2398:                 }
 2399:                 if ((setfile) && (filesel != null) && (filesel != 'undefined') && (filesel != '')) {
 2400:                     selelem = form.elements[filesel];
 2401:                     var i, numfiles = selelem.options.length -1;
 2402:                     if (numfiles >=0) {
 2403:                         for (i = numfiles; i >= 0; i--) {
 2404:                             selelem.remove(i);
 2405:                         }
 2406:                     }
 2407:                     var x;
 2408:                     for (x in data.files) {
 2409:                         if (Array.isArray(data.files[x])) {
 2410:                             if (data.files[x].length > 1) {
 2411:                                 selelem.options[selelem.options.length] = new Option('$se','');
 2412:                             }
 2413:                             var len = data.files[x].length;
 2414:                             if (len) {
 2415:                                 var k;
 2416:                                 for (k = 0; k < len; k++) {
 2417:                                     selelem.options[selelem.options.length] = new Option(data.files[x][k],data.files[x][k]);
 2418:                                 }
 2419:                                 selelem.selectedIndex = 0;
 2420:                             }
 2421:                         }
 2422:                     }
 2423:                     if (selelem.options.length == 0) {
 2424:                         selelem.options[selelem.options.length] = new Option('','');
 2425:                         selelem.selectedIndex = 0;
 2426:                     }
 2427:                 }
 2428:             }
 2429:         }
 2430:         http.send(params);
 2431:     }
 2432: END
 2433: }
 2434: 
 2435: =pod
 2436: 
 2437: =head1 Excel and CSV file utility routines
 2438: 
 2439: =cut
 2440: 
 2441: ###############################################################
 2442: ###############################################################
 2443: 
 2444: =pod
 2445: 
 2446: =over 4
 2447: 
 2448: =item * &csv_translate($text) 
 2449: 
 2450: Translate $text to allow it to be output as a 'comma separated values' 
 2451: format.
 2452: 
 2453: =cut
 2454: 
 2455: ###############################################################
 2456: ###############################################################
 2457: sub csv_translate {
 2458:     my $text = shift;
 2459:     $text =~ s/\"/\"\"/g;
 2460:     $text =~ s/\n/ /g;
 2461:     return $text;
 2462: }
 2463: 
 2464: ###############################################################
 2465: ###############################################################
 2466: 
 2467: =pod
 2468: 
 2469: =item * &define_excel_formats()
 2470: 
 2471: Define some commonly used Excel cell formats.
 2472: 
 2473: Currently supported formats:
 2474: 
 2475: =over 4
 2476: 
 2477: =item header
 2478: 
 2479: =item bold
 2480: 
 2481: =item h1
 2482: 
 2483: =item h2
 2484: 
 2485: =item h3
 2486: 
 2487: =item h4
 2488: 
 2489: =item i
 2490: 
 2491: =item date
 2492: 
 2493: =back
 2494: 
 2495: Inputs: $workbook
 2496: 
 2497: Returns: $format, a hash reference.
 2498: 
 2499: 
 2500: =cut
 2501: 
 2502: ###############################################################
 2503: ###############################################################
 2504: sub define_excel_formats {
 2505:     my ($workbook) = @_;
 2506:     my $format;
 2507:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 2508:                                                 bottom    => 1,
 2509:                                                 align     => 'center');
 2510:     $format->{'bold'} = $workbook->add_format(bold=>1);
 2511:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 2512:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 2513:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 2514:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 2515:     $format->{'i'}    = $workbook->add_format(italic=>1);
 2516:     $format->{'date'} = $workbook->add_format(num_format=>
 2517:                                             'mm/dd/yyyy hh:mm:ss');
 2518:     return $format;
 2519: }
 2520: 
 2521: ###############################################################
 2522: ###############################################################
 2523: 
 2524: =pod
 2525: 
 2526: =item * &create_workbook()
 2527: 
 2528: Create an Excel worksheet.  If it fails, output message on the
 2529: request object and return undefs.
 2530: 
 2531: Inputs: Apache request object
 2532: 
 2533: Returns (undef) on failure, 
 2534:     Excel worksheet object, scalar with filename, and formats 
 2535:     from &Apache::loncommon::define_excel_formats on success
 2536: 
 2537: =cut
 2538: 
 2539: ###############################################################
 2540: ###############################################################
 2541: sub create_workbook {
 2542:     my ($r) = @_;
 2543:         #
 2544:     # Create the excel spreadsheet
 2545:     my $filename = '/prtspool/'.
 2546:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2547:         time.'_'.rand(1000000000).'.xls';
 2548:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 2549:     if (! defined($workbook)) {
 2550:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 2551:         $r->print(
 2552:             '<p class="LC_error">'
 2553:            .&mt('Problems occurred in creating the new Excel file.')
 2554:            .' '.&mt('This error has been logged.')
 2555:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2556:            .'</p>'
 2557:         );
 2558:         return (undef);
 2559:     }
 2560:     #
 2561:     $workbook->set_tempdir(LONCAPA::tempdir());
 2562:     #
 2563:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 2564:     return ($workbook,$filename,$format);
 2565: }
 2566: 
 2567: ###############################################################
 2568: ###############################################################
 2569: 
 2570: =pod
 2571: 
 2572: =item * &create_text_file()
 2573: 
 2574: Create a file to write to and eventually make available to the user.
 2575: If file creation fails, outputs an error message on the request object and 
 2576: return undefs.
 2577: 
 2578: Inputs: Apache request object, and file suffix
 2579: 
 2580: Returns (undef) on failure, 
 2581:     Filehandle and filename on success.
 2582: 
 2583: =cut
 2584: 
 2585: ###############################################################
 2586: ###############################################################
 2587: sub create_text_file {
 2588:     my ($r,$suffix) = @_;
 2589:     if (! defined($suffix)) { $suffix = 'txt'; };
 2590:     my $fh;
 2591:     my $filename = '/prtspool/'.
 2592:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2593:         time.'_'.rand(1000000000).'.'.$suffix;
 2594:     $fh = Apache::File->new('>/home/httpd'.$filename);
 2595:     if (! defined($fh)) {
 2596:         $r->log_error("Couldn't open $filename for output $!");
 2597:         $r->print(
 2598:             '<p class="LC_error">'
 2599:            .&mt('Problems occurred in creating the output file.')
 2600:            .' '.&mt('This error has been logged.')
 2601:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2602:            .'</p>'
 2603:         );
 2604:     }
 2605:     return ($fh,$filename)
 2606: }
 2607: 
 2608: 
 2609: =pod 
 2610: 
 2611: =back
 2612: 
 2613: =cut
 2614: 
 2615: ###############################################################
 2616: ##        Home server <option> list generating code          ##
 2617: ###############################################################
 2618: 
 2619: # ------------------------------------------
 2620: 
 2621: sub domain_select {
 2622:     my ($name,$value,$multiple,$incdoms,$excdoms)=@_;
 2623:     my @possdoms;
 2624:     if (ref($incdoms) eq 'ARRAY') {
 2625:         @possdoms = @{$incdoms};
 2626:     } else {
 2627:         @possdoms = &Apache::lonnet::all_domains();
 2628:     }
 2629: 
 2630:     my %domains=map { 
 2631: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 2632:     } @possdoms;
 2633: 
 2634:     if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
 2635:         foreach my $dom (@{$excdoms}) {
 2636:             delete($domains{$dom});
 2637:         }
 2638:     }
 2639: 
 2640:     if ($multiple) {
 2641: 	$domains{''}=&mt('Any domain');
 2642: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2643: 	return &multiple_select_form($name,$value,4,\%domains);
 2644:     } else {
 2645: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2646: 	return &select_form($name,$value,\%domains);
 2647:     }
 2648: }
 2649: 
 2650: #-------------------------------------------
 2651: 
 2652: =pod
 2653: 
 2654: =head1 Routines for form select boxes
 2655: 
 2656: =over 4
 2657: 
 2658: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 2659: 
 2660: Returns a string containing a <select> element int multiple mode
 2661: 
 2662: 
 2663: Args:
 2664:   $name - name of the <select> element
 2665:   $value - scalar or array ref of values that should already be selected
 2666:   $size - number of rows long the select element is
 2667:   $hash - the elements should be 'option' => 'shown text'
 2668:           (shown text should already have been &mt())
 2669:   $order - (optional) array ref of the order to show the elements in
 2670: 
 2671: =cut
 2672: 
 2673: #-------------------------------------------
 2674: sub multiple_select_form {
 2675:     my ($name,$value,$size,$hash,$order)=@_;
 2676:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 2677:     my $output='';
 2678:     if (! defined($size)) {
 2679:         $size = 4;
 2680:         if (scalar(keys(%$hash))<4) {
 2681:             $size = scalar(keys(%$hash));
 2682:         }
 2683:     }
 2684:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 2685:     my @order;
 2686:     if (ref($order) eq 'ARRAY')  {
 2687:         @order = @{$order};
 2688:     } else {
 2689:         @order = sort(keys(%$hash));
 2690:     }
 2691:     if (exists($$hash{'select_form_order'})) {
 2692:         @order = @{$$hash{'select_form_order'}};
 2693:     }
 2694:         
 2695:     foreach my $key (@order) {
 2696:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 2697:         $output.='selected="selected" ' if ($selected{$key});
 2698:         $output.='>'.$hash->{$key}."</option>\n";
 2699:     }
 2700:     $output.="</select>\n";
 2701:     return $output;
 2702: }
 2703: 
 2704: #-------------------------------------------
 2705: 
 2706: =pod
 2707: 
 2708: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
 2709: 
 2710: Returns a string containing a <select name='$name' size='1'> form to 
 2711: allow a user to select options from a ref to a hash containing:
 2712: option_name => displayed text. An optional $onchange can include
 2713: a javascript onchange item, e.g., onchange="this.form.submit();".
 2714: An optional arg -- $readonly -- if true will cause the select form
 2715: to be disabled, e.g., for the case where an instructor has a section-
 2716: specific role, and is viewing/modifying parameters. 
 2717: 
 2718: See lonrights.pm for an example invocation and use.
 2719: 
 2720: =cut
 2721: 
 2722: #-------------------------------------------
 2723: sub select_form {
 2724:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
 2725:     return unless (ref($hashref) eq 'HASH');
 2726:     if ($onchange) {
 2727:         $onchange = ' onchange="'.$onchange.'"';
 2728:     }
 2729:     my $disabled;
 2730:     if ($readonly) {
 2731:         $disabled = ' disabled="disabled"';
 2732:     }
 2733:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2734:     my @keys;
 2735:     if (exists($hashref->{'select_form_order'})) {
 2736: 	@keys=@{$hashref->{'select_form_order'}};
 2737:     } else {
 2738: 	@keys=sort(keys(%{$hashref}));
 2739:     }
 2740:     foreach my $key (@keys) {
 2741:         $selectform.=
 2742: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2743:             ($key eq $def ? 'selected="selected" ' : '').
 2744:                 ">".$hashref->{$key}."</option>\n";
 2745:     }
 2746:     $selectform.="</select>";
 2747:     return $selectform;
 2748: }
 2749: 
 2750: # For display filters
 2751: 
 2752: sub display_filter {
 2753:     my ($context) = @_;
 2754:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2755:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2756:     my $phraseinput = 'hidden';
 2757:     my $includeinput = 'hidden';
 2758:     my ($checked,$includetypestext);
 2759:     if ($env{'form.displayfilter'} eq 'containing') {
 2760:         $phraseinput = 'text'; 
 2761:         if ($context eq 'parmslog') {
 2762:             $includeinput = 'checkbox';
 2763:             if ($env{'form.includetypes'}) {
 2764:                 $checked = ' checked="checked"';
 2765:             }
 2766:             $includetypestext = &mt('Include parameter types');
 2767:         }
 2768:     } else {
 2769:         $includetypestext = '&nbsp;';
 2770:     }
 2771:     my ($additional,$secondid,$thirdid);
 2772:     if ($context eq 'parmslog') {
 2773:         $additional = 
 2774:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2775:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2776:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2777:             '</label>';
 2778:         $secondid = 'includetypes';
 2779:         $thirdid = 'includetypestext';
 2780:     }
 2781:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2782:                                                     '$secondid','$thirdid')";
 2783:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2784: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},'',undef,
 2785: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2786: 	   '</label></span> <span class="LC_nobreak">'.
 2787:            &mt('Filter: [_1]',
 2788: 	   &select_form($env{'form.displayfilter'},
 2789: 			'displayfilter',
 2790: 			{'currentfolder' => 'Current folder/page',
 2791: 			 'containing' => 'Containing phrase',
 2792: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2793: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2794:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2795:                          '" />'.$additional;
 2796: }
 2797: 
 2798: sub display_filter_js {
 2799:     my $includetext = &mt('Include parameter types');
 2800:     return <<"ENDJS";
 2801:   
 2802: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2803:     var firstType = 'hidden';
 2804:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2805:         firstType = 'text';
 2806:     }
 2807:     firstObject = document.getElementById(firstid);
 2808:     if (typeof(firstObject) == 'object') {
 2809:         if (firstObject.type != firstType) {
 2810:             changeInputType(firstObject,firstType);
 2811:         }
 2812:     }
 2813:     if (context == 'parmslog') {
 2814:         var secondType = 'hidden';
 2815:         if (firstType == 'text') {
 2816:             secondType = 'checkbox';
 2817:         }
 2818:         secondObject = document.getElementById(secondid);  
 2819:         if (typeof(secondObject) == 'object') {
 2820:             if (secondObject.type != secondType) {
 2821:                 changeInputType(secondObject,secondType);
 2822:             }
 2823:         }
 2824:         var textItem = document.getElementById(thirdid);
 2825:         var currtext = textItem.innerHTML;
 2826:         var newtext;
 2827:         if (firstType == 'text') {
 2828:             newtext = '$includetext';
 2829:         } else {
 2830:             newtext = '&nbsp;';
 2831:         }
 2832:         if (currtext != newtext) {
 2833:             textItem.innerHTML = newtext;
 2834:         }
 2835:     }
 2836:     return;
 2837: }
 2838: 
 2839: function changeInputType(oldObject,newType) {
 2840:     var newObject = document.createElement('input');
 2841:     newObject.type = newType;
 2842:     if (oldObject.size) {
 2843:         newObject.size = oldObject.size;
 2844:     }
 2845:     if (oldObject.value) {
 2846:         newObject.value = oldObject.value;
 2847:     }
 2848:     if (oldObject.name) {
 2849:         newObject.name = oldObject.name;
 2850:     }
 2851:     if (oldObject.id) {
 2852:         newObject.id = oldObject.id;
 2853:     }
 2854:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2855:     return;
 2856: }
 2857: 
 2858: ENDJS
 2859: }
 2860: 
 2861: sub gradeleveldescription {
 2862:     my $gradelevel=shift;
 2863:     my %gradelevels=(0 => 'Not specified',
 2864: 		     1 => 'Grade 1',
 2865: 		     2 => 'Grade 2',
 2866: 		     3 => 'Grade 3',
 2867: 		     4 => 'Grade 4',
 2868: 		     5 => 'Grade 5',
 2869: 		     6 => 'Grade 6',
 2870: 		     7 => 'Grade 7',
 2871: 		     8 => 'Grade 8',
 2872: 		     9 => 'Grade 9',
 2873: 		     10 => 'Grade 10',
 2874: 		     11 => 'Grade 11',
 2875: 		     12 => 'Grade 12',
 2876: 		     13 => 'Grade 13',
 2877: 		     14 => '100 Level',
 2878: 		     15 => '200 Level',
 2879: 		     16 => '300 Level',
 2880: 		     17 => '400 Level',
 2881: 		     18 => 'Graduate Level');
 2882:     return &mt($gradelevels{$gradelevel});
 2883: }
 2884: 
 2885: sub select_level_form {
 2886:     my ($deflevel,$name)=@_;
 2887:     unless ($deflevel) { $deflevel=0; }
 2888:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2889:     for (my $i=0; $i<=18; $i++) {
 2890:         $selectform.="<option value=\"$i\" ".
 2891:             ($i==$deflevel ? 'selected="selected" ' : '').
 2892:                 ">".&gradeleveldescription($i)."</option>\n";
 2893:     }
 2894:     $selectform.="</select>";
 2895:     return $selectform;
 2896: }
 2897: 
 2898: #-------------------------------------------
 2899: 
 2900: =pod
 2901: 
 2902: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
 2903: 
 2904: Returns a string containing a <select name='$name' size='1'> form to 
 2905: allow a user to select the domain to preform an operation in.  
 2906: See loncreateuser.pm for an example invocation and use.
 2907: 
 2908: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2909: selected");
 2910: 
 2911: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2912: 
 2913: 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.
 2914: 
 2915: The optional $incdoms is a reference to an array of domains which will be the only available options.
 2916: 
 2917: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
 2918: 
 2919: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
 2920: 
 2921: =cut
 2922: 
 2923: #-------------------------------------------
 2924: sub select_dom_form {
 2925:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
 2926:     if ($onchange) {
 2927:         $onchange = ' onchange="'.$onchange.'"';
 2928:     }
 2929:     if ($disabled) {
 2930:         $disabled = ' disabled="disabled"';
 2931:     }
 2932:     my (@domains,%exclude);
 2933:     if (ref($incdoms) eq 'ARRAY') {
 2934:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2935:     } else {
 2936:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2937:     }
 2938:     if ($includeempty) { @domains=('',@domains); }
 2939:     if (ref($excdoms) eq 'ARRAY') {
 2940:         map { $exclude{$_} = 1; } @{$excdoms}; 
 2941:     }
 2942:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2943:     foreach my $dom (@domains) {
 2944:         next if ($exclude{$dom});
 2945:         $selectdomain.="<option value=\"$dom\" ".
 2946:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2947:         if ($showdomdesc) {
 2948:             if ($dom ne '') {
 2949:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2950:                 if ($domdesc ne '') {
 2951:                     $selectdomain .= ' ('.$domdesc.')';
 2952:                 }
 2953:             } 
 2954:         }
 2955:         $selectdomain .= "</option>\n";
 2956:     }
 2957:     $selectdomain.="</select>";
 2958:     return $selectdomain;
 2959: }
 2960: 
 2961: #-------------------------------------------
 2962: 
 2963: =pod
 2964: 
 2965: =item * &home_server_form_item($domain,$name,$defaultflag)
 2966: 
 2967: input: 4 arguments (two required, two optional) - 
 2968:     $domain - domain of new user
 2969:     $name - name of form element
 2970:     $default - Value of 'default' causes a default item to be first 
 2971:                             option, and selected by default. 
 2972:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2973:                             if 1 server found, or default, if 0 found.
 2974: output: returns 2 items: 
 2975: (a) form element which contains either:
 2976:    (i) <select name="$name">
 2977:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2978:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2979:        </select>
 2980:        form item if there are multiple library servers in $domain, or
 2981:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2982:        if there is only one library server in $domain.
 2983: 
 2984: (b) number of library servers found.
 2985: 
 2986: See loncreateuser.pm for example of use.
 2987: 
 2988: =cut
 2989: 
 2990: #-------------------------------------------
 2991: sub home_server_form_item {
 2992:     my ($domain,$name,$default,$hide) = @_;
 2993:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2994:     my $result;
 2995:     my $numlib = keys(%servers);
 2996:     if ($numlib > 1) {
 2997:         $result .= '<select name="'.$name.'" />'."\n";
 2998:         if ($default) {
 2999:             $result .= '<option value="default" selected="selected">'.&mt('default').
 3000:                        '</option>'."\n";
 3001:         }
 3002:         foreach my $hostid (sort(keys(%servers))) {
 3003:             $result.= '<option value="'.$hostid.'">'.
 3004: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 3005:         }
 3006:         $result .= '</select>'."\n";
 3007:     } elsif ($numlib == 1) {
 3008:         my $hostid;
 3009:         foreach my $item (keys(%servers)) {
 3010:             $hostid = $item;
 3011:         }
 3012:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 3013:                    $hostid.'" />';
 3014:                    if (!$hide) {
 3015:                        $result .= $hostid.' '.$servers{$hostid};
 3016:                    }
 3017:                    $result .= "\n";
 3018:     } elsif ($default) {
 3019:         $result .= '<input type="hidden" name="'.$name.
 3020:                    '" value="default" />';
 3021:                    if (!$hide) {
 3022:                        $result .= &mt('default');
 3023:                    }
 3024:                    $result .= "\n";
 3025:     }
 3026:     return ($result,$numlib);
 3027: }
 3028: 
 3029: =pod
 3030: 
 3031: =back 
 3032: 
 3033: =cut
 3034: 
 3035: ###############################################################
 3036: ##                  Decoding User Agent                      ##
 3037: ###############################################################
 3038: 
 3039: =pod
 3040: 
 3041: =head1 Decoding the User Agent
 3042: 
 3043: =over 4
 3044: 
 3045: =item * &decode_user_agent()
 3046: 
 3047: Inputs: $r
 3048: 
 3049: Outputs:
 3050: 
 3051: =over 4
 3052: 
 3053: =item * $httpbrowser
 3054: 
 3055: =item * $clientbrowser
 3056: 
 3057: =item * $clientversion
 3058: 
 3059: =item * $clientmathml
 3060: 
 3061: =item * $clientunicode
 3062: 
 3063: =item * $clientos
 3064: 
 3065: =item * $clientmobile
 3066: 
 3067: =item * $clientinfo
 3068: 
 3069: =item * $clientosversion
 3070: 
 3071: =back
 3072: 
 3073: =back 
 3074: 
 3075: =cut
 3076: 
 3077: ###############################################################
 3078: ###############################################################
 3079: sub decode_user_agent {
 3080:     my ($r)=@_;
 3081:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 3082:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 3083:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 3084:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 3085:     my $clientbrowser='unknown';
 3086:     my $clientversion='0';
 3087:     my $clientmathml='';
 3088:     my $clientunicode='0';
 3089:     my $clientmobile=0;
 3090:     my $clientosversion='';
 3091:     for (my $i=0;$i<=$#browsertype;$i++) {
 3092:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
 3093: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 3094: 	    $clientbrowser=$bname;
 3095:             $httpbrowser=~/$vreg/i;
 3096: 	    $clientversion=$1;
 3097:             $clientmathml=($clientversion>=$minv);
 3098:             $clientunicode=($clientversion>=$univ);
 3099: 	}
 3100:     }
 3101:     my $clientos='unknown';
 3102:     my $clientinfo;
 3103:     if (($httpbrowser=~/linux/i) ||
 3104:         ($httpbrowser=~/unix/i) ||
 3105:         ($httpbrowser=~/ux/i) ||
 3106:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 3107:     if (($httpbrowser=~/vax/i) ||
 3108:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 3109:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 3110:     if (($httpbrowser=~/mac/i) ||
 3111:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 3112:     if ($httpbrowser=~/win/i) {
 3113:         $clientos='win';
 3114:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
 3115:             $clientosversion = $1;
 3116:         }
 3117:     }
 3118:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 3119:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 3120:         $clientmobile=lc($1);
 3121:     }
 3122:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 3123:         $clientinfo = 'firefox-'.$1;
 3124:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 3125:         $clientinfo = 'chromeframe-'.$1;
 3126:     }
 3127:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 3128:             $clientunicode,$clientos,$clientmobile,$clientinfo,
 3129:             $clientosversion);
 3130: }
 3131: 
 3132: ###############################################################
 3133: ##    Authentication changing form generation subroutines    ##
 3134: ###############################################################
 3135: ##
 3136: ## All of the authform_xxxxxxx subroutines take their inputs in a
 3137: ## hash, and have reasonable default values.
 3138: ##
 3139: ##    formname = the name given in the <form> tag.
 3140: #-------------------------------------------
 3141: 
 3142: =pod
 3143: 
 3144: =head1 Authentication Routines
 3145: 
 3146: =over 4
 3147: 
 3148: =item * &authform_xxxxxx()
 3149: 
 3150: The authform_xxxxxx subroutines provide javascript and html forms which 
 3151: handle some of the conveniences required for authentication forms.  
 3152: This is not an optimal method, but it works.  
 3153: 
 3154: =over 4
 3155: 
 3156: =item * authform_header
 3157: 
 3158: =item * authform_authorwarning
 3159: 
 3160: =item * authform_nochange
 3161: 
 3162: =item * authform_kerberos
 3163: 
 3164: =item * authform_internal
 3165: 
 3166: =item * authform_filesystem
 3167: 
 3168: =item * authform_lti
 3169: 
 3170: =back
 3171: 
 3172: See loncreateuser.pm for invocation and use examples.
 3173: 
 3174: =cut
 3175: 
 3176: #-------------------------------------------
 3177: sub authform_header{  
 3178:     my %in = (
 3179:         formname => 'cu',
 3180:         kerb_def_dom => '',
 3181:         @_,
 3182:     );
 3183:     $in{'formname'} = 'document.' . $in{'formname'};
 3184:     my $result='';
 3185: 
 3186: #---------------------------------------------- Code for upper case translation
 3187:     my $Javascript_toUpperCase;
 3188:     unless ($in{kerb_def_dom}) {
 3189:         $Javascript_toUpperCase =<<"END";
 3190:         switch (choice) {
 3191:            case 'krb': currentform.elements[choicearg].value =
 3192:                currentform.elements[choicearg].value.toUpperCase();
 3193:                break;
 3194:            default:
 3195:         }
 3196: END
 3197:     } else {
 3198:         $Javascript_toUpperCase = "";
 3199:     }
 3200: 
 3201:     my $radioval = "'nochange'";
 3202:     if (defined($in{'curr_authtype'})) {
 3203:         if ($in{'curr_authtype'} ne '') {
 3204:             $radioval = "'".$in{'curr_authtype'}."arg'";
 3205:         }
 3206:     }
 3207:     my $argfield = 'null';
 3208:     if (defined($in{'mode'})) {
 3209:         if ($in{'mode'} eq 'modifycourse')  {
 3210:             if (defined($in{'curr_autharg'})) {
 3211:                 if ($in{'curr_autharg'} ne '') {
 3212:                     $argfield = "'$in{'curr_autharg'}'";
 3213:                 }
 3214:             }
 3215:         }
 3216:     }
 3217: 
 3218:     $result.=<<"END";
 3219: var current = new Object();
 3220: current.radiovalue = $radioval;
 3221: current.argfield = $argfield;
 3222: 
 3223: function changed_radio(choice,currentform) {
 3224:     var choicearg = choice + 'arg';
 3225:     // If a radio button in changed, we need to change the argfield
 3226:     if (current.radiovalue != choice) {
 3227:         current.radiovalue = choice;
 3228:         if (current.argfield != null) {
 3229:             currentform.elements[current.argfield].value = '';
 3230:         }
 3231:         if (choice == 'nochange') {
 3232:             current.argfield = null;
 3233:         } else {
 3234:             current.argfield = choicearg;
 3235:             switch(choice) {
 3236:                 case 'krb': 
 3237:                     currentform.elements[current.argfield].value = 
 3238:                         "$in{'kerb_def_dom'}";
 3239:                 break;
 3240:               default:
 3241:                 break;
 3242:             }
 3243:         }
 3244:     }
 3245:     return;
 3246: }
 3247: 
 3248: function changed_text(choice,currentform) {
 3249:     var choicearg = choice + 'arg';
 3250:     if (currentform.elements[choicearg].value !='') {
 3251:         $Javascript_toUpperCase
 3252:         // clear old field
 3253:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 3254:             currentform.elements[current.argfield].value = '';
 3255:         }
 3256:         current.argfield = choicearg;
 3257:     }
 3258:     set_auth_radio_buttons(choice,currentform);
 3259:     return;
 3260: }
 3261: 
 3262: function set_auth_radio_buttons(newvalue,currentform) {
 3263:     var numauthchoices = currentform.login.length;
 3264:     if (typeof numauthchoices  == "undefined") {
 3265:         return;
 3266:     } 
 3267:     var i=0;
 3268:     while (i < numauthchoices) {
 3269:         if (currentform.login[i].value == newvalue) { break; }
 3270:         i++;
 3271:     }
 3272:     if (i == numauthchoices) {
 3273:         return;
 3274:     }
 3275:     current.radiovalue = newvalue;
 3276:     currentform.login[i].checked = true;
 3277:     return;
 3278: }
 3279: END
 3280:     return $result;
 3281: }
 3282: 
 3283: sub authform_authorwarning {
 3284:     my $result='';
 3285:     $result='<i>'.
 3286:         &mt('As a general rule, only authors or co-authors should be '.
 3287:             'filesystem authenticated '.
 3288:             '(which allows access to the server filesystem).')."</i>\n";
 3289:     return $result;
 3290: }
 3291: 
 3292: sub authform_nochange {
 3293:     my %in = (
 3294:               formname => 'document.cu',
 3295:               kerb_def_dom => 'MSU.EDU',
 3296:               @_,
 3297:           );
 3298:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3299:     my $result;
 3300:     if (!$authnum) {
 3301:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 3302:     } else {
 3303:         $result = '<label>'.&mt('[_1] Do not change login data',
 3304:                   '<input type="radio" name="login" value="nochange" '.
 3305:                   'checked="checked" onclick="'.
 3306:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 3307: 	    '</label>';
 3308:     }
 3309:     return $result;
 3310: }
 3311: 
 3312: sub authform_kerberos {
 3313:     my %in = (
 3314:               formname => 'document.cu',
 3315:               kerb_def_dom => 'MSU.EDU',
 3316:               kerb_def_auth => 'krb4',
 3317:               @_,
 3318:               );
 3319:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 3320:         $autharg,$jscall,$disabled);
 3321:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3322:     if ($in{'kerb_def_auth'} eq 'krb5') {
 3323:        $check5 = ' checked="checked"';
 3324:     } else {
 3325:        $check4 = ' checked="checked"';
 3326:     }
 3327:     if ($in{'readonly'}) {
 3328:         $disabled = ' disabled="disabled"';
 3329:     }
 3330:     $krbarg = $in{'kerb_def_dom'};
 3331:     if (defined($in{'curr_authtype'})) {
 3332:         if ($in{'curr_authtype'} eq 'krb') {
 3333:             $krbcheck = ' checked="checked"';
 3334:             if (defined($in{'mode'})) {
 3335:                 if ($in{'mode'} eq 'modifyuser') {
 3336:                     $krbcheck = '';
 3337:                 }
 3338:             }
 3339:             if (defined($in{'curr_kerb_ver'})) {
 3340:                 if ($in{'curr_krb_ver'} eq '5') {
 3341:                     $check5 = ' checked="checked"';
 3342:                     $check4 = '';
 3343:                 } else {
 3344:                     $check4 = ' checked="checked"';
 3345:                     $check5 = '';
 3346:                 }
 3347:             }
 3348:             if (defined($in{'curr_autharg'})) {
 3349:                 $krbarg = $in{'curr_autharg'};
 3350:             }
 3351:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 3352:                 if (defined($in{'curr_autharg'})) {
 3353:                     $result = 
 3354:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 3355:         $in{'curr_autharg'},$krbver);
 3356:                 } else {
 3357:                     $result =
 3358:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 3359:                 }
 3360:                 return $result; 
 3361:             }
 3362:         }
 3363:     } else {
 3364:         if ($authnum == 1) {
 3365:             $authtype = '<input type="hidden" name="login" value="krb" />';
 3366:         }
 3367:     }
 3368:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 3369:         return;
 3370:     } elsif ($authtype eq '') {
 3371:         if (defined($in{'mode'})) {
 3372:             if ($in{'mode'} eq 'modifycourse') {
 3373:                 if ($authnum == 1) {
 3374:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
 3375:                 }
 3376:             }
 3377:         }
 3378:     }
 3379:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 3380:     if ($authtype eq '') {
 3381:         $authtype = '<input type="radio" name="login" value="krb" '.
 3382:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 3383:                     $krbcheck.$disabled.' />';
 3384:     }
 3385:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 3386:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 3387:          $in{'curr_authtype'} eq 'krb5') ||
 3388:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 3389:          $in{'curr_authtype'} eq 'krb4')) {
 3390:         $result .= &mt
 3391:         ('[_1] Kerberos authenticated with domain [_2] '.
 3392:          '[_3] Version 4 [_4] Version 5 [_5]',
 3393:          '<label>'.$authtype,
 3394:          '</label><input type="text" size="10" name="krbarg" '.
 3395:              'value="'.$krbarg.'" '.
 3396:              'onchange="'.$jscall.'"'.$disabled.' />',
 3397:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
 3398:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
 3399: 	 '</label>');
 3400:     } elsif ($can_assign{'krb4'}) {
 3401:         $result .= &mt
 3402:         ('[_1] Kerberos authenticated with domain [_2] '.
 3403:          '[_3] Version 4 [_4]',
 3404:          '<label>'.$authtype,
 3405:          '</label><input type="text" size="10" name="krbarg" '.
 3406:              'value="'.$krbarg.'" '.
 3407:              'onchange="'.$jscall.'"'.$disabled.' />',
 3408:          '<label><input type="hidden" name="krbver" value="4" />',
 3409:          '</label>');
 3410:     } elsif ($can_assign{'krb5'}) {
 3411:         $result .= &mt
 3412:         ('[_1] Kerberos authenticated with domain [_2] '.
 3413:          '[_3] Version 5 [_4]',
 3414:          '<label>'.$authtype,
 3415:          '</label><input type="text" size="10" name="krbarg" '.
 3416:              'value="'.$krbarg.'" '.
 3417:              'onchange="'.$jscall.'"'.$disabled.' />',
 3418:          '<label><input type="hidden" name="krbver" value="5" />',
 3419:          '</label>');
 3420:     }
 3421:     return $result;
 3422: }
 3423: 
 3424: sub authform_internal {
 3425:     my %in = (
 3426:                 formname => 'document.cu',
 3427:                 kerb_def_dom => 'MSU.EDU',
 3428:                 @_,
 3429:                 );
 3430:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
 3431:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3432:     if ($in{'readonly'}) {
 3433:         $disabled = ' disabled="disabled"';
 3434:     }
 3435:     if (defined($in{'curr_authtype'})) {
 3436:         if ($in{'curr_authtype'} eq 'int') {
 3437:             if ($can_assign{'int'}) {
 3438:                 $intcheck = 'checked="checked" ';
 3439:                 if (defined($in{'mode'})) {
 3440:                     if ($in{'mode'} eq 'modifyuser') {
 3441:                         $intcheck = '';
 3442:                     }
 3443:                 }
 3444:                 if (defined($in{'curr_autharg'})) {
 3445:                     $intarg = $in{'curr_autharg'};
 3446:                 }
 3447:             } else {
 3448:                 $result = &mt('Currently internally authenticated.');
 3449:                 return $result;
 3450:             }
 3451:         }
 3452:     } else {
 3453:         if ($authnum == 1) {
 3454:             $authtype = '<input type="hidden" name="login" value="int" />';
 3455:         }
 3456:     }
 3457:     if (!$can_assign{'int'}) {
 3458:         return;
 3459:     } elsif ($authtype eq '') {
 3460:         if (defined($in{'mode'})) {
 3461:             if ($in{'mode'} eq 'modifycourse') {
 3462:                 if ($authnum == 1) {
 3463:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
 3464:                 }
 3465:             }
 3466:         }
 3467:     }
 3468:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 3469:     if ($authtype eq '') {
 3470:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 3471:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
 3472:     }
 3473:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 3474:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3475:     $result = &mt
 3476:         ('[_1] Internally authenticated (with initial password [_2])',
 3477:          '<label>'.$authtype,'</label>'.$autharg);
 3478:     $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>';
 3479:     return $result;
 3480: }
 3481: 
 3482: sub authform_local {
 3483:     my %in = (
 3484:               formname => 'document.cu',
 3485:               kerb_def_dom => 'MSU.EDU',
 3486:               @_,
 3487:               );
 3488:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
 3489:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3490:     if ($in{'readonly'}) {
 3491:         $disabled = ' disabled="disabled"';
 3492:     } 
 3493:     if (defined($in{'curr_authtype'})) {
 3494:         if ($in{'curr_authtype'} eq 'loc') {
 3495:             if ($can_assign{'loc'}) {
 3496:                 $loccheck = 'checked="checked" ';
 3497:                 if (defined($in{'mode'})) {
 3498:                     if ($in{'mode'} eq 'modifyuser') {
 3499:                         $loccheck = '';
 3500:                     }
 3501:                 }
 3502:                 if (defined($in{'curr_autharg'})) {
 3503:                     $locarg = $in{'curr_autharg'};
 3504:                 }
 3505:             } else {
 3506:                 $result = &mt('Currently using local (institutional) authentication.');
 3507:                 return $result;
 3508:             }
 3509:         }
 3510:     } else {
 3511:         if ($authnum == 1) {
 3512:             $authtype = '<input type="hidden" name="login" value="loc" />';
 3513:         }
 3514:     }
 3515:     if (!$can_assign{'loc'}) {
 3516:         return;
 3517:     } elsif ($authtype eq '') {
 3518:         if (defined($in{'mode'})) {
 3519:             if ($in{'mode'} eq 'modifycourse') {
 3520:                 if ($authnum == 1) {
 3521:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
 3522:                 }
 3523:             }
 3524:         }
 3525:     }
 3526:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 3527:     if ($authtype eq '') {
 3528:         $authtype = '<input type="radio" name="login" value="loc" '.
 3529:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 3530:                     $jscall.'"'.$disabled.' />';
 3531:     }
 3532:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 3533:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3534:     $result = &mt('[_1] Local Authentication with argument [_2]',
 3535:                   '<label>'.$authtype,'</label>'.$autharg);
 3536:     return $result;
 3537: }
 3538: 
 3539: sub authform_filesystem {
 3540:     my %in = (
 3541:               formname => 'document.cu',
 3542:               kerb_def_dom => 'MSU.EDU',
 3543:               @_,
 3544:               );
 3545:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
 3546:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3547:     if ($in{'readonly'}) {
 3548:         $disabled = ' disabled="disabled"';
 3549:     }
 3550:     if (defined($in{'curr_authtype'})) {
 3551:         if ($in{'curr_authtype'} eq 'fsys') {
 3552:             if ($can_assign{'fsys'}) {
 3553:                 $fsyscheck = 'checked="checked" ';
 3554:                 if (defined($in{'mode'})) {
 3555:                     if ($in{'mode'} eq 'modifyuser') {
 3556:                         $fsyscheck = '';
 3557:                     }
 3558:                 }
 3559:             } else {
 3560:                 $result = &mt('Currently Filesystem Authenticated.');
 3561:                 return $result;
 3562:             }
 3563:         }
 3564:     } else {
 3565:         if ($authnum == 1) {
 3566:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 3567:         }
 3568:     }
 3569:     if (!$can_assign{'fsys'}) {
 3570:         return;
 3571:     } elsif ($authtype eq '') {
 3572:         if (defined($in{'mode'})) {
 3573:             if ($in{'mode'} eq 'modifycourse') {
 3574:                 if ($authnum == 1) {
 3575:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
 3576:                 }
 3577:             }
 3578:         }
 3579:     }
 3580:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 3581:     if ($authtype eq '') {
 3582:         $authtype = '<input type="radio" name="login" value="fsys" '.
 3583:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 3584:                     $jscall.'"'.$disabled.' />';
 3585:     }
 3586:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
 3587:                ' onchange="'.$jscall.'"'.$disabled.' />';
 3588:     $result = &mt
 3589:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 3590:          '<label>'.$authtype,'</label>'.$autharg);
 3591:     return $result;
 3592: }
 3593: 
 3594: sub authform_lti {
 3595:     my %in = (
 3596:               formname => 'document.cu',
 3597:               kerb_def_dom => 'MSU.EDU',
 3598:               @_,
 3599:               );
 3600:     my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
 3601:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3602:     if ($in{'readonly'}) {
 3603:         $disabled = ' disabled="disabled"';
 3604:     }
 3605:     if (defined($in{'curr_authtype'})) {
 3606:         if ($in{'curr_authtype'} eq 'lti') {
 3607:             if ($can_assign{'lti'}) {
 3608:                 $lticheck = 'checked="checked" ';
 3609:                 if (defined($in{'mode'})) {
 3610:                     if ($in{'mode'} eq 'modifyuser') {
 3611:                         $lticheck = '';
 3612:                     }
 3613:                 }
 3614:             } else {
 3615:                 $result = &mt('Currently LTI Authenticated.');
 3616:                 return $result;
 3617:             }
 3618:         }
 3619:     } else {
 3620:         if ($authnum == 1) {
 3621:             $authtype = '<input type="hidden" name="login" value="lti" />';
 3622:         }
 3623:     }
 3624:     if (!$can_assign{'lti'}) {
 3625:         return;
 3626:     } elsif ($authtype eq '') {
 3627:         if (defined($in{'mode'})) {
 3628:             if ($in{'mode'} eq 'modifycourse') {
 3629:                 if ($authnum == 1) {
 3630:                     $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
 3631:                 }
 3632:             }
 3633:         }
 3634:     }
 3635:     $jscall = "javascript:changed_radio('lti',$in{'formname'});";
 3636:     if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
 3637:         $authtype = '<input type="radio" name="login" value="lti" '.
 3638:                     $lticheck.' onchange="'.$jscall.'" onclick="'.
 3639:                     $jscall.'"'.$disabled.' />';
 3640:     }
 3641:     $autharg = '<input type="hidden" name="ltiarg" value="" />';
 3642:     if ($authtype) {
 3643:         $result = &mt('[_1] LTI Authenticated',
 3644:                       '<label>'.$authtype.'</label>'.$autharg);
 3645:     } else {
 3646:         $result = '<b>'.&mt('LTI Authenticated').'</b>'.
 3647:                   $autharg;
 3648:     }
 3649:     return $result;
 3650: }
 3651: 
 3652: sub get_assignable_auth {
 3653:     my ($dom) = @_;
 3654:     if ($dom eq '') {
 3655:         $dom = $env{'request.role.domain'};
 3656:     }
 3657:     my %can_assign = (
 3658:                           krb4 => 1,
 3659:                           krb5 => 1,
 3660:                           int  => 1,
 3661:                           loc  => 1,
 3662:                           lti  => 1,
 3663:                      );
 3664:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 3665:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 3666:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 3667:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 3668:             my $context;
 3669:             if ($env{'request.role'} =~ /^au/) {
 3670:                 $context = 'author';
 3671:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
 3672:                 $context = 'domain';
 3673:             } elsif ($env{'request.course.id'}) {
 3674:                 $context = 'course';
 3675:             }
 3676:             if ($context) {
 3677:                 if (ref($authhash->{$context}) eq 'HASH') {
 3678:                    %can_assign = %{$authhash->{$context}}; 
 3679:                 }
 3680:             }
 3681:         }
 3682:     }
 3683:     my $authnum = 0;
 3684:     foreach my $key (keys(%can_assign)) {
 3685:         if ($can_assign{$key}) {
 3686:             $authnum ++;
 3687:         }
 3688:     }
 3689:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 3690:         $authnum --;
 3691:     }
 3692:     return ($authnum,%can_assign);
 3693: }
 3694: 
 3695: sub check_passwd_rules {
 3696:     my ($domain,$plainpass) = @_;
 3697:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
 3698:     my ($min,$max,@chars,@brokerule,$warning);
 3699:     $min = $Apache::lonnet::passwdmin;
 3700:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
 3701:         if ($passwdconf{'min'} =~ /^\d+$/) {
 3702:             if ($passwdconf{'min'} > $min) {
 3703:                 $min = $passwdconf{'min'};
 3704:             }
 3705:         }
 3706:         if ($passwdconf{'max'} =~ /^\d+$/) {
 3707:             $max = $passwdconf{'max'};
 3708:         }
 3709:         @chars = @{$passwdconf{'chars'}};
 3710:     }
 3711:     if (($min) && (length($plainpass) < $min)) {
 3712:         push(@brokerule,'min');
 3713:     }
 3714:     if (($max) && (length($plainpass) > $max)) {
 3715:         push(@brokerule,'max');
 3716:     }
 3717:     if (@chars) {
 3718:         my %rules;
 3719:         map { $rules{$_} = 1; } @chars;
 3720:         if ($rules{'uc'}) {
 3721:             unless ($plainpass =~ /[A-Z]/) {
 3722:                 push(@brokerule,'uc');
 3723:             }
 3724:         }
 3725:         if ($rules{'lc'}) {
 3726:             unless ($plainpass =~ /[a-z]/) {
 3727:                 push(@brokerule,'lc');
 3728:             }
 3729:         }
 3730:         if ($rules{'num'}) {
 3731:             unless ($plainpass =~ /\d/) {
 3732:                 push(@brokerule,'num');
 3733:             }
 3734:         }
 3735:         if ($rules{'spec'}) {
 3736:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
 3737:                 push(@brokerule,'spec');
 3738:             }
 3739:         }
 3740:     }
 3741:     if (@brokerule) {
 3742:         my %rulenames = &Apache::lonlocal::texthash(
 3743:             uc   => 'At least one upper case letter',
 3744:             lc   => 'At least one lower case letter',
 3745:             num  => 'At least one number',
 3746:             spec => 'At least one non-alphanumeric',
 3747:         );
 3748:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
 3749:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
 3750:         $rulenames{'num'} .= ': 0123456789';
 3751:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
 3752:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
 3753:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
 3754:         $warning = &mt('Password did not satisfy the following:').'<ul>';
 3755:         foreach my $rule ('min','max','uc','lc','num','spec') {
 3756:             if (grep(/^$rule$/,@brokerule)) {
 3757:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
 3758:             }
 3759:         }
 3760:         $warning .= '</ul>';
 3761:     }
 3762:     if (wantarray) {
 3763:         return @brokerule;
 3764:     }
 3765:     return $warning;
 3766: }
 3767: 
 3768: sub passwd_validation_js {
 3769:     my ($currpasswdval,$domain,$context,$id) = @_;
 3770:     my (%passwdconf,$alertmsg);
 3771:     if ($context eq 'linkprot') {
 3772:         my %domconfig = &Apache::lonnet::get_dom('configuration',['ltisec'],$domain);
 3773:         if (ref($domconfig{'ltisec'}) eq 'HASH') {
 3774:             if (ref($domconfig{'ltisec'}{'rules'}) eq 'HASH') {
 3775:                 %passwdconf = %{$domconfig{'ltisec'}{'rules'}};
 3776:             }
 3777:         }
 3778:         if ($id eq 'add') {
 3779:             $alertmsg = &mt('Secret for added launcher did not satisfy requirement(s):').'\n\n';
 3780:         } elsif ($id =~ /^\d+$/) {
 3781:             my $pos = $id+1;
 3782:             $alertmsg = &mt('Secret for launcher [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
 3783:         } else {
 3784:             $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
 3785:         }
 3786:     } else {
 3787:         %passwdconf = &Apache::lonnet::get_passwdconf($domain);
 3788:         $alertmsg = &mt('Initial password did not satisfy requirement(s):').'\n\n';
 3789:     }
 3790:     my ($min,$max,@chars,$numrules,$intargjs,%alert);
 3791:     $numrules = 0;
 3792:     $min = $Apache::lonnet::passwdmin;
 3793:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
 3794:         if ($passwdconf{'min'} =~ /^\d+$/) {
 3795:             if ($passwdconf{'min'} > $min) {
 3796:                 $min = $passwdconf{'min'};
 3797:             }
 3798:         }
 3799:         if ($passwdconf{'max'} =~ /^\d+$/) {
 3800:             $max = $passwdconf{'max'};
 3801:             $numrules ++;
 3802:         }
 3803:         @chars = @{$passwdconf{'chars'}};
 3804:         if (@chars) {
 3805:             $numrules ++;
 3806:         }
 3807:     }
 3808:     if ($min > 0) {
 3809:         $numrules ++;
 3810:     }
 3811:     if (($min > 0) || ($max ne '') || (@chars > 0)) {
 3812:         if ($min) {
 3813:             $alert{'min'} = &mt('minimum [quant,_1,character]',$min).'\n';
 3814:         }
 3815:         if ($max) {
 3816:             $alert{'max'} = &mt('maximum [quant,_1,character]',$max).'\n';
 3817:         }
 3818:         my (@charalerts,@charrules);
 3819:         if (@chars) {
 3820:             if (grep(/^uc$/,@chars)) {
 3821:                 push(@charalerts,&mt('contain at least one upper case letter'));
 3822:                 push(@charrules,'uc');
 3823:             }
 3824:             if (grep(/^lc$/,@chars)) {
 3825:                 push(@charalerts,&mt('contain at least one lower case letter'));
 3826:                 push(@charrules,'lc');
 3827:             }
 3828:             if (grep(/^num$/,@chars)) {
 3829:                 push(@charalerts,&mt('contain at least one number'));
 3830:                 push(@charrules,'num');
 3831:             }
 3832:             if (grep(/^spec$/,@chars)) {
 3833:                 push(@charalerts,&mt('contain at least one non-alphanumeric'));
 3834:                 push(@charrules,'spec');
 3835:             }
 3836:         }
 3837:         $intargjs = qq|            var rulesmsg = '';\n|.
 3838:                     qq|            var currpwval = $currpasswdval;\n|;
 3839:             if ($min) {
 3840:                 $intargjs .= qq|
 3841:             if (currpwval.length < $min) {
 3842:                 rulesmsg += ' - $alert{min}';
 3843:             }
 3844: |;
 3845:             }
 3846:             if ($max) {
 3847:                 $intargjs .= qq|
 3848:             if (currpwval.length > $max) {
 3849:                 rulesmsg += ' - $alert{max}';
 3850:             }
 3851: |;
 3852:             }
 3853:             if (@chars > 0) {
 3854:                 my $charrulestr = '"'.join('","',@charrules).'"';
 3855:                 my $charalertstr = '"'.join('","',@charalerts).'"';
 3856:                 $intargjs .= qq|            var brokerules = new Array();\n|.
 3857:                              qq|            var charrules = new Array($charrulestr);\n|.
 3858:                              qq|            var charalerts = new Array($charalertstr);\n|;
 3859:                 my %rules;
 3860:                 map { $rules{$_} = 1; } @chars;
 3861:                 if ($rules{'uc'}) {
 3862:                     $intargjs .= qq|
 3863:             var ucRegExp = /[A-Z]/;
 3864:             if (!ucRegExp.test(currpwval)) {
 3865:                 brokerules.push('uc');
 3866:             }
 3867: |;
 3868:                 }
 3869:                 if ($rules{'lc'}) {
 3870:                     $intargjs .= qq|
 3871:             var lcRegExp = /[a-z]/;
 3872:             if (!lcRegExp.test(currpwval)) {
 3873:                 brokerules.push('lc');
 3874:             }
 3875: |;
 3876:                 }
 3877:                 if ($rules{'num'}) {
 3878:                      $intargjs .= qq|
 3879:             var numRegExp = /[0-9]/;
 3880:             if (!numRegExp.test(currpwval)) {
 3881:                 brokerules.push('num');
 3882:             }
 3883: |;
 3884:                 }
 3885:                 if ($rules{'spec'}) {
 3886:                      $intargjs .= q|
 3887:             var specRegExp = /[!"#$%&'()*+,\-.\/:;<=>?@[\\^\]_`{\|}~]/;
 3888:             if (!specRegExp.test(currpwval)) {
 3889:                 brokerules.push('spec');
 3890:             }
 3891: |;
 3892:                 }
 3893:                 $intargjs .= qq|
 3894:             if (brokerules.length > 0) {
 3895:                 for (var i=0; i<brokerules.length; i++) {
 3896:                     for (var j=0; j<charrules.length; j++) {
 3897:                         if (brokerules[i] == charrules[j]) {
 3898:                             rulesmsg += ' - '+charalerts[j]+'\\n';
 3899:                             break;
 3900:                         }
 3901:                     }
 3902:                 }
 3903:             }
 3904: |;
 3905:             }
 3906:             $intargjs .= qq|
 3907:             if (rulesmsg != '') {
 3908:                 rulesmsg = '$alertmsg'+rulesmsg;
 3909:                 alert(rulesmsg);
 3910:                 return false;
 3911:             }
 3912: |;
 3913:     }
 3914:     return ($numrules,$intargjs);
 3915: }
 3916: 
 3917: ###############################################################
 3918: ##    Get Kerberos Defaults for Domain                 ##
 3919: ###############################################################
 3920: ##
 3921: ## Returns default kerberos version and an associated argument
 3922: ## as listed in file domain.tab. If not listed, provides
 3923: ## appropriate default domain and kerberos version.
 3924: ##
 3925: #-------------------------------------------
 3926: 
 3927: =pod
 3928: 
 3929: =item * &get_kerberos_defaults()
 3930: 
 3931: get_kerberos_defaults($target_domain) returns the default kerberos
 3932: version and domain. If not found, it defaults to version 4 and the 
 3933: domain of the server.
 3934: 
 3935: =over 4
 3936: 
 3937: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 3938: 
 3939: =back
 3940: 
 3941: =back
 3942: 
 3943: =cut
 3944: 
 3945: #-------------------------------------------
 3946: sub get_kerberos_defaults {
 3947:     my $domain=shift;
 3948:     my ($krbdef,$krbdefdom);
 3949:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 3950:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 3951:         $krbdef = $domdefaults{'auth_def'};
 3952:         $krbdefdom = $domdefaults{'auth_arg_def'};
 3953:     } else {
 3954:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 3955:         my $krbdefdom=$1;
 3956:         $krbdefdom=~tr/a-z/A-Z/;
 3957:         $krbdef = "krb4";
 3958:     }
 3959:     return ($krbdef,$krbdefdom);
 3960: }
 3961: 
 3962: 
 3963: ###############################################################
 3964: ##                Thesaurus Functions                        ##
 3965: ###############################################################
 3966: 
 3967: =pod
 3968: 
 3969: =head1 Thesaurus Functions
 3970: 
 3971: =over 4
 3972: 
 3973: =item * &initialize_keywords()
 3974: 
 3975: Initializes the package variable %Keywords if it is empty.  Uses the
 3976: package variable $thesaurus_db_file.
 3977: 
 3978: =cut
 3979: 
 3980: ###################################################
 3981: 
 3982: sub initialize_keywords {
 3983:     return 1 if (scalar keys(%Keywords));
 3984:     # If we are here, %Keywords is empty, so fill it up
 3985:     #   Make sure the file we need exists...
 3986:     if (! -e $thesaurus_db_file) {
 3987:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 3988:                                  " failed because it does not exist");
 3989:         return 0;
 3990:     }
 3991:     #   Set up the hash as a database
 3992:     my %thesaurus_db;
 3993:     if (! tie(%thesaurus_db,'GDBM_File',
 3994:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3995:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 3996:                                  $thesaurus_db_file);
 3997:         return 0;
 3998:     } 
 3999:     #  Get the average number of appearances of a word.
 4000:     my $avecount = $thesaurus_db{'average.count'};
 4001:     #  Put keywords (those that appear > average) into %Keywords
 4002:     while (my ($word,$data)=each (%thesaurus_db)) {
 4003:         my ($count,undef) = split /:/,$data;
 4004:         $Keywords{$word}++ if ($count > $avecount);
 4005:     }
 4006:     untie %thesaurus_db;
 4007:     # Remove special values from %Keywords.
 4008:     foreach my $value ('total.count','average.count') {
 4009:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 4010:   }
 4011:     return 1;
 4012: }
 4013: 
 4014: ###################################################
 4015: 
 4016: =pod
 4017: 
 4018: =item * &keyword($word)
 4019: 
 4020: Returns true if $word is a keyword.  A keyword is a word that appears more 
 4021: than the average number of times in the thesaurus database.  Calls 
 4022: &initialize_keywords
 4023: 
 4024: =cut
 4025: 
 4026: ###################################################
 4027: 
 4028: sub keyword {
 4029:     return if (!&initialize_keywords());
 4030:     my $word=lc(shift());
 4031:     $word=~s/\W//g;
 4032:     return exists($Keywords{$word});
 4033: }
 4034: 
 4035: ###############################################################
 4036: 
 4037: =pod 
 4038: 
 4039: =item * &get_related_words()
 4040: 
 4041: Look up a word in the thesaurus.  Takes a scalar argument and returns
 4042: an array of words.  If the keyword is not in the thesaurus, an empty array
 4043: will be returned.  The order of the words returned is determined by the
 4044: database which holds them.
 4045: 
 4046: Uses global $thesaurus_db_file.
 4047: 
 4048: 
 4049: =cut
 4050: 
 4051: ###############################################################
 4052: sub get_related_words {
 4053:     my $keyword = shift;
 4054:     my %thesaurus_db;
 4055:     if (! -e $thesaurus_db_file) {
 4056:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 4057:                                  "failed because the file does not exist");
 4058:         return ();
 4059:     }
 4060:     if (! tie(%thesaurus_db,'GDBM_File',
 4061:               $thesaurus_db_file,&GDBM_READER(),0640)){
 4062:         return ();
 4063:     } 
 4064:     my @Words=();
 4065:     my $count=0;
 4066:     if (exists($thesaurus_db{$keyword})) {
 4067: 	# The first element is the number of times
 4068: 	# the word appears.  We do not need it now.
 4069: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 4070: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 4071: 	my $threshold=$mostfrequentcount/10;
 4072:         foreach my $possibleword (@RelatedWords) {
 4073:             my ($word,$wordcount)=split(/\,/,$possibleword);
 4074:             if ($wordcount>$threshold) {
 4075: 		push(@Words,$word);
 4076:                 $count++;
 4077:                 if ($count>10) { last; }
 4078: 	    }
 4079:         }
 4080:     }
 4081:     untie %thesaurus_db;
 4082:     return @Words;
 4083: }
 4084: ###############################################################
 4085: #
 4086: #  Spell checking
 4087: #
 4088: 
 4089: =pod
 4090: 
 4091: =back
 4092: 
 4093: =head1 Spell checking
 4094: 
 4095: =over 4
 4096: 
 4097: =item * &check_spelling($wordlist $language)
 4098: 
 4099: Takes a string containing words and feeds it to an external
 4100: spellcheck program via a pipeline. Returns a string containing
 4101: them mis-spelled words.
 4102: 
 4103: Parameters:
 4104: 
 4105: =over 4
 4106: 
 4107: =item - $wordlist
 4108: 
 4109: String that will be fed into the spellcheck program.
 4110: 
 4111: =item - $language
 4112: 
 4113: Language string that specifies the language for which the spell
 4114: check will be performed.
 4115: 
 4116: =back
 4117: 
 4118: =back
 4119: 
 4120: Note: This sub assumes that aspell is installed.
 4121: 
 4122: 
 4123: =cut
 4124: 
 4125: 
 4126: sub check_spelling {
 4127:     my ($wordlist, $language) = @_;
 4128:     my @misspellings;
 4129:     
 4130:     # Generate the speller and set the langauge.
 4131:     # if explicitly selected:
 4132: 
 4133:     my $speller = Text::Aspell->new;
 4134:     if ($language) {
 4135: 	$speller->set_option('lang', $language);
 4136:     }
 4137: 
 4138:     # Turn the word list into an array of words by splittingon whitespace
 4139: 
 4140:     my @words = split(/\s+/, $wordlist);
 4141: 
 4142:     foreach my $word (@words) {
 4143: 	if(! $speller->check($word)) {
 4144: 	    push(@misspellings, $word);
 4145: 	}
 4146:     }
 4147:     return join(' ', @misspellings);
 4148:     
 4149: }
 4150: 
 4151: # -------------------------------------------------------------- Plaintext name
 4152: =pod
 4153: 
 4154: =head1 User Name Functions
 4155: 
 4156: =over 4
 4157: 
 4158: =item * &plainname($uname,$udom,$first)
 4159: 
 4160: Takes a users logon name and returns it as a string in
 4161: "first middle last generation" form 
 4162: if $first is set to 'lastname' then it returns it as
 4163: 'lastname generation, firstname middlename' if their is a lastname
 4164: 
 4165: =cut
 4166: 
 4167: 
 4168: ###############################################################
 4169: sub plainname {
 4170:     my ($uname,$udom,$first)=@_;
 4171:     return if (!defined($uname) || !defined($udom));
 4172:     my %names=&getnames($uname,$udom);
 4173:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 4174: 					  $names{'middlename'},
 4175: 					  $names{'lastname'},
 4176: 					  $names{'generation'},$first);
 4177:     $name=~s/^\s+//;
 4178:     $name=~s/\s+$//;
 4179:     $name=~s/\s+/ /g;
 4180:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 4181:     return $name;
 4182: }
 4183: 
 4184: # -------------------------------------------------------------------- Nickname
 4185: =pod
 4186: 
 4187: =item * &nickname($uname,$udom)
 4188: 
 4189: Gets a users name and returns it as a string as
 4190: 
 4191: "&quot;nickname&quot;"
 4192: 
 4193: if the user has a nickname or
 4194: 
 4195: "first middle last generation"
 4196: 
 4197: if the user does not
 4198: 
 4199: =cut
 4200: 
 4201: sub nickname {
 4202:     my ($uname,$udom)=@_;
 4203:     return if (!defined($uname) || !defined($udom));
 4204:     my %names=&getnames($uname,$udom);
 4205:     my $name=$names{'nickname'};
 4206:     if ($name) {
 4207:        $name='&quot;'.$name.'&quot;'; 
 4208:     } else {
 4209:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 4210: 	     $names{'lastname'}.' '.$names{'generation'};
 4211:        $name=~s/\s+$//;
 4212:        $name=~s/\s+/ /g;
 4213:     }
 4214:     return $name;
 4215: }
 4216: 
 4217: sub getnames {
 4218:     my ($uname,$udom)=@_;
 4219:     return if (!defined($uname) || !defined($udom));
 4220:     if ($udom eq 'public' && $uname eq 'public') {
 4221: 	return ('lastname' => &mt('Public'));
 4222:     }
 4223:     my $id=$uname.':'.$udom;
 4224:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 4225:     if ($cached) {
 4226: 	return %{$names};
 4227:     } else {
 4228: 	my %loadnames=&Apache::lonnet::get('environment',
 4229:                     ['firstname','middlename','lastname','generation','nickname'],
 4230: 					 $udom,$uname);
 4231: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 4232: 	return %loadnames;
 4233:     }
 4234: }
 4235: 
 4236: # -------------------------------------------------------------------- getemails
 4237: 
 4238: =pod
 4239: 
 4240: =item * &getemails($uname,$udom)
 4241: 
 4242: Gets a user's email information and returns it as a hash with keys:
 4243: notification, critnotification, permanentemail
 4244: 
 4245: For notification and critnotification, values are comma-separated lists 
 4246: of e-mail addresses; for permanentemail, value is a single e-mail address.
 4247:  
 4248: 
 4249: =cut
 4250: 
 4251: 
 4252: sub getemails {
 4253:     my ($uname,$udom)=@_;
 4254:     if ($udom eq 'public' && $uname eq 'public') {
 4255: 	return;
 4256:     }
 4257:     if (!$udom) { $udom=$env{'user.domain'}; }
 4258:     if (!$uname) { $uname=$env{'user.name'}; }
 4259:     my $id=$uname.':'.$udom;
 4260:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 4261:     if ($cached) {
 4262: 	return %{$names};
 4263:     } else {
 4264: 	my %loadnames=&Apache::lonnet::get('environment',
 4265:                     			   ['notification','critnotification',
 4266: 					    'permanentemail'],
 4267: 					   $udom,$uname);
 4268: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 4269: 	return %loadnames;
 4270:     }
 4271: }
 4272: 
 4273: sub flush_email_cache {
 4274:     my ($uname,$udom)=@_;
 4275:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4276:     if (!$uname) { $uname=$env{'user.name'};   }
 4277:     return if ($udom eq 'public' && $uname eq 'public');
 4278:     my $id=$uname.':'.$udom;
 4279:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 4280: }
 4281: 
 4282: # -------------------------------------------------------------------- getlangs
 4283: 
 4284: =pod
 4285: 
 4286: =item * &getlangs($uname,$udom)
 4287: 
 4288: Gets a user's language preference and returns it as a hash with key:
 4289: language.
 4290: 
 4291: =cut
 4292: 
 4293: 
 4294: sub getlangs {
 4295:     my ($uname,$udom) = @_;
 4296:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4297:     if (!$uname) { $uname=$env{'user.name'};   }
 4298:     my $id=$uname.':'.$udom;
 4299:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 4300:     if ($cached) {
 4301:         return %{$langs};
 4302:     } else {
 4303:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 4304:                                            $udom,$uname);
 4305:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 4306:         return %loadlangs;
 4307:     }
 4308: }
 4309: 
 4310: sub flush_langs_cache {
 4311:     my ($uname,$udom)=@_;
 4312:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4313:     if (!$uname) { $uname=$env{'user.name'};   }
 4314:     return if ($udom eq 'public' && $uname eq 'public');
 4315:     my $id=$uname.':'.$udom;
 4316:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 4317: }
 4318: 
 4319: # ------------------------------------------------------------------ Screenname
 4320: 
 4321: =pod
 4322: 
 4323: =item * &screenname($uname,$udom)
 4324: 
 4325: Gets a users screenname and returns it as a string
 4326: 
 4327: =cut
 4328: 
 4329: sub screenname {
 4330:     my ($uname,$udom)=@_;
 4331:     if ($uname eq $env{'user.name'} &&
 4332: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 4333:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 4334:     return $names{'screenname'};
 4335: }
 4336: 
 4337: 
 4338: # ------------------------------------------------------------- Confirm Wrapper
 4339: =pod
 4340: 
 4341: =item * &confirmwrapper($message)
 4342: 
 4343: Wrap messages about completion of operation in box
 4344: 
 4345: =cut
 4346: 
 4347: sub confirmwrapper {
 4348:     my ($message)=@_;
 4349:     if ($message) {
 4350:         return "\n".'<div class="LC_confirm_box">'."\n"
 4351:                .$message."\n"
 4352:                .'</div>'."\n";
 4353:     } else {
 4354:         return $message;
 4355:     }
 4356: }
 4357: 
 4358: # ------------------------------------------------------------- Message Wrapper
 4359: 
 4360: sub messagewrapper {
 4361:     my ($link,$username,$domain,$subject,$text)=@_;
 4362:     return 
 4363:         '<a href="/adm/email?compose=individual&amp;'.
 4364:         'recname='.$username.'&amp;recdom='.$domain.
 4365: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 4366:         'title="'.&mt('Send message').'">'.$link.'</a>';
 4367: }
 4368: 
 4369: # --------------------------------------------------------------- Notes Wrapper
 4370: 
 4371: sub noteswrapper {
 4372:     my ($link,$un,$do)=@_;
 4373:     return 
 4374: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 4375: }
 4376: 
 4377: # ------------------------------------------------------------- Aboutme Wrapper
 4378: 
 4379: sub aboutmewrapper {
 4380:     my ($link,$username,$domain,$target,$class)=@_;
 4381:     if (!defined($username)  && !defined($domain)) {
 4382:         return;
 4383:     }
 4384:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 4385: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 4386: }
 4387: 
 4388: # ------------------------------------------------------------ Syllabus Wrapper
 4389: 
 4390: sub syllabuswrapper {
 4391:     my ($linktext,$coursedir,$domain)=@_;
 4392:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 4393: }
 4394: 
 4395: # -----------------------------------------------------------------------------
 4396: 
 4397: sub aboutme_on {
 4398:     my ($uname,$udom)=@_;
 4399:     unless ($uname) { $uname=$env{'user.name'}; }
 4400:     unless ($udom)  { $udom=$env{'user.domain'}; }
 4401:     return if ($udom eq 'public' && $uname eq 'public');
 4402:     my $hashkey=$uname.':'.$udom;
 4403:     my ($aboutme,$cached)=&Apache::lonnet::is_cached_new('aboutme',$hashkey);
 4404:     if ($cached) {
 4405:         return $aboutme;
 4406:     }
 4407:     $aboutme = &Apache::lonnet::usertools_access($uname,$udom,'aboutme');
 4408:     &Apache::lonnet::do_cache_new('aboutme',$hashkey,$aboutme,3600);
 4409:     return $aboutme;
 4410: }
 4411: 
 4412: sub devalidate_aboutme_cache {
 4413:     my ($uname,$udom)=@_;
 4414:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4415:     if (!$uname) { $uname=$env{'user.name'};   }
 4416:     return if ($udom eq 'public' && $uname eq 'public');
 4417:     my $id=$uname.':'.$udom;
 4418:     &Apache::lonnet::devalidate_cache_new('aboutme',$id);
 4419: }
 4420: 
 4421: sub track_student_link {
 4422:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 4423:     my $link ="/adm/trackstudent?";
 4424:     my $title = 'View recent activity';
 4425:     if (defined($sname) && $sname !~ /^\s*$/ &&
 4426:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 4427:         $link .= "selected_student=$sname:$sdom";
 4428:         $title .= ' of this student';
 4429:     } 
 4430:     if (defined($target) && $target !~ /^\s*$/) {
 4431:         $target = qq{target="$target"};
 4432:     } else {
 4433:         $target = '';
 4434:     }
 4435:     if ($start) { $link.='&amp;start='.$start; }
 4436:     if ($only_body) { $link .= '&amp;only_body=1'; }
 4437:     $title = &mt($title);
 4438:     $linktext = &mt($linktext);
 4439:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 4440: 	&help_open_topic('View_recent_activity');
 4441: }
 4442: 
 4443: sub slot_reservations_link {
 4444:     my ($linktext,$sname,$sdom,$target) = @_;
 4445:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 4446:     my $title = 'View slot reservation history';
 4447:     if (defined($sname) && $sname !~ /^\s*$/ &&
 4448:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 4449:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 4450:         $title .= ' of this student';
 4451:     }
 4452:     if (defined($target) && $target !~ /^\s*$/) {
 4453:         $target = qq{target="$target"};
 4454:     } else {
 4455:         $target = '';
 4456:     }
 4457:     $title = &mt($title);
 4458:     $linktext = &mt($linktext);
 4459:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 4460: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 4461: 
 4462: }
 4463: 
 4464: # ===================================================== Display a student photo
 4465: 
 4466: 
 4467: sub student_image_tag {
 4468:     my ($domain,$user)=@_;
 4469:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 4470:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 4471: 	return '<img src="'.$imgsrc.'" align="right" />';
 4472:     } else {
 4473: 	return '';
 4474:     }
 4475: }
 4476: 
 4477: =pod
 4478: 
 4479: =back
 4480: 
 4481: =head1 Access .tab File Data
 4482: 
 4483: =over 4
 4484: 
 4485: =item * &languageids() 
 4486: 
 4487: returns list of all language ids
 4488: 
 4489: =cut
 4490: 
 4491: sub languageids {
 4492:     return sort(keys(%language));
 4493: }
 4494: 
 4495: =pod
 4496: 
 4497: =item * &languagedescription() 
 4498: 
 4499: returns description of a specified language id
 4500: 
 4501: =cut
 4502: 
 4503: sub languagedescription {
 4504:     my $code=shift;
 4505:     return  ($supported_language{$code}?'* ':'').
 4506:             $language{$code}.
 4507: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 4508: }
 4509: 
 4510: =pod
 4511: 
 4512: =item * &plainlanguagedescription
 4513: 
 4514: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 4515: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 4516: 
 4517: =cut
 4518: 
 4519: sub plainlanguagedescription {
 4520:     my $code=shift;
 4521:     return $language{$code};
 4522: }
 4523: 
 4524: =pod
 4525: 
 4526: =item * &supportedlanguagecode
 4527: 
 4528: Returns the supported language code (e.g. sptutf maps to pt) given a language
 4529: code.
 4530: 
 4531: =cut
 4532: 
 4533: sub supportedlanguagecode {
 4534:     my $code=shift;
 4535:     return $supported_language{$code};
 4536: }
 4537: 
 4538: =pod
 4539: 
 4540: =item * &latexlanguage()
 4541: 
 4542: Given a language key code returns the correspondnig language to use
 4543: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 4544: is no supported hyphenation for the language code.
 4545: 
 4546: =cut
 4547: 
 4548: sub latexlanguage {
 4549:     my $code = shift;
 4550:     return $latex_language{$code};
 4551: }
 4552: 
 4553: =pod
 4554: 
 4555: =item * &latexhyphenation()
 4556: 
 4557: Same as above but what's supplied is the language as it might be stored
 4558: in the metadata.
 4559: 
 4560: =cut
 4561: 
 4562: sub latexhyphenation {
 4563:     my $key = shift;
 4564:     return $latex_language_bykey{$key};
 4565: }
 4566: 
 4567: =pod
 4568: 
 4569: =item * &copyrightids() 
 4570: 
 4571: returns list of all copyrights
 4572: 
 4573: =cut
 4574: 
 4575: sub copyrightids {
 4576:     return sort(keys(%cprtag));
 4577: }
 4578: 
 4579: =pod
 4580: 
 4581: =item * &copyrightdescription() 
 4582: 
 4583: returns description of a specified copyright id
 4584: 
 4585: =cut
 4586: 
 4587: sub copyrightdescription {
 4588:     return &mt($cprtag{shift(@_)});
 4589: }
 4590: 
 4591: =pod
 4592: 
 4593: =item * &source_copyrightids() 
 4594: 
 4595: returns list of all source copyrights
 4596: 
 4597: =cut
 4598: 
 4599: sub source_copyrightids {
 4600:     return sort(keys(%scprtag));
 4601: }
 4602: 
 4603: =pod
 4604: 
 4605: =item * &source_copyrightdescription() 
 4606: 
 4607: returns description of a specified source copyright id
 4608: 
 4609: =cut
 4610: 
 4611: sub source_copyrightdescription {
 4612:     return &mt($scprtag{shift(@_)});
 4613: }
 4614: 
 4615: =pod
 4616: 
 4617: =item * &filecategories() 
 4618: 
 4619: returns list of all file categories
 4620: 
 4621: =cut
 4622: 
 4623: sub filecategories {
 4624:     return sort(keys(%category_extensions));
 4625: }
 4626: 
 4627: =pod
 4628: 
 4629: =item * &filecategorytypes() 
 4630: 
 4631: returns list of file types belonging to a given file
 4632: category
 4633: 
 4634: =cut
 4635: 
 4636: sub filecategorytypes {
 4637:     my ($cat) = @_;
 4638:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
 4639:         return @{$category_extensions{lc($cat)}};
 4640:     } else {
 4641:         return ();
 4642:     }
 4643: }
 4644: 
 4645: =pod
 4646: 
 4647: =item * &fileembstyle() 
 4648: 
 4649: returns embedding style for a specified file type
 4650: 
 4651: =cut
 4652: 
 4653: sub fileembstyle {
 4654:     return $fe{lc(shift(@_))};
 4655: }
 4656: 
 4657: sub filemimetype {
 4658:     return $fm{lc(shift(@_))};
 4659: }
 4660: 
 4661: 
 4662: sub filecategoryselect {
 4663:     my ($name,$value)=@_;
 4664:     return &select_form($value,$name,
 4665:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 4666: }
 4667: 
 4668: =pod
 4669: 
 4670: =item * &filedescription() 
 4671: 
 4672: returns description for a specified file type
 4673: 
 4674: =cut
 4675: 
 4676: sub filedescription {
 4677:     my $file_description = $fd{lc(shift())};
 4678:     $file_description =~ s:([\[\]]):~$1:g;
 4679:     return &mt($file_description);
 4680: }
 4681: 
 4682: =pod
 4683: 
 4684: =item * &filedescriptionex() 
 4685: 
 4686: returns description for a specified file type with
 4687: extra formatting
 4688: 
 4689: =cut
 4690: 
 4691: sub filedescriptionex {
 4692:     my $ex=shift;
 4693:     my $file_description = $fd{lc($ex)};
 4694:     $file_description =~ s:([\[\]]):~$1:g;
 4695:     return '.'.$ex.' '.&mt($file_description);
 4696: }
 4697: 
 4698: # End of .tab access
 4699: =pod
 4700: 
 4701: =back
 4702: 
 4703: =cut
 4704: 
 4705: # ------------------------------------------------------------------ File Types
 4706: sub fileextensions {
 4707:     return sort(keys(%fe));
 4708: }
 4709: 
 4710: # ----------------------------------------------------------- Display Languages
 4711: # returns a hash with all desired display languages
 4712: #
 4713: 
 4714: sub display_languages {
 4715:     my %languages=();
 4716:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 4717: 	$languages{$lang}=1;
 4718:     }
 4719:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 4720:     if ($env{'form.displaylanguage'}) {
 4721: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 4722: 	    $languages{$lang}=1;
 4723:         }
 4724:     }
 4725:     return %languages;
 4726: }
 4727: 
 4728: sub languages {
 4729:     my ($possible_langs) = @_;
 4730:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 4731:     if (!ref($possible_langs)) {
 4732: 	if( wantarray ) {
 4733: 	    return @preferred_langs;
 4734: 	} else {
 4735: 	    return $preferred_langs[0];
 4736: 	}
 4737:     }
 4738:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 4739:     my @preferred_possibilities;
 4740:     foreach my $preferred_lang (@preferred_langs) {
 4741: 	if (exists($possibilities{$preferred_lang})) {
 4742: 	    push(@preferred_possibilities, $preferred_lang);
 4743: 	}
 4744:     }
 4745:     if( wantarray ) {
 4746: 	return @preferred_possibilities;
 4747:     }
 4748:     return $preferred_possibilities[0];
 4749: }
 4750: 
 4751: sub user_lang {
 4752:     my ($touname,$toudom,$fromcid) = @_;
 4753:     my @userlangs;
 4754:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 4755:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 4756:                     $env{'course.'.$fromcid.'.languages'}));
 4757:     } else {
 4758:         my %langhash = &getlangs($touname,$toudom);
 4759:         if ($langhash{'languages'} ne '') {
 4760:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 4761:         } else {
 4762:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 4763:             if ($domdefs{'lang_def'} ne '') {
 4764:                 @userlangs = ($domdefs{'lang_def'});
 4765:             }
 4766:         }
 4767:     }
 4768:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 4769:     my $user_lh = Apache::localize->get_handle(@languages);
 4770:     return $user_lh;
 4771: }
 4772: 
 4773: 
 4774: ###############################################################
 4775: ##               Student Answer Attempts                     ##
 4776: ###############################################################
 4777: 
 4778: =pod
 4779: 
 4780: =head1 Alternate Problem Views
 4781: 
 4782: =over 4
 4783: 
 4784: =item * &get_previous_attempt($symb, $username, $domain, $course,
 4785:     $getattempt, $regexp, $gradesub, $usec, $identifier)
 4786: 
 4787: Return string with previous attempt on problem. Arguments:
 4788: 
 4789: =over 4
 4790: 
 4791: =item * $symb: Problem, including path
 4792: 
 4793: =item * $username: username of the desired student
 4794: 
 4795: =item * $domain: domain of the desired student
 4796: 
 4797: =item * $course: Course ID
 4798: 
 4799: =item * $getattempt: Leave blank for all attempts, otherwise put
 4800:     something
 4801: 
 4802: =item * $regexp: if string matches this regexp, the string will be
 4803:     sent to $gradesub
 4804: 
 4805: =item * $gradesub: routine that processes the string if it matches $regexp
 4806: 
 4807: =item * $usec: section of the desired student
 4808: 
 4809: =item * $identifier: counter for student (multiple students one problem) or 
 4810:     problem (one student; whole sequence).
 4811: 
 4812: =back
 4813: 
 4814: The output string is a table containing all desired attempts, if any.
 4815: 
 4816: =cut
 4817: 
 4818: sub get_previous_attempt {
 4819:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
 4820:   my $prevattempts='';
 4821:   no strict 'refs';
 4822:   if ($symb) {
 4823:     my (%returnhash)=
 4824:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 4825:     if ($returnhash{'version'}) {
 4826:       my %lasthash=();
 4827:       my $version;
 4828:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 4829:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
 4830:             if ($key =~ /\.rawrndseed$/) {
 4831:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
 4832:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
 4833:             } else {
 4834:                 $lasthash{$key}=$returnhash{$version.':'.$key};
 4835:             }
 4836:         }
 4837:       }
 4838:       $prevattempts=&start_data_table().&start_data_table_header_row();
 4839:       $prevattempts.='<th>'.&mt('History').'</th>';
 4840:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
 4841:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 4842:       foreach my $key (sort(keys(%lasthash))) {
 4843: 	my ($ign,@parts) = split(/\./,$key);
 4844: 	if ($#parts > 0) {
 4845: 	  my $data=$parts[-1];
 4846:           next if ($data eq 'foilorder');
 4847: 	  pop(@parts);
 4848:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 4849:           if ($data eq 'type') {
 4850:               unless ($showsurv) {
 4851:                   my $id = join(',',@parts);
 4852:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 4853:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 4854:                       $lasthidden{$ign.'.'.$id} = 1;
 4855:                   }
 4856:               }
 4857:               if ($identifier ne '') {
 4858:                   my $id = join(',',@parts);
 4859:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
 4860:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
 4861:                       $hidestatus{$ign.'.'.$id} = 1;
 4862:                   }
 4863:               }
 4864:           } elsif ($data eq 'regrader') {
 4865:               if (($identifier ne '') && (@parts)) {
 4866:                   my $id = join(',',@parts);
 4867:                   $regraded{$ign.'.'.$id} = 1;
 4868:               }
 4869:           } 
 4870: 	} else {
 4871: 	  if ($#parts == 0) {
 4872: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 4873: 	  } else {
 4874: 	    $prevattempts.='<th>'.$ign.'</th>';
 4875: 	  }
 4876: 	}
 4877:       }
 4878:       $prevattempts.=&end_data_table_header_row();
 4879:       if ($getattempt eq '') {
 4880:         my (%solved,%resets,%probstatus);
 4881:         if (($identifier ne '') && (keys(%regraded) > 0)) {
 4882:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 4883:                 foreach my $id (keys(%regraded)) {
 4884:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
 4885:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
 4886:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
 4887:                         push(@{$resets{$id}},$version);
 4888:                     }
 4889:                 }
 4890:             }
 4891:         }
 4892: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 4893:             my (@hidden,@unsolved);
 4894:             if (%typeparts) {
 4895:                 foreach my $id (keys(%typeparts)) {
 4896:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
 4897:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 4898:                         push(@hidden,$id);
 4899:                     } elsif ($identifier ne '') {
 4900:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
 4901:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
 4902:                                 ($hidestatus{$id})) {
 4903:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
 4904:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
 4905:                                 push(@{$solved{$id}},$version);
 4906:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
 4907:                                      (ref($solved{$id}) eq 'ARRAY')) {
 4908:                                 my $skip;
 4909:                                 if (ref($resets{$id}) eq 'ARRAY') {
 4910:                                     foreach my $reset (@{$resets{$id}}) {
 4911:                                         if ($reset > $solved{$id}[-1]) {
 4912:                                             $skip=1;
 4913:                                             last;
 4914:                                         }
 4915:                                     }
 4916:                                 }
 4917:                                 unless ($skip) {
 4918:                                     my ($ign,$partslist) = split(/\./,$id,2);
 4919:                                     push(@unsolved,$partslist);
 4920:                                 }
 4921:                             }
 4922:                         }
 4923:                     }
 4924:                 }
 4925:             }
 4926:             $prevattempts.=&start_data_table_row().
 4927:                            '<td>'.&mt('Transaction [_1]',$version);
 4928:             if (@unsolved) {
 4929:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
 4930:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
 4931:                                  &mt('Hide').'</label></span>';
 4932:             }
 4933:             $prevattempts .= '</td>';
 4934:             if (@hidden) {
 4935:                 foreach my $key (sort(keys(%lasthash))) {
 4936:                     next if ($key =~ /\.foilorder$/);
 4937:                     my $hide;
 4938:                     foreach my $id (@hidden) {
 4939:                         if ($key =~ /^\Q$id\E/) {
 4940:                             $hide = 1;
 4941:                             last;
 4942:                         }
 4943:                     }
 4944:                     if ($hide) {
 4945:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4946:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 4947:                             my $value = &format_previous_attempt_value($key,
 4948:                                              $returnhash{$version.':'.$key});
 4949:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4950:                         } else {
 4951:                             $prevattempts.='<td>&nbsp;</td>';
 4952:                         }
 4953:                     } else {
 4954:                         if ($key =~ /\./) {
 4955:                             my $value = $returnhash{$version.':'.$key};
 4956:                             if ($key =~ /\.rndseed$/) {
 4957:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 4958:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4959:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4960:                                 }
 4961:                             }
 4962:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4963:                                            '&nbsp;</td>';
 4964:                         } else {
 4965:                             $prevattempts.='<td>&nbsp;</td>';
 4966:                         }
 4967:                     }
 4968:                 }
 4969:             } else {
 4970: 	        foreach my $key (sort(keys(%lasthash))) {
 4971:                     next if ($key =~ /\.foilorder$/);
 4972:                     my $value = $returnhash{$version.':'.$key};
 4973:                     if ($key =~ /\.rndseed$/) {
 4974:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 4975:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4976:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4977:                         }
 4978:                     }
 4979:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4980:                                    '&nbsp;</td>';
 4981: 	        }
 4982:             }
 4983: 	    $prevattempts.=&end_data_table_row();
 4984: 	 }
 4985:       }
 4986:       my @currhidden = keys(%lasthidden);
 4987:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 4988:       foreach my $key (sort(keys(%lasthash))) {
 4989:           next if ($key =~ /\.foilorder$/);
 4990:           if (%typeparts) {
 4991:               my $hidden;
 4992:               foreach my $id (@currhidden) {
 4993:                   if ($key =~ /^\Q$id\E/) {
 4994:                       $hidden = 1;
 4995:                       last;
 4996:                   }
 4997:               }
 4998:               if ($hidden) {
 4999:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 5000:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 5001:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 5002:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 5003:                           $value = &$gradesub($value);
 5004:                       }
 5005:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
 5006:                   } else {
 5007:                       $prevattempts.='<td>&nbsp;</td>';
 5008:                   }
 5009:               } else {
 5010:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 5011:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 5012:                       $value = &$gradesub($value);
 5013:                   }
 5014:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 5015:               }
 5016:           } else {
 5017: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 5018: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 5019:                   $value = &$gradesub($value);
 5020:               }
 5021: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
 5022:           }
 5023:       }
 5024:       $prevattempts.= &end_data_table_row().&end_data_table();
 5025:     } else {
 5026:       my $msg;
 5027:       if ($symb =~ /ext\.tool$/) {
 5028:           $msg = &mt('No grade passed back.');
 5029:       } else {
 5030:           $msg = &mt('Nothing submitted - no attempts.');
 5031:       }
 5032:       $prevattempts=
 5033: 	  &start_data_table().&start_data_table_row().
 5034: 	  '<td>'.$msg.'</td>'.
 5035: 	  &end_data_table_row().&end_data_table();
 5036:     }
 5037:   } else {
 5038:     $prevattempts=
 5039: 	  &start_data_table().&start_data_table_row().
 5040: 	  '<td>'.&mt('No data.').'</td>'.
 5041: 	  &end_data_table_row().&end_data_table();
 5042:   }
 5043: }
 5044: 
 5045: sub format_previous_attempt_value {
 5046:     my ($key,$value) = @_;
 5047:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 5048:         $value = &Apache::lonlocal::locallocaltime($value);
 5049:     } elsif (ref($value) eq 'ARRAY') {
 5050:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
 5051:     } elsif ($key =~ /answerstring$/) {
 5052:         my %answers = &Apache::lonnet::str2hash($value);
 5053:         my @answer = %answers;
 5054:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
 5055:         my @anskeys = sort(keys(%answers));
 5056:         if (@anskeys == 1) {
 5057:             my $answer = $answers{$anskeys[0]};
 5058:             if ($answer =~ m{\0}) {
 5059:                 $answer =~ s{\0}{,}g;
 5060:             }
 5061:             my $tag_internal_answer_name = 'INTERNAL';
 5062:             if ($anskeys[0] eq $tag_internal_answer_name) {
 5063:                 $value = $answer; 
 5064:             } else {
 5065:                 $value = $anskeys[0].'='.$answer;
 5066:             }
 5067:         } else {
 5068:             foreach my $ans (@anskeys) {
 5069:                 my $answer = $answers{$ans};
 5070:                 if ($answer =~ m{\0}) {
 5071:                     $answer =~ s{\0}{,}g;
 5072:                 }
 5073:                 $value .=  $ans.'='.$answer.'<br />';;
 5074:             } 
 5075:         }
 5076:     } else {
 5077:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
 5078:     }
 5079:     return $value;
 5080: }
 5081: 
 5082: 
 5083: sub relative_to_absolute {
 5084:     my ($url,$output)=@_;
 5085:     my $parser=HTML::TokeParser->new(\$output);
 5086:     my $token;
 5087:     my $thisdir=$url;
 5088:     my @rlinks=();
 5089:     while ($token=$parser->get_token) {
 5090: 	if ($token->[0] eq 'S') {
 5091: 	    if ($token->[1] eq 'a') {
 5092: 		if ($token->[2]->{'href'}) {
 5093: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 5094: 		}
 5095: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 5096: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 5097: 	    } elsif ($token->[1] eq 'base') {
 5098: 		$thisdir=$token->[2]->{'href'};
 5099: 	    }
 5100: 	}
 5101:     }
 5102:     $thisdir=~s-/[^/]*$--;
 5103:     foreach my $link (@rlinks) {
 5104: 	unless (($link=~/^https?\:\/\//i) ||
 5105: 		($link=~/^\//) ||
 5106: 		($link=~/^javascript:/i) ||
 5107: 		($link=~/^mailto:/i) ||
 5108: 		($link=~/^\#/)) {
 5109: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 5110: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 5111: 	}
 5112:     }
 5113: # -------------------------------------------------- Deal with Applet codebases
 5114:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 5115:     return $output;
 5116: }
 5117: 
 5118: =pod
 5119: 
 5120: =item * &get_student_view()
 5121: 
 5122: show a snapshot of what student was looking at
 5123: 
 5124: =cut
 5125: 
 5126: sub get_student_view {
 5127:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 5128:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 5129:   my (%form);
 5130:   my @elements=('symb','courseid','domain','username');
 5131:   foreach my $element (@elements) {
 5132:       $form{'grade_'.$element}=eval '$'.$element #'
 5133:   }
 5134:   if (defined($moreenv)) {
 5135:       %form=(%form,%{$moreenv});
 5136:   }
 5137:   if (defined($target)) { $form{'grade_target'} = $target; }
 5138:   $feedurl=&Apache::lonnet::clutter($feedurl);
 5139:   if (($feedurl =~ /ext\.tool$/) && ($target eq 'tex')) {
 5140:       $feedurl =~ s{^/adm/wrapper}{};
 5141:   }
 5142:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 5143:   $userview=~s/\<body[^\>]*\>//gi;
 5144:   $userview=~s/\<\/body\>//gi;
 5145:   $userview=~s/\<html\>//gi;
 5146:   $userview=~s/\<\/html\>//gi;
 5147:   $userview=~s/\<head\>//gi;
 5148:   $userview=~s/\<\/head\>//gi;
 5149:   $userview=~s/action\s*\=/would_be_action\=/gi;
 5150:   $userview=&relative_to_absolute($feedurl,$userview);
 5151:   if (wantarray) {
 5152:      return ($userview,$response);
 5153:   } else {
 5154:      return $userview;
 5155:   }
 5156: }
 5157: 
 5158: sub get_student_view_with_retries {
 5159:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 5160: 
 5161:     my $ok = 0;                 # True if we got a good response.
 5162:     my $content;
 5163:     my $response;
 5164: 
 5165:     # Try to get the student_view done. within the retries count:
 5166:     
 5167:     do {
 5168:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 5169:          $ok      = $response->is_success;
 5170:          if (!$ok) {
 5171:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 5172:          }
 5173:          $retries--;
 5174:     } while (!$ok && ($retries > 0));
 5175:     
 5176:     if (!$ok) {
 5177:        $content = '';          # On error return an empty content.
 5178:     }
 5179:     if (wantarray) {
 5180:        return ($content, $response);
 5181:     } else {
 5182:        return $content;
 5183:     }
 5184: }
 5185: 
 5186: sub css_links {
 5187:     my ($currsymb,$level) = @_;
 5188:     my ($links,@symbs,%cssrefs,%httpref);
 5189:     if ($level eq 'map') {
 5190:         my $navmap = Apache::lonnavmaps::navmap->new();
 5191:         if (ref($navmap)) {
 5192:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
 5193:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
 5194:             foreach my $res (@resources) {
 5195:                 if (ref($res) && $res->symb()) {
 5196:                     push(@symbs,$res->symb());
 5197:                 }
 5198:             }
 5199:         }
 5200:     } else {
 5201:         @symbs = ($currsymb);
 5202:     }
 5203:     foreach my $symb (@symbs) {
 5204:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
 5205:         if ($css_href =~ /\S/) {
 5206:             unless ($css_href =~ m{https?://}) {
 5207:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
 5208:                 my $proburl =  &Apache::lonnet::clutter($url);
 5209:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
 5210:                 unless ($css_href =~ m{^/}) {
 5211:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
 5212:                 }
 5213:                 if ($css_href =~ m{^/(res|uploaded)/}) {
 5214:                     unless (($httpref{'httpref.'.$css_href}) ||
 5215:                             (&Apache::lonnet::is_on_map($css_href))) {
 5216:                         my $thisurl = $proburl;
 5217:                         if ($env{'httpref.'.$proburl}) {
 5218:                             $thisurl = $env{'httpref.'.$proburl};
 5219:                         }
 5220:                         $httpref{'httpref.'.$css_href} = $thisurl;
 5221:                     }
 5222:                 }
 5223:             }
 5224:             $cssrefs{$css_href} = 1;
 5225:         }
 5226:     }
 5227:     if (keys(%httpref)) {
 5228:         &Apache::lonnet::appenv(\%httpref);
 5229:     }
 5230:     if (keys(%cssrefs)) {
 5231:         foreach my $css_href (keys(%cssrefs)) {
 5232:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
 5233:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
 5234:         }
 5235:     }
 5236:     return $links;
 5237: }
 5238: 
 5239: =pod
 5240: 
 5241: =item * &get_student_answers() 
 5242: 
 5243: show a snapshot of how student was answering problem
 5244: 
 5245: =cut
 5246: 
 5247: sub get_student_answers {
 5248:   my ($symb,$username,$domain,$courseid,%form) = @_;
 5249:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 5250:   my (%moreenv);
 5251:   my @elements=('symb','courseid','domain','username');
 5252:   foreach my $element (@elements) {
 5253:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 5254:   }
 5255:   $moreenv{'grade_target'}='answer';
 5256:   %moreenv=(%form,%moreenv);
 5257:   $feedurl = &Apache::lonnet::clutter($feedurl);
 5258:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 5259:   return $userview;
 5260: }
 5261: 
 5262: =pod
 5263: 
 5264: =item * &submlink()
 5265: 
 5266: Inputs: $text $uname $udom $symb $target
 5267: 
 5268: Returns: A link to grades.pm such as to see the SUBM view of a student
 5269: 
 5270: =cut
 5271: 
 5272: ###############################################
 5273: sub submlink {
 5274:     my ($text,$uname,$udom,$symb,$target)=@_;
 5275:     if (!($uname && $udom)) {
 5276: 	(my $cursymb, my $courseid,$udom,$uname)=
 5277: 	    &Apache::lonnet::whichuser($symb);
 5278: 	if (!$symb) { $symb=$cursymb; }
 5279:     }
 5280:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 5281:     $symb=&escape($symb);
 5282:     if ($target) { $target=" target=\"$target\""; }
 5283:     return
 5284:         '<a href="/adm/grades?command=submission'.
 5285:         '&amp;symb='.$symb.
 5286:         '&amp;student='.$uname.
 5287:         '&amp;userdom='.$udom.'"'.
 5288:         $target.'>'.$text.'</a>';
 5289: }
 5290: ##############################################
 5291: 
 5292: =pod
 5293: 
 5294: =item * &pgrdlink()
 5295: 
 5296: Inputs: $text $uname $udom $symb $target
 5297: 
 5298: Returns: A link to grades.pm such as to see the PGRD view of a student
 5299: 
 5300: =cut
 5301: 
 5302: ###############################################
 5303: sub pgrdlink {
 5304:     my $link=&submlink(@_);
 5305:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 5306:     return $link;
 5307: }
 5308: ##############################################
 5309: 
 5310: =pod
 5311: 
 5312: =item * &pprmlink()
 5313: 
 5314: Inputs: $text $uname $udom $symb $target
 5315: 
 5316: Returns: A link to parmset.pm such as to see the PPRM view of a
 5317: student and a specific resource
 5318: 
 5319: =cut
 5320: 
 5321: ###############################################
 5322: sub pprmlink {
 5323:     my ($text,$uname,$udom,$symb,$target)=@_;
 5324:     if (!($uname && $udom)) {
 5325: 	(my $cursymb, my $courseid,$udom,$uname)=
 5326: 	    &Apache::lonnet::whichuser($symb);
 5327: 	if (!$symb) { $symb=$cursymb; }
 5328:     }
 5329:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 5330:     $symb=&escape($symb);
 5331:     if ($target) { $target="target=\"$target\""; }
 5332:     return '<a href="/adm/parmset?command=set&amp;'.
 5333: 	'symb='.$symb.'&amp;uname='.$uname.
 5334: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 5335: }
 5336: ##############################################
 5337: 
 5338: =pod
 5339: 
 5340: =back
 5341: 
 5342: =cut
 5343: 
 5344: ###############################################
 5345: 
 5346: 
 5347: sub timehash {
 5348:     my ($thistime) = @_;
 5349:     my $timezone = &Apache::lonlocal::gettimezone();
 5350:     my $dt = DateTime->from_epoch(epoch => $thistime)
 5351:                      ->set_time_zone($timezone);
 5352:     my $wday = $dt->day_of_week();
 5353:     if ($wday == 7) { $wday = 0; }
 5354:     return ( 'second' => $dt->second(),
 5355:              'minute' => $dt->minute(),
 5356:              'hour'   => $dt->hour(),
 5357:              'day'     => $dt->day_of_month(),
 5358:              'month'   => $dt->month(),
 5359:              'year'    => $dt->year(),
 5360:              'weekday' => $wday,
 5361:              'dayyear' => $dt->day_of_year(),
 5362:              'dlsav'   => $dt->is_dst() );
 5363: }
 5364: 
 5365: sub utc_string {
 5366:     my ($date)=@_;
 5367:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 5368: }
 5369: 
 5370: sub maketime {
 5371:     my %th=@_;
 5372:     my ($epoch_time,$timezone,$dt);
 5373:     $timezone = &Apache::lonlocal::gettimezone();
 5374:     eval {
 5375:         $dt = DateTime->new( year   => $th{'year'},
 5376:                              month  => $th{'month'},
 5377:                              day    => $th{'day'},
 5378:                              hour   => $th{'hour'},
 5379:                              minute => $th{'minute'},
 5380:                              second => $th{'second'},
 5381:                              time_zone => $timezone,
 5382:                          );
 5383:     };
 5384:     if (!$@) {
 5385:         $epoch_time = $dt->epoch;
 5386:         if ($epoch_time) {
 5387:             return $epoch_time;
 5388:         }
 5389:     }
 5390:     return POSIX::mktime(
 5391:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 5392:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 5393: }
 5394: 
 5395: #########################################
 5396: 
 5397: sub findallcourses {
 5398:     my ($roles,$uname,$udom) = @_;
 5399:     my %roles;
 5400:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 5401:     my %courses;
 5402:     my $now=time;
 5403:     if (!defined($uname)) {
 5404:         $uname = $env{'user.name'};
 5405:     }
 5406:     if (!defined($udom)) {
 5407:         $udom = $env{'user.domain'};
 5408:     }
 5409:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 5410:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 5411:         if (!%roles) {
 5412:             %roles = (
 5413:                        cc => 1,
 5414:                        co => 1,
 5415:                        in => 1,
 5416:                        ep => 1,
 5417:                        ta => 1,
 5418:                        cr => 1,
 5419:                        st => 1,
 5420:              );
 5421:         }
 5422:         foreach my $entry (keys(%roleshash)) {
 5423:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 5424:             if ($trole =~ /^cr/) { 
 5425:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 5426:             } else {
 5427:                 next if (!exists($roles{$trole}));
 5428:             }
 5429:             if ($tend) {
 5430:                 next if ($tend < $now);
 5431:             }
 5432:             if ($tstart) {
 5433:                 next if ($tstart > $now);
 5434:             }
 5435:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 5436:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 5437:             my $value = $trole.'/'.$cdom.'/';
 5438:             if ($secpart eq '') {
 5439:                 ($cnum,$role) = split(/_/,$cnumpart); 
 5440:                 $sec = 'none';
 5441:                 $value .= $cnum.'/';
 5442:             } else {
 5443:                 $cnum = $cnumpart;
 5444:                 ($sec,$role) = split(/_/,$secpart);
 5445:                 $value .= $cnum.'/'.$sec;
 5446:             }
 5447:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 5448:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 5449:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 5450:                 }
 5451:             } else {
 5452:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 5453:             }
 5454:         }
 5455:     } else {
 5456:         foreach my $key (keys(%env)) {
 5457: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 5458:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 5459: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 5460: 	        next if ($role eq 'ca' || $role eq 'aa');
 5461: 	        next if (%roles && !exists($roles{$role}));
 5462: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 5463:                 my $active=1;
 5464:                 if ($starttime) {
 5465: 		    if ($now<$starttime) { $active=0; }
 5466:                 }
 5467:                 if ($endtime) {
 5468:                     if ($now>$endtime) { $active=0; }
 5469:                 }
 5470:                 if ($active) {
 5471:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 5472:                     if ($sec eq '') {
 5473:                         $sec = 'none';
 5474:                     } else {
 5475:                         $value .= $sec;
 5476:                     }
 5477:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 5478:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 5479:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 5480:                         }
 5481:                     } else {
 5482:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 5483:                     }
 5484:                 }
 5485:             }
 5486:         }
 5487:     }
 5488:     return %courses;
 5489: }
 5490: 
 5491: ###############################################
 5492: 
 5493: sub blockcheck {
 5494:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
 5495:     unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
 5496:         my ($has_evb,$check_ipaccess);
 5497:         my $dom = $env{'user.domain'};
 5498:         if ($env{'request.course.id'}) {
 5499:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5500:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5501:             my $checkrole = "cm./$cdom/$cnum";
 5502:             my $sec = $env{'request.course.sec'};
 5503:             if ($sec ne '') {
 5504:                 $checkrole .= "/$sec";
 5505:             }
 5506:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 5507:                 ($env{'request.role'} !~ /^st/)) {
 5508:                 $has_evb = 1;
 5509:             }
 5510:             unless ($has_evb) {
 5511:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
 5512:                     ($activity eq 'boards') || ($activity eq 'groups') || ($activity eq 'chat')) {
 5513:                     if ($udom eq $cdom) {
 5514:                         $check_ipaccess = 1;
 5515:                     }
 5516:                 }
 5517:             }
 5518:         } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
 5519:                 ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
 5520:             my $checkrole;
 5521:             if ($env{'request.role.domain'} eq '') {
 5522:                 $checkrole = "cm./$env{'user.domain'}/";
 5523:             } else {
 5524:                 $checkrole = "cm./$env{'request.role.domain'}/";
 5525:             }
 5526:             if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
 5527:                 $has_evb = 1;
 5528:             }
 5529:         }
 5530:         unless ($has_evb || $check_ipaccess) {
 5531:             my @machinedoms = &Apache::lonnet::current_machine_domains();
 5532:             if (($dom eq 'public') && ($activity eq 'port')) {
 5533:                 $dom = $udom;
 5534:             }
 5535:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
 5536:                 $check_ipaccess = 1;
 5537:             } else {
 5538:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 5539:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
 5540:                 my $prim = &Apache::lonnet::domain($dom,'primary');
 5541:                 my $intdom = &Apache::lonnet::internet_dom($prim);
 5542:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
 5543:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
 5544:                         $check_ipaccess = 1;
 5545:                     }
 5546:                 }
 5547:             }
 5548:         }
 5549:         if ($check_ipaccess) {
 5550:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
 5551:             unless (defined($cached)) {
 5552:                 my %domconfig =
 5553:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
 5554:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
 5555:             }
 5556:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
 5557:                 foreach my $id (keys(%{$ipaccessref})) {
 5558:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
 5559:                         my $range = $ipaccessref->{$id}->{'ip'};
 5560:                         if ($range) {
 5561:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
 5562:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
 5563:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
 5564:                                         return ('','','',$id,$dom);
 5565:                                         last;
 5566:                                     }
 5567:                                 }
 5568:                             }
 5569:                         }
 5570:                     }
 5571:                 }
 5572:             }
 5573:         }
 5574:         if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
 5575:             return ();
 5576:         }
 5577:     }
 5578:     if (defined($udom) && defined($uname)) {
 5579:         # If uname and udom are for a course, check for blocks in the course.
 5580:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
 5581:             my ($startblock,$endblock,$triggerblock) =
 5582:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
 5583:             return ($startblock,$endblock,$triggerblock);
 5584:         }
 5585:     } else {
 5586:         $udom = $env{'user.domain'};
 5587:         $uname = $env{'user.name'};
 5588:     }
 5589: 
 5590:     my $startblock = 0;
 5591:     my $endblock = 0;
 5592:     my $triggerblock = '';
 5593:     my %live_courses;
 5594:     unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
 5595:         %live_courses = &findallcourses(undef,$uname,$udom);
 5596:     }
 5597: 
 5598:     # If uname is for a user, and activity is course-specific, i.e.,
 5599:     # boards, chat or groups, check for blocking in current course only.
 5600: 
 5601:     if (($activity eq 'boards' || $activity eq 'chat' ||
 5602:          $activity eq 'groups' || $activity eq 'printout' ||
 5603:          $activity eq 'search' || $activity eq 'reinit' ||
 5604:          $activity eq 'alert') &&
 5605:         ($env{'request.course.id'})) {
 5606:         foreach my $key (keys(%live_courses)) {
 5607:             if ($key ne $env{'request.course.id'}) {
 5608:                 delete($live_courses{$key});
 5609:             }
 5610:         }
 5611:     }
 5612: 
 5613:     my $otheruser = 0;
 5614:     my %own_courses;
 5615:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 5616:         # Resource belongs to user other than current user.
 5617:         $otheruser = 1;
 5618:         # Gather courses for current user
 5619:         %own_courses = 
 5620:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 5621:     }
 5622: 
 5623:     # Gather active course roles - course coordinator, instructor, 
 5624:     # exam proctor, ta, student, or custom role.
 5625: 
 5626:     foreach my $course (keys(%live_courses)) {
 5627:         my ($cdom,$cnum);
 5628:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 5629:             $cdom = $env{'course.'.$course.'.domain'};
 5630:             $cnum = $env{'course.'.$course.'.num'};
 5631:         } else {
 5632:             ($cdom,$cnum) = split(/_/,$course); 
 5633:         }
 5634:         my $no_ownblock = 0;
 5635:         my $no_userblock = 0;
 5636:         if ($otheruser && $activity ne 'com') {
 5637:             # Check if current user has 'evb' priv for this
 5638:             if (defined($own_courses{$course})) {
 5639:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 5640:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5641:                     if ($sec ne 'none') {
 5642:                         $checkrole .= '/'.$sec;
 5643:                     }
 5644:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5645:                         $no_ownblock = 1;
 5646:                         last;
 5647:                     }
 5648:                 }
 5649:             }
 5650:             # if they have 'evb' priv and are currently not playing student
 5651:             next if (($no_ownblock) &&
 5652:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 5653:         }
 5654:         foreach my $sec (keys(%{$live_courses{$course}})) {
 5655:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5656:             if ($sec ne 'none') {
 5657:                 $checkrole .= '/'.$sec;
 5658:             }
 5659:             if ($otheruser) {
 5660:                 # Resource belongs to user other than current user.
 5661:                 # Assemble privs for that user, and check for 'evb' priv.
 5662:                 my (%allroles,%userroles);
 5663:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 5664:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 5665:                         my ($trole,$tdom,$tnum,$tsec);
 5666:                         if ($entry =~ /^cr/) {
 5667:                             ($trole,$tdom,$tnum,$tsec) = 
 5668:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 5669:                         } else {
 5670:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 5671:                         }
 5672:                         my ($spec,$area,$trest);
 5673:                         $area = '/'.$tdom.'/'.$tnum;
 5674:                         $trest = $tnum;
 5675:                         if ($tsec ne '') {
 5676:                             $area .= '/'.$tsec;
 5677:                             $trest .= '/'.$tsec;
 5678:                         }
 5679:                         $spec = $trole.'.'.$area;
 5680:                         if ($trole =~ /^cr/) {
 5681:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 5682:                                                               $tdom,$spec,$trest,$area);
 5683:                         } else {
 5684:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 5685:                                                                 $tdom,$spec,$trest,$area);
 5686:                         }
 5687:                     }
 5688:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 5689:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 5690:                         if ($1) {
 5691:                             $no_userblock = 1;
 5692:                             last;
 5693:                         }
 5694:                     }
 5695:                 }
 5696:             } else {
 5697:                 # Resource belongs to current user
 5698:                 # Check for 'evb' priv via lonnet::allowed().
 5699:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5700:                     $no_ownblock = 1;
 5701:                     last;
 5702:                 }
 5703:             }
 5704:         }
 5705:         # if they have the evb priv and are currently not playing student
 5706:         next if (($no_ownblock) &&
 5707:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 5708:         next if ($no_userblock);
 5709: 
 5710:         # Retrieve blocking times and identity of blocker for course
 5711:         # of specified user, unless user has 'evb' privilege.
 5712: 
 5713:         my ($start,$end,$trigger) = 
 5714:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
 5715:         if (($start != 0) && 
 5716:             (($startblock == 0) || ($startblock > $start))) {
 5717:             $startblock = $start;
 5718:             if ($trigger ne '') {
 5719:                 $triggerblock = $trigger;
 5720:             }
 5721:         }
 5722:         if (($end != 0)  &&
 5723:             (($endblock == 0) || ($endblock < $end))) {
 5724:             $endblock = $end;
 5725:             if ($trigger ne '') {
 5726:                 $triggerblock = $trigger;
 5727:             }
 5728:         }
 5729:     }
 5730:     return ($startblock,$endblock,$triggerblock);
 5731: }
 5732: 
 5733: sub get_blocks {
 5734:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
 5735:     my $startblock = 0;
 5736:     my $endblock = 0;
 5737:     my $triggerblock = '';
 5738:     my $course = $cdom.'_'.$cnum;
 5739:     $setters->{$course} = {};
 5740:     $setters->{$course}{'staff'} = [];
 5741:     $setters->{$course}{'times'} = [];
 5742:     $setters->{$course}{'triggers'} = [];
 5743:     my (@blockers,%triggered);
 5744:     my $now = time;
 5745:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 5746:     if ($activity eq 'docs') {
 5747:         my ($blocked,$nosymbcache,$noenccheck);
 5748:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
 5749:             $blocked = 1;
 5750:             $nosymbcache = 1;
 5751:             $noenccheck = 1;
 5752:         }
 5753:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
 5754:         foreach my $block (@blockers) {
 5755:             if ($block =~ /^firstaccess____(.+)$/) {
 5756:                 my $item = $1;
 5757:                 my $type = 'map';
 5758:                 my $timersymb = $item;
 5759:                 if ($item eq 'course') {
 5760:                     $type = 'course';
 5761:                 } elsif ($item =~ /___\d+___/) {
 5762:                     $type = 'resource';
 5763:                 } else {
 5764:                     $timersymb = &Apache::lonnet::symbread($item);
 5765:                 }
 5766:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5767:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 5768:                 $triggered{$block} = {
 5769:                                        start => $start,
 5770:                                        end   => $end,
 5771:                                        type  => $type,
 5772:                                      };
 5773:             }
 5774:         }
 5775:     } else {
 5776:         foreach my $block (keys(%commblocks)) {
 5777:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 5778:                 my ($start,$end) = ($1,$2);
 5779:                 if ($start <= time && $end >= time) {
 5780:                     if (ref($commblocks{$block}) eq 'HASH') {
 5781:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5782:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5783:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 5784:                                     push(@blockers,$block);
 5785:                                 }
 5786:                             }
 5787:                         }
 5788:                     }
 5789:                 }
 5790:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 5791:                 my $item = $1;
 5792:                 my $timersymb = $item; 
 5793:                 my $type = 'map';
 5794:                 if ($item eq 'course') {
 5795:                     $type = 'course';
 5796:                 } elsif ($item =~ /___\d+___/) {
 5797:                     $type = 'resource';
 5798:                 } else {
 5799:                     $timersymb = &Apache::lonnet::symbread($item);
 5800:                 }
 5801:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5802:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 5803:                 if ($start && $end) {
 5804:                     if (($start <= time) && ($end >= time)) {
 5805:                         if (ref($commblocks{$block}) eq 'HASH') {
 5806:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5807:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5808:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
 5809:                                         push(@blockers,$block);
 5810:                                         $triggered{$block} = {
 5811:                                                                start => $start,
 5812:                                                                end   => $end,
 5813:                                                                type  => $type,
 5814:                                                              };
 5815:                                     }
 5816:                                 }
 5817:                             }
 5818:                         }
 5819:                     }
 5820:                 }
 5821:             }
 5822:         }
 5823:     }
 5824:     foreach my $blocker (@blockers) {
 5825:         my ($staff_name,$staff_dom,$title,$blocks) =
 5826:             &parse_block_record($commblocks{$blocker});
 5827:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 5828:         my ($start,$end,$triggertype);
 5829:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 5830:             ($start,$end) = ($1,$2);
 5831:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 5832:             $start = $triggered{$blocker}{'start'};
 5833:             $end = $triggered{$blocker}{'end'};
 5834:             $triggertype = $triggered{$blocker}{'type'};
 5835:         }
 5836:         if ($start) {
 5837:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 5838:             if ($triggertype) {
 5839:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 5840:             } else {
 5841:                 push(@{$$setters{$course}{'triggers'}},0);
 5842:             }
 5843:             if ( ($startblock == 0) || ($startblock > $start) ) {
 5844:                 $startblock = $start;
 5845:                 if ($triggertype) {
 5846:                     $triggerblock = $blocker;
 5847:                 }
 5848:             }
 5849:             if ( ($endblock == 0) || ($endblock < $end) ) {
 5850:                $endblock = $end;
 5851:                if ($triggertype) {
 5852:                    $triggerblock = $blocker;
 5853:                }
 5854:             }
 5855:         }
 5856:     }
 5857:     return ($startblock,$endblock,$triggerblock);
 5858: }
 5859: 
 5860: sub parse_block_record {
 5861:     my ($record) = @_;
 5862:     my ($setuname,$setudom,$title,$blocks);
 5863:     if (ref($record) eq 'HASH') {
 5864:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 5865:         $title = &unescape($record->{'event'});
 5866:         $blocks = $record->{'blocks'};
 5867:     } else {
 5868:         my @data = split(/:/,$record,3);
 5869:         if (scalar(@data) eq 2) {
 5870:             $title = $data[1];
 5871:             ($setuname,$setudom) = split(/@/,$data[0]);
 5872:         } else {
 5873:             ($setuname,$setudom,$title) = @data;
 5874:         }
 5875:         $blocks = { 'com' => 'on' };
 5876:     }
 5877:     return ($setuname,$setudom,$title,$blocks);
 5878: }
 5879: 
 5880: sub blocking_status {
 5881:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
 5882:     my %setters;
 5883: 
 5884: # check for active blocking
 5885:     if ($clientip eq '') {
 5886:         $clientip = &Apache::lonnet::get_requestor_ip();
 5887:     }
 5888:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
 5889:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
 5890:     my $blocked = 0;
 5891:     if (($startblock && $endblock) || ($by_ip)) {
 5892:         $blocked = 1;
 5893:     }
 5894: 
 5895: # caller just wants to know whether a block is active
 5896:     if (!wantarray) { return $blocked; }
 5897: 
 5898: # build a link to a popup window containing the details
 5899:     my $querystring  = "?activity=$activity";
 5900: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
 5901:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
 5902:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
 5903:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
 5904:     } elsif ($activity eq 'docs') {
 5905:         my $showurl = &Apache::lonenc::check_encrypt($url);
 5906:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
 5907:         if ($symb) {
 5908:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
 5909:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
 5910:         }
 5911:     }
 5912: 
 5913:     my $output .= <<'END_MYBLOCK';
 5914: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 5915:     var options = "width=" + w + ",height=" + h + ",";
 5916:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 5917:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 5918:     var newWin = window.open(url, wdwName, options);
 5919:     newWin.focus();
 5920: }
 5921: END_MYBLOCK
 5922: 
 5923:     $output = Apache::lonhtmlcommon::scripttag($output);
 5924:   
 5925:     my $popupUrl = "/adm/blockingstatus/$querystring";
 5926:     my $text = &mt('Communication Blocked');
 5927:     my $class = 'LC_comblock';
 5928:     if ($activity eq 'docs') {
 5929:         $text = &mt('Content Access Blocked');
 5930:         $class = '';
 5931:     } elsif ($activity eq 'printout') {
 5932:         $text = &mt('Printing Blocked');
 5933:     } elsif ($activity eq 'passwd') {
 5934:         $text = &mt('Password Changing Blocked');
 5935:     } elsif ($activity eq 'grades') {
 5936:         $text = &mt('Gradebook Blocked');
 5937:     } elsif ($activity eq 'search') {
 5938:         $text = &mt('Search Blocked');
 5939:     } elsif ($activity eq 'alert') {
 5940:         $text = &mt('Checking Critical Messages Blocked');
 5941:     } elsif ($activity eq 'reinit') {
 5942:         $text = &mt('Checking Course Update Blocked');
 5943:     } elsif ($activity eq 'about') {
 5944:         $text = &mt('Access to User Information Pages Blocked');
 5945:     } elsif ($activity eq 'wishlist') {
 5946:         $text = &mt('Access to Stored Links Blocked');
 5947:     } elsif ($activity eq 'annotate') {
 5948:         $text = &mt('Access to Annotations Blocked');
 5949:     }
 5950:     $output .= <<"END_BLOCK";
 5951: <div class='$class'>
 5952:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 5953:   title='$text'>
 5954:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 5955:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 5956:   title='$text'>$text</a>
 5957: </div>
 5958: 
 5959: END_BLOCK
 5960: 
 5961:     return ($blocked, $output);
 5962: }
 5963: 
 5964: ###############################################
 5965: 
 5966: sub check_ip_acc {
 5967:     my ($acc,$clientip)=@_;
 5968:     &Apache::lonxml::debug("acc is $acc");
 5969:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 5970:         return 1;
 5971:     }
 5972:     my ($ip,$allowed);
 5973:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
 5974:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
 5975:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
 5976:     } else {
 5977:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
 5978:         $ip = $remote_ip || $env{'request.host'} || $clientip;
 5979:     }
 5980: 
 5981:     my $name;
 5982:     my %access = (
 5983:                      allowfrom => 1,
 5984:                      denyfrom  => 0,
 5985:                  );
 5986:     my @allows;
 5987:     my @denies;
 5988:     foreach my $item (split(',',$acc)) {
 5989:         $item =~ s/^\s*//;
 5990:         $item =~ s/\s*$//;
 5991:         my $pattern;
 5992:         if ($item =~ /^\!(.+)$/) {
 5993:             push(@denies,$1);
 5994:         } else {
 5995:             push(@allows,$item);
 5996:         }
 5997:    }
 5998:    my $numdenies = scalar(@denies);
 5999:    my $numallows = scalar(@allows);
 6000:    my $count = 0;
 6001:    foreach my $pattern (@denies,@allows) {
 6002:         $count ++; 
 6003:         my $acctype = 'allowfrom';
 6004:         if ($count <= $numdenies) {
 6005:             $acctype = 'denyfrom';
 6006:         }
 6007:         if ($pattern =~ /\*$/) {
 6008:             #35.8.*
 6009:             $pattern=~s/\*//;
 6010:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 6011:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 6012:             #35.8.3.[34-56]
 6013:             my $low=$2;
 6014:             my $high=$3;
 6015:             $pattern=$1;
 6016:             if ($ip =~ /^\Q$pattern\E/) {
 6017:                 my $last=(split(/\./,$ip))[3];
 6018:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
 6019:             }
 6020:         } elsif ($pattern =~ /^\*/) {
 6021:             #*.msu.edu
 6022:             $pattern=~s/\*//;
 6023:             if (!defined($name)) {
 6024:                 use Socket;
 6025:                 my $netaddr=inet_aton($ip);
 6026:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 6027:             }
 6028:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 6029:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 6030:             #127.0.0.1
 6031:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 6032:         } else {
 6033:             #some.name.com
 6034:             if (!defined($name)) {
 6035:                 use Socket;
 6036:                 my $netaddr=inet_aton($ip);
 6037:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 6038:             }
 6039:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 6040:         }
 6041:         if ($allowed =~ /^(0|1)$/) { last; }
 6042:     }
 6043:     if ($allowed eq '') {
 6044:         if ($numdenies && !$numallows) {
 6045:             $allowed = 1;
 6046:         } else {
 6047:             $allowed = 0;
 6048:         }
 6049:     }
 6050:     return $allowed;
 6051: }
 6052: 
 6053: ###############################################
 6054: 
 6055: =pod
 6056: 
 6057: =head1 Domain Template Functions
 6058: 
 6059: =over 4
 6060: 
 6061: =item * &determinedomain()
 6062: 
 6063: Inputs: $domain (usually will be undef)
 6064: 
 6065: Returns: Determines which domain should be used for designs
 6066: 
 6067: =cut
 6068: 
 6069: ###############################################
 6070: sub determinedomain {
 6071:     my $domain=shift;
 6072:     if (! $domain) {
 6073:         # Determine domain if we have not been given one
 6074:         $domain = &Apache::lonnet::default_login_domain();
 6075:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 6076:         if ($env{'request.role.domain'}) { 
 6077:             $domain=$env{'request.role.domain'}; 
 6078:         }
 6079:     }
 6080:     return $domain;
 6081: }
 6082: ###############################################
 6083: 
 6084: sub devalidate_domconfig_cache {
 6085:     my ($udom)=@_;
 6086:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 6087: }
 6088: 
 6089: # ---------------------- Get domain configuration for a domain
 6090: sub get_domainconf {
 6091:     my ($udom) = @_;
 6092:     my $cachetime=1800;
 6093:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 6094:     if (defined($cached)) { return %{$result}; }
 6095: 
 6096:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 6097: 					     ['login','rolecolors','autoenroll'],$udom);
 6098:     my (%designhash,%legacy);
 6099:     if (keys(%domconfig) > 0) {
 6100:         if (ref($domconfig{'login'}) eq 'HASH') {
 6101:             if (keys(%{$domconfig{'login'}})) {
 6102:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 6103:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 6104:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
 6105:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 6106:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
 6107:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
 6108:                                         if ($key eq 'loginvia') {
 6109:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 6110:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 6111:                                                 $designhash{$udom.'.login.loginvia'} = $server;
 6112:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 6113: 
 6114:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 6115:                                                 } else {
 6116:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 6117:                                                 }
 6118:                                             }
 6119:                                         } elsif ($key eq 'headtag') {
 6120:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
 6121:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
 6122:                                             }
 6123:                                         }
 6124:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
 6125:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
 6126:                                         }
 6127:                                     }
 6128:                                 }
 6129:                             }
 6130:                         } elsif ($key eq 'saml') {
 6131:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 6132:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
 6133:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
 6134:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
 6135:                                         foreach my $item ('text','img','alt','url','title','window','notsso') {
 6136:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
 6137:                                         }
 6138:                                     }
 6139:                                 }
 6140:                             }
 6141:                         } else {
 6142:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 6143:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 6144:                                     $domconfig{'login'}{$key}{$img};
 6145:                             }
 6146:                         }
 6147:                     } else {
 6148:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 6149:                     }
 6150:                 }
 6151:             } else {
 6152:                 $legacy{'login'} = 1;
 6153:             }
 6154:         } else {
 6155:             $legacy{'login'} = 1;
 6156:         }
 6157:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 6158:             if (keys(%{$domconfig{'rolecolors'}})) {
 6159:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 6160:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 6161:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 6162:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 6163:                         }
 6164:                     }
 6165:                 }
 6166:             } else {
 6167:                 $legacy{'rolecolors'} = 1;
 6168:             }
 6169:         } else {
 6170:             $legacy{'rolecolors'} = 1;
 6171:         }
 6172:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 6173:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 6174:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 6175:             }
 6176:         }
 6177:         if (keys(%legacy) > 0) {
 6178:             my %legacyhash = &get_legacy_domconf($udom);
 6179:             foreach my $item (keys(%legacyhash)) {
 6180:                 if ($item =~ /^\Q$udom\E\.login/) {
 6181:                     if ($legacy{'login'}) { 
 6182:                         $designhash{$item} = $legacyhash{$item};
 6183:                     }
 6184:                 } else {
 6185:                     if ($legacy{'rolecolors'}) {
 6186:                         $designhash{$item} = $legacyhash{$item};
 6187:                     }
 6188:                 }
 6189:             }
 6190:         }
 6191:     } else {
 6192:         %designhash = &get_legacy_domconf($udom); 
 6193:     }
 6194:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 6195: 				  $cachetime);
 6196:     return %designhash;
 6197: }
 6198: 
 6199: sub get_legacy_domconf {
 6200:     my ($udom) = @_;
 6201:     my %legacyhash;
 6202:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 6203:     my $designfile =  $designdir.'/'.$udom.'.tab';
 6204:     if (-e $designfile) {
 6205:         if ( open (my $fh,'<',$designfile) ) {
 6206:             while (my $line = <$fh>) {
 6207:                 next if ($line =~ /^\#/);
 6208:                 chomp($line);
 6209:                 my ($key,$val)=(split(/\=/,$line));
 6210:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 6211:             }
 6212:             close($fh);
 6213:         }
 6214:     }
 6215:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 6216:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 6217:     }
 6218:     return %legacyhash;
 6219: }
 6220: 
 6221: =pod
 6222: 
 6223: =item * &domainlogo()
 6224: 
 6225: Inputs: $domain (usually will be undef)
 6226: 
 6227: Returns: A link to a domain logo, if the domain logo exists.
 6228: If the domain logo does not exist, a description of the domain.
 6229: 
 6230: =cut
 6231: 
 6232: ###############################################
 6233: sub domainlogo {
 6234:     my $domain = &determinedomain(shift);
 6235:     my %designhash = &get_domainconf($domain);    
 6236:     # See if there is a logo
 6237:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 6238:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 6239:         if ($imgsrc =~ m{^/(adm|res)/}) {
 6240: 	    if ($imgsrc =~ m{^/res/}) {
 6241: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 6242: 		&Apache::lonnet::repcopy($local_name);
 6243: 	    }
 6244: 	   $imgsrc = &lonhttpdurl($imgsrc);
 6245:         }
 6246:         my $alttext = $domain;
 6247:         if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
 6248:             $alttext = $designhash{$domain.'.login.alttext_domlogo'};
 6249:         }
 6250:         return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
 6251:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 6252:         return &Apache::lonnet::domain($domain,'description');
 6253:     } else {
 6254:         return '';
 6255:     }
 6256: }
 6257: ##############################################
 6258: 
 6259: =pod
 6260: 
 6261: =item * &designparm()
 6262: 
 6263: Inputs: $which parameter; $domain (usually will be undef)
 6264: 
 6265: Returns: value of designparamter $which
 6266: 
 6267: =cut
 6268: 
 6269: 
 6270: ##############################################
 6271: sub designparm {
 6272:     my ($which,$domain)=@_;
 6273:     if (exists($env{'environment.color.'.$which})) {
 6274:         return $env{'environment.color.'.$which};
 6275:     }
 6276:     $domain=&determinedomain($domain);
 6277:     my %domdesign;
 6278:     unless ($domain eq 'public') {
 6279:         %domdesign = &get_domainconf($domain);
 6280:     }
 6281:     my $output;
 6282:     if ($domdesign{$domain.'.'.$which} ne '') {
 6283:         $output = $domdesign{$domain.'.'.$which};
 6284:     } else {
 6285:         $output = $defaultdesign{$which};
 6286:     }
 6287:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 6288:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 6289:         if ($output =~ m{^/(adm|res)/}) {
 6290:             if ($output =~ m{^/res/}) {
 6291:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 6292:                 &Apache::lonnet::repcopy($local_name);
 6293:             }
 6294:             $output = &lonhttpdurl($output);
 6295:         }
 6296:     }
 6297:     return $output;
 6298: }
 6299: 
 6300: ##############################################
 6301: =pod
 6302: 
 6303: =item * &authorspace()
 6304: 
 6305: Inputs: $url (usually will be undef).
 6306: 
 6307: Returns: Path to Authoring Space containing the resource or 
 6308:          directory being viewed (or for which action is being taken). 
 6309:          If $url is provided, and begins /priv/<domain>/<uname>
 6310:          the path will be that portion of the $context argument.
 6311:          Otherwise the path will be for the author space of the current
 6312:          user when the current role is author, or for that of the 
 6313:          co-author/assistant co-author space when the current role 
 6314:          is co-author or assistant co-author.
 6315: 
 6316: =cut
 6317: 
 6318: sub authorspace {
 6319:     my ($url) = @_;
 6320:     if ($url ne '') {
 6321:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 6322:            return $1;
 6323:         }
 6324:     }
 6325:     my $caname = '';
 6326:     my $cadom = '';
 6327:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 6328:         ($cadom,$caname) =
 6329:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 6330:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 6331:         $caname = $env{'user.name'};
 6332:         $cadom = $env{'user.domain'};
 6333:     }
 6334:     if (($caname ne '') && ($cadom ne '')) {
 6335:         return "/priv/$cadom/$caname/";
 6336:     }
 6337:     return;
 6338: }
 6339: 
 6340: ##############################################
 6341: =pod
 6342: 
 6343: =item * &head_subbox()
 6344: 
 6345: Inputs: $content (contains HTML code with page functions, etc.)
 6346: 
 6347: Returns: HTML div with $content
 6348:          To be included in page header
 6349: 
 6350: =cut
 6351: 
 6352: sub head_subbox {
 6353:     my ($content)=@_;
 6354:     my $output =
 6355:         '<div class="LC_head_subbox">'
 6356:        .$content
 6357:        .'</div>'
 6358: }
 6359: 
 6360: ##############################################
 6361: =pod
 6362: 
 6363: =item * &CSTR_pageheader()
 6364: 
 6365: Input: (optional) filename from which breadcrumb trail is built.
 6366:        In most cases no input as needed, as $env{'request.filename'}
 6367:        is appropriate for use in building the breadcrumb trail.
 6368:        frameset flag
 6369:        If page header is being requested for use in a frameset, then
 6370:        the second (option) argument -- frameset will be true, and
 6371:        the target attribute set for links should be target="_parent".
 6372:        If $title is supplied as the thitd arg, that will be used to 
 6373:        the left of the breadcrumbs tail for the current path.
 6374: 
 6375: Returns: HTML div with CSTR path and recent box
 6376:          To be included on Authoring Space pages
 6377: 
 6378: =cut
 6379: 
 6380: sub CSTR_pageheader {
 6381:     my ($trailfile,$frameset,$title) = @_;
 6382:     if ($trailfile eq '') {
 6383:         $trailfile = $env{'request.filename'};
 6384:     }
 6385: 
 6386: # this is for resources; directories have customtitle, and crumbs
 6387: # and select recent are created in lonpubdir.pm
 6388: 
 6389:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 6390:     my ($udom,$uname,$thisdisfn)=
 6391:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 6392:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 6393:     $formaction =~ s{/+}{/}g;
 6394: 
 6395:     my $parentpath = '';
 6396:     my $lastitem = '';
 6397:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 6398:         $parentpath = $1;
 6399:         $lastitem = $2;
 6400:     } else {
 6401:         $lastitem = $thisdisfn;
 6402:     }
 6403: 
 6404:     my $crsauthor;
 6405:     if (($env{'request.course.id'}) &&
 6406:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
 6407:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
 6408:         $crsauthor = 1;
 6409:         if ($title eq '') {
 6410:             $title = &mt('Course Authoring Space');
 6411:         }
 6412:     } elsif ($title eq '') {
 6413:         $title = &mt('Authoring Space');
 6414:     }
 6415: 
 6416:     my ($target,$crumbtarget) = (' target="_top"','_top');
 6417:     if ($frameset) {
 6418:         $target = ' target="_parent"';
 6419:         $crumbtarget = '_parent';
 6420:     } elsif (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
 6421:         $target = '';
 6422:         $crumbtarget = '';
 6423:     } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
 6424:         $target = ' target="'.$env{'request.deeplink.target'}.'"';
 6425:         $crumbtarget = $env{'request.deeplink.target'};
 6426:     }
 6427: 
 6428:     my $output =
 6429:          '<div>'
 6430:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 6431:         .'<b>'.$title.'</b> '
 6432:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
 6433:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
 6434: 
 6435:     if ($lastitem) {
 6436:         $output .=
 6437:              '<span class="LC_filename">'
 6438:             .$lastitem
 6439:             .'</span>';
 6440:     }
 6441: 
 6442:     if ($crsauthor) {
 6443:         $output .= '</form>'.&Apache::lonmenu::constspaceform($frameset);
 6444:     } else {
 6445:         $output .=
 6446:              '<br />'
 6447:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
 6448:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 6449:             .'</form>'
 6450:             .&Apache::lonmenu::constspaceform($frameset);
 6451:     }
 6452:     $output .= '</div>';
 6453: 
 6454:     return $output;
 6455: }
 6456: 
 6457: ###############################################
 6458: ###############################################
 6459: 
 6460: =pod
 6461: 
 6462: =back
 6463: 
 6464: =head1 HTML Helpers
 6465: 
 6466: =over 4
 6467: 
 6468: =item * &bodytag()
 6469: 
 6470: Returns a uniform header for LON-CAPA web pages.
 6471: 
 6472: Inputs: 
 6473: 
 6474: =over 4
 6475: 
 6476: =item * $title, A title to be displayed on the page.
 6477: 
 6478: =item * $function, the current role (can be undef).
 6479: 
 6480: =item * $addentries, extra parameters for the <body> tag.
 6481: 
 6482: =item * $bodyonly, if defined, only return the <body> tag.
 6483: 
 6484: =item * $domain, if defined, force a given domain.
 6485: 
 6486: =item * $forcereg, if page should register as content page (relevant for 
 6487:             text interface only)
 6488: 
 6489: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 6490:                      navigational links
 6491: 
 6492: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 6493: 
 6494: =item * $args, optional argument valid values are
 6495:             no_auto_mt_title -> prevents &mt()ing the title arg
 6496:             use_absolute     -> for external resource or syllabus, this will
 6497:                                 contain https://<hostname> if server uses
 6498:                                 https (as per hosts.tab), but request is for http
 6499:             hostname         -> hostname, from $r->hostname().
 6500: 
 6501: =item * $advtoolsref, optional argument, ref to an array containing
 6502:             inlineremote items to be added in "Functions" menu below
 6503:             breadcrumbs.
 6504: 
 6505: =item * $ltiscope, optional argument, will be one of: resource, map or
 6506:             course, if LON-CAPA is in LTI Provider context. Value is
 6507:             the scope of use, i.e., launch was for access to a single, a map
 6508:             or the entire course.
 6509: 
 6510: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
 6511:             context, this will contain the URL for the landing item in
 6512:             the course, after launch from an LTI Consumer
 6513: 
 6514: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
 6515:             context, this will contain a reference to hash of items
 6516:             to be included in the page header and/or inline menu.
 6517: 
 6518: =item * $menucoll, optional argument, if specific menu collection is in
 6519:             effect, either set as the default for the course, or set for
 6520:             the deeplink paramater for $env{'request.deeplink.login'}
 6521:             then $menucoll will be the number of that collection. 
 6522: 
 6523: =item * $menuref, optional argument, reference to a hash, containing the
 6524:             menu options included for the menu in effect, based on the
 6525:             configuration for the numbered menu collection in use.  
 6526: 
 6527: =item * $showncrumbsref, reference to a scalar. Calls to lonmenu::innerregister
 6528:             within &bodytag() can result in calls to lonhtmlcommon::breadcrumbs(),
 6529:             if so, $showncrumbsref is set there to 1, and will propagate back
 6530:             via &bodytag() to &start_page(), to prevent lonhtmlcommon::breadcrumbs()
 6531:             being called a second time.
 6532: 
 6533: =back
 6534: 
 6535: Returns: A uniform header for LON-CAPA web pages.  
 6536: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 6537: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 6538: other decorations will be returned.
 6539: 
 6540: =cut
 6541: 
 6542: sub bodytag {
 6543:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 6544:         $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri,
 6545:         $ltimenu,$menucoll,$menuref,$showncrumbsref)=@_;
 6546: 
 6547:     my $public;
 6548:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 6549:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 6550:         $public = 1;
 6551:     }
 6552:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 6553:     my $httphost = $args->{'use_absolute'};
 6554:     my $hostname = $args->{'hostname'};
 6555: 
 6556:     $function = &get_users_function() if (!$function);
 6557:     my $img =    &designparm($function.'.img',$domain);
 6558:     my $font =   &designparm($function.'.font',$domain);
 6559:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 6560: 
 6561:     my %design = ( 'style'   => 'margin-top: 0',
 6562: 		   'bgcolor' => $pgbg,
 6563: 		   'text'    => $font,
 6564:                    'alink'   => &designparm($function.'.alink',$domain),
 6565: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 6566: 		   'link'    => &designparm($function.'.link',$domain),);
 6567:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 6568: 
 6569:  # role and realm
 6570:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
 6571:     if ($realm) {
 6572:         $realm = '/'.$realm;
 6573:     }
 6574:     if ($role eq 'ca') {
 6575:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 6576:         $realm = &plainname($rname,$rdom);
 6577:     } 
 6578: # realm
 6579:     my ($cid,$sec);
 6580:     if ($env{'request.course.id'}) {
 6581:         $cid = $env{'request.course.id'};
 6582:         if ($env{'request.course.sec'}) {
 6583:             $sec = $env{'request.course.sec'};
 6584:         }
 6585:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
 6586:         if (&Apache::lonnet::is_course($1,$2)) {
 6587:             $cid = $1.'_'.$2;
 6588:             $sec = $3;
 6589:         }
 6590:     }
 6591:     if ($cid) {
 6592:         if ($env{'request.role'} !~ /^cr/) {
 6593:             $role = &Apache::lonnet::plaintext($role,&course_type());
 6594:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
 6595:             if ($env{'request.role.desc'}) {
 6596:                 $role = $env{'request.role.desc'};
 6597:             } else {
 6598:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
 6599:             }
 6600:         } else {
 6601:             $role = (split(/\//,$role,4))[-1]; 
 6602:         }
 6603:         if ($sec) {
 6604:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
 6605:         }   
 6606: 	$realm = $env{'course.'.$cid.'.description'};
 6607:     } else {
 6608:         $role = &Apache::lonnet::plaintext($role);
 6609:     }
 6610: 
 6611:     if (!$realm) { $realm='&nbsp;'; }
 6612: 
 6613:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 6614: 
 6615: # construct main body tag
 6616:     my $bodytag = "<body $extra_body_attr>".
 6617: 	&Apache::lontexconvert::init_math_support();
 6618: 
 6619:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 6620: 
 6621:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 6622:         return $bodytag;
 6623:     }
 6624: 
 6625:     if ($public) {
 6626: 	undef($role);
 6627:     }
 6628: 
 6629:     my $showcrstitle = 1;
 6630:     if (($cid) && ($env{'request.lti.login'})) {
 6631:         if (ref($ltimenu) eq 'HASH') {
 6632:             unless ($ltimenu->{'role'}) {
 6633:                 undef($role);
 6634:             }
 6635:             unless ($ltimenu->{'coursetitle'}) {
 6636:                 $realm='&nbsp;';
 6637:                 $showcrstitle = 0;
 6638:             }
 6639:         }
 6640:     } elsif (($cid) && ($menucoll)) {
 6641:         if (ref($menuref) eq 'HASH') {
 6642:             unless ($menuref->{'role'}) {
 6643:                 undef($role);
 6644:             }
 6645:             unless ($menuref->{'crs'}) {
 6646:                 $realm='&nbsp;';
 6647:                 $showcrstitle = 0;
 6648:             }
 6649:         }
 6650:     }
 6651: 
 6652:     my $titleinfo = '<h1>'.$title.'</h1>';
 6653:     #
 6654:     # Extra info if you are the DC
 6655:     my $dc_info = '';
 6656:     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
 6657:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
 6658:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 6659:         $dc_info =~ s/\s+$//;
 6660:     }
 6661: 
 6662:     my $crstype;
 6663:     if ($cid) {
 6664:         $crstype = $env{'course.'.$cid.'.type'};
 6665:     } elsif ($args->{'crstype'}) {
 6666:         $crstype = $args->{'crstype'};
 6667:     }
 6668:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
 6669:         undef($role);
 6670:     } else {
 6671:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
 6672:     }
 6673: 
 6674:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 6675: 
 6676:         #    if ($env{'request.state'} eq 'construct') {
 6677:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 6678:         #    }
 6679: 
 6680:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 6681:             Apache::lonmenu::utilityfunctions($httphost), 'start');
 6682: 
 6683:         unless ($args->{'no_primary_menu'}) {
 6684:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
 6685:                                                               $args->{'links_disabled'},
 6686:                                                               $args->{'links_target'});
 6687: 
 6688:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 6689:                 if ($dc_info) {
 6690:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 6691:                 }
 6692:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 6693:                                <em>$realm</em> $dc_info</div>|;
 6694:                 return $bodytag;
 6695:             }
 6696: 
 6697:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 6698:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 6699:             }
 6700: 
 6701:             $bodytag .= $right;
 6702: 
 6703:             if ($dc_info) {
 6704:                 $dc_info = &dc_courseid_toggle($dc_info);
 6705:             }
 6706:             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 6707:         }
 6708: 
 6709:         #if directed to not display the secondary menu, don't.  
 6710:         if ($args->{'no_secondary_menu'}) {
 6711:             return $bodytag;
 6712:         }
 6713:         #don't show menus for public users
 6714:         if (!$public){
 6715:             unless ($args->{'no_inline_menu'}) {
 6716:                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
 6717:                                                             $args->{'no_primary_menu'},
 6718:                                                             $menucoll,$menuref,
 6719:                                                             $args->{'links_disabled'},
 6720:                                                             $args->{'links_target'});
 6721:             }
 6722:             $bodytag .= Apache::lonmenu::serverform();
 6723:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 6724:             if ($env{'request.state'} eq 'construct') {
 6725:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 6726:                                 $args->{'bread_crumbs'},'','',$hostname,
 6727:                                 $ltiscope,$ltiuri,$showncrumbsref);
 6728:             } elsif ($forcereg) {
 6729:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 6730:                                 $args->{'group'},$args->{'hide_buttons'},
 6731:                                 $hostname,$ltiscope,$ltiuri,$showncrumbsref);
 6732:             } else {
 6733:                 $bodytag .= 
 6734:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 6735:                                                         $forcereg,$args->{'group'},
 6736:                                                         $args->{'bread_crumbs'},
 6737:                                                         $advtoolsref,'',$hostname);
 6738:             }
 6739:         }else{
 6740:             # this is to seperate menu from content when there's no secondary
 6741:             # menu. Especially needed for public accessible ressources.
 6742:             $bodytag .= '<hr style="clear:both" />';
 6743:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 6744:         }
 6745: 
 6746:         return $bodytag;
 6747: }
 6748: 
 6749: sub dc_courseid_toggle {
 6750:     my ($dc_info) = @_;
 6751:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 6752:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 6753:            &mt('(More ...)').'</a></span>'.
 6754:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 6755: }
 6756: 
 6757: sub make_attr_string {
 6758:     my ($register,$attr_ref) = @_;
 6759: 
 6760:     if ($attr_ref && !ref($attr_ref)) {
 6761: 	die("addentries Must be a hash ref ".
 6762: 	    join(':',caller(1))." ".
 6763: 	    join(':',caller(0))." ");
 6764:     }
 6765: 
 6766:     if ($register) {
 6767: 	my ($on_load,$on_unload);
 6768: 	foreach my $key (keys(%{$attr_ref})) {
 6769: 	    if      (lc($key) eq 'onload') {
 6770: 		$on_load.=$attr_ref->{$key}.';';
 6771: 		delete($attr_ref->{$key});
 6772: 
 6773: 	    } elsif (lc($key) eq 'onunload') {
 6774: 		$on_unload.=$attr_ref->{$key}.';';
 6775: 		delete($attr_ref->{$key});
 6776: 	    }
 6777: 	}
 6778: 	$attr_ref->{'onload'}  = $on_load;
 6779: 	$attr_ref->{'onunload'}= $on_unload;
 6780:     }
 6781: 
 6782:     my $attr_string;
 6783:     foreach my $attr (sort(keys(%$attr_ref))) {
 6784: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 6785:     }
 6786:     return $attr_string;
 6787: }
 6788: 
 6789: 
 6790: ###############################################
 6791: ###############################################
 6792: 
 6793: =pod
 6794: 
 6795: =item * &endbodytag()
 6796: 
 6797: Returns a uniform footer for LON-CAPA web pages.
 6798: 
 6799: Inputs: 1 - optional reference to an args hash
 6800: If in the hash, key for noredirectlink has a value which evaluates to true,
 6801: a 'Continue' link is not displayed if the page contains an
 6802: internal redirect in the <head></head> section,
 6803: i.e., $env{'internal.head.redirect'} exists   
 6804: 
 6805: =cut
 6806: 
 6807: sub endbodytag {
 6808:     my ($args) = @_;
 6809:     my $endbodytag;
 6810:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 6811:         $endbodytag='</body>';
 6812:     }
 6813:     if ( exists( $env{'internal.head.redirect'} ) ) {
 6814:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 6815:             my ($endbodyjs,$idattr);
 6816:             if ($env{'internal.head.to_opener'}) {
 6817:                 my $linkid = 'LC_continue_link';
 6818:                 $idattr = ' id="'.$linkid.'"';
 6819:                 my $redirect_for_js = &js_escape($env{'internal.head.redirect'});
 6820:                 $endbodyjs=<<ENDJS;
 6821: <script type="text/javascript">
 6822: // <![CDATA[
 6823: function ebFunction(evt) {
 6824:     evt.preventDefault();
 6825:     var dest = '$redirect_for_js';
 6826:     if (window.opener != null && !window.opener.closed) {
 6827:         window.opener.location.href=dest;
 6828:         window.close();
 6829:     } else {
 6830:         window.location.href=dest;
 6831:     }
 6832:     return false;
 6833: }
 6834: 
 6835: \$(document).ready(function () {
 6836:   if (document.getElementById('$linkid')) {
 6837:     var clickelem = document.getElementById('$linkid');
 6838:     clickelem.addEventListener('click',ebFunction,false);
 6839:   }
 6840: });
 6841: // ]]>
 6842: </script>
 6843: ENDJS
 6844:             }
 6845: 	    $endbodytag=
 6846: 	        "$endbodyjs<br /><a href=\"$env{'internal.head.redirect'}\"$idattr>".
 6847: 	        &mt('Continue').'</a>'.
 6848: 	        $endbodytag;
 6849:         }
 6850:     }
 6851:     return $endbodytag;
 6852: }
 6853: 
 6854: =pod
 6855: 
 6856: =item * &standard_css()
 6857: 
 6858: Returns a style sheet
 6859: 
 6860: Inputs: (all optional)
 6861:             domain         -> force to color decorate a page for a specific
 6862:                                domain
 6863:             function       -> force usage of a specific rolish color scheme
 6864:             bgcolor        -> override the default page bgcolor
 6865: 
 6866: =cut
 6867: 
 6868: sub standard_css {
 6869:     my ($function,$domain,$bgcolor) = @_;
 6870:     $function  = &get_users_function() if (!$function);
 6871:     my $img    = &designparm($function.'.img',   $domain);
 6872:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 6873:     my $font   = &designparm($function.'.font',  $domain);
 6874:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 6875: #second colour for later usage
 6876:     my $sidebg = &designparm($function.'.sidebg',$domain);
 6877:     my $pgbg_or_bgcolor =
 6878: 	         $bgcolor ||
 6879: 	         &designparm($function.'.pgbg',  $domain);
 6880:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 6881:     my $alink  = &designparm($function.'.alink', $domain);
 6882:     my $vlink  = &designparm($function.'.vlink', $domain);
 6883:     my $link   = &designparm($function.'.link',  $domain);
 6884: 
 6885:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 6886:     my $mono                 = 'monospace';
 6887:     my $data_table_head      = $sidebg;
 6888:     my $data_table_light     = '#FAFAFA';
 6889:     my $data_table_dark      = '#E0E0E0';
 6890:     my $data_table_darker    = '#CCCCCC';
 6891:     my $data_table_highlight = '#FFFF00';
 6892:     my $mail_new             = '#FFBB77';
 6893:     my $mail_new_hover       = '#DD9955';
 6894:     my $mail_read            = '#BBBB77';
 6895:     my $mail_read_hover      = '#999944';
 6896:     my $mail_replied         = '#AAAA88';
 6897:     my $mail_replied_hover   = '#888855';
 6898:     my $mail_other           = '#99BBBB';
 6899:     my $mail_other_hover     = '#669999';
 6900:     my $table_header         = '#DDDDDD';
 6901:     my $feedback_link_bg     = '#BBBBBB';
 6902:     my $lg_border_color      = '#C8C8C8';
 6903:     my $button_hover         = '#BF2317';
 6904: 
 6905:     my $border = ($env{'browser.type'} eq 'explorer' ||
 6906:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 6907:                                              : '0 3px 0 4px';
 6908: 
 6909: 
 6910:     return <<END;
 6911: 
 6912: /* needed for iframe to allow 100% height in FF */
 6913: body, html { 
 6914:     margin: 0;
 6915:     padding: 0 0.5%;
 6916:     height: 99%; /* to avoid scrollbars */
 6917: }
 6918: 
 6919: body {
 6920:   font-family: $sans;
 6921:   line-height:130%;
 6922:   font-size:0.83em;
 6923:   color:$font;
 6924: }
 6925: 
 6926: a:focus,
 6927: a:focus img {
 6928:   color: red;
 6929: }
 6930: 
 6931: form, .inline {
 6932:   display: inline;
 6933: }
 6934: 
 6935: .LC_right {
 6936:   text-align:right;
 6937: }
 6938: 
 6939: .LC_middle {
 6940:   vertical-align:middle;
 6941: }
 6942: 
 6943: .LC_floatleft {
 6944:   float: left;
 6945: }
 6946: 
 6947: .LC_floatright {
 6948:   float: right;
 6949: }
 6950: 
 6951: .LC_400Box {
 6952:   width:400px;
 6953: }
 6954: 
 6955: .LC_iframecontainer {
 6956:     width: 98%;
 6957:     margin: 0;
 6958:     position: fixed;
 6959:     top: 8.5em;
 6960:     bottom: 0;
 6961: }
 6962: 
 6963: .LC_iframecontainer iframe{
 6964:     border: none;
 6965:     width: 100%;
 6966:     height: 100%;
 6967: }
 6968: 
 6969: .LC_filename {
 6970:   font-family: $mono;
 6971:   white-space:pre;
 6972:   font-size: 120%;
 6973: }
 6974: 
 6975: .LC_fileicon {
 6976:   border: none;
 6977:   height: 1.3em;
 6978:   vertical-align: text-bottom;
 6979:   margin-right: 0.3em;
 6980:   text-decoration:none;
 6981: }
 6982: 
 6983: .LC_setting {
 6984:   text-decoration:underline;
 6985: }
 6986: 
 6987: .LC_error {
 6988:   color: red;
 6989: }
 6990: 
 6991: .LC_warning {
 6992:   color: darkorange;
 6993: }
 6994: 
 6995: .LC_diff_removed {
 6996:   color: red;
 6997: }
 6998: 
 6999: .LC_info,
 7000: .LC_success,
 7001: .LC_diff_added {
 7002:   color: green;
 7003: }
 7004: 
 7005: div.LC_confirm_box {
 7006:   background-color: #FAFAFA;
 7007:   border: 1px solid $lg_border_color;
 7008:   margin-right: 0;
 7009:   padding: 5px;
 7010: }
 7011: 
 7012: div.LC_confirm_box .LC_error img,
 7013: div.LC_confirm_box .LC_success img {
 7014:   vertical-align: middle;
 7015: }
 7016: 
 7017: .LC_maxwidth {
 7018:   max-width: 100%;
 7019:   height: auto;
 7020: }
 7021: 
 7022: .LC_textsize_mobile {
 7023:   \@media only screen and (max-device-width: 480px) {
 7024:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
 7025:   }
 7026: }
 7027: 
 7028: .LC_icon {
 7029:   border: none;
 7030:   vertical-align: middle;
 7031: }
 7032: 
 7033: .LC_docs_spacer {
 7034:   width: 25px;
 7035:   height: 1px;
 7036:   border: none;
 7037: }
 7038: 
 7039: .LC_internal_info {
 7040:   color: #999999;
 7041: }
 7042: 
 7043: .LC_discussion {
 7044:   background: $data_table_dark;
 7045:   border: 1px solid black;
 7046:   margin: 2px;
 7047: }
 7048: 
 7049: .LC_disc_action_left {
 7050:   background: $sidebg;
 7051:   text-align: left;
 7052:   padding: 4px;
 7053:   margin: 2px;
 7054: }
 7055: 
 7056: .LC_disc_action_right {
 7057:   background: $sidebg;
 7058:   text-align: right;
 7059:   padding: 4px;
 7060:   margin: 2px;
 7061: }
 7062: 
 7063: .LC_disc_new_item {
 7064:   background: white;
 7065:   border: 2px solid red;
 7066:   margin: 4px;
 7067:   padding: 4px;
 7068: }
 7069: 
 7070: .LC_disc_old_item {
 7071:   background: white;
 7072:   margin: 4px;
 7073:   padding: 4px;
 7074: }
 7075: 
 7076: table.LC_pastsubmission {
 7077:   border: 1px solid black;
 7078:   margin: 2px;
 7079: }
 7080: 
 7081: table#LC_menubuttons {
 7082:   width: 100%;
 7083:   background: $pgbg;
 7084:   border: 2px;
 7085:   border-collapse: separate;
 7086:   padding: 0;
 7087: }
 7088: 
 7089: table#LC_title_bar a {
 7090:   color: $fontmenu;
 7091: }
 7092: 
 7093: table#LC_title_bar {
 7094:   clear: both;
 7095:   display: none;
 7096: }
 7097: 
 7098: table#LC_title_bar,
 7099: table.LC_breadcrumbs, /* obsolete? */
 7100: table#LC_title_bar.LC_with_remote {
 7101:   width: 100%;
 7102:   border-color: $pgbg;
 7103:   border-style: solid;
 7104:   border-width: $border;
 7105:   background: $pgbg;
 7106:   color: $fontmenu;
 7107:   border-collapse: collapse;
 7108:   padding: 0;
 7109:   margin: 0;
 7110: }
 7111: 
 7112: ul.LC_breadcrumb_tools_outerlist {
 7113:     margin: 0;
 7114:     padding: 0;
 7115:     position: relative;
 7116:     list-style: none;
 7117: }
 7118: ul.LC_breadcrumb_tools_outerlist li {
 7119:     display: inline;
 7120: }
 7121: 
 7122: .LC_breadcrumb_tools_navigation {
 7123:     padding: 0;
 7124:     margin: 0;
 7125:     float: left;
 7126: }
 7127: .LC_breadcrumb_tools_tools {
 7128:     padding: 0;
 7129:     margin: 0;
 7130:     float: right;
 7131: }
 7132: 
 7133: .LC_placement_prog {
 7134:     padding-right: 20px;
 7135:     font-weight: bold;
 7136:     font-size: 90%;
 7137: }
 7138: 
 7139: table#LC_title_bar td {
 7140:   background: $tabbg;
 7141: }
 7142: 
 7143: table#LC_menubuttons img {
 7144:   border: none;
 7145: }
 7146: 
 7147: .LC_breadcrumbs_component {
 7148:   float: right;
 7149:   margin: 0 1em;
 7150: }
 7151: .LC_breadcrumbs_component img {
 7152:   vertical-align: middle;
 7153: }
 7154: 
 7155: .LC_breadcrumbs_hoverable {
 7156:   background: $sidebg;
 7157: }
 7158: 
 7159: td.LC_table_cell_checkbox {
 7160:   text-align: center;
 7161: }
 7162: 
 7163: .LC_fontsize_small {
 7164:   font-size: 70%;
 7165: }
 7166: 
 7167: #LC_breadcrumbs {
 7168:   clear:both;
 7169:   background: $sidebg;
 7170:   border-bottom: 1px solid $lg_border_color;
 7171:   line-height: 2.5em;
 7172:   overflow: hidden;
 7173:   margin: 0;
 7174:   padding: 0;
 7175:   text-align: left;
 7176: }
 7177: 
 7178: .LC_head_subbox, .LC_actionbox {
 7179:   clear:both;
 7180:   background: #F8F8F8; /* $sidebg; */
 7181:   border: 1px solid $sidebg;
 7182:   margin: 0 0 10px 0;
 7183:   padding: 3px;
 7184:   text-align: left;
 7185: }
 7186: 
 7187: .LC_fontsize_medium {
 7188:   font-size: 85%;
 7189: }
 7190: 
 7191: .LC_fontsize_large {
 7192:   font-size: 120%;
 7193: }
 7194: 
 7195: .LC_menubuttons_inline_text {
 7196:   color: $font;
 7197:   font-size: 90%;
 7198:   padding-left:3px;
 7199: }
 7200: 
 7201: .LC_menubuttons_inline_text img{
 7202:   vertical-align: middle;
 7203: }
 7204: 
 7205: li.LC_menubuttons_inline_text img {
 7206:   cursor:pointer;
 7207:   text-decoration: none;
 7208: }
 7209: 
 7210: .LC_menubuttons_link {
 7211:   text-decoration: none;
 7212: }
 7213: 
 7214: .LC_menubuttons_category {
 7215:   color: $font;
 7216:   background: $pgbg;
 7217:   font-size: larger;
 7218:   font-weight: bold;
 7219: }
 7220: 
 7221: td.LC_menubuttons_text {
 7222:   color: $font;
 7223: }
 7224: 
 7225: .LC_current_location {
 7226:   background: $tabbg;
 7227: }
 7228: 
 7229: td.LC_zero_height {
 7230:   line-height: 0; 
 7231:   cellpadding: 0;
 7232: }
 7233: 
 7234: table.LC_data_table {
 7235:   border: 1px solid #000000;
 7236:   border-collapse: separate;
 7237:   border-spacing: 1px;
 7238:   background: $pgbg;
 7239: }
 7240: 
 7241: .LC_data_table_dense {
 7242:   font-size: small;
 7243: }
 7244: 
 7245: table.LC_nested_outer {
 7246:   border: 1px solid #000000;
 7247:   border-collapse: collapse;
 7248:   border-spacing: 0;
 7249:   width: 100%;
 7250: }
 7251: 
 7252: table.LC_innerpickbox,
 7253: table.LC_nested {
 7254:   border: none;
 7255:   border-collapse: collapse;
 7256:   border-spacing: 0;
 7257:   width: 100%;
 7258: }
 7259: 
 7260: table.LC_data_table tr th,
 7261: table.LC_calendar tr th,
 7262: table.LC_prior_tries tr th,
 7263: table.LC_innerpickbox tr th {
 7264:   font-weight: bold;
 7265:   background-color: $data_table_head;
 7266:   color:$fontmenu;
 7267:   font-size:90%;
 7268: }
 7269: 
 7270: table.LC_innerpickbox tr th,
 7271: table.LC_innerpickbox tr td {
 7272:   vertical-align: top;
 7273: }
 7274: 
 7275: table.LC_data_table tr.LC_info_row > td {
 7276:   background-color: #CCCCCC;
 7277:   font-weight: bold;
 7278:   text-align: left;
 7279: }
 7280: 
 7281: table.LC_data_table tr.LC_odd_row > td {
 7282:   background-color: $data_table_light;
 7283:   padding: 2px;
 7284:   vertical-align: top;
 7285: }
 7286: 
 7287: table.LC_pick_box tr > td.LC_odd_row {
 7288:   background-color: $data_table_light;
 7289:   vertical-align: top;
 7290: }
 7291: 
 7292: table.LC_data_table tr.LC_even_row > td {
 7293:   background-color: $data_table_dark;
 7294:   padding: 2px;
 7295:   vertical-align: top;
 7296: }
 7297: 
 7298: table.LC_pick_box tr > td.LC_even_row {
 7299:   background-color: $data_table_dark;
 7300:   vertical-align: top;
 7301: }
 7302: 
 7303: table.LC_data_table tr.LC_data_table_highlight td {
 7304:   background-color: $data_table_darker;
 7305: }
 7306: 
 7307: table.LC_data_table tr td.LC_leftcol_header {
 7308:   background-color: $data_table_head;
 7309:   font-weight: bold;
 7310: }
 7311: 
 7312: table.LC_data_table tr.LC_empty_row td,
 7313: table.LC_nested tr.LC_empty_row td {
 7314:   font-weight: bold;
 7315:   font-style: italic;
 7316:   text-align: center;
 7317:   padding: 8px;
 7318: }
 7319: 
 7320: table.LC_data_table tr.LC_empty_row td,
 7321: table.LC_data_table tr.LC_footer_row td {
 7322:   background-color: $sidebg;
 7323: }
 7324: 
 7325: table.LC_nested tr.LC_empty_row td {
 7326:   background-color: #FFFFFF;
 7327: }
 7328: 
 7329: table.LC_caption {
 7330: }
 7331: 
 7332: table.LC_nested tr.LC_empty_row td {
 7333:   padding: 4ex
 7334: }
 7335: 
 7336: table.LC_nested_outer tr th {
 7337:   font-weight: bold;
 7338:   color:$fontmenu;
 7339:   background-color: $data_table_head;
 7340:   font-size: small;
 7341:   border-bottom: 1px solid #000000;
 7342: }
 7343: 
 7344: table.LC_nested_outer tr td.LC_subheader {
 7345:   background-color: $data_table_head;
 7346:   font-weight: bold;
 7347:   font-size: small;
 7348:   border-bottom: 1px solid #000000;
 7349:   text-align: right;
 7350: }
 7351: 
 7352: table.LC_nested tr.LC_info_row td {
 7353:   background-color: #CCCCCC;
 7354:   font-weight: bold;
 7355:   font-size: small;
 7356:   text-align: center;
 7357: }
 7358: 
 7359: table.LC_nested tr.LC_info_row td.LC_left_item,
 7360: table.LC_nested_outer tr th.LC_left_item {
 7361:   text-align: left;
 7362: }
 7363: 
 7364: table.LC_nested td {
 7365:   background-color: #FFFFFF;
 7366:   font-size: small;
 7367: }
 7368: 
 7369: table.LC_nested_outer tr th.LC_right_item,
 7370: table.LC_nested tr.LC_info_row td.LC_right_item,
 7371: table.LC_nested tr.LC_odd_row td.LC_right_item,
 7372: table.LC_nested tr td.LC_right_item {
 7373:   text-align: right;
 7374: }
 7375: 
 7376: table.LC_nested tr.LC_odd_row td {
 7377:   background-color: #EEEEEE;
 7378: }
 7379: 
 7380: table.LC_createuser {
 7381: }
 7382: 
 7383: table.LC_createuser tr.LC_section_row td {
 7384:   font-size: small;
 7385: }
 7386: 
 7387: table.LC_createuser tr.LC_info_row td  {
 7388:   background-color: #CCCCCC;
 7389:   font-weight: bold;
 7390:   text-align: center;
 7391: }
 7392: 
 7393: table.LC_calendar {
 7394:   border: 1px solid #000000;
 7395:   border-collapse: collapse;
 7396:   width: 98%;
 7397: }
 7398: 
 7399: table.LC_calendar_pickdate {
 7400:   font-size: xx-small;
 7401: }
 7402: 
 7403: table.LC_calendar tr td {
 7404:   border: 1px solid #000000;
 7405:   vertical-align: top;
 7406:   width: 14%;
 7407: }
 7408: 
 7409: table.LC_calendar tr td.LC_calendar_day_empty {
 7410:   background-color: $data_table_dark;
 7411: }
 7412: 
 7413: table.LC_calendar tr td.LC_calendar_day_current {
 7414:   background-color: $data_table_highlight;
 7415: }
 7416: 
 7417: table.LC_data_table tr td.LC_mail_new {
 7418:   background-color: $mail_new;
 7419: }
 7420: 
 7421: table.LC_data_table tr.LC_mail_new:hover {
 7422:   background-color: $mail_new_hover;
 7423: }
 7424: 
 7425: table.LC_data_table tr td.LC_mail_read {
 7426:   background-color: $mail_read;
 7427: }
 7428: 
 7429: /*
 7430: table.LC_data_table tr.LC_mail_read:hover {
 7431:   background-color: $mail_read_hover;
 7432: }
 7433: */
 7434: 
 7435: table.LC_data_table tr td.LC_mail_replied {
 7436:   background-color: $mail_replied;
 7437: }
 7438: 
 7439: /*
 7440: table.LC_data_table tr.LC_mail_replied:hover {
 7441:   background-color: $mail_replied_hover;
 7442: }
 7443: */
 7444: 
 7445: table.LC_data_table tr td.LC_mail_other {
 7446:   background-color: $mail_other;
 7447: }
 7448: 
 7449: /*
 7450: table.LC_data_table tr.LC_mail_other:hover {
 7451:   background-color: $mail_other_hover;
 7452: }
 7453: */
 7454: 
 7455: table.LC_data_table tr > td.LC_browser_file,
 7456: table.LC_data_table tr > td.LC_browser_file_published {
 7457:   background: #AAEE77;
 7458: }
 7459: 
 7460: table.LC_data_table tr > td.LC_browser_file_locked,
 7461: table.LC_data_table tr > td.LC_browser_file_unpublished {
 7462:   background: #FFAA99;
 7463: }
 7464: 
 7465: table.LC_data_table tr > td.LC_browser_file_obsolete {
 7466:   background: #888888;
 7467: }
 7468: 
 7469: table.LC_data_table tr > td.LC_browser_file_modified,
 7470: table.LC_data_table tr > td.LC_browser_file_metamodified {
 7471:   background: #F8F866;
 7472: }
 7473: 
 7474: table.LC_data_table tr.LC_browser_folder > td {
 7475:   background: #E0E8FF;
 7476: }
 7477: 
 7478: table.LC_data_table tr > td.LC_roles_is {
 7479:   /* background: #77FF77; */
 7480: }
 7481: 
 7482: table.LC_data_table tr > td.LC_roles_future {
 7483:   border-right: 8px solid #FFFF77;
 7484: }
 7485: 
 7486: table.LC_data_table tr > td.LC_roles_will {
 7487:   border-right: 8px solid #FFAA77;
 7488: }
 7489: 
 7490: table.LC_data_table tr > td.LC_roles_expired {
 7491:   border-right: 8px solid #FF7777;
 7492: }
 7493: 
 7494: table.LC_data_table tr > td.LC_roles_will_not {
 7495:   border-right: 8px solid #AAFF77;
 7496: }
 7497: 
 7498: table.LC_data_table tr > td.LC_roles_selected {
 7499:   border-right: 8px solid #11CC55;
 7500: }
 7501: 
 7502: span.LC_current_location {
 7503:   font-size:larger;
 7504:   background: $pgbg;
 7505: }
 7506: 
 7507: span.LC_current_nav_location {
 7508:   font-weight:bold;
 7509:   background: $sidebg;
 7510: }
 7511: 
 7512: span.LC_parm_menu_item {
 7513:   font-size: larger;
 7514: }
 7515: 
 7516: span.LC_parm_scope_all {
 7517:   color: red;
 7518: }
 7519: 
 7520: span.LC_parm_scope_folder {
 7521:   color: green;
 7522: }
 7523: 
 7524: span.LC_parm_scope_resource {
 7525:   color: orange;
 7526: }
 7527: 
 7528: span.LC_parm_part {
 7529:   color: blue;
 7530: }
 7531: 
 7532: span.LC_parm_folder,
 7533: span.LC_parm_symb {
 7534:   font-size: x-small;
 7535:   font-family: $mono;
 7536:   color: #AAAAAA;
 7537: }
 7538: 
 7539: ul.LC_parm_parmlist li {
 7540:   display: inline-block;
 7541:   padding: 0.3em 0.8em;
 7542:   vertical-align: top;
 7543:   width: 150px;
 7544:   border-top:1px solid $lg_border_color;
 7545: }
 7546: 
 7547: td.LC_parm_overview_level_menu,
 7548: td.LC_parm_overview_map_menu,
 7549: td.LC_parm_overview_parm_selectors,
 7550: td.LC_parm_overview_restrictions  {
 7551:   border: 1px solid black;
 7552:   border-collapse: collapse;
 7553: }
 7554: 
 7555: span.LC_parm_recursive,
 7556: td.LC_parm_recursive {
 7557:   font-weight: bold;
 7558:   font-size: smaller;
 7559: }
 7560: 
 7561: table.LC_parm_overview_restrictions td {
 7562:   border-width: 1px 4px 1px 4px;
 7563:   border-style: solid;
 7564:   border-color: $pgbg;
 7565:   text-align: center;
 7566: }
 7567: 
 7568: table.LC_parm_overview_restrictions th {
 7569:   background: $tabbg;
 7570:   border-width: 1px 4px 1px 4px;
 7571:   border-style: solid;
 7572:   border-color: $pgbg;
 7573: }
 7574: 
 7575: table#LC_helpmenu {
 7576:   border: none;
 7577:   height: 55px;
 7578:   border-spacing: 0;
 7579: }
 7580: 
 7581: table#LC_helpmenu fieldset legend {
 7582:   font-size: larger;
 7583: }
 7584: 
 7585: table#LC_helpmenu_links {
 7586:   width: 100%;
 7587:   border: 1px solid black;
 7588:   background: $pgbg;
 7589:   padding: 0;
 7590:   border-spacing: 1px;
 7591: }
 7592: 
 7593: table#LC_helpmenu_links tr td {
 7594:   padding: 1px;
 7595:   background: $tabbg;
 7596:   text-align: center;
 7597:   font-weight: bold;
 7598: }
 7599: 
 7600: table#LC_helpmenu_links a:link,
 7601: table#LC_helpmenu_links a:visited,
 7602: table#LC_helpmenu_links a:active {
 7603:   text-decoration: none;
 7604:   color: $font;
 7605: }
 7606: 
 7607: table#LC_helpmenu_links a:hover {
 7608:   text-decoration: underline;
 7609:   color: $vlink;
 7610: }
 7611: 
 7612: .LC_chrt_popup_exists {
 7613:   border: 1px solid #339933;
 7614:   margin: -1px;
 7615: }
 7616: 
 7617: .LC_chrt_popup_up {
 7618:   border: 1px solid yellow;
 7619:   margin: -1px;
 7620: }
 7621: 
 7622: .LC_chrt_popup {
 7623:   border: 1px solid #8888FF;
 7624:   background: #CCCCFF;
 7625: }
 7626: 
 7627: table.LC_pick_box {
 7628:   border-collapse: separate;
 7629:   background: white;
 7630:   border: 1px solid black;
 7631:   border-spacing: 1px;
 7632: }
 7633: 
 7634: table.LC_pick_box td.LC_pick_box_title {
 7635:   background: $sidebg;
 7636:   font-weight: bold;
 7637:   text-align: left;
 7638:   vertical-align: top;
 7639:   width: 184px;
 7640:   padding: 8px;
 7641: }
 7642: 
 7643: table.LC_pick_box td.LC_pick_box_value {
 7644:   text-align: left;
 7645:   padding: 8px;
 7646: }
 7647: 
 7648: table.LC_pick_box td.LC_pick_box_select {
 7649:   text-align: left;
 7650:   padding: 8px;
 7651: }
 7652: 
 7653: table.LC_pick_box td.LC_pick_box_separator {
 7654:   padding: 0;
 7655:   height: 1px;
 7656:   background: black;
 7657: }
 7658: 
 7659: table.LC_pick_box td.LC_pick_box_submit {
 7660:   text-align: right;
 7661: }
 7662: 
 7663: table.LC_pick_box td.LC_evenrow_value {
 7664:   text-align: left;
 7665:   padding: 8px;
 7666:   background-color: $data_table_light;
 7667: }
 7668: 
 7669: table.LC_pick_box td.LC_oddrow_value {
 7670:   text-align: left;
 7671:   padding: 8px;
 7672:   background-color: $data_table_light;
 7673: }
 7674: 
 7675: span.LC_helpform_receipt_cat {
 7676:   font-weight: bold;
 7677: }
 7678: 
 7679: table.LC_group_priv_box {
 7680:   background: white;
 7681:   border: 1px solid black;
 7682:   border-spacing: 1px;
 7683: }
 7684: 
 7685: table.LC_group_priv_box td.LC_pick_box_title {
 7686:   background: $tabbg;
 7687:   font-weight: bold;
 7688:   text-align: right;
 7689:   width: 184px;
 7690: }
 7691: 
 7692: table.LC_group_priv_box td.LC_groups_fixed {
 7693:   background: $data_table_light;
 7694:   text-align: center;
 7695: }
 7696: 
 7697: table.LC_group_priv_box td.LC_groups_optional {
 7698:   background: $data_table_dark;
 7699:   text-align: center;
 7700: }
 7701: 
 7702: table.LC_group_priv_box td.LC_groups_functionality {
 7703:   background: $data_table_darker;
 7704:   text-align: center;
 7705:   font-weight: bold;
 7706: }
 7707: 
 7708: table.LC_group_priv td {
 7709:   text-align: left;
 7710:   padding: 0;
 7711: }
 7712: 
 7713: .LC_navbuttons {
 7714:   margin: 2ex 0ex 2ex 0ex;
 7715: }
 7716: 
 7717: .LC_topic_bar {
 7718:   font-weight: bold;
 7719:   background: $tabbg;
 7720:   margin: 1em 0em 1em 2em;
 7721:   padding: 3px;
 7722:   font-size: 1.2em;
 7723: }
 7724: 
 7725: .LC_topic_bar span {
 7726:   left: 0.5em;
 7727:   position: absolute;
 7728:   vertical-align: middle;
 7729:   font-size: 1.2em;
 7730: }
 7731: 
 7732: table.LC_course_group_status {
 7733:   margin: 20px;
 7734: }
 7735: 
 7736: table.LC_status_selector td {
 7737:   vertical-align: top;
 7738:   text-align: center;
 7739:   padding: 4px;
 7740: }
 7741: 
 7742: div.LC_feedback_link {
 7743:   clear: both;
 7744:   background: $sidebg;
 7745:   width: 100%;
 7746:   padding-bottom: 10px;
 7747:   border: 1px $tabbg solid;
 7748:   height: 22px;
 7749:   line-height: 22px;
 7750:   padding-top: 5px;
 7751: }
 7752: 
 7753: div.LC_feedback_link img {
 7754:   height: 22px;
 7755:   vertical-align:middle;
 7756: }
 7757: 
 7758: div.LC_feedback_link a {
 7759:   text-decoration: none;
 7760: }
 7761: 
 7762: div.LC_comblock {
 7763:   display:inline;
 7764:   color:$font;
 7765:   font-size:90%;
 7766: }
 7767: 
 7768: div.LC_feedback_link div.LC_comblock {
 7769:   padding-left:5px;
 7770: }
 7771: 
 7772: div.LC_feedback_link div.LC_comblock a {
 7773:   color:$font;
 7774: }
 7775: 
 7776: span.LC_feedback_link {
 7777:   /* background: $feedback_link_bg; */
 7778:   font-size: larger;
 7779: }
 7780: 
 7781: span.LC_message_link {
 7782:   /* background: $feedback_link_bg; */
 7783:   font-size: larger;
 7784:   position: absolute;
 7785:   right: 1em;
 7786: }
 7787: 
 7788: table.LC_prior_tries {
 7789:   border: 1px solid #000000;
 7790:   border-collapse: separate;
 7791:   border-spacing: 1px;
 7792: }
 7793: 
 7794: table.LC_prior_tries td {
 7795:   padding: 2px;
 7796: }
 7797: 
 7798: .LC_answer_correct {
 7799:   background: lightgreen;
 7800:   color: darkgreen;
 7801:   padding: 6px;
 7802: }
 7803: 
 7804: .LC_answer_charged_try {
 7805:   background: #FFAAAA;
 7806:   color: darkred;
 7807:   padding: 6px;
 7808: }
 7809: 
 7810: .LC_answer_not_charged_try,
 7811: .LC_answer_no_grade,
 7812: .LC_answer_late {
 7813:   background: lightyellow;
 7814:   color: black;
 7815:   padding: 6px;
 7816: }
 7817: 
 7818: .LC_answer_previous {
 7819:   background: lightblue;
 7820:   color: darkblue;
 7821:   padding: 6px;
 7822: }
 7823: 
 7824: .LC_answer_no_message {
 7825:   background: #FFFFFF;
 7826:   color: black;
 7827:   padding: 6px;
 7828: }
 7829: 
 7830: .LC_answer_unknown,
 7831: .LC_answer_warning {
 7832:   background: orange;
 7833:   color: black;
 7834:   padding: 6px;
 7835: }
 7836: 
 7837: span.LC_prior_numerical,
 7838: span.LC_prior_string,
 7839: span.LC_prior_custom,
 7840: span.LC_prior_reaction,
 7841: span.LC_prior_math {
 7842:   font-family: $mono;
 7843:   white-space: pre;
 7844: }
 7845: 
 7846: span.LC_prior_string {
 7847:   font-family: $mono;
 7848:   white-space: pre;
 7849: }
 7850: 
 7851: table.LC_prior_option {
 7852:   width: 100%;
 7853:   border-collapse: collapse;
 7854: }
 7855: 
 7856: table.LC_prior_rank,
 7857: table.LC_prior_match {
 7858:   border-collapse: collapse;
 7859: }
 7860: 
 7861: table.LC_prior_option tr td,
 7862: table.LC_prior_rank tr td,
 7863: table.LC_prior_match tr td {
 7864:   border: 1px solid #000000;
 7865: }
 7866: 
 7867: .LC_nobreak {
 7868:   white-space: nowrap;
 7869: }
 7870: 
 7871: span.LC_cusr_emph {
 7872:   font-style: italic;
 7873: }
 7874: 
 7875: span.LC_cusr_subheading {
 7876:   font-weight: normal;
 7877:   font-size: 85%;
 7878: }
 7879: 
 7880: div.LC_docs_entry_move {
 7881:   border: 1px solid #BBBBBB;
 7882:   background: #DDDDDD;
 7883:   width: 22px;
 7884:   padding: 1px;
 7885:   margin: 0;
 7886: }
 7887: 
 7888: table.LC_data_table tr > td.LC_docs_entry_commands,
 7889: table.LC_data_table tr > td.LC_docs_entry_parameter {
 7890:   font-size: x-small;
 7891: }
 7892: 
 7893: .LC_docs_entry_parameter {
 7894:   white-space: nowrap;
 7895: }
 7896: 
 7897: .LC_docs_copy {
 7898:   color: #000099;
 7899: }
 7900: 
 7901: .LC_docs_cut {
 7902:   color: #550044;
 7903: }
 7904: 
 7905: .LC_docs_rename {
 7906:   color: #009900;
 7907: }
 7908: 
 7909: .LC_docs_remove {
 7910:   color: #990000;
 7911: }
 7912: 
 7913: .LC_docs_alias {
 7914:   color: #440055;  
 7915: }
 7916: 
 7917: .LC_domprefs_email,
 7918: .LC_docs_alias_name,
 7919: .LC_docs_reinit_warn,
 7920: .LC_docs_ext_edit {
 7921:   font-size: x-small;
 7922: }
 7923: 
 7924: table.LC_docs_adddocs td,
 7925: table.LC_docs_adddocs th {
 7926:   border: 1px solid #BBBBBB;
 7927:   padding: 4px;
 7928:   background: #DDDDDD;
 7929: }
 7930: 
 7931: table.LC_sty_begin {
 7932:   background: #BBFFBB;
 7933: }
 7934: 
 7935: table.LC_sty_end {
 7936:   background: #FFBBBB;
 7937: }
 7938: 
 7939: table.LC_double_column {
 7940:   border-width: 0;
 7941:   border-collapse: collapse;
 7942:   width: 100%;
 7943:   padding: 2px;
 7944: }
 7945: 
 7946: table.LC_double_column tr td.LC_left_col {
 7947:   top: 2px;
 7948:   left: 2px;
 7949:   width: 47%;
 7950:   vertical-align: top;
 7951: }
 7952: 
 7953: table.LC_double_column tr td.LC_right_col {
 7954:   top: 2px;
 7955:   right: 2px;
 7956:   width: 47%;
 7957:   vertical-align: top;
 7958: }
 7959: 
 7960: div.LC_left_float {
 7961:   float: left;
 7962:   padding-right: 5%;
 7963:   padding-bottom: 4px;
 7964: }
 7965: 
 7966: div.LC_clear_float_header {
 7967:   padding-bottom: 2px;
 7968: }
 7969: 
 7970: div.LC_clear_float_footer {
 7971:   padding-top: 10px;
 7972:   clear: both;
 7973: }
 7974: 
 7975: div.LC_grade_show_user {
 7976: /*  border-left: 5px solid $sidebg; */
 7977:   border-top: 5px solid #000000;
 7978:   margin: 50px 0 0 0;
 7979:   padding: 15px 0 5px 10px;
 7980: }
 7981: 
 7982: div.LC_grade_show_user_odd_row {
 7983: /*  border-left: 5px solid #000000; */
 7984: }
 7985: 
 7986: div.LC_grade_show_user div.LC_Box {
 7987:   margin-right: 50px;
 7988: }
 7989: 
 7990: div.LC_grade_submissions,
 7991: div.LC_grade_message_center,
 7992: div.LC_grade_info_links {
 7993:   margin: 5px;
 7994:   width: 99%;
 7995:   background: #FFFFFF;
 7996: }
 7997: 
 7998: div.LC_grade_submissions_header,
 7999: div.LC_grade_message_center_header {
 8000:   font-weight: bold;
 8001:   font-size: large;
 8002: }
 8003: 
 8004: div.LC_grade_submissions_body,
 8005: div.LC_grade_message_center_body {
 8006:   border: 1px solid black;
 8007:   width: 99%;
 8008:   background: #FFFFFF;
 8009: }
 8010: 
 8011: table.LC_scantron_action {
 8012:   width: 100%;
 8013: }
 8014: 
 8015: table.LC_scantron_action tr th {
 8016:   font-weight:bold;
 8017:   font-style:normal;
 8018: }
 8019: 
 8020: .LC_edit_problem_header,
 8021: div.LC_edit_problem_footer {
 8022:   font-weight: normal;
 8023:   font-size:  medium;
 8024:   margin: 2px;
 8025:   background-color: $sidebg;
 8026: }
 8027: 
 8028: div.LC_edit_problem_header,
 8029: div.LC_edit_problem_header div,
 8030: div.LC_edit_problem_footer,
 8031: div.LC_edit_problem_footer div,
 8032: div.LC_edit_problem_editxml_header,
 8033: div.LC_edit_problem_editxml_header div {
 8034:   z-index: 100;
 8035: }
 8036: 
 8037: div.LC_edit_problem_header_title {
 8038:   font-weight: bold;
 8039:   font-size: larger;
 8040:   background: $tabbg;
 8041:   padding: 3px;
 8042:   margin: 0 0 5px 0;
 8043: }
 8044: 
 8045: table.LC_edit_problem_header_title {
 8046:   width: 100%;
 8047:   background: $tabbg;
 8048: }
 8049: 
 8050: div.LC_edit_actionbar {
 8051:     background-color: $sidebg;
 8052:     margin: 0;
 8053:     padding: 0;
 8054:     line-height: 200%;
 8055: }
 8056: 
 8057: div.LC_edit_actionbar div{
 8058:     padding: 0;
 8059:     margin: 0;
 8060:     display: inline-block;
 8061: }
 8062: 
 8063: .LC_edit_opt {
 8064:   padding-left: 1em;
 8065:   white-space: nowrap;
 8066: }
 8067: 
 8068: .LC_edit_problem_latexhelper{
 8069:     text-align: right;
 8070: }
 8071: 
 8072: #LC_edit_problem_colorful div{
 8073:     margin-left: 40px;
 8074: }
 8075: 
 8076: #LC_edit_problem_codemirror div{
 8077:     margin-left: 0px;
 8078: }
 8079: 
 8080: img.stift {
 8081:   border-width: 0;
 8082:   vertical-align: middle;
 8083: }
 8084: 
 8085: table td.LC_mainmenu_col_fieldset {
 8086:   vertical-align: top;
 8087: }
 8088: 
 8089: div.LC_createcourse {
 8090:   margin: 10px 10px 10px 10px;
 8091: }
 8092: 
 8093: .LC_dccid {
 8094:   float: right;
 8095:   margin: 0.2em 0 0 0;
 8096:   padding: 0;
 8097:   font-size: 90%;
 8098:   display:none;
 8099: }
 8100: 
 8101: ol.LC_primary_menu a:hover,
 8102: ol#LC_MenuBreadcrumbs a:hover,
 8103: ol#LC_PathBreadcrumbs a:hover,
 8104: ul#LC_secondary_menu a:hover,
 8105: .LC_FormSectionClearButton input:hover
 8106: ul.LC_TabContent   li:hover a {
 8107:   color:$button_hover;
 8108:   text-decoration:none;
 8109: }
 8110: 
 8111: h1 {
 8112:   padding: 0;
 8113:   line-height:130%;
 8114: }
 8115: 
 8116: h2,
 8117: h3,
 8118: h4,
 8119: h5,
 8120: h6 {
 8121:   margin: 5px 0 5px 0;
 8122:   padding: 0;
 8123:   line-height:130%;
 8124: }
 8125: 
 8126: .LC_hcell {
 8127:   padding:3px 15px 3px 15px;
 8128:   margin: 0;
 8129:   background-color:$tabbg;
 8130:   color:$fontmenu;
 8131:   border-bottom:solid 1px $lg_border_color;
 8132: }
 8133: 
 8134: .LC_Box > .LC_hcell {
 8135:   margin: 0 -10px 10px -10px;
 8136: }
 8137: 
 8138: .LC_noBorder {
 8139:   border: 0;
 8140: }
 8141: 
 8142: .LC_FormSectionClearButton input {
 8143:   background-color:transparent;
 8144:   border: none;
 8145:   cursor:pointer;
 8146:   text-decoration:underline;
 8147: }
 8148: 
 8149: .LC_help_open_topic {
 8150:   color: #FFFFFF;
 8151:   background-color: #EEEEFF;
 8152:   margin: 1px;
 8153:   padding: 4px;
 8154:   border: 1px solid #000033;
 8155:   white-space: nowrap;
 8156:   /* vertical-align: middle; */
 8157: }
 8158: 
 8159: dl,
 8160: ul,
 8161: div,
 8162: fieldset {
 8163:   margin: 10px 10px 10px 0;
 8164:   /* overflow: hidden; */
 8165: }
 8166: 
 8167: fieldset#LC_selectuser {
 8168:     margin: 0;
 8169:     padding: 0;
 8170: }
 8171: 
 8172: article.geogebraweb div {
 8173:     margin: 0;
 8174: }
 8175: 
 8176: fieldset > legend {
 8177:   font-weight: bold;
 8178:   padding: 0 5px 0 5px;
 8179: }
 8180: 
 8181: #LC_nav_bar {
 8182:   float: left;
 8183:   background-color: $pgbg_or_bgcolor;
 8184:   margin: 0 0 2px 0;
 8185: }
 8186: 
 8187: #LC_realm {
 8188:   margin: 0.2em 0 0 0;
 8189:   padding: 0;
 8190:   font-weight: bold;
 8191:   text-align: center;
 8192:   background-color: $pgbg_or_bgcolor;
 8193: }
 8194: 
 8195: #LC_nav_bar em {
 8196:   font-weight: bold;
 8197:   font-style: normal;
 8198: }
 8199: 
 8200: ol.LC_primary_menu {
 8201:   margin: 0;
 8202:   padding: 0;
 8203: }
 8204: 
 8205: ol#LC_PathBreadcrumbs {
 8206:   margin: 0;
 8207: }
 8208: 
 8209: ol.LC_primary_menu li {
 8210:   color: RGB(80, 80, 80);
 8211:   vertical-align: middle;
 8212:   text-align: left;
 8213:   list-style: none;
 8214:   position: relative;
 8215:   float: left;
 8216:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
 8217:   line-height: 1.5em;
 8218: }
 8219: 
 8220: ol.LC_primary_menu li a,
 8221: ol.LC_primary_menu li p {
 8222:   display: block;
 8223:   margin: 0;
 8224:   padding: 0 5px 0 10px;
 8225:   text-decoration: none;
 8226: }
 8227: 
 8228: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
 8229:   display: inline-block;
 8230:   width: 95%;
 8231:   text-align: left;
 8232: }
 8233: 
 8234: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
 8235:   display: inline-block;	
 8236:   width: 5%;
 8237:   float: right;
 8238:   text-align: right;
 8239:   font-size: 70%;
 8240: }
 8241: 
 8242: ol.LC_primary_menu ul {
 8243:   display: none;
 8244:   width: 15em;
 8245:   background-color: $data_table_light;
 8246:   position: absolute;
 8247:   top: 100%;
 8248: }
 8249: 
 8250: ol.LC_primary_menu ul ul {
 8251:   left: 100%;
 8252:   top: 0;
 8253: }
 8254: 
 8255: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
 8256:   display: block;
 8257:   position: absolute;
 8258:   margin: 0;
 8259:   padding: 0;
 8260:   z-index: 2;
 8261: }
 8262: 
 8263: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 8264: /* First Submenu -> size should be smaller than the menu title of the whole menu */
 8265:   font-size: 90%;
 8266:   vertical-align: top;
 8267:   float: none;
 8268:   border-left: 1px solid black;
 8269:   border-right: 1px solid black;
 8270: /* A dark bottom border to visualize different menu options; 
 8271: overwritten in the create_submenu routine for the last border-bottom of the menu */
 8272:   border-bottom: 1px solid $data_table_dark; 
 8273: }
 8274: 
 8275: ol.LC_primary_menu li li p:hover {
 8276:   color:$button_hover;
 8277:   text-decoration:none;
 8278:   background-color:$data_table_dark;
 8279: }
 8280: 
 8281: ol.LC_primary_menu li li a:hover {
 8282:    color:$button_hover;
 8283:    background-color:$data_table_dark;
 8284: }
 8285: 
 8286: /* Font-size equal to the size of the predecessors*/
 8287: ol.LC_primary_menu li:hover li li {
 8288:   font-size: 100%;
 8289: }
 8290: 
 8291: ol.LC_primary_menu li img {
 8292:   vertical-align: bottom;
 8293:   height: 1.1em;
 8294:   margin: 0.2em 0 0 0;
 8295: }
 8296: 
 8297: ol.LC_primary_menu a {
 8298:   color: RGB(80, 80, 80);
 8299:   text-decoration: none;
 8300: }
 8301: 
 8302: ol.LC_primary_menu a.LC_new_message {
 8303:   font-weight:bold;
 8304:   color: darkred;
 8305: }
 8306: 
 8307: ol.LC_docs_parameters {
 8308:   margin-left: 0;
 8309:   padding: 0;
 8310:   list-style: none;
 8311: }
 8312: 
 8313: ol.LC_docs_parameters li {
 8314:   margin: 0;
 8315:   padding-right: 20px;
 8316:   display: inline;
 8317: }
 8318: 
 8319: ol.LC_docs_parameters li:before {
 8320:   content: "\\002022 \\0020";
 8321: }
 8322: 
 8323: li.LC_docs_parameters_title {
 8324:   font-weight: bold;
 8325: }
 8326: 
 8327: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 8328:   content: "";
 8329: }
 8330: 
 8331: ul#LC_secondary_menu {
 8332:   clear: right;
 8333:   color: $fontmenu;
 8334:   background: $tabbg;
 8335:   list-style: none;
 8336:   padding: 0;
 8337:   margin: 0;
 8338:   width: 100%;
 8339:   text-align: left;
 8340:   float: left;
 8341: }
 8342: 
 8343: ul#LC_secondary_menu li {
 8344:   font-weight: bold;
 8345:   line-height: 1.8em;
 8346:   border-right: 1px solid black;
 8347:   float: left;
 8348: }
 8349: 
 8350: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 8351:   background-color: $data_table_light;
 8352: }
 8353: 
 8354: ul#LC_secondary_menu li a {
 8355:   padding: 0 0.8em;
 8356: }
 8357: 
 8358: ul#LC_secondary_menu li ul {
 8359:   display: none;
 8360: }
 8361: 
 8362: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 8363:   display: block;
 8364:   position: absolute;
 8365:   margin: 0;
 8366:   padding: 0;
 8367:   list-style:none;
 8368:   float: none;
 8369:   background-color: $data_table_light;
 8370:   z-index: 2;
 8371:   margin-left: -1px;
 8372: }
 8373: 
 8374: ul#LC_secondary_menu li ul li {
 8375:   font-size: 90%;
 8376:   vertical-align: top;
 8377:   border-left: 1px solid black;
 8378:   border-right: 1px solid black;
 8379:   background-color: $data_table_light;
 8380:   list-style:none;
 8381:   float: none;
 8382: }
 8383: 
 8384: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 8385:   background-color: $data_table_dark;
 8386: }
 8387: 
 8388: ul.LC_TabContent {
 8389:   display:block;
 8390:   background: $sidebg;
 8391:   border-bottom: solid 1px $lg_border_color;
 8392:   list-style:none;
 8393:   margin: -1px -10px 0 -10px;
 8394:   padding: 0;
 8395: }
 8396: 
 8397: ul.LC_TabContent li,
 8398: ul.LC_TabContentBigger li {
 8399:   float:left;
 8400: }
 8401: 
 8402: ul#LC_secondary_menu li a {
 8403:   color: $fontmenu;
 8404:   text-decoration: none;
 8405: }
 8406: 
 8407: ul.LC_TabContent {
 8408:   min-height:20px;
 8409: }
 8410: 
 8411: ul.LC_TabContent li {
 8412:   vertical-align:middle;
 8413:   padding: 0 16px 0 10px;
 8414:   background-color:$tabbg;
 8415:   border-bottom:solid 1px $lg_border_color;
 8416:   border-left: solid 1px $font;
 8417: }
 8418: 
 8419: ul.LC_TabContent .right {
 8420:   float:right;
 8421: }
 8422: 
 8423: ul.LC_TabContent li a,
 8424: ul.LC_TabContent li {
 8425:   color:rgb(47,47,47);
 8426:   text-decoration:none;
 8427:   font-size:95%;
 8428:   font-weight:bold;
 8429:   min-height:20px;
 8430: }
 8431: 
 8432: ul.LC_TabContent li a:hover,
 8433: ul.LC_TabContent li a:focus {
 8434:   color: $button_hover;
 8435:   background:none;
 8436:   outline:none;
 8437: }
 8438: 
 8439: ul.LC_TabContent li:hover {
 8440:   color: $button_hover;
 8441:   cursor:pointer;
 8442: }
 8443: 
 8444: ul.LC_TabContent li.active {
 8445:   color: $font;
 8446:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 8447:   border-bottom:solid 1px #FFFFFF;
 8448:   cursor: default;
 8449: }
 8450: 
 8451: ul.LC_TabContent li.active a {
 8452:   color:$font;
 8453:   background:#FFFFFF;
 8454:   outline: none;
 8455: }
 8456: 
 8457: ul.LC_TabContent li.goback {
 8458:   float: left;
 8459:   border-left: none;
 8460: }
 8461: 
 8462: #maincoursedoc {
 8463:   clear:both;
 8464: }
 8465: 
 8466: ul.LC_TabContentBigger {
 8467:   display:block;
 8468:   list-style:none;
 8469:   padding: 0;
 8470: }
 8471: 
 8472: ul.LC_TabContentBigger li {
 8473:   vertical-align:bottom;
 8474:   height: 30px;
 8475:   font-size:110%;
 8476:   font-weight:bold;
 8477:   color: #737373;
 8478: }
 8479: 
 8480: ul.LC_TabContentBigger li.active {
 8481:   position: relative;
 8482:   top: 1px;
 8483: }
 8484: 
 8485: ul.LC_TabContentBigger li a {
 8486:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 8487:   height: 30px;
 8488:   line-height: 30px;
 8489:   text-align: center;
 8490:   display: block;
 8491:   text-decoration: none;
 8492:   outline: none;  
 8493: }
 8494: 
 8495: ul.LC_TabContentBigger li.active a {
 8496:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 8497:   color:$font;
 8498: }
 8499: 
 8500: ul.LC_TabContentBigger li b {
 8501:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 8502:   display: block;
 8503:   float: left;
 8504:   padding: 0 30px;
 8505:   border-bottom: 1px solid $lg_border_color;
 8506: }
 8507: 
 8508: ul.LC_TabContentBigger li:hover b {
 8509:   color:$button_hover;
 8510: }
 8511: 
 8512: ul.LC_TabContentBigger li.active b {
 8513:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 8514:   color:$font;
 8515:   border: 0;
 8516: }
 8517: 
 8518: 
 8519: ul.LC_CourseBreadcrumbs {
 8520:   background: $sidebg;
 8521:   height: 2em;
 8522:   padding-left: 10px;
 8523:   margin: 0;
 8524:   list-style-position: inside;
 8525: }
 8526: 
 8527: ol#LC_MenuBreadcrumbs,
 8528: ol#LC_PathBreadcrumbs {
 8529:   padding-left: 10px;
 8530:   margin: 0;
 8531:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 8532: }
 8533: 
 8534: ol#LC_MenuBreadcrumbs li,
 8535: ol#LC_PathBreadcrumbs li,
 8536: ul.LC_CourseBreadcrumbs li {
 8537:   display: inline;
 8538:   white-space: normal;  
 8539: }
 8540: 
 8541: ol#LC_MenuBreadcrumbs li a,
 8542: ul.LC_CourseBreadcrumbs li a {
 8543:   text-decoration: none;
 8544:   font-size:90%;
 8545: }
 8546: 
 8547: ol#LC_MenuBreadcrumbs h1 {
 8548:   display: inline;
 8549:   font-size: 90%;
 8550:   line-height: 2.5em;
 8551:   margin: 0;
 8552:   padding: 0;
 8553: }
 8554: 
 8555: ol#LC_PathBreadcrumbs li a {
 8556:   text-decoration:none;
 8557:   font-size:100%;
 8558:   font-weight:bold;
 8559: }
 8560: 
 8561: .LC_Box {
 8562:   border: solid 1px $lg_border_color;
 8563:   padding: 0 10px 10px 10px;
 8564: }
 8565: 
 8566: .LC_DocsBox {
 8567:   border: solid 1px $lg_border_color;
 8568:   padding: 0 0 10px 10px;
 8569: }
 8570: 
 8571: .LC_AboutMe_Image {
 8572:   float:left;
 8573:   margin-right:10px;
 8574: }
 8575: 
 8576: .LC_Clear_AboutMe_Image {
 8577:   clear:left;
 8578: }
 8579: 
 8580: dl.LC_ListStyleClean dt {
 8581:   padding-right: 5px;
 8582:   display: table-header-group;
 8583: }
 8584: 
 8585: dl.LC_ListStyleClean dd {
 8586:   display: table-row;
 8587: }
 8588: 
 8589: .LC_ListStyleClean,
 8590: .LC_ListStyleSimple,
 8591: .LC_ListStyleNormal,
 8592: .LC_ListStyleSpecial {
 8593:   /* display:block; */
 8594:   list-style-position: inside;
 8595:   list-style-type: none;
 8596:   overflow: hidden;
 8597:   padding: 0;
 8598: }
 8599: 
 8600: .LC_ListStyleSimple li,
 8601: .LC_ListStyleSimple dd,
 8602: .LC_ListStyleNormal li,
 8603: .LC_ListStyleNormal dd,
 8604: .LC_ListStyleSpecial li,
 8605: .LC_ListStyleSpecial dd {
 8606:   margin: 0;
 8607:   padding: 5px 5px 5px 10px;
 8608:   clear: both;
 8609: }
 8610: 
 8611: .LC_ListStyleClean li,
 8612: .LC_ListStyleClean dd {
 8613:   padding-top: 0;
 8614:   padding-bottom: 0;
 8615: }
 8616: 
 8617: .LC_ListStyleSimple dd,
 8618: .LC_ListStyleSimple li {
 8619:   border-bottom: solid 1px $lg_border_color;
 8620: }
 8621: 
 8622: .LC_ListStyleSpecial li,
 8623: .LC_ListStyleSpecial dd {
 8624:   list-style-type: none;
 8625:   background-color: RGB(220, 220, 220);
 8626:   margin-bottom: 4px;
 8627: }
 8628: 
 8629: table.LC_SimpleTable {
 8630:   margin:5px;
 8631:   border:solid 1px $lg_border_color;
 8632: }
 8633: 
 8634: table.LC_SimpleTable tr {
 8635:   padding: 0;
 8636:   border:solid 1px $lg_border_color;
 8637: }
 8638: 
 8639: table.LC_SimpleTable thead {
 8640:   background:rgb(220,220,220);
 8641: }
 8642: 
 8643: div.LC_columnSection {
 8644:   display: block;
 8645:   clear: both;
 8646:   overflow: hidden;
 8647:   margin: 0;
 8648: }
 8649: 
 8650: div.LC_columnSection>* {
 8651:   float: left;
 8652:   margin: 10px 20px 10px 0;
 8653:   overflow:hidden;
 8654: }
 8655: 
 8656: table em {
 8657:   font-weight: bold;
 8658:   font-style: normal;
 8659: }
 8660: 
 8661: table.LC_tableBrowseRes,
 8662: table.LC_tableOfContent {
 8663:   border:none;
 8664:   border-spacing: 1px;
 8665:   padding: 3px;
 8666:   background-color: #FFFFFF;
 8667:   font-size: 90%;
 8668: }
 8669: 
 8670: table.LC_tableOfContent {
 8671:   border-collapse: collapse;
 8672: }
 8673: 
 8674: table.LC_tableBrowseRes a,
 8675: table.LC_tableOfContent a {
 8676:   background-color: transparent;
 8677:   text-decoration: none;
 8678: }
 8679: 
 8680: table.LC_tableOfContent img {
 8681:   border: none;
 8682:   height: 1.3em;
 8683:   vertical-align: text-bottom;
 8684:   margin-right: 0.3em;
 8685: }
 8686: 
 8687: a#LC_content_toolbar_firsthomework {
 8688:   background-image:url(/res/adm/pages/open-first-problem.gif);
 8689: }
 8690: 
 8691: a#LC_content_toolbar_everything {
 8692:   background-image:url(/res/adm/pages/show-all.gif);
 8693: }
 8694: 
 8695: a#LC_content_toolbar_uncompleted {
 8696:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 8697: }
 8698: 
 8699: #LC_content_toolbar_clearbubbles {
 8700:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 8701: }
 8702: 
 8703: a#LC_content_toolbar_changefolder {
 8704:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 8705: }
 8706: 
 8707: a#LC_content_toolbar_changefolder_toggled {
 8708:   background-image:url(/res/adm/pages/open-all-folders.gif);
 8709: }
 8710: 
 8711: a#LC_content_toolbar_edittoplevel {
 8712:   background-image:url(/res/adm/pages/edittoplevel.gif);
 8713: }
 8714: 
 8715: a#LC_content_toolbar_printout {
 8716:   background-image:url(/res/adm/pages/printout.gif);
 8717: }
 8718: 
 8719: ul#LC_toolbar li a:hover {
 8720:   background-position: bottom center;
 8721: }
 8722: 
 8723: ul#LC_toolbar {
 8724:   padding: 0;
 8725:   margin: 2px;
 8726:   list-style:none;
 8727:   position:relative;
 8728:   background-color:white;
 8729:   overflow: auto;
 8730: }
 8731: 
 8732: ul#LC_toolbar li {
 8733:   border:1px solid white;
 8734:   padding: 0;
 8735:   margin: 0;
 8736:   float: left;
 8737:   display:inline;
 8738:   vertical-align:middle;
 8739:   white-space: nowrap;
 8740: }
 8741: 
 8742: 
 8743: a.LC_toolbarItem {
 8744:   display:block;
 8745:   padding: 0;
 8746:   margin: 0;
 8747:   height: 32px;
 8748:   width: 32px;
 8749:   color:white;
 8750:   border: none;
 8751:   background-repeat:no-repeat;
 8752:   background-color:transparent;
 8753: }
 8754: 
 8755: ul.LC_funclist {
 8756:     margin: 0;
 8757:     padding: 0.5em 1em 0.5em 0;
 8758: }
 8759: 
 8760: ul.LC_funclist > li:first-child {
 8761:     font-weight:bold; 
 8762:     margin-left:0.8em;
 8763: }
 8764: 
 8765: ul.LC_funclist + ul.LC_funclist {
 8766:     /* 
 8767:        left border as a seperator if we have more than
 8768:        one list 
 8769:     */
 8770:     border-left: 1px solid $sidebg;
 8771:     /* 
 8772:        this hides the left border behind the border of the 
 8773:        outer box if element is wrapped to the next 'line' 
 8774:     */
 8775:     margin-left: -1px;
 8776: }
 8777: 
 8778: ul.LC_funclist li {
 8779:   display: inline;
 8780:   white-space: nowrap;
 8781:   margin: 0 0 0 25px;
 8782:   line-height: 150%;
 8783: }
 8784: 
 8785: .LC_hidden {
 8786:   display: none;
 8787: }
 8788: 
 8789: .LCmodal-overlay {
 8790: 		position:fixed;
 8791: 		top:0;
 8792: 		right:0;
 8793: 		bottom:0;
 8794: 		left:0;
 8795: 		height:100%;
 8796: 		width:100%;
 8797: 		margin:0;
 8798: 		padding:0;
 8799: 		background:#999;
 8800: 		opacity:.75;
 8801: 		filter: alpha(opacity=75);
 8802: 		-moz-opacity: 0.75;
 8803: 		z-index:101;
 8804: }
 8805: 
 8806: * html .LCmodal-overlay {   
 8807: 		position: absolute;
 8808: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 8809: }
 8810: 
 8811: .LCmodal-window {
 8812: 		position:fixed;
 8813: 		top:50%;
 8814: 		left:50%;
 8815: 		margin:0;
 8816: 		padding:0;
 8817: 		z-index:102;
 8818: 	}
 8819: 
 8820: * html .LCmodal-window {
 8821: 		position:absolute;
 8822: }
 8823: 
 8824: .LCclose-window {
 8825: 		position:absolute;
 8826: 		width:32px;
 8827: 		height:32px;
 8828: 		right:8px;
 8829: 		top:8px;
 8830: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 8831: 		text-indent:-99999px;
 8832: 		overflow:hidden;
 8833: 		cursor:pointer;
 8834: }
 8835: 
 8836: .LCisDisabled {
 8837:   cursor: not-allowed;
 8838:   opacity: 0.5;
 8839: }
 8840: 
 8841: a[aria-disabled="true"] {
 8842:   color: currentColor;
 8843:   display: inline-block;  /* For IE11/ MS Edge bug */
 8844:   pointer-events: none;
 8845:   text-decoration: none;
 8846: }
 8847: 
 8848: pre.LC_wordwrap {
 8849:   white-space: pre-wrap;
 8850:   white-space: -moz-pre-wrap;
 8851:   white-space: -pre-wrap;
 8852:   white-space: -o-pre-wrap;
 8853:   word-wrap: break-word;
 8854: }
 8855: 
 8856: /*
 8857:   styles used for response display
 8858: */
 8859: div.LC_radiofoil, div.LC_rankfoil {
 8860:   margin: .5em 0em .5em 0em;
 8861: }
 8862: table.LC_itemgroup {
 8863:   margin-top: 1em;
 8864: }
 8865: 
 8866: /*
 8867:   styles used by TTH when "Default set of options to pass to tth/m
 8868:   when converting TeX" in course settings has been set
 8869: 
 8870:   option passed: -t
 8871: 
 8872: */
 8873: 
 8874: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 8875: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 8876: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 8877: td div.norm {line-height:normal;}
 8878: 
 8879: /*
 8880:   option passed -y3
 8881: */
 8882: 
 8883: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 8884: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 8885: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 8886: 
 8887: /*
 8888:   sections with roles, for content only
 8889: */
 8890: section[class^="role-"] {
 8891:   padding-left: 10px;
 8892:   padding-right: 5px;
 8893:   margin-top: 8px;
 8894:   margin-bottom: 8px;
 8895:   border: 1px solid #2A4;
 8896:   border-radius: 5px;
 8897:   box-shadow: 0px 1px 1px #BBB;
 8898: }
 8899: section[class^="role-"]>h1 {
 8900:   position: relative;
 8901:   margin: 0px;
 8902:   padding-top: 10px;
 8903:   padding-left: 40px;
 8904: }
 8905: section[class^="role-"]>h1:before {
 8906:   position: absolute;
 8907:   left: -5px;
 8908:   top: 5px;
 8909: }
 8910: section.role-activity>h1:before {
 8911:   content:url('/adm/daxe/images/section_icons/activity.png');
 8912: }
 8913: section.role-advice>h1:before {
 8914:   content:url('/adm/daxe/images/section_icons/advice.png');
 8915: }
 8916: section.role-bibliography>h1:before {
 8917:   content:url('/adm/daxe/images/section_icons/bibliography.png');
 8918: }
 8919: section.role-citation>h1:before {
 8920:   content:url('/adm/daxe/images/section_icons/citation.png');
 8921: }
 8922: section.role-conclusion>h1:before {
 8923:   content:url('/adm/daxe/images/section_icons/conclusion.png');
 8924: }
 8925: section.role-definition>h1:before {
 8926:   content:url('/adm/daxe/images/section_icons/definition.png');
 8927: }
 8928: section.role-demonstration>h1:before {
 8929:   content:url('/adm/daxe/images/section_icons/demonstration.png');
 8930: }
 8931: section.role-example>h1:before {
 8932:   content:url('/adm/daxe/images/section_icons/example.png');
 8933: }
 8934: section.role-explanation>h1:before {
 8935:   content:url('/adm/daxe/images/section_icons/explanation.png');
 8936: }
 8937: section.role-introduction>h1:before {
 8938:   content:url('/adm/daxe/images/section_icons/introduction.png');
 8939: }
 8940: section.role-method>h1:before {
 8941:   content:url('/adm/daxe/images/section_icons/method.png');
 8942: }
 8943: section.role-more_information>h1:before {
 8944:   content:url('/adm/daxe/images/section_icons/more_information.png');
 8945: }
 8946: section.role-objectives>h1:before {
 8947:   content:url('/adm/daxe/images/section_icons/objectives.png');
 8948: }
 8949: section.role-prerequisites>h1:before {
 8950:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
 8951: }
 8952: section.role-remark>h1:before {
 8953:   content:url('/adm/daxe/images/section_icons/remark.png');
 8954: }
 8955: section.role-reminder>h1:before {
 8956:   content:url('/adm/daxe/images/section_icons/reminder.png');
 8957: }
 8958: section.role-summary>h1:before {
 8959:   content:url('/adm/daxe/images/section_icons/summary.png');
 8960: }
 8961: section.role-syntax>h1:before {
 8962:   content:url('/adm/daxe/images/section_icons/syntax.png');
 8963: }
 8964: section.role-warning>h1:before {
 8965:   content:url('/adm/daxe/images/section_icons/warning.png');
 8966: }
 8967: 
 8968: #LC_minitab_header {
 8969:   float:left;
 8970:   width:100%;
 8971:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
 8972:   font-size:93%;
 8973:   line-height:normal;
 8974:   margin: 0.5em 0 0.5em 0;
 8975: }
 8976: #LC_minitab_header ul {
 8977:   margin:0;
 8978:   padding:10px 10px 0;
 8979:   list-style:none;
 8980: }
 8981: #LC_minitab_header li {
 8982:   float:left;
 8983:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
 8984:   margin:0;
 8985:   padding:0 0 0 9px;
 8986: }
 8987: #LC_minitab_header a {
 8988:   display:block;
 8989:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
 8990:   padding:5px 15px 4px 6px;
 8991: }
 8992: #LC_minitab_header #LC_current_minitab {
 8993:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
 8994: }
 8995: #LC_minitab_header #LC_current_minitab a {
 8996:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
 8997:   padding-bottom:5px;
 8998: }
 8999: 
 9000: 
 9001: END
 9002: }
 9003: 
 9004: =pod
 9005: 
 9006: =item * &headtag()
 9007: 
 9008: Returns a uniform footer for LON-CAPA web pages.
 9009: 
 9010: Inputs: $title - optional title for the head
 9011:         $head_extra - optional extra HTML to put inside the <head>
 9012:         $args - optional arguments
 9013:             force_register - if is true call registerurl so the remote is 
 9014:                              informed
 9015:             redirect       -> array ref of
 9016:                                    1- seconds before redirect occurs
 9017:                                    2- url to redirect to
 9018:                                    3- whether the side effect should occur
 9019:                            (side effect of setting 
 9020:                                $env{'internal.head.redirect'} to the url 
 9021:                                redirected to)
 9022:                                    4- whether the redirect target should be
 9023:                                       the opener of the current (pop-up)
 9024:                                       window (side effect of setting
 9025:                                       $env{'internal.head.to_opener'} to
 9026:                                       1, if true.
 9027:                                    5- whether encrypt check should be skipped
 9028:             domain         -> force to color decorate a page for a specific
 9029:                                domain
 9030:             function       -> force usage of a specific rolish color scheme
 9031:             bgcolor        -> override the default page bgcolor
 9032:             no_auto_mt_title
 9033:                            -> prevent &mt()ing the title arg
 9034: 
 9035: =cut
 9036: 
 9037: sub headtag {
 9038:     my ($title,$head_extra,$args) = @_;
 9039:     
 9040:     my $function = $args->{'function'} || &get_users_function();
 9041:     my $domain   = $args->{'domain'}   || &determinedomain();
 9042:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 9043:     my $httphost = $args->{'use_absolute'};
 9044:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 9045: 		   $Apache::lonnet::perlvar{'lonVersion'},
 9046: 		   #time(),
 9047: 		   $env{'environment.color.timestamp'},
 9048: 		   $function,$domain,$bgcolor);
 9049: 
 9050:     $url = '/adm/css/'.&escape($url).'.css';
 9051: 
 9052:     my $result =
 9053: 	'<head>'.
 9054: 	&font_settings($args);
 9055: 
 9056:     my $inhibitprint;
 9057:     if ($args->{'print_suppress'}) {
 9058:         $inhibitprint = &print_suppression();
 9059:     }
 9060: 
 9061:     if (!$args->{'frameset'}) {
 9062: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 9063:     }
 9064:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
 9065:         $result .= Apache::lonxml::display_title();
 9066:     }
 9067:     if (!$args->{'no_nav_bar'} 
 9068: 	&& !$args->{'only_body'}
 9069: 	&& !$args->{'frameset'}) {
 9070: 	$result .= &help_menu_js($httphost);
 9071:         $result.=&modal_window();
 9072:         $result.=&togglebox_script();
 9073:         $result.=&wishlist_window();
 9074:         $result.=&LCprogressbarUpdate_script();
 9075:     } else {
 9076:         if ($args->{'add_modal'}) {
 9077:            $result.=&modal_window();
 9078:         }
 9079:         if ($args->{'add_wishlist'}) {
 9080:            $result.=&wishlist_window();
 9081:         }
 9082:         if ($args->{'add_togglebox'}) {
 9083:            $result.=&togglebox_script();
 9084:         }
 9085:         if ($args->{'add_progressbar'}) {
 9086:            $result.=&LCprogressbarUpdate_script();
 9087:         }
 9088:     }
 9089:     if (ref($args->{'redirect'})) {
 9090: 	my ($time,$url,$inhibit_continue,$to_opener,$skip_enc_check) = @{$args->{'redirect'}};
 9091:         if (!$skip_enc_check) {
 9092:             $url = &Apache::lonenc::check_encrypt($url);
 9093:         }
 9094: 	if (!$inhibit_continue) {
 9095: 	    $env{'internal.head.redirect'} = $url;
 9096: 	}
 9097: 	$result.=<<"ADDMETA";
 9098: <meta http-equiv="pragma" content="no-cache" />
 9099: ADDMETA
 9100:         if ($to_opener) {
 9101:             $env{'internal.head.to_opener'} = 1;
 9102:             my $dest = &js_escape($url);
 9103:             my $timeout = int($time * 1000);
 9104:             $result .=<<"ENDJS";
 9105: <script type="text/javascript">
 9106: // <![CDATA[
 9107: function LC_To_Opener() {
 9108:     var dest = '$dest';
 9109:     if (dest != '') {
 9110:         if (window.opener != null && !window.opener.closed) {
 9111:             window.opener.location.href=dest;
 9112:             window.close();
 9113:         } else {
 9114:             window.location.href=dest;
 9115:         }
 9116:     }
 9117: }
 9118: \$(document).ready(function () {
 9119:     setTimeout('LC_To_Opener()',$timeout);
 9120: });
 9121: // ]]>
 9122: </script>
 9123: ENDJS
 9124:         } else {
 9125:             $result.=<<"ADDMETA";
 9126: <meta http-equiv="Refresh" content="$time; url=$url" />
 9127: ADDMETA
 9128:         }
 9129:     } else {
 9130:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
 9131:             my $requrl = $env{'request.uri'};
 9132:             if ($requrl eq '') {
 9133:                 $requrl = $ENV{'REQUEST_URI'};
 9134:                 $requrl =~ s/\?.+$//;
 9135:             }
 9136:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
 9137:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
 9138:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
 9139:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
 9140:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
 9141:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
 9142:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 9143:                     my ($offload,$offloadoth);
 9144:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
 9145:                         if ($domdefs{'offloadnow'}{$lonhost}) {
 9146:                             $offload = 1;
 9147:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
 9148:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
 9149:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
 9150:                                     $offloadoth = 1;
 9151:                                     $dom_in_use = $env{'user.domain'};
 9152:                                 }
 9153:                             }
 9154:                         }
 9155:                     }
 9156:                     unless ($offload) {
 9157:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
 9158:                             if ($domdefs{'offloadoth'}{$lonhost}) {
 9159:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
 9160:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
 9161:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
 9162:                                         $offload = 1;
 9163:                                         $offloadoth = 1;
 9164:                                         $dom_in_use = $env{'user.domain'};
 9165:                                     }
 9166:                                 }
 9167:                             }
 9168:                         }
 9169:                     }
 9170:                     if ($offload) {
 9171:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
 9172:                         if (($newserver eq '') && ($offloadoth)) {
 9173:                             my @domains = &Apache::lonnet::current_machine_domains();
 9174:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) { 
 9175:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
 9176:                             }
 9177:                         }
 9178:                         if (($newserver) && ($newserver ne $lonhost)) {
 9179:                             my $numsec = 5;
 9180:                             my $timeout = $numsec * 1000;
 9181:                             my ($newurl,$locknum,%locks,$msg);
 9182:                             if ($env{'request.role.adv'}) {
 9183:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
 9184:                             }
 9185:                             my $disable_submit = 0;
 9186:                             if ($requrl =~ /$LONCAPA::assess_re/) {
 9187:                                 $disable_submit = 1;
 9188:                             }
 9189:                             if ($locknum) {
 9190:                                 my @lockinfo = sort(values(%locks));
 9191:                                 $msg = &mt('Once the following tasks are complete:')." \n".
 9192:                                        join(", ",sort(values(%locks)))."\n";
 9193:                                 if (&show_course()) {
 9194:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
 9195:                                 } else {
 9196:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
 9197:                                 }
 9198:                             } else {
 9199:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
 9200:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
 9201:                                 }
 9202:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
 9203:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
 9204:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
 9205:                                     $newurl .= '&role='.$env{'request.role'};
 9206:                                 }
 9207:                                 if ($env{'request.symb'}) {
 9208:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
 9209:                                     if ($shownsymb =~ m{^/enc/}) {
 9210:                                         my $reqdmajor = 2;
 9211:                                         my $reqdminor = 11;
 9212:                                         my $reqdsubminor = 3;
 9213:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
 9214:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
 9215:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
 9216:                                         if (($major eq '' && $minor eq '') ||
 9217:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
 9218:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
 9219:                                              ($reqdsubminor > $subminor))))) {
 9220:                                             undef($shownsymb);
 9221:                                         }
 9222:                                     }
 9223:                                     if ($shownsymb) {
 9224:                                         &js_escape(\$shownsymb);
 9225:                                         $newurl .= '&symb='.$shownsymb;
 9226:                                     }
 9227:                                 } else {
 9228:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
 9229:                                     &js_escape(\$shownurl);
 9230:                                     $newurl .= '&origurl='.$shownurl;
 9231:                                 }
 9232:                             }
 9233:                             &js_escape(\$msg);
 9234:                             $result.=<<OFFLOAD
 9235: <meta http-equiv="pragma" content="no-cache" />
 9236: <script type="text/javascript">
 9237: // <![CDATA[
 9238: function LC_Offload_Now() {
 9239:     var dest = "$newurl";
 9240:     if (dest != '') {
 9241:         window.location.href="$newurl";
 9242:     }
 9243: }
 9244: \$(document).ready(function () {
 9245:     window.alert('$msg');
 9246:     if ($disable_submit) {
 9247:         \$(".LC_hwk_submit").prop("disabled", true);
 9248:         \$( ".LC_textline" ).prop( "readonly", "readonly");
 9249:     }
 9250:     setTimeout('LC_Offload_Now()', $timeout);
 9251: });
 9252: // ]]>
 9253: </script>
 9254: OFFLOAD
 9255:                         }
 9256:                     }
 9257:                 }
 9258:             }
 9259:         }
 9260:     }
 9261:     if (!defined($title)) {
 9262: 	$title = 'The LearningOnline Network with CAPA';
 9263:     }
 9264:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 9265:     $result .= '<title> LON-CAPA '.$title.'</title>'
 9266: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
 9267:     if (!$args->{'frameset'}) {
 9268:         $result .= ' /';
 9269:     }
 9270:     $result .= '>' 
 9271:         .$inhibitprint
 9272: 	.$head_extra;
 9273:     my $clientmobile;
 9274:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 9275:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
 9276:     } else {
 9277:         $clientmobile = $env{'browser.mobile'};
 9278:     }
 9279:     if ($clientmobile) {
 9280:         $result .= '
 9281: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 9282: <meta name="apple-mobile-web-app-capable" content="yes" />';
 9283:     }
 9284:     $result .= '<meta name="google" content="notranslate" />'."\n";
 9285:     return $result.'</head>';
 9286: }
 9287: 
 9288: =pod
 9289: 
 9290: =item * &font_settings()
 9291: 
 9292: Returns neccessary <meta> to set the proper encoding
 9293: 
 9294: Inputs: optional reference to HASH -- $args passed to &headtag()
 9295: 
 9296: =cut
 9297: 
 9298: sub font_settings {
 9299:     my ($args) = @_;
 9300:     my $headerstring='';
 9301:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
 9302:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
 9303:         $headerstring.=
 9304:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
 9305:         if (!$args->{'frameset'}) {
 9306: 	    $headerstring.= ' /';
 9307:         }
 9308: 	$headerstring .= '>'."\n";
 9309:     }
 9310:     return $headerstring;
 9311: }
 9312: 
 9313: =pod
 9314: 
 9315: =item * &print_suppression()
 9316: 
 9317: In course context returns css which causes the body to be blank when media="print",
 9318: if printout generation is unavailable for the current resource.
 9319: 
 9320: This could be because:
 9321: 
 9322: (a) printstartdate is in the future
 9323: 
 9324: (b) printenddate is in the past
 9325: 
 9326: (c) there is an active exam block with "printout"
 9327: functionality blocked
 9328: 
 9329: Users with pav, pfo or evb privileges are exempt.
 9330: 
 9331: Inputs: none
 9332: 
 9333: =cut
 9334: 
 9335: 
 9336: sub print_suppression {
 9337:     my $noprint;
 9338:     if ($env{'request.course.id'}) {
 9339:         my $scope = $env{'request.course.id'};
 9340:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 9341:             (&Apache::lonnet::allowed('pfo',$scope))) {
 9342:             return;
 9343:         }
 9344:         if ($env{'request.course.sec'} ne '') {
 9345:             $scope .= "/$env{'request.course.sec'}";
 9346:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 9347:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 9348:                 return;
 9349:             }
 9350:         }
 9351:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9352:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9353:         my $clientip = &Apache::lonnet::get_requestor_ip();
 9354:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
 9355:         if ($blocked) {
 9356:             my $checkrole = "cm./$cdom/$cnum";
 9357:             if ($env{'request.course.sec'} ne '') {
 9358:                 $checkrole .= "/$env{'request.course.sec'}";
 9359:             }
 9360:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 9361:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 9362:                 $noprint = 1;
 9363:             }
 9364:         }
 9365:         unless ($noprint) {
 9366:             my $symb = &Apache::lonnet::symbread();
 9367:             if ($symb ne '') {
 9368:                 my $navmap = Apache::lonnavmaps::navmap->new();
 9369:                 if (ref($navmap)) {
 9370:                     my $res = $navmap->getBySymb($symb);
 9371:                     if (ref($res)) {
 9372:                         if (!$res->resprintable()) {
 9373:                             $noprint = 1;
 9374:                         }
 9375:                     }
 9376:                 }
 9377:             }
 9378:         }
 9379:         if ($noprint) {
 9380:             return <<"ENDSTYLE";
 9381: <style type="text/css" media="print">
 9382:     body { display:none }
 9383: </style>
 9384: ENDSTYLE
 9385:         }
 9386:     }
 9387:     return;
 9388: }
 9389: 
 9390: =pod
 9391: 
 9392: =item * &xml_begin()
 9393: 
 9394: Returns the needed doctype and <html>
 9395: 
 9396: Inputs: none
 9397: 
 9398: =cut
 9399: 
 9400: sub xml_begin {
 9401:     my ($is_frameset) = @_;
 9402:     my $output='';
 9403: 
 9404:     if ($env{'browser.mathml'}) {
 9405: 	$output='<?xml version="1.0"?>'
 9406:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 9407: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 9408:             
 9409: #	    .'<!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">] >'
 9410: 	    .'<!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">'
 9411:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 9412: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 9413:     } elsif ($is_frameset) {
 9414:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
 9415:                 '<html>'."\n";
 9416:     } else {
 9417: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
 9418:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
 9419:     }
 9420:     return $output;
 9421: }
 9422: 
 9423: =pod
 9424: 
 9425: =item * &start_page()
 9426: 
 9427: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 9428: 
 9429: Inputs:
 9430: 
 9431: =over 4
 9432: 
 9433: $title - optional title for the page
 9434: 
 9435: $head_extra - optional extra HTML to incude inside the <head>
 9436: 
 9437: $args - additional optional args supported are:
 9438: 
 9439: =over 8
 9440: 
 9441:              only_body      -> is true will set &bodytag() onlybodytag
 9442:                                     arg on
 9443:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 9444:              add_entries    -> additional attributes to add to the  <body>
 9445:              domain         -> force to color decorate a page for a 
 9446:                                     specific domain
 9447:              function       -> force usage of a specific rolish color
 9448:                                     scheme
 9449:              redirect       -> see &headtag()
 9450:              bgcolor        -> override the default page bg color
 9451:              js_ready       -> return a string ready for being used in 
 9452:                                     a javascript writeln
 9453:              html_encode    -> return a string ready for being used in 
 9454:                                     a html attribute
 9455:              force_register -> if is true will turn on the &bodytag()
 9456:                                     $forcereg arg
 9457:              frameset       -> if true will start with a <frameset>
 9458:                                     rather than <body>
 9459:              skip_phases    -> hash ref of 
 9460:                                     head -> skip the <html><head> generation
 9461:                                     body -> skip all <body> generation
 9462:              no_auto_mt_title -> prevent &mt()ing the title arg
 9463:              bread_crumbs ->             Array containing breadcrumbs
 9464:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 9465:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
 9466:                                     to lonhtmlcommon::breadcrumbs
 9467:              group          -> includes the current group, if page is for a 
 9468:                                specific group
 9469:              use_absolute   -> for request for external resource or syllabus, this
 9470:                                will contain https://<hostname> if server uses
 9471:                                https (as per hosts.tab), but request is for http
 9472:              hostname       -> hostname, originally from $r->hostname(), (optional).
 9473:              links_disabled -> Links in primary and secondary menus are disabled
 9474:                                (Can enable them once page has loaded - see lonroles.pm
 9475:                                for an example).
 9476:              links_target   -> Target for links, e.g., _parent (optional).
 9477: 
 9478: =back
 9479: 
 9480: =back
 9481: 
 9482: =cut
 9483: 
 9484: sub start_page {
 9485:     my ($title,$head_extra,$args) = @_;
 9486:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 9487: 
 9488:     $env{'internal.start_page'}++;
 9489:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
 9490: 
 9491:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 9492:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
 9493:     }
 9494: 
 9495:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
 9496:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
 9497:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
 9498:                 $args->{'no_primary_menu'} = 1;
 9499:             }
 9500:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
 9501:                 $args->{'no_inline_menu'} = 1;
 9502:             }
 9503:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
 9504:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
 9505:             }
 9506:         } else {
 9507:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9508:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
 9509:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
 9510:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
 9511:                     $args->{'no_primary_menu'} = 1;
 9512:                 }
 9513:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
 9514:                     $args->{'no_inline_menu'} = 1;
 9515:                 }
 9516:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
 9517:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
 9518:                 }
 9519:             }
 9520:         }
 9521:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
 9522:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
 9523:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
 9524:     } elsif ($env{'request.course.id'}) {
 9525:         my $expiretime=600;
 9526:         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
 9527:             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
 9528:         }
 9529:         my ($deeplinkmenu,$menuref);
 9530:         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
 9531:         if ($menucoll) {
 9532:             if (ref($menuref) eq 'HASH') {
 9533:                 %menu = %{$menuref};
 9534:             }
 9535:             if ($menu{'top'} eq 'n') {
 9536:                 $args->{'no_primary_menu'} = 1;
 9537:             }
 9538:             if ($menu{'inline'} eq 'n') {
 9539:                 unless (&Apache::lonnet::allowed('opa')) {
 9540:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9541:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9542:                     my $crstype = &course_type();
 9543:                     my $now = time;
 9544:                     my $ccrole;
 9545:                     if ($crstype eq 'Community') {
 9546:                         $ccrole = 'co';
 9547:                     } else {
 9548:                         $ccrole = 'cc';
 9549:                     }
 9550:                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
 9551:                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
 9552:                         if ((($start) && ($start<0)) ||
 9553:                             (($end) && ($end<$now))  ||
 9554:                             (($start) && ($now<$start))) {
 9555:                             $args->{'no_inline_menu'} = 1;
 9556:                         }
 9557:                     } else {
 9558:                         $args->{'no_inline_menu'} = 1;
 9559:                     }
 9560:                 }
 9561:             }
 9562:         }
 9563:     }
 9564: 
 9565:     my $showncrumbs;
 9566:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 9567: 	if ($args->{'frameset'}) {
 9568: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 9569: 						$args->{'add_entries'});
 9570: 	    $result .= "\n<frameset $attr_string>\n";
 9571:         } else {
 9572:             $result .=
 9573:                 &bodytag($title, 
 9574:                          $args->{'function'},       $args->{'add_entries'},
 9575:                          $args->{'only_body'},      $args->{'domain'},
 9576:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 9577:                          $args->{'bgcolor'},        $args,
 9578:                          \@advtools,$ltiscope,$ltiuri,\%ltimenu,$menucoll,
 9579:                          \%menu,\$showncrumbs);
 9580:         }
 9581:     }
 9582: 
 9583:     if ($args->{'js_ready'}) {
 9584: 		$result = &js_ready($result);
 9585:     }
 9586:     if ($args->{'html_encode'}) {
 9587: 		$result = &html_encode($result);
 9588:     }
 9589: 
 9590:     # Preparation for new and consistent functionlist at top of screen
 9591:     # if ($args->{'functionlist'}) {
 9592:     #            $result .= &build_functionlist();
 9593:     #}
 9594: 
 9595:     # Don't add anything more if only_body wanted or in const space
 9596:     return $result if    $args->{'only_body'} 
 9597:                       || $env{'request.state'} eq 'construct';
 9598: 
 9599:     #Breadcrumbs
 9600:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 9601:         unless ($showncrumbs) {
 9602: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 9603: 		#if any br links exists, add them to the breadcrumbs
 9604: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 9605: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 9606: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 9607: 			}
 9608: 		}
 9609:                 # if @advtools array contains items add then to the breadcrumbs
 9610:                 if (@advtools > 0) {
 9611:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 9612:                 }
 9613:                 my $menulink;
 9614:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
 9615:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
 9616:                      ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
 9617:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
 9618:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
 9619:                      (!$env{'request.role.adv'}))) {
 9620:                     $menulink = 0;
 9621:                 } else {
 9622:                     undef($menulink);
 9623:                 }
 9624:                 my $linkprotout;
 9625:                 if ($env{'request.deeplink.login'}) {
 9626:                     my $linkprotout = &Apache::lonmenu::linkprot_exit();
 9627:                     if ($linkprotout) {
 9628:                         &Apache::lonhtmlcommon::add_breadcrumb_tool('tools',$linkprotout);
 9629:                     }
 9630:                 }
 9631: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 9632: 		if(exists($args->{'bread_crumbs_component'})){
 9633: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
 9634:                 } else {
 9635: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
 9636: 		}
 9637:         }
 9638:     }
 9639:     return $result;
 9640: }
 9641: 
 9642: sub end_page {
 9643:     my ($args) = @_;
 9644:     $env{'internal.end_page'}++;
 9645:     my $result;
 9646:     if ($args->{'discussion'}) {
 9647: 	my ($target,$parser);
 9648: 	if (ref($args->{'discussion'})) {
 9649: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 9650: 				$args->{'discussion'}{'parser'});
 9651: 	}
 9652: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 9653:     }
 9654:     if ($args->{'frameset'}) {
 9655: 	$result .= '</frameset>';
 9656:     } else {
 9657: 	$result .= &endbodytag($args);
 9658:     }
 9659:     unless ($args->{'notbody'}) {
 9660:         $result .= "\n</html>";
 9661:     }
 9662: 
 9663:     if ($args->{'js_ready'}) {
 9664: 	$result = &js_ready($result);
 9665:     }
 9666: 
 9667:     if ($args->{'html_encode'}) {
 9668: 	$result = &html_encode($result);
 9669:     }
 9670: 
 9671:     return $result;
 9672: }
 9673: 
 9674: sub menucoll_in_effect {
 9675:     my ($menucoll,$deeplinkmenu,%menu);
 9676:     if ($env{'request.course.id'}) {
 9677:         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
 9678:         if ($env{'request.deeplink.login'}) {
 9679:             my ($deeplink_symb,$deeplink,$check_login_symb);
 9680:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9681:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9682:             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
 9683:                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
 9684:                     my $navmap = Apache::lonnavmaps::navmap->new();
 9685:                     if (ref($navmap)) {
 9686:                         $deeplink = $navmap->get_mapparam(undef,
 9687:                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
 9688:                                                           '0.deeplink');
 9689:                     } else {
 9690:                         $check_login_symb = 1;
 9691:                     }
 9692:                 } else {
 9693:                     my $symb = &Apache::lonnet::symbread();
 9694:                     if ($symb) {
 9695:                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
 9696:                     } else {
 9697:                         $check_login_symb = 1;
 9698:                     }
 9699:                 }
 9700:             } else {
 9701:                 $check_login_symb = 1;
 9702:             }
 9703:             if ($check_login_symb) {
 9704:                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
 9705:                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
 9706:                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
 9707:                     my $navmap = Apache::lonnavmaps::navmap->new();
 9708:                     if (ref($navmap)) {
 9709:                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
 9710:                     }
 9711:                 } else {
 9712:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
 9713:                 }
 9714:             }
 9715:             if ($deeplink ne '') {
 9716:                 my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
 9717:                 if ($display =~ /^\d+$/) {
 9718:                     $deeplinkmenu = 1;
 9719:                     $menucoll = $display;
 9720:                 }
 9721:             }
 9722:         }
 9723:         if ($menucoll) {
 9724:             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
 9725:         }
 9726:     }
 9727:     return ($menucoll,$deeplinkmenu,\%menu);
 9728: }
 9729: 
 9730: sub deeplink_login_symb {
 9731:     my ($cnum,$cdom) = @_;
 9732:     my $login_symb;
 9733:     if ($env{'request.deeplink.login'}) {
 9734:         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
 9735:     }
 9736:     return $login_symb;
 9737: }
 9738: 
 9739: sub symb_from_tinyurl {
 9740:     my ($url,$cnum,$cdom) = @_;
 9741:     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
 9742:         my $key = $1;
 9743:         my ($tinyurl,$login);
 9744:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
 9745:         if (defined($cached)) {
 9746:             $tinyurl = $result;
 9747:         } else {
 9748:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
 9749:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
 9750:             if ($currtiny{$key} ne '') {
 9751:                 $tinyurl = $currtiny{$key};
 9752:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
 9753:             }
 9754:         }
 9755:         if ($tinyurl ne '') {
 9756:             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
 9757:             if (wantarray) {
 9758:                 return ($cnumreq,$symb);
 9759:             } elsif ($cnumreq eq $cnum) {
 9760:                 return $symb;
 9761:             }
 9762:         }
 9763:     }
 9764:     if (wantarray) {
 9765:         return ();
 9766:     } else {
 9767:         return;
 9768:     }
 9769: }
 9770: 
 9771: sub usable_exttools {
 9772:     my %tooltypes;
 9773:     if ($env{'request.course.id'}) {
 9774:         if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'}) {
 9775:            if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'both') {
 9776:                %tooltypes = (
 9777:                              crs => 1,
 9778:                              dom => 1,
 9779:                             );
 9780:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'crs') {
 9781:                $tooltypes{'crs'} = 1;
 9782:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'dom') {
 9783:                $tooltypes{'dom'} = 1;
 9784:            }
 9785:         } else {
 9786:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9787:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9788:             my $crstype = lc($env{'course.'.$env{'request.course.id'}.'.type'});
 9789:             if ($crstype eq '') {
 9790:                 $crstype = 'course';
 9791:             }
 9792:             if ($crstype eq 'course') {
 9793:                 if ($env{'course.'.$env{'request.course.id'}.'internal.coursecode'}) {
 9794:                     $crstype = 'official';
 9795:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.textbook'}) {
 9796:                     $crstype = 'textbook';
 9797:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.lti'}) {
 9798:                     $crstype = 'lti';
 9799:                 } else {
 9800:                     $crstype = 'unofficial';
 9801:                 }
 9802:             }
 9803:             my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 9804:             if ($domdefaults{$crstype.'domexttool'}) {
 9805:                 $tooltypes{'dom'} = 1;
 9806:             }
 9807:             if ($domdefaults{$crstype.'exttool'}) {
 9808:                 $tooltypes{'crs'} = 1;
 9809:             }
 9810:         }
 9811:     }
 9812:     return %tooltypes;
 9813: }
 9814: 
 9815: sub wishlist_window {
 9816:     return(<<'ENDWISHLIST');
 9817: <script type="text/javascript">
 9818: // <![CDATA[
 9819: // <!-- BEGIN LON-CAPA Internal
 9820: function set_wishlistlink(title, path) {
 9821:     if (!title) {
 9822:         title = document.title;
 9823:         title = title.replace(/^LON-CAPA /,'');
 9824:     }
 9825:     title = encodeURIComponent(title);
 9826:     title = title.replace("'","\\\'");
 9827:     if (!path) {
 9828:         path = location.pathname;
 9829:     }
 9830:     path = encodeURIComponent(path);
 9831:     path = path.replace("'","\\\'");
 9832:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 9833:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 9834: }
 9835: // END LON-CAPA Internal -->
 9836: // ]]>
 9837: </script>
 9838: ENDWISHLIST
 9839: }
 9840: 
 9841: sub modal_window {
 9842:     return(<<'ENDMODAL');
 9843: <script type="text/javascript">
 9844: // <![CDATA[
 9845: // <!-- BEGIN LON-CAPA Internal
 9846: var modalWindow = {
 9847: 	parent:"body",
 9848: 	windowId:null,
 9849: 	content:null,
 9850: 	width:null,
 9851: 	height:null,
 9852: 	close:function()
 9853: 	{
 9854: 	        $(".LCmodal-window").remove();
 9855: 	        $(".LCmodal-overlay").remove();
 9856: 	},
 9857: 	open:function()
 9858: 	{
 9859: 		var modal = "";
 9860: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 9861: 		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;\">";
 9862: 		modal += this.content;
 9863: 		modal += "</div>";	
 9864: 
 9865: 		$(this.parent).append(modal);
 9866: 
 9867: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 9868: 		$(".LCclose-window").click(function(){modalWindow.close();});
 9869: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 9870: 	}
 9871: };
 9872: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
 9873: 	{
 9874:                 source = source.replace(/'/g,"&#39;");
 9875: 		modalWindow.windowId = "myModal";
 9876: 		modalWindow.width = width;
 9877: 		modalWindow.height = height;
 9878: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
 9879: 		modalWindow.open();
 9880: 	};
 9881: // END LON-CAPA Internal -->
 9882: // ]]>
 9883: </script>
 9884: ENDMODAL
 9885: }
 9886: 
 9887: sub modal_link {
 9888:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
 9889:     unless ($width) { $width=480; }
 9890:     unless ($height) { $height=400; }
 9891:     unless ($scrolling) { $scrolling='yes'; }
 9892:     unless ($transparency) { $transparency='true'; }
 9893: 
 9894:     my $target_attr;
 9895:     if (defined($target)) {
 9896:         $target_attr = 'target="'.$target.'"';
 9897:     }
 9898:     return <<"ENDLINK";
 9899: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
 9900: ENDLINK
 9901: }
 9902: 
 9903: sub modal_adhoc_script {
 9904:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
 9905:     my $mathjax;
 9906:     if ($possmathjax) {
 9907:         $mathjax = <<'ENDJAX';
 9908:                if (typeof MathJax == 'object') {
 9909:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
 9910:                }
 9911: ENDJAX
 9912:     }
 9913:     return (<<ENDADHOC);
 9914: <script type="text/javascript">
 9915: // <![CDATA[
 9916:         var $funcname = function()
 9917:         {
 9918:                 modalWindow.windowId = "myModal";
 9919:                 modalWindow.width = $width;
 9920:                 modalWindow.height = $height;
 9921:                 modalWindow.content = '$content';
 9922:                 modalWindow.open();
 9923:                 $mathjax
 9924:         };  
 9925: // ]]>
 9926: </script>
 9927: ENDADHOC
 9928: }
 9929: 
 9930: sub modal_adhoc_inner {
 9931:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
 9932:     my $innerwidth=$width-20;
 9933:     $content=&js_ready(
 9934:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 9935:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
 9936:                  $content.
 9937:                  &end_scrollbox().
 9938:                  &end_page()
 9939:              );
 9940:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
 9941: }
 9942: 
 9943: sub modal_adhoc_window {
 9944:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
 9945:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
 9946:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 9947: }
 9948: 
 9949: sub modal_adhoc_launch {
 9950:     my ($funcname,$width,$height,$content)=@_;
 9951:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 9952: <script type="text/javascript">
 9953: // <![CDATA[
 9954: $funcname();
 9955: // ]]>
 9956: </script>
 9957: ENDLAUNCH
 9958: }
 9959: 
 9960: sub modal_adhoc_close {
 9961:     return (<<ENDCLOSE);
 9962: <script type="text/javascript">
 9963: // <![CDATA[
 9964: modalWindow.close();
 9965: // ]]>
 9966: </script>
 9967: ENDCLOSE
 9968: }
 9969: 
 9970: sub togglebox_script {
 9971:    return(<<ENDTOGGLE);
 9972: <script type="text/javascript"> 
 9973: // <![CDATA[
 9974: function LCtoggleDisplay(id,hidetext,showtext) {
 9975:    link = document.getElementById(id + "link").childNodes[0];
 9976:    with (document.getElementById(id).style) {
 9977:       if (display == "none" ) {
 9978:           display = "inline";
 9979:           link.nodeValue = hidetext;
 9980:         } else {
 9981:           display = "none";
 9982:           link.nodeValue = showtext;
 9983:        }
 9984:    }
 9985: }
 9986: // ]]>
 9987: </script>
 9988: ENDTOGGLE
 9989: }
 9990: 
 9991: sub start_togglebox {
 9992:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 9993:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 9994:     unless ($showtext) { $showtext=&mt('show'); }
 9995:     unless ($hidetext) { $hidetext=&mt('hide'); }
 9996:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 9997:     return &start_data_table().
 9998:            &start_data_table_header_row().
 9999:            '<td bgcolor="'.$headerbg.'">'.$heading.
10000:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
10001:            $showtext.'\')">'.$showtext.'</a>]</td>'.
10002:            &end_data_table_header_row().
10003:            '<tr id="'.$id.'" style="display:none""><td>';
10004: }
10005: 
10006: sub end_togglebox {
10007:     return '</td></tr>'.&end_data_table();
10008: }
10009: 
10010: sub LCprogressbar_script {
10011:    my ($id,$number_to_do)=@_;
10012:    if ($number_to_do) {
10013:        return(<<ENDPROGRESS);
10014: <script type="text/javascript">
10015: // <![CDATA[
10016: \$('#progressbar$id').progressbar({
10017:   value: 0,
10018:   change: function(event, ui) {
10019:     var newVal = \$(this).progressbar('option', 'value');
10020:     \$('.pblabel', this).text(LCprogressTxt);
10021:   }
10022: });
10023: // ]]>
10024: </script>
10025: ENDPROGRESS
10026:    } else {
10027:        return(<<ENDPROGRESS);
10028: <script type="text/javascript">
10029: // <![CDATA[
10030: \$('#progressbar$id').progressbar({
10031:   value: false,
10032:   create: function(event, ui) {
10033:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
10034:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
10035:   }
10036: });
10037: // ]]>
10038: </script>
10039: ENDPROGRESS
10040:    }
10041: }
10042: 
10043: sub LCprogressbarUpdate_script {
10044:    return(<<ENDPROGRESSUPDATE);
10045: <style type="text/css">
10046: .ui-progressbar { position:relative; }
10047: .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%; }
10048: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
10049: </style>
10050: <script type="text/javascript">
10051: // <![CDATA[
10052: var LCprogressTxt='---';
10053: 
10054: function LCupdateProgress(percent,progresstext,id,maxnum) {
10055:    LCprogressTxt=progresstext;
10056:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
10057:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
10058:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
10059:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
10060:    } else {
10061:        \$('#progressbar'+id).progressbar('value',percent);
10062:    }
10063: }
10064: // ]]>
10065: </script>
10066: ENDPROGRESSUPDATE
10067: }
10068: 
10069: my $LClastpercent;
10070: my $LCidcnt;
10071: my $LCcurrentid;
10072: 
10073: sub LCprogressbar {
10074:     my ($r,$number_to_do,$preamble)=@_;
10075:     $LClastpercent=0;
10076:     $LCidcnt++;
10077:     $LCcurrentid=$$.'_'.$LCidcnt;
10078:     my ($starting,$content);
10079:     if ($number_to_do) {
10080:         $starting=&mt('Starting');
10081:         $content=(<<ENDPROGBAR);
10082: $preamble
10083:   <div id="progressbar$LCcurrentid">
10084:     <span class="pblabel">$starting</span>
10085:   </div>
10086: ENDPROGBAR
10087:     } else {
10088:         $starting=&mt('Loading...');
10089:         $LClastpercent='false';
10090:         $content=(<<ENDPROGBAR);
10091: $preamble
10092:   <div id="progressbar$LCcurrentid">
10093:       <div class="progress-label">$starting</div>
10094:   </div>
10095: ENDPROGBAR
10096:     }
10097:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
10098: }
10099: 
10100: sub LCprogressbarUpdate {
10101:     my ($r,$val,$text,$number_to_do)=@_;
10102:     if ($number_to_do) {
10103:         unless ($val) { 
10104:             if ($LClastpercent) {
10105:                 $val=$LClastpercent;
10106:             } else {
10107:                 $val=0;
10108:             }
10109:         }
10110:         if ($val<0) { $val=0; }
10111:         if ($val>100) { $val=0; }
10112:         $LClastpercent=$val;
10113:         unless ($text) { $text=$val.'%'; }
10114:     } else {
10115:         $val = 'false';
10116:     }
10117:     $text=&js_ready($text);
10118:     &r_print($r,<<ENDUPDATE);
10119: <script type="text/javascript">
10120: // <![CDATA[
10121: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
10122: // ]]>
10123: </script>
10124: ENDUPDATE
10125: }
10126: 
10127: sub LCprogressbarClose {
10128:     my ($r)=@_;
10129:     $LClastpercent=0;
10130:     &r_print($r,<<ENDCLOSE);
10131: <script type="text/javascript">
10132: // <![CDATA[
10133: \$("#progressbar$LCcurrentid").hide('slow'); 
10134: // ]]>
10135: </script>
10136: ENDCLOSE
10137: }
10138: 
10139: sub r_print {
10140:     my ($r,$to_print)=@_;
10141:     if ($r) {
10142:       $r->print($to_print);
10143:       $r->rflush();
10144:     } else {
10145:       print($to_print);
10146:     }
10147: }
10148: 
10149: sub html_encode {
10150:     my ($result) = @_;
10151: 
10152:     $result = &HTML::Entities::encode($result,'<>&"');
10153:     
10154:     return $result;
10155: }
10156: 
10157: sub js_ready {
10158:     my ($result) = @_;
10159: 
10160:     $result =~ s/[\n\r]/ /xmsg;
10161:     $result =~ s/\\/\\\\/xmsg;
10162:     $result =~ s/'/\\'/xmsg;
10163:     $result =~ s{</}{<\\/}xmsg;
10164:     
10165:     return $result;
10166: }
10167: 
10168: sub validate_page {
10169:     if (  exists($env{'internal.start_page'})
10170: 	  &&     $env{'internal.start_page'} > 1) {
10171: 	&Apache::lonnet::logthis('start_page called multiple times '.
10172: 				 $env{'internal.start_page'}.' '.
10173: 				 $ENV{'request.filename'});
10174:     }
10175:     if (  exists($env{'internal.end_page'})
10176: 	  &&     $env{'internal.end_page'} > 1) {
10177: 	&Apache::lonnet::logthis('end_page called multiple times '.
10178: 				 $env{'internal.end_page'}.' '.
10179: 				 $env{'request.filename'});
10180:     }
10181:     if (     exists($env{'internal.start_page'})
10182: 	&& ! exists($env{'internal.end_page'})) {
10183: 	&Apache::lonnet::logthis('start_page called without end_page '.
10184: 				 $env{'request.filename'});
10185:     }
10186:     if (   ! exists($env{'internal.start_page'})
10187: 	&&   exists($env{'internal.end_page'})) {
10188: 	&Apache::lonnet::logthis('end_page called without start_page'.
10189: 				 $env{'request.filename'});
10190:     }
10191: }
10192: 
10193: 
10194: sub start_scrollbox {
10195:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
10196:     unless ($outerwidth) { $outerwidth='520px'; }
10197:     unless ($width) { $width='500px'; }
10198:     unless ($height) { $height='200px'; }
10199:     my ($table_id,$div_id,$tdcol);
10200:     if ($id ne '') {
10201:         $table_id = ' id="table_'.$id.'"';
10202:         $div_id = ' id="div_'.$id.'"';
10203:     }
10204:     if ($bgcolor ne '') {
10205:         $tdcol = "background-color: $bgcolor;";
10206:     }
10207:     my $nicescroll_js;
10208:     if ($env{'browser.mobile'}) {
10209:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
10210:     }
10211:     return <<"END";
10212: $nicescroll_js
10213: 
10214: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
10215: <div style="overflow:auto; width:$width; height:$height;"$div_id>
10216: END
10217: }
10218: 
10219: sub end_scrollbox {
10220:     return '</div></td></tr></table>';
10221: }
10222: 
10223: sub nicescroll_javascript {
10224:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
10225:     my %options;
10226:     if (ref($cursor) eq 'HASH') {
10227:         %options = %{$cursor};
10228:     }
10229:     unless ($options{'railalign'} =~ /^left|right$/) {
10230:         $options{'railalign'} = 'left';
10231:     }
10232:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
10233:         my $function  = &get_users_function();
10234:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
10235:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
10236:             $options{'cursorcolor'} = '#00F';
10237:         }
10238:     }
10239:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
10240:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
10241:             $options{'cursoropacity'}='1.0';
10242:         }
10243:     } else {
10244:         $options{'cursoropacity'}='1.0';
10245:     }
10246:     if ($options{'cursorfixedheight'} eq 'none') {
10247:         delete($options{'cursorfixedheight'});
10248:     } else {
10249:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
10250:     }
10251:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
10252:         delete($options{'railoffset'});
10253:     }
10254:     my @niceoptions;
10255:     while (my($key,$value) = each(%options)) {
10256:         if ($value =~ /^\{.+\}$/) {
10257:             push(@niceoptions,$key.':'.$value);
10258:         } else {
10259:             push(@niceoptions,$key.':"'.$value.'"');
10260:         }
10261:     }
10262:     my $nicescroll_js = '
10263: $(document).ready(
10264:       function() {
10265:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
10266:       }
10267: );
10268: ';
10269:     if ($framecheck) {
10270:         $nicescroll_js .= '
10271: function expand_div(caller) {
10272:     if (top === self) {
10273:         document.getElementById("'.$id.'").style.width = "auto";
10274:         document.getElementById("'.$id.'").style.height = "auto";
10275:     } else {
10276:         try {
10277:             if (parent.frames) {
10278:                 if (parent.frames.length > 1) {
10279:                     var framesrc = parent.frames[1].location.href;
10280:                     var currsrc = framesrc.replace(/\#.*$/,"");
10281:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
10282:                         document.getElementById("'.$id.'").style.width = "auto";
10283:                         document.getElementById("'.$id.'").style.height = "auto";
10284:                     }
10285:                 }
10286:             }
10287:         } catch (e) {
10288:             return;
10289:         }
10290:     }
10291:     return;
10292: }
10293: ';
10294:     }
10295:     if ($needjsready) {
10296:         $nicescroll_js = '
10297: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
10298:     } else {
10299:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
10300:     }
10301:     return $nicescroll_js;
10302: }
10303: 
10304: sub simple_error_page {
10305:     my ($r,$title,$msg,$args) = @_;
10306:     my %displayargs;
10307:     if (ref($args) eq 'HASH') {
10308:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
10309:         if ($args->{'only_body'}) {
10310:             $displayargs{'only_body'} = 1;
10311:         }
10312:         if ($args->{'no_nav_bar'}) {
10313:             $displayargs{'no_nav_bar'} = 1;
10314:         }
10315:     } else {
10316:         $msg = &mt($msg);
10317:     }
10318: 
10319:     my $page =
10320: 	&Apache::loncommon::start_page($title,'',\%displayargs).
10321: 	'<p class="LC_error">'.$msg.'</p>'.
10322: 	&Apache::loncommon::end_page();
10323:     if (ref($r)) {
10324: 	$r->print($page);
10325: 	return;
10326:     }
10327:     return $page;
10328: }
10329: 
10330: {
10331:     my @row_count;
10332: 
10333:     sub start_data_table_count {
10334:         unshift(@row_count, 0);
10335:         return;
10336:     }
10337: 
10338:     sub end_data_table_count {
10339:         shift(@row_count);
10340:         return;
10341:     }
10342: 
10343:     sub start_data_table {
10344: 	my ($add_class,$id) = @_;
10345: 	my $css_class = (join(' ','LC_data_table',$add_class));
10346:         my $table_id;
10347:         if (defined($id)) {
10348:             $table_id = ' id="'.$id.'"';
10349:         }
10350: 	&start_data_table_count();
10351: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
10352:     }
10353: 
10354:     sub end_data_table {
10355: 	&end_data_table_count();
10356: 	return '</table>'."\n";;
10357:     }
10358: 
10359:     sub start_data_table_row {
10360: 	my ($add_class, $id) = @_;
10361: 	$row_count[0]++;
10362: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
10363: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
10364:         $id = (' id="'.$id.'"') unless ($id eq '');
10365:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
10366:     }
10367:     
10368:     sub continue_data_table_row {
10369: 	my ($add_class, $id) = @_;
10370: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
10371: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
10372:         $id = (' id="'.$id.'"') unless ($id eq '');
10373:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
10374:     }
10375: 
10376:     sub end_data_table_row {
10377: 	return '</tr>'."\n";;
10378:     }
10379: 
10380:     sub start_data_table_empty_row {
10381: #	$row_count[0]++;
10382: 	return  '<tr class="LC_empty_row" >'."\n";;
10383:     }
10384: 
10385:     sub end_data_table_empty_row {
10386: 	return '</tr>'."\n";;
10387:     }
10388: 
10389:     sub start_data_table_header_row {
10390: 	return  '<tr class="LC_header_row">'."\n";;
10391:     }
10392: 
10393:     sub end_data_table_header_row {
10394: 	return '</tr>'."\n";;
10395:     }
10396: 
10397:     sub data_table_caption {
10398:         my $caption = shift;
10399:         return "<caption class=\"LC_caption\">$caption</caption>";
10400:     }
10401: }
10402: 
10403: =pod
10404: 
10405: =item * &inhibit_menu_check($arg)
10406: 
10407: Checks for a inhibitmenu state and generates output to preserve it
10408: 
10409: Inputs:         $arg - can be any of
10410:                      - undef - in which case the return value is a string 
10411:                                to add  into arguments list of a uri
10412:                      - 'input' - in which case the return value is a HTML
10413:                                  <form> <input> field of type hidden to
10414:                                  preserve the value
10415:                      - a url - in which case the return value is the url with
10416:                                the neccesary cgi args added to preserve the
10417:                                inhibitmenu state
10418:                      - a ref to a url - no return value, but the string is
10419:                                         updated to include the neccessary cgi
10420:                                         args to preserve the inhibitmenu state
10421: 
10422: =cut
10423: 
10424: sub inhibit_menu_check {
10425:     my ($arg) = @_;
10426:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
10427:     if ($arg eq 'input') {
10428: 	if ($env{'form.inhibitmenu'}) {
10429: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
10430: 	} else {
10431: 	    return
10432: 	}
10433:     }
10434:     if ($env{'form.inhibitmenu'}) {
10435: 	if (ref($arg)) {
10436: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
10437: 	} elsif ($arg eq '') {
10438: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
10439: 	} else {
10440: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
10441: 	}
10442:     }
10443:     if (!ref($arg)) {
10444: 	return $arg;
10445:     }
10446: }
10447: 
10448: ###############################################
10449: 
10450: =pod
10451: 
10452: =back
10453: 
10454: =head1 User Information Routines
10455: 
10456: =over 4
10457: 
10458: =item * &get_users_function()
10459: 
10460: Used by &bodytag to determine the current users primary role.
10461: Returns either 'student','coordinator','admin', or 'author'.
10462: 
10463: =cut
10464: 
10465: ###############################################
10466: sub get_users_function {
10467:     my $function = 'norole';
10468:     if ($env{'request.role'}=~/^(st)/) {
10469:         $function='student';
10470:     }
10471:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
10472:         $function='coordinator';
10473:     }
10474:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
10475:         $function='admin';
10476:     }
10477:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
10478:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
10479:         $function='author';
10480:     }
10481:     return $function;
10482: }
10483: 
10484: ###############################################
10485: 
10486: =pod
10487: 
10488: =item * &show_course()
10489: 
10490: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
10491: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
10492: 
10493: Inputs:
10494: None
10495: 
10496: Outputs:
10497: Scalar: 1 if 'Course' to be used, 0 otherwise.
10498: 
10499: =cut
10500: 
10501: ###############################################
10502: sub show_course {
10503:     my ($udom,$uname) = @_;
10504:     if (($udom ne '') && ($uname ne '')) {
10505:         if (($udom ne $env{'user.domain'}) || ($uname ne $env{'user.name'})) {
10506:             if (&Apache::lonnet::is_advanced($udom,$uname)) {
10507:                 return 0;
10508:             } else {
10509:                 return 1;
10510:             }
10511:         }
10512:     }
10513:     my $course = !$env{'user.adv'};
10514:     if (!$env{'user.adv'}) {
10515:         foreach my $env (keys(%env)) {
10516:             next if ($env !~ m/^user\.priv\./);
10517:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
10518:                 $course = 0;
10519:                 last;
10520:             }
10521:         }
10522:     }
10523:     return $course;
10524: }
10525: 
10526: ###############################################
10527: 
10528: =pod
10529: 
10530: =item * &check_user_status()
10531: 
10532: Determines current status of supplied role for a
10533: specific user. Roles can be active, previous or future.
10534: 
10535: Inputs: 
10536: user's domain, user's username, course's domain,
10537: course's number, optional section ID.
10538: 
10539: Outputs:
10540: role status: active, previous or future. 
10541: 
10542: =cut
10543: 
10544: sub check_user_status {
10545:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
10546:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
10547:     my @uroles = keys(%userinfo);
10548:     my $srchstr;
10549:     my $active_chk = 'none';
10550:     my $now = time;
10551:     if (@uroles > 0) {
10552:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
10553:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
10554:         } else {
10555:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
10556:         }
10557:         if (grep/^\Q$srchstr\E$/,@uroles) {
10558:             my $role_end = 0;
10559:             my $role_start = 0;
10560:             $active_chk = 'active';
10561:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
10562:                 $role_end = $1;
10563:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
10564:                     $role_start = $1;
10565:                 }
10566:             }
10567:             if ($role_start > 0) {
10568:                 if ($now < $role_start) {
10569:                     $active_chk = 'future';
10570:                 }
10571:             }
10572:             if ($role_end > 0) {
10573:                 if ($now > $role_end) {
10574:                     $active_chk = 'previous';
10575:                 }
10576:             }
10577:         }
10578:     }
10579:     return $active_chk;
10580: }
10581: 
10582: ###############################################
10583: 
10584: =pod
10585: 
10586: =item * &get_sections()
10587: 
10588: Determines all the sections for a course including
10589: sections with students and sections containing other roles.
10590: Incoming parameters: 
10591: 
10592: 1. domain
10593: 2. course number 
10594: 3. reference to array containing roles for which sections should 
10595: be gathered (optional).
10596: 4. reference to array containing status types for which sections 
10597: should be gathered (optional).
10598: 
10599: If the third argument is undefined, sections are gathered for any role. 
10600: If the fourth argument is undefined, sections are gathered for any status.
10601: Permissible values are 'active' or 'future' or 'previous'.
10602:  
10603: Returns section hash (keys are section IDs, values are
10604: number of users in each section), subject to the
10605: optional roles filter, optional status filter 
10606: 
10607: =cut
10608: 
10609: ###############################################
10610: sub get_sections {
10611:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
10612:     if (!defined($cdom) || !defined($cnum)) {
10613:         my $cid =  $env{'request.course.id'};
10614: 
10615: 	return if (!defined($cid));
10616: 
10617:         $cdom = $env{'course.'.$cid.'.domain'};
10618:         $cnum = $env{'course.'.$cid.'.num'};
10619:     }
10620: 
10621:     my %sectioncount;
10622:     my $now = time;
10623: 
10624:     my $check_students = 1;
10625:     my $only_students = 0;
10626:     if (ref($possible_roles) eq 'ARRAY') {
10627:         if (grep(/^st$/,@{$possible_roles})) {
10628:             if (@{$possible_roles} == 1) {
10629:                 $only_students = 1;
10630:             }
10631:         } else {
10632:             $check_students = 0;
10633:         }
10634:     }
10635: 
10636:     if ($check_students) { 
10637: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
10638: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
10639: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
10640:         my $start_index = &Apache::loncoursedata::CL_START();
10641:         my $end_index = &Apache::loncoursedata::CL_END();
10642:         my $status;
10643: 	while (my ($student,$data) = each(%$classlist)) {
10644: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
10645: 				                     $data->[$status_index],
10646:                                                      $data->[$start_index],
10647:                                                      $data->[$end_index]);
10648:             if ($stu_status eq 'Active') {
10649:                 $status = 'active';
10650:             } elsif ($end < $now) {
10651:                 $status = 'previous';
10652:             } elsif ($start > $now) {
10653:                 $status = 'future';
10654:             } 
10655: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
10656:                 if ((!defined($possible_status)) || (($status ne '') && 
10657:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
10658: 		    $sectioncount{$section}++;
10659:                 }
10660: 	    }
10661: 	}
10662:     }
10663:     if ($only_students) {
10664:         return %sectioncount;
10665:     }
10666:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10667:     foreach my $user (sort(keys(%courseroles))) {
10668: 	if ($user !~ /^(\w{2})/) { next; }
10669: 	my ($role) = ($user =~ /^(\w{2})/);
10670: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
10671: 	my ($section,$status);
10672: 	if ($role eq 'cr' &&
10673: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
10674: 	    $section=$1;
10675: 	}
10676: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
10677: 	if (!defined($section) || $section eq '-1') { next; }
10678:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
10679:         if ($end == -1 && $start == -1) {
10680:             next; #deleted role
10681:         }
10682:         if (!defined($possible_status)) { 
10683:             $sectioncount{$section}++;
10684:         } else {
10685:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
10686:                 $status = 'active';
10687:             } elsif ($end < $now) {
10688:                 $status = 'future';
10689:             } elsif ($start > $now) {
10690:                 $status = 'previous';
10691:             }
10692:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
10693:                 $sectioncount{$section}++;
10694:             }
10695:         }
10696:     }
10697:     return %sectioncount;
10698: }
10699: 
10700: ###############################################
10701: 
10702: =pod
10703: 
10704: =item * &get_course_users()
10705: 
10706: Retrieves usernames:domains for users in the specified course
10707: with specific role(s), and access status. 
10708: 
10709: Incoming parameters:
10710: 1. course domain
10711: 2. course number
10712: 3. access status: users must have - either active, 
10713: previous, future, or all.
10714: 4. reference to array of permissible roles
10715: 5. reference to array of section restrictions (optional)
10716: 6. reference to results object (hash of hashes).
10717: 7. reference to optional userdata hash
10718: 8. reference to optional statushash
10719: 9. flag if privileged users (except those set to unhide in
10720:    course settings) should be excluded    
10721: Keys of top level results hash are roles.
10722: Keys of inner hashes are username:domain, with 
10723: values set to access type.
10724: Optional userdata hash returns an array with arguments in the 
10725: same order as loncoursedata::get_classlist() for student data.
10726: 
10727: Optional statushash returns
10728: 
10729: Entries for end, start, section and status are blank because
10730: of the possibility of multiple values for non-student roles.
10731: 
10732: =cut
10733: 
10734: ###############################################
10735: 
10736: sub get_course_users {
10737:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
10738:     my %idx = ();
10739:     my %seclists;
10740: 
10741:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
10742:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
10743:     $idx{end} = &Apache::loncoursedata::CL_END();
10744:     $idx{start} = &Apache::loncoursedata::CL_START();
10745:     $idx{id} = &Apache::loncoursedata::CL_ID();
10746:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
10747:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
10748:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
10749: 
10750:     if (grep(/^st$/,@{$roles})) {
10751:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
10752:         my $now = time;
10753:         foreach my $student (keys(%{$classlist})) {
10754:             my $match = 0;
10755:             my $secmatch = 0;
10756:             my $section = $$classlist{$student}[$idx{section}];
10757:             my $status = $$classlist{$student}[$idx{status}];
10758:             if ($section eq '') {
10759:                 $section = 'none';
10760:             }
10761:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
10762:                 if (grep(/^all$/,@{$sections})) {
10763:                     $secmatch = 1;
10764:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
10765:                     if (grep(/^none$/,@{$sections})) {
10766:                         $secmatch = 1;
10767:                     }
10768:                 } else {  
10769: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
10770: 		        $secmatch = 1;
10771:                     }
10772: 		}
10773:                 if (!$secmatch) {
10774:                     next;
10775:                 }
10776:             }
10777:             if (defined($$types{'active'})) {
10778:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
10779:                     push(@{$$users{st}{$student}},'active');
10780:                     $match = 1;
10781:                 }
10782:             }
10783:             if (defined($$types{'previous'})) {
10784:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
10785:                     push(@{$$users{st}{$student}},'previous');
10786:                     $match = 1;
10787:                 }
10788:             }
10789:             if (defined($$types{'future'})) {
10790:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
10791:                     push(@{$$users{st}{$student}},'future');
10792:                     $match = 1;
10793:                 }
10794:             }
10795:             if ($match) {
10796:                 push(@{$seclists{$student}},$section);
10797:                 if (ref($userdata) eq 'HASH') {
10798:                     $$userdata{$student} = $$classlist{$student};
10799:                 }
10800:                 if (ref($statushash) eq 'HASH') {
10801:                     $statushash->{$student}{'st'}{$section} = $status;
10802:                 }
10803:             }
10804:         }
10805:     }
10806:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
10807:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10808:         my $now = time;
10809:         my %displaystatus = ( previous => 'Expired',
10810:                               active   => 'Active',
10811:                               future   => 'Future',
10812:                             );
10813:         my (%nothide,@possdoms);
10814:         if ($hidepriv) {
10815:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
10816:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
10817:                 if ($user !~ /:/) {
10818:                     $nothide{join(':',split(/[\@]/,$user))}=1;
10819:                 } else {
10820:                     $nothide{$user} = 1;
10821:                 }
10822:             }
10823:             my @possdoms = ($cdom);
10824:             if ($coursehash{'checkforpriv'}) {
10825:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
10826:             }
10827:         }
10828:         foreach my $person (sort(keys(%coursepersonnel))) {
10829:             my $match = 0;
10830:             my $secmatch = 0;
10831:             my $status;
10832:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
10833:             $user =~ s/:$//;
10834:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
10835:             if ($end == -1 || $start == -1) {
10836:                 next;
10837:             }
10838:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
10839:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
10840:                 my ($uname,$udom) = split(/:/,$user);
10841:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
10842:                     if (grep(/^all$/,@{$sections})) {
10843:                         $secmatch = 1;
10844:                     } elsif ($usec eq '') {
10845:                         if (grep(/^none$/,@{$sections})) {
10846:                             $secmatch = 1;
10847:                         }
10848:                     } else {
10849:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
10850:                             $secmatch = 1;
10851:                         }
10852:                     }
10853:                     if (!$secmatch) {
10854:                         next;
10855:                     }
10856:                 }
10857:                 if ($usec eq '') {
10858:                     $usec = 'none';
10859:                 }
10860:                 if ($uname ne '' && $udom ne '') {
10861:                     if ($hidepriv) {
10862:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
10863:                             (!$nothide{$uname.':'.$udom})) {
10864:                             next;
10865:                         }
10866:                     }
10867:                     if ($end > 0 && $end < $now) {
10868:                         $status = 'previous';
10869:                     } elsif ($start > $now) {
10870:                         $status = 'future';
10871:                     } else {
10872:                         $status = 'active';
10873:                     }
10874:                     foreach my $type (keys(%{$types})) { 
10875:                         if ($status eq $type) {
10876:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
10877:                                 push(@{$$users{$role}{$user}},$type);
10878:                             }
10879:                             $match = 1;
10880:                         }
10881:                     }
10882:                     if (($match) && (ref($userdata) eq 'HASH')) {
10883:                         if (!exists($$userdata{$uname.':'.$udom})) {
10884: 			    &get_user_info($udom,$uname,\%idx,$userdata);
10885:                         }
10886:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
10887:                             push(@{$seclists{$uname.':'.$udom}},$usec);
10888:                         }
10889:                         if (ref($statushash) eq 'HASH') {
10890:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
10891:                         }
10892:                     }
10893:                 }
10894:             }
10895:         }
10896:         if (grep(/^ow$/,@{$roles})) {
10897:             if ((defined($cdom)) && (defined($cnum))) {
10898:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
10899:                 if ( defined($csettings{'internal.courseowner'}) ) {
10900:                     my $owner = $csettings{'internal.courseowner'};
10901:                     next if ($owner eq '');
10902:                     my ($ownername,$ownerdom);
10903:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
10904:                         $ownername = $1;
10905:                         $ownerdom = $2;
10906:                     } else {
10907:                         $ownername = $owner;
10908:                         $ownerdom = $cdom;
10909:                         $owner = $ownername.':'.$ownerdom;
10910:                     }
10911:                     @{$$users{'ow'}{$owner}} = 'any';
10912:                     if (defined($userdata) && 
10913: 			!exists($$userdata{$owner})) {
10914: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
10915:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
10916:                             push(@{$seclists{$owner}},'none');
10917:                         }
10918:                         if (ref($statushash) eq 'HASH') {
10919:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
10920:                         }
10921: 		    }
10922:                 }
10923:             }
10924:         }
10925:         foreach my $user (keys(%seclists)) {
10926:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
10927:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
10928:         }
10929:     }
10930:     return;
10931: }
10932: 
10933: sub get_user_info {
10934:     my ($udom,$uname,$idx,$userdata) = @_;
10935:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
10936: 	&plainname($uname,$udom,'lastname');
10937:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
10938:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
10939:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
10940:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
10941:     return;
10942: }
10943: 
10944: ###############################################
10945: 
10946: =pod
10947: 
10948: =item * &get_user_quota()
10949: 
10950: Retrieves quota assigned for storage of user files.
10951: Default is to report quota for portfolio files.
10952: 
10953: Incoming parameters:
10954: 1. user's username
10955: 2. user's domain
10956: 3. quota name - portfolio, author, or course
10957:    (if no quota name provided, defaults to portfolio).
10958: 4. crstype - official, unofficial, textbook, placement or community, 
10959:    if quota name is course
10960: 
10961: Returns:
10962: 1. Disk quota (in MB) assigned to student.
10963: 2. (Optional) Type of setting: custom or default
10964:    (individually assigned or default for user's 
10965:    institutional status).
10966: 3. (Optional) - User's institutional status (e.g., faculty, staff
10967:    or student - types as defined in localenroll::inst_usertypes 
10968:    for user's domain, which determines default quota for user.
10969: 4. (Optional) - Default quota which would apply to the user.
10970: 
10971: If a value has been stored in the user's environment, 
10972: it will return that, otherwise it returns the maximal default
10973: defined for the user's institutional status(es) in the domain.
10974: 
10975: =cut
10976: 
10977: ###############################################
10978: 
10979: 
10980: sub get_user_quota {
10981:     my ($uname,$udom,$quotaname,$crstype) = @_;
10982:     my ($quota,$quotatype,$settingstatus,$defquota);
10983:     if (!defined($udom)) {
10984:         $udom = $env{'user.domain'};
10985:     }
10986:     if (!defined($uname)) {
10987:         $uname = $env{'user.name'};
10988:     }
10989:     if (($udom eq '' || $uname eq '') ||
10990:         ($udom eq 'public') && ($uname eq 'public')) {
10991:         $quota = 0;
10992:         $quotatype = 'default';
10993:         $defquota = 0; 
10994:     } else {
10995:         my $inststatus;
10996:         if ($quotaname eq 'course') {
10997:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
10998:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
10999:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
11000:             } else {
11001:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
11002:                 $quota = $cenv{'internal.uploadquota'};
11003:             }
11004:         } else {
11005:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
11006:                 if ($quotaname eq 'author') {
11007:                     $quota = $env{'environment.authorquota'};
11008:                 } else {
11009:                     $quota = $env{'environment.portfolioquota'};
11010:                 }
11011:                 $inststatus = $env{'environment.inststatus'};
11012:             } else {
11013:                 my %userenv = 
11014:                     &Apache::lonnet::get('environment',['portfolioquota',
11015:                                          'authorquota','inststatus'],$udom,$uname);
11016:                 my ($tmp) = keys(%userenv);
11017:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11018:                     if ($quotaname eq 'author') {
11019:                         $quota = $userenv{'authorquota'};
11020:                     } else {
11021:                         $quota = $userenv{'portfolioquota'};
11022:                     }
11023:                     $inststatus = $userenv{'inststatus'};
11024:                 } else {
11025:                     undef(%userenv);
11026:                 }
11027:             }
11028:         }
11029:         if ($quota eq '' || wantarray) {
11030:             if ($quotaname eq 'course') {
11031:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
11032:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
11033:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
11034:                     ($crstype eq 'placement')) { 
11035:                     $defquota = $domdefs{$crstype.'quota'};
11036:                 }
11037:                 if ($defquota eq '') {
11038:                     $defquota = 500;
11039:                 }
11040:             } else {
11041:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
11042:             }
11043:             if ($quota eq '') {
11044:                 $quota = $defquota;
11045:                 $quotatype = 'default';
11046:             } else {
11047:                 $quotatype = 'custom';
11048:             }
11049:         }
11050:     }
11051:     if (wantarray) {
11052:         return ($quota,$quotatype,$settingstatus,$defquota);
11053:     } else {
11054:         return $quota;
11055:     }
11056: }
11057: 
11058: ###############################################
11059: 
11060: =pod
11061: 
11062: =item * &default_quota()
11063: 
11064: Retrieves default quota assigned for storage of user portfolio files,
11065: given an (optional) user's institutional status.
11066: 
11067: Incoming parameters:
11068: 
11069: 1. domain
11070: 2. (Optional) institutional status(es).  This is a : separated list of 
11071:    status types (e.g., faculty, staff, student etc.)
11072:    which apply to the user for whom the default is being retrieved.
11073:    If the institutional status string in undefined, the domain
11074:    default quota will be returned.
11075: 3.  quota name - portfolio, author, or course
11076:    (if no quota name provided, defaults to portfolio).
11077: 
11078: Returns:
11079: 
11080: 1. Default disk quota (in MB) for user portfolios in the domain.
11081: 2. (Optional) institutional type which determined the value of the
11082:    default quota.
11083: 
11084: If a value has been stored in the domain's configuration db,
11085: it will return that, otherwise it returns 20 (for backwards 
11086: compatibility with domains which have not set up a configuration
11087: db file; the original statically defined portfolio quota was 20 MB). 
11088: 
11089: If the user's status includes multiple types (e.g., staff and student),
11090: the largest default quota which applies to the user determines the
11091: default quota returned.
11092: 
11093: =cut
11094: 
11095: ###############################################
11096: 
11097: 
11098: sub default_quota {
11099:     my ($udom,$inststatus,$quotaname) = @_;
11100:     my ($defquota,$settingstatus);
11101:     my %quotahash = &Apache::lonnet::get_dom('configuration',
11102:                                             ['quotas'],$udom);
11103:     my $key = 'defaultquota';
11104:     if ($quotaname eq 'author') {
11105:         $key = 'authorquota';
11106:     }
11107:     if (ref($quotahash{'quotas'}) eq 'HASH') {
11108:         if ($inststatus ne '') {
11109:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
11110:             foreach my $item (@statuses) {
11111:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
11112:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
11113:                         if ($defquota eq '') {
11114:                             $defquota = $quotahash{'quotas'}{$key}{$item};
11115:                             $settingstatus = $item;
11116:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
11117:                             $defquota = $quotahash{'quotas'}{$key}{$item};
11118:                             $settingstatus = $item;
11119:                         }
11120:                     }
11121:                 } elsif ($key eq 'defaultquota') {
11122:                     if ($quotahash{'quotas'}{$item} ne '') {
11123:                         if ($defquota eq '') {
11124:                             $defquota = $quotahash{'quotas'}{$item};
11125:                             $settingstatus = $item;
11126:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
11127:                             $defquota = $quotahash{'quotas'}{$item};
11128:                             $settingstatus = $item;
11129:                         }
11130:                     }
11131:                 }
11132:             }
11133:         }
11134:         if ($defquota eq '') {
11135:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
11136:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
11137:             } elsif ($key eq 'defaultquota') {
11138:                 $defquota = $quotahash{'quotas'}{'default'};
11139:             }
11140:             $settingstatus = 'default';
11141:             if ($defquota eq '') {
11142:                 if ($quotaname eq 'author') {
11143:                     $defquota = 500;
11144:                 }
11145:             }
11146:         }
11147:     } else {
11148:         $settingstatus = 'default';
11149:         if ($quotaname eq 'author') {
11150:             $defquota = 500;
11151:         } else {
11152:             $defquota = 20;
11153:         }
11154:     }
11155:     if (wantarray) {
11156:         return ($defquota,$settingstatus);
11157:     } else {
11158:         return $defquota;
11159:     }
11160: }
11161: 
11162: ###############################################
11163: 
11164: =pod
11165: 
11166: =item * &excess_filesize_warning()
11167: 
11168: Returns warning message if upload of file to authoring space, or copying
11169: of existing file within authoring space will cause quota for the authoring
11170: space to be exceeded.
11171: 
11172: Same, if upload of a file directly to a course/community via Course Editor
11173: will cause quota for uploaded content for the course to be exceeded.
11174: 
11175: Inputs: 7 
11176: 1. username or coursenum
11177: 2. domain
11178: 3. context ('author' or 'course')
11179: 4. filename of file for which action is being requested
11180: 5. filesize (kB) of file
11181: 6. action being taken: copy or upload.
11182: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
11183: 
11184: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
11185:          otherwise return null.
11186: 
11187: =back
11188: 
11189: =cut
11190: 
11191: sub excess_filesize_warning {
11192:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
11193:     my $current_disk_usage = 0;
11194:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
11195:     if ($context eq 'author') {
11196:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
11197:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
11198:     } else {
11199:         foreach my $subdir ('docs','supplemental') {
11200:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
11201:         }
11202:     }
11203:     $disk_quota = int($disk_quota * 1000);
11204:     if (($current_disk_usage + $filesize) > $disk_quota) {
11205:         return '<p class="LC_warning">'.
11206:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
11207:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
11208:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
11209:                             $disk_quota,$current_disk_usage).
11210:                '</p>';
11211:     }
11212:     return;
11213: }
11214: 
11215: ###############################################
11216: 
11217: 
11218: 
11219: 
11220: sub get_secgrprole_info {
11221:     my ($cdom,$cnum,$needroles,$type)  = @_;
11222:     my %sections_count = &get_sections($cdom,$cnum);
11223:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
11224:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
11225:     my @groups = sort(keys(%curr_groups));
11226:     my $allroles = [];
11227:     my $rolehash;
11228:     my $accesshash = {
11229:                      active => 'Currently has access',
11230:                      future => 'Will have future access',
11231:                      previous => 'Previously had access',
11232:                   };
11233:     if ($needroles) {
11234:         $rolehash = {'all' => 'all'};
11235:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
11236: 	if (&Apache::lonnet::error(%user_roles)) {
11237: 	    undef(%user_roles);
11238: 	}
11239:         foreach my $item (keys(%user_roles)) {
11240:             my ($role)=split(/\:/,$item,2);
11241:             if ($role eq 'cr') { next; }
11242:             if ($role =~ /^cr/) {
11243:                 $$rolehash{$role} = (split('/',$role))[3];
11244:             } else {
11245:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
11246:             }
11247:         }
11248:         foreach my $key (sort(keys(%{$rolehash}))) {
11249:             push(@{$allroles},$key);
11250:         }
11251:         push (@{$allroles},'st');
11252:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
11253:     }
11254:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
11255: }
11256: 
11257: sub user_picker {
11258:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
11259:     my $currdom = $dom;
11260:     my @alldoms = &Apache::lonnet::all_domains();
11261:     if (@alldoms == 1) {
11262:         my %domsrch = &Apache::lonnet::get_dom('configuration',
11263:                                                ['directorysrch'],$alldoms[0]);
11264:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
11265:         my $showdom = $domdesc;
11266:         if ($showdom eq '') {
11267:             $showdom = $dom;
11268:         }
11269:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
11270:             if ((!$domsrch{'directorysrch'}{'available'}) &&
11271:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
11272:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
11273:             }
11274:         }
11275:     }
11276:     my %curr_selected = (
11277:                         srchin => 'dom',
11278:                         srchby => 'lastname',
11279:                       );
11280:     my $srchterm;
11281:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
11282:         if ($srch->{'srchby'} ne '') {
11283:             $curr_selected{'srchby'} = $srch->{'srchby'};
11284:         }
11285:         if ($srch->{'srchin'} ne '') {
11286:             $curr_selected{'srchin'} = $srch->{'srchin'};
11287:         }
11288:         if ($srch->{'srchtype'} ne '') {
11289:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
11290:         }
11291:         if ($srch->{'srchdomain'} ne '') {
11292:             $currdom = $srch->{'srchdomain'};
11293:         }
11294:         $srchterm = $srch->{'srchterm'};
11295:     }
11296:     my %html_lt=&Apache::lonlocal::texthash(
11297:                     'usr'       => 'Search criteria',
11298:                     'doma'      => 'Domain/institution to search',
11299:                     'uname'     => 'username',
11300:                     'lastname'  => 'last name',
11301:                     'lastfirst' => 'last name, first name',
11302:                     'crs'       => 'in this course',
11303:                     'dom'       => 'in selected LON-CAPA domain', 
11304:                     'alc'       => 'all LON-CAPA',
11305:                     'instd'     => 'in institutional directory for selected domain',
11306:                     'exact'     => 'is',
11307:                     'contains'  => 'contains',
11308:                     'begins'    => 'begins with',
11309:                                        );
11310:     my %js_lt=&Apache::lonlocal::texthash(
11311:                     'youm'      => "You must include some text to search for.",
11312:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
11313:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
11314:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
11315:                     'ymcd'      => "You must choose a domain when using a domain search.",
11316:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
11317:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
11318:                      'thfo'     => "The following need to be corrected before the search can be run:",
11319:                                        );
11320:     &html_escape(\%html_lt);
11321:     &js_escape(\%js_lt);
11322:     my $domform;
11323:     my $allow_blank = 1;
11324:     if ($fixeddom) {
11325:         $allow_blank = 0;
11326:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
11327:     } else {
11328:         my $defdom = $env{'request.role.domain'};
11329:         my ($trusted,$untrusted);
11330:         if (($context eq 'requestcrs') || ($context eq 'course')) {
11331:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
11332:         } elsif ($context eq 'author') {
11333:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
11334:         } elsif ($context eq 'domain') {
11335:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
11336:         }
11337:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
11338:     }
11339:     my $srchinsel = ' <select name="srchin">';
11340: 
11341:     my @srchins = ('crs','dom','alc','instd');
11342: 
11343:     foreach my $option (@srchins) {
11344:         # FIXME 'alc' option unavailable until 
11345:         #       loncreateuser::print_user_query_page()
11346:         #       has been completed.
11347:         next if ($option eq 'alc');
11348:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
11349:         next if ($option eq 'crs' && !$env{'request.course.id'});
11350:         next if (($option eq 'instd') && ($noinstd));
11351:         if ($curr_selected{'srchin'} eq $option) {
11352:             $srchinsel .= ' 
11353:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
11354:         } else {
11355:             $srchinsel .= '
11356:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
11357:         }
11358:     }
11359:     $srchinsel .= "\n  </select>\n";
11360: 
11361:     my $srchbysel =  ' <select name="srchby">';
11362:     foreach my $option ('lastname','lastfirst','uname') {
11363:         if ($curr_selected{'srchby'} eq $option) {
11364:             $srchbysel .= '
11365:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
11366:         } else {
11367:             $srchbysel .= '
11368:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
11369:          }
11370:     }
11371:     $srchbysel .= "\n  </select>\n";
11372: 
11373:     my $srchtypesel = ' <select name="srchtype">';
11374:     foreach my $option ('begins','contains','exact') {
11375:         if ($curr_selected{'srchtype'} eq $option) {
11376:             $srchtypesel .= '
11377:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
11378:         } else {
11379:             $srchtypesel .= '
11380:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
11381:         }
11382:     }
11383:     $srchtypesel .= "\n  </select>\n";
11384: 
11385:     my ($newuserscript,$new_user_create);
11386:     my $context_dom = $env{'request.role.domain'};
11387:     if ($context eq 'requestcrs') {
11388:         if ($env{'form.coursedom'} ne '') { 
11389:             $context_dom = $env{'form.coursedom'};
11390:         }
11391:     }
11392:     if ($forcenewuser) {
11393:         if (ref($srch) eq 'HASH') {
11394:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
11395:                 if ($cancreate) {
11396:                     $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>';
11397:                 } else {
11398:                     my $helplink = 'javascript:helpMenu('."'display'".')';
11399:                     my %usertypetext = (
11400:                         official   => 'institutional',
11401:                         unofficial => 'non-institutional',
11402:                     );
11403:                     $new_user_create = '<p class="LC_warning">'
11404:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
11405:                                       .' '
11406:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
11407:                                           ,'<a href="'.$helplink.'">','</a>')
11408:                                       .'</p><br />';
11409:                 }
11410:             }
11411:         }
11412: 
11413:         $newuserscript = <<"ENDSCRIPT";
11414: 
11415: function setSearch(createnew,callingForm) {
11416:     if (createnew == 1) {
11417:         for (var i=0; i<callingForm.srchby.length; i++) {
11418:             if (callingForm.srchby.options[i].value == 'uname') {
11419:                 callingForm.srchby.selectedIndex = i;
11420:             }
11421:         }
11422:         for (var i=0; i<callingForm.srchin.length; i++) {
11423:             if ( callingForm.srchin.options[i].value == 'dom') {
11424: 		callingForm.srchin.selectedIndex = i;
11425:             }
11426:         }
11427:         for (var i=0; i<callingForm.srchtype.length; i++) {
11428:             if (callingForm.srchtype.options[i].value == 'exact') {
11429:                 callingForm.srchtype.selectedIndex = i;
11430:             }
11431:         }
11432:         for (var i=0; i<callingForm.srchdomain.length; i++) {
11433:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
11434:                 callingForm.srchdomain.selectedIndex = i;
11435:             }
11436:         }
11437:     }
11438: }
11439: ENDSCRIPT
11440: 
11441:     }
11442: 
11443:     my $output = <<"END_BLOCK";
11444: <script type="text/javascript">
11445: // <![CDATA[
11446: function validateEntry(callingForm) {
11447: 
11448:     var checkok = 1;
11449:     var srchin;
11450:     for (var i=0; i<callingForm.srchin.length; i++) {
11451: 	if ( callingForm.srchin[i].checked ) {
11452: 	    srchin = callingForm.srchin[i].value;
11453: 	}
11454:     }
11455: 
11456:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
11457:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
11458:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
11459:     var srchterm =  callingForm.srchterm.value;
11460:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
11461:     var msg = "";
11462: 
11463:     if (srchterm == "") {
11464:         checkok = 0;
11465:         msg += "$js_lt{'youm'}\\n";
11466:     }
11467: 
11468:     if (srchtype== 'begins') {
11469:         if (srchterm.length < 2) {
11470:             checkok = 0;
11471:             msg += "$js_lt{'thte'}\\n";
11472:         }
11473:     }
11474: 
11475:     if (srchtype== 'contains') {
11476:         if (srchterm.length < 3) {
11477:             checkok = 0;
11478:             msg += "$js_lt{'thet'}\\n";
11479:         }
11480:     }
11481:     if (srchin == 'instd') {
11482:         if (srchdomain == '') {
11483:             checkok = 0;
11484:             msg += "$js_lt{'yomc'}\\n";
11485:         }
11486:     }
11487:     if (srchin == 'dom') {
11488:         if (srchdomain == '') {
11489:             checkok = 0;
11490:             msg += "$js_lt{'ymcd'}\\n";
11491:         }
11492:     }
11493:     if (srchby == 'lastfirst') {
11494:         if (srchterm.indexOf(",") == -1) {
11495:             checkok = 0;
11496:             msg += "$js_lt{'whus'}\\n";
11497:         }
11498:         if (srchterm.indexOf(",") == srchterm.length -1) {
11499:             checkok = 0;
11500:             msg += "$js_lt{'whse'}\\n";
11501:         }
11502:     }
11503:     if (checkok == 0) {
11504:         alert("$js_lt{'thfo'}\\n"+msg);
11505:         return;
11506:     }
11507:     if (checkok == 1) {
11508:         callingForm.submit();
11509:     }
11510: }
11511: 
11512: $newuserscript
11513: 
11514: // ]]>
11515: </script>
11516: 
11517: $new_user_create
11518: 
11519: END_BLOCK
11520: 
11521:     $output .= &Apache::lonhtmlcommon::start_pick_box().
11522:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
11523:                $domform.
11524:                &Apache::lonhtmlcommon::row_closure().
11525:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
11526:                $srchbysel.
11527:                $srchtypesel. 
11528:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
11529:                $srchinsel.
11530:                &Apache::lonhtmlcommon::row_closure(1). 
11531:                &Apache::lonhtmlcommon::end_pick_box().
11532:                '<br />';
11533:     return ($output,1);
11534: }
11535: 
11536: sub user_rule_check {
11537:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
11538:     my ($response,%inst_response);
11539:     if (ref($usershash) eq 'HASH') {
11540:         if (keys(%{$usershash}) > 1) {
11541:             my (%by_username,%by_id,%userdoms);
11542:             my $checkid; 
11543:             if (ref($checks) eq 'HASH') {
11544:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
11545:                     $checkid = 1;
11546:                 }
11547:             }
11548:             foreach my $user (keys(%{$usershash})) {
11549:                 my ($uname,$udom) = split(/:/,$user);
11550:                 if ($checkid) {
11551:                     if (ref($usershash->{$user}) eq 'HASH') {
11552:                         if ($usershash->{$user}->{'id'} ne '') {
11553:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
11554:                             $userdoms{$udom} = 1;
11555:                             if (ref($inst_results) eq 'HASH') {
11556:                                 $inst_results->{$uname.':'.$udom} = {};
11557:                             }
11558:                         }
11559:                     }
11560:                 } else {
11561:                     $by_username{$udom}{$uname} = 1;
11562:                     $userdoms{$udom} = 1;
11563:                     if (ref($inst_results) eq 'HASH') {
11564:                         $inst_results->{$uname.':'.$udom} = {};
11565:                     }
11566:                 }
11567:             }
11568:             foreach my $udom (keys(%userdoms)) {
11569:                 if (!$got_rules->{$udom}) {
11570:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
11571:                                                              ['usercreation'],$udom);
11572:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
11573:                         foreach my $item ('username','id') {
11574:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
11575:                                 $$curr_rules{$udom}{$item} =
11576:                                     $domconfig{'usercreation'}{$item.'_rule'};
11577:                             }
11578:                         }
11579:                     }
11580:                     $got_rules->{$udom} = 1;
11581:                 }
11582:             }
11583:             if ($checkid) {
11584:                 foreach my $udom (keys(%by_id)) {
11585:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
11586:                     if ($outcome eq 'ok') {
11587:                         foreach my $id (keys(%{$by_id{$udom}})) {
11588:                             my $uname = $by_id{$udom}{$id};
11589:                             $inst_response{$uname.':'.$udom} = $outcome;
11590:                         }
11591:                         if (ref($results) eq 'HASH') {
11592:                             foreach my $uname (keys(%{$results})) {
11593:                                 if (exists($inst_response{$uname.':'.$udom})) {
11594:                                     $inst_response{$uname.':'.$udom} = $outcome;
11595:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
11596:                                 }
11597:                             }
11598:                         }
11599:                     }
11600:                 }
11601:             } else {
11602:                 foreach my $udom (keys(%by_username)) {
11603:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
11604:                     if ($outcome eq 'ok') {
11605:                         foreach my $uname (keys(%{$by_username{$udom}})) {
11606:                             $inst_response{$uname.':'.$udom} = $outcome;
11607:                         }
11608:                         if (ref($results) eq 'HASH') {
11609:                             foreach my $uname (keys(%{$results})) {
11610:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
11611:                             }
11612:                         }
11613:                     }
11614:                 }
11615:             }
11616:         } elsif (keys(%{$usershash}) == 1) {
11617:             my $user = (keys(%{$usershash}))[0];
11618:             my ($uname,$udom) = split(/:/,$user);
11619:             if (($udom ne '') && ($uname ne '')) {
11620:                 if (ref($usershash->{$user}) eq 'HASH') {
11621:                     if (ref($checks) eq 'HASH') {
11622:                         if (defined($checks->{'username'})) {
11623:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
11624:                                 &Apache::lonnet::get_instuser($udom,$uname);
11625:                         } elsif (defined($checks->{'id'})) {
11626:                             if ($usershash->{$user}->{'id'} ne '') {
11627:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
11628:                                     &Apache::lonnet::get_instuser($udom,undef,
11629:                                                                   $usershash->{$user}->{'id'});
11630:                             } else {
11631:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
11632:                                     &Apache::lonnet::get_instuser($udom,$uname);
11633:                             }
11634:                         }
11635:                     } else {
11636:                        ($inst_response{$user},%{$inst_results->{$user}}) =
11637:                             &Apache::lonnet::get_instuser($udom,$uname);
11638:                        return;
11639:                     }
11640:                     if (!$got_rules->{$udom}) {
11641:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
11642:                                                                  ['usercreation'],$udom);
11643:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
11644:                             foreach my $item ('username','id') {
11645:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
11646:                                    $$curr_rules{$udom}{$item} = 
11647:                                        $domconfig{'usercreation'}{$item.'_rule'};
11648:                                 }
11649:                             }
11650:                         }
11651:                         $got_rules->{$udom} = 1;
11652:                     }
11653:                 }
11654:             } else {
11655:                 return;
11656:             }
11657:         } else {
11658:             return;
11659:         }
11660:         foreach my $user (keys(%{$usershash})) {
11661:             my ($uname,$udom) = split(/:/,$user);
11662:             next if (($udom eq '') || ($uname eq ''));
11663:             my $id;
11664:             if (ref($inst_results) eq 'HASH') {
11665:                 if (ref($inst_results->{$user}) eq 'HASH') {
11666:                     $id = $inst_results->{$user}->{'id'};
11667:                 }
11668:             }
11669:             if ($id eq '') { 
11670:                 if (ref($usershash->{$user})) {
11671:                     $id = $usershash->{$user}->{'id'};
11672:                 }
11673:             }
11674:             foreach my $item (keys(%{$checks})) {
11675:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
11676:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
11677:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
11678:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
11679:                                                                              $$curr_rules{$udom}{$item});
11680:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
11681:                                 if ($rule_check{$rule}) {
11682:                                     $$rulematch{$user}{$item} = $rule;
11683:                                     if ($inst_response{$user} eq 'ok') {
11684:                                         if (ref($inst_results) eq 'HASH') {
11685:                                             if (ref($inst_results->{$user}) eq 'HASH') {
11686:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
11687:                                                     $$alerts{$item}{$udom}{$uname} = 1;
11688:                                                 } elsif ($item eq 'id') {
11689:                                                     if ($inst_results->{$user}->{'id'} eq '') {
11690:                                                         $$alerts{$item}{$udom}{$uname} = 1;
11691:                                                     }
11692:                                                 }
11693:                                             }
11694:                                         }
11695:                                     }
11696:                                     last;
11697:                                 }
11698:                             }
11699:                         }
11700:                     }
11701:                 }
11702:             }
11703:         }
11704:     }
11705:     return;
11706: }
11707: 
11708: sub user_rule_formats {
11709:     my ($domain,$domdesc,$curr_rules,$check) = @_;
11710:     my %text = ( 
11711:                  'username' => 'Usernames',
11712:                  'id'       => 'IDs',
11713:                );
11714:     my $output;
11715:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
11716:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
11717:         if (@{$ruleorder} > 0) {
11718:             $output = '<br />'.
11719:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
11720:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
11721:                       ' <ul>';
11722:             foreach my $rule (@{$ruleorder}) {
11723:                 if (ref($curr_rules) eq 'ARRAY') {
11724:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
11725:                         if (ref($rules->{$rule}) eq 'HASH') {
11726:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
11727:                                         $rules->{$rule}{'desc'}.'</li>';
11728:                         }
11729:                     }
11730:                 }
11731:             }
11732:             $output .= '</ul>';
11733:         }
11734:     }
11735:     return $output;
11736: }
11737: 
11738: sub instrule_disallow_msg {
11739:     my ($checkitem,$domdesc,$count,$mode) = @_;
11740:     my $response;
11741:     my %text = (
11742:                   item   => 'username',
11743:                   items  => 'usernames',
11744:                   match  => 'matches',
11745:                   do     => 'does',
11746:                   action => 'a username',
11747:                   one    => 'one',
11748:                );
11749:     if ($count > 1) {
11750:         $text{'item'} = 'usernames';
11751:         $text{'match'} ='match';
11752:         $text{'do'} = 'do';
11753:         $text{'action'} = 'usernames',
11754:         $text{'one'} = 'ones';
11755:     }
11756:     if ($checkitem eq 'id') {
11757:         $text{'items'} = 'IDs';
11758:         $text{'item'} = 'ID';
11759:         $text{'action'} = 'an ID';
11760:         if ($count > 1) {
11761:             $text{'item'} = 'IDs';
11762:             $text{'action'} = 'IDs';
11763:         }
11764:     }
11765:     $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 />';
11766:     if ($mode eq 'upload') {
11767:         if ($checkitem eq 'username') {
11768:             $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'}.");
11769:         } elsif ($checkitem eq 'id') {
11770:             $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.");
11771:         }
11772:     } elsif ($mode eq 'selfcreate') {
11773:         if ($checkitem eq 'id') {
11774:             $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.");
11775:         }
11776:     } else {
11777:         if ($checkitem eq 'username') {
11778:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
11779:         } elsif ($checkitem eq 'id') {
11780:             $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.");
11781:         }
11782:     }
11783:     return $response;
11784: }
11785: 
11786: sub personal_data_fieldtitles {
11787:     my %fieldtitles = &Apache::lonlocal::texthash (
11788:                         id => 'Student/Employee ID',
11789:                         permanentemail => 'E-mail address',
11790:                         lastname => 'Last Name',
11791:                         firstname => 'First Name',
11792:                         middlename => 'Middle Name',
11793:                         generation => 'Generation',
11794:                         gen => 'Generation',
11795:                         inststatus => 'Affiliation',
11796:                    );
11797:     return %fieldtitles;
11798: }
11799: 
11800: sub sorted_inst_types {
11801:     my ($dom) = @_;
11802:     my ($usertypes,$order);
11803:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
11804:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
11805:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
11806:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
11807:     } else {
11808:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
11809:     }
11810:     my $othertitle = &mt('All users');
11811:     if ($env{'request.course.id'}) {
11812:         $othertitle  = &mt('Any users');
11813:     }
11814:     my @types;
11815:     if (ref($order) eq 'ARRAY') {
11816:         @types = @{$order};
11817:     }
11818:     if (@types == 0) {
11819:         if (ref($usertypes) eq 'HASH') {
11820:             @types = sort(keys(%{$usertypes}));
11821:         }
11822:     }
11823:     if (keys(%{$usertypes}) > 0) {
11824:         $othertitle = &mt('Other users');
11825:     }
11826:     return ($othertitle,$usertypes,\@types);
11827: }
11828: 
11829: sub get_institutional_codes {
11830:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
11831: # Get complete list of course sections to update
11832:     my @currsections = ();
11833:     my @currxlists = ();
11834:     my (%unclutteredsec,%unclutteredlcsec);
11835:     my $coursecode = $$settings{'internal.coursecode'};
11836:     my $crskey = $crs.':'.$coursecode;
11837:     @{$unclutteredsec{$crskey}} = ();
11838:     @{$unclutteredlcsec{$crskey}} = ();
11839: 
11840:     if ($$settings{'internal.sectionnums'} ne '') {
11841:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
11842:     }
11843: 
11844:     if ($$settings{'internal.crosslistings'} ne '') {
11845:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
11846:     }
11847: 
11848:     if (@currxlists > 0) {
11849:         foreach my $xl (@currxlists) {
11850:             if ($xl =~ /^([^:]+):(\w*)$/) {
11851:                 unless (grep/^$1$/,@{$allcourses}) {
11852:                     push(@{$allcourses},$1);
11853:                     $$LC_code{$1} = $2;
11854:                 }
11855:             }
11856:         }
11857:     }
11858: 
11859:     if (@currsections > 0) {
11860:         foreach my $sec (@currsections) {
11861:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
11862:                 my $instsec = $1;
11863:                 my $lc_sec = $2;
11864:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
11865:                     push(@{$unclutteredsec{$crskey}},$instsec);
11866:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
11867:                 }
11868:             }
11869:         }
11870:     }
11871: 
11872:     if (@{$unclutteredsec{$crskey}} > 0) {
11873:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
11874:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
11875:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
11876:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
11877:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
11878:                     push(@{$allcourses},$sec);
11879:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
11880:                 }
11881:             }
11882:         }
11883:     }
11884:     return;
11885: }
11886: 
11887: sub get_standard_codeitems {
11888:     return ('Year','Semester','Department','Number','Section');
11889: }
11890: 
11891: =pod
11892: 
11893: =head1 Slot Helpers
11894: 
11895: =over 4
11896: 
11897: =item * sorted_slots()
11898: 
11899: Sorts an array of slot names in order of an optional sort key,
11900: default sort is by slot start time (earliest first). 
11901: 
11902: Inputs:
11903: 
11904: =over 4
11905: 
11906: slotsarr  - Reference to array of unsorted slot names.
11907: 
11908: slots     - Reference to hash of hash, where outer hash keys are slot names.
11909: 
11910: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
11911: 
11912: =back
11913: 
11914: Returns:
11915: 
11916: =over 4
11917: 
11918: sorted   - An array of slot names sorted by a specified sort key 
11919:            (default sort key is start time of the slot).
11920: 
11921: =back
11922: 
11923: =cut
11924: 
11925: 
11926: sub sorted_slots {
11927:     my ($slotsarr,$slots,$sortkey) = @_;
11928:     if ($sortkey eq '') {
11929:         $sortkey = 'starttime';
11930:     }
11931:     my @sorted;
11932:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
11933:         @sorted =
11934:             sort {
11935:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
11936:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
11937:                      }
11938:                      if (ref($slots->{$a})) { return -1;}
11939:                      if (ref($slots->{$b})) { return 1;}
11940:                      return 0;
11941:                  } @{$slotsarr};
11942:     }
11943:     return @sorted;
11944: }
11945: 
11946: =pod
11947: 
11948: =item * get_future_slots()
11949: 
11950: Inputs:
11951: 
11952: =over 4
11953: 
11954: cnum - course number
11955: 
11956: cdom - course domain
11957: 
11958: now - current UNIX time
11959: 
11960: symb - optional symb
11961: 
11962: =back
11963: 
11964: Returns:
11965: 
11966: =over 4
11967: 
11968: sorted_reservable - ref to array of student_schedulable slots currently 
11969:                     reservable, ordered by end date of reservation period.
11970: 
11971: reservable_now - ref to hash of student_schedulable slots currently
11972:                  reservable.
11973: 
11974:     Keys in inner hash are:
11975:     (a) symb: either blank or symb to which slot use is restricted.
11976:     (b) endreserve: end date of reservation period.
11977:     (c) uniqueperiod: start,end dates when slot is to be uniquely
11978:         selected.
11979: 
11980: sorted_future - ref to array of student_schedulable slots reservable in
11981:                 the future, ordered by start date of reservation period.
11982: 
11983: future_reservable - ref to hash of student_schedulable slots reservable
11984:                     in the future.
11985: 
11986:     Keys in inner hash are:
11987:     (a) symb: either blank or symb to which slot use is restricted.
11988:     (b) startreserve: start date of reservation period.
11989:     (c) uniqueperiod: start,end dates when slot is to be uniquely
11990:         selected.
11991: 
11992: =back
11993: 
11994: =cut
11995: 
11996: sub get_future_slots {
11997:     my ($cnum,$cdom,$now,$symb) = @_;
11998:     my $map;
11999:     if ($symb) {
12000:         ($map) = &Apache::lonnet::decode_symb($symb);
12001:     }
12002:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
12003:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
12004:     foreach my $slot (keys(%slots)) {
12005:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
12006:         if ($symb) {
12007:             if ($slots{$slot}->{'symb'} ne '') {
12008:                 my $canuse;
12009:                 my %oksymbs;
12010:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
12011:                 map { $oksymbs{$_} = 1; } @slotsymbs;
12012:                 if ($oksymbs{$symb}) {
12013:                     $canuse = 1;
12014:                 } else {
12015:                     foreach my $item (@slotsymbs) {
12016:                         if ($item =~ /\.(page|sequence)$/) {
12017:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
12018:                             if (($map ne '') && ($map eq $sloturl)) {
12019:                                 $canuse = 1;
12020:                                 last;
12021:                             }
12022:                         }
12023:                     }
12024:                 }
12025:                 next unless ($canuse);
12026:             }
12027:         }
12028:         if (($slots{$slot}->{'starttime'} > $now) &&
12029:             ($slots{$slot}->{'endtime'} > $now)) {
12030:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
12031:                 my $userallowed = 0;
12032:                 if ($slots{$slot}->{'allowedsections'}) {
12033:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
12034:                     if (!defined($env{'request.role.sec'})
12035:                         && grep(/^No section assigned$/,@allowed_sec)) {
12036:                         $userallowed=1;
12037:                     } else {
12038:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
12039:                             $userallowed=1;
12040:                         }
12041:                     }
12042:                     unless ($userallowed) {
12043:                         if (defined($env{'request.course.groups'})) {
12044:                             my @groups = split(/:/,$env{'request.course.groups'});
12045:                             foreach my $group (@groups) {
12046:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
12047:                                     $userallowed=1;
12048:                                     last;
12049:                                 }
12050:                             }
12051:                         }
12052:                     }
12053:                 }
12054:                 if ($slots{$slot}->{'allowedusers'}) {
12055:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
12056:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
12057:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
12058:                         $userallowed = 1;
12059:                     }
12060:                 }
12061:                 next unless($userallowed);
12062:             }
12063:             my $startreserve = $slots{$slot}->{'startreserve'};
12064:             my $endreserve = $slots{$slot}->{'endreserve'};
12065:             my $symb = $slots{$slot}->{'symb'};
12066:             my $uniqueperiod;
12067:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
12068:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
12069:             }
12070:             if (($startreserve < $now) &&
12071:                 (!$endreserve || $endreserve > $now)) {
12072:                 my $lastres = $endreserve;
12073:                 if (!$lastres) {
12074:                     $lastres = $slots{$slot}->{'starttime'};
12075:                 }
12076:                 $reservable_now{$slot} = {
12077:                                            symb       => $symb,
12078:                                            endreserve => $lastres,
12079:                                            uniqueperiod => $uniqueperiod,
12080:                                          };
12081:             } elsif (($startreserve > $now) &&
12082:                      (!$endreserve || $endreserve > $startreserve)) {
12083:                 $future_reservable{$slot} = {
12084:                                               symb         => $symb,
12085:                                               startreserve => $startreserve,
12086:                                               uniqueperiod => $uniqueperiod,
12087:                                             };
12088:             }
12089:         }
12090:     }
12091:     my @unsorted_reservable = keys(%reservable_now);
12092:     if (@unsorted_reservable > 0) {
12093:         @sorted_reservable = 
12094:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
12095:     }
12096:     my @unsorted_future = keys(%future_reservable);
12097:     if (@unsorted_future > 0) {
12098:         @sorted_future =
12099:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
12100:     }
12101:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
12102: }
12103: 
12104: =pod
12105: 
12106: =back
12107: 
12108: =head1 HTTP Helpers
12109: 
12110: =over 4
12111: 
12112: =item * &get_unprocessed_cgi($query,$possible_names)
12113: 
12114: Modify the %env hash to contain unprocessed CGI form parameters held in
12115: $query.  The parameters listed in $possible_names (an array reference),
12116: will be set in $env{'form.name'} if they do not already exist.
12117: 
12118: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
12119: $possible_names is an ref to an array of form element names.  As an example:
12120: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
12121: will result in $env{'form.uname'} and $env{'form.udom'} being set.
12122: 
12123: =cut
12124: 
12125: sub get_unprocessed_cgi {
12126:   my ($query,$possible_names)= @_;
12127:   # $Apache::lonxml::debug=1;
12128:   foreach my $pair (split(/&/,$query)) {
12129:     my ($name, $value) = split(/=/,$pair);
12130:     $name = &unescape($name);
12131:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
12132:       $value =~ tr/+/ /;
12133:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
12134:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
12135:     }
12136:   }
12137: }
12138: 
12139: =pod
12140: 
12141: =item * &cacheheader() 
12142: 
12143: returns cache-controlling header code
12144: 
12145: =cut
12146: 
12147: sub cacheheader {
12148:     unless ($env{'request.method'} eq 'GET') { return ''; }
12149:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
12150:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
12151:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
12152:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
12153:     return $output;
12154: }
12155: 
12156: =pod
12157: 
12158: =item * &no_cache($r) 
12159: 
12160: specifies header code to not have cache
12161: 
12162: =cut
12163: 
12164: sub no_cache {
12165:     my ($r) = @_;
12166:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
12167: 	$env{'request.method'} ne 'GET') { return ''; }
12168:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
12169:     $r->no_cache(1);
12170:     $r->header_out("Expires" => $date);
12171:     $r->header_out("Pragma" => "no-cache");
12172: }
12173: 
12174: sub content_type {
12175:     my ($r,$type,$charset) = @_;
12176:     if ($r) {
12177: 	#  Note that printout.pl calls this with undef for $r.
12178: 	&no_cache($r);
12179:     }
12180:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
12181:     unless ($charset) {
12182: 	$charset=&Apache::lonlocal::current_encoding;
12183:     }
12184:     if ($charset) { $type.='; charset='.$charset; }
12185:     if ($r) {
12186: 	$r->content_type($type);
12187:     } else {
12188: 	print("Content-type: $type\n\n");
12189:     }
12190: }
12191: 
12192: =pod
12193: 
12194: =item * &add_to_env($name,$value) 
12195: 
12196: adds $name to the %env hash with value
12197: $value, if $name already exists, the entry is converted to an array
12198: reference and $value is added to the array.
12199: 
12200: =cut
12201: 
12202: sub add_to_env {
12203:   my ($name,$value)=@_;
12204:   if (defined($env{$name})) {
12205:     if (ref($env{$name})) {
12206:       #already have multiple values
12207:       push(@{ $env{$name} },$value);
12208:     } else {
12209:       #first time seeing multiple values, convert hash entry to an arrayref
12210:       my $first=$env{$name};
12211:       undef($env{$name});
12212:       push(@{ $env{$name} },$first,$value);
12213:     }
12214:   } else {
12215:     $env{$name}=$value;
12216:   }
12217: }
12218: 
12219: =pod
12220: 
12221: =item * &get_env_multiple($name) 
12222: 
12223: gets $name from the %env hash, it seemlessly handles the cases where multiple
12224: values may be defined and end up as an array ref.
12225: 
12226: returns an array of values
12227: 
12228: =cut
12229: 
12230: sub get_env_multiple {
12231:     my ($name) = @_;
12232:     my @values;
12233:     if (defined($env{$name})) {
12234:         # exists is it an array
12235:         if (ref($env{$name})) {
12236:             @values=@{ $env{$name} };
12237:         } else {
12238:             $values[0]=$env{$name};
12239:         }
12240:     }
12241:     return(@values);
12242: }
12243: 
12244: # Looks at given dependencies, and returns something depending on the context.
12245: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
12246: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
12247: # For all other contexts, returns ($output, $counter, $numpathchg).
12248: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
12249: # $counter: integer with the number of existing dependencies when no HTML output is returned, and the number of missing dependencies when an HTML output is returned.
12250: # $numpathchg: integer with the number of cleaned up dependency paths.
12251: # \%existing: hash reference clean path -> 1 only for existing dependencies.
12252: # \%mapping: hash reference clean path -> original path for all dependencies.
12253: # @param {string} actionurl - The path to the handler, indicative of the context.
12254: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
12255: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
12256: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
12257: # @param {hash reference} args - More parameters ! Possible keys: error_on_invalid_names (boolean), ignore_remote_references (boolean), current_path (string), docs_url (string), docs_title (string), context (string)
12258: # @return {Array} - array depending on the context (not a reference)
12259: sub ask_for_embedded_content {
12260:     # NOTE: documentation was added afterwards, it could be wrong
12261:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
12262:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
12263:         %currsubfile,%unused,$rem);
12264:     my $counter = 0;
12265:     my $numnew = 0;
12266:     my $numremref = 0;
12267:     my $numinvalid = 0;
12268:     my $numpathchg = 0;
12269:     my $numexisting = 0;
12270:     my $numunused = 0;
12271:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
12272:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
12273:     my $heading = &mt('Upload embedded files');
12274:     my $buttontext = &mt('Upload');
12275: 
12276:     # fills these variables based on the context:
12277:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
12278:     # $path, $fileloc, $title, $rem, $filename
12279:     if ($env{'request.course.id'}) {
12280:         if ($actionurl eq '/adm/dependencies') {
12281:             $navmap = Apache::lonnavmaps::navmap->new();
12282:         }
12283:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12284:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12285:     }
12286:     if (($actionurl eq '/adm/portfolio') || 
12287:         ($actionurl eq '/adm/coursegrp_portfolio')) {
12288:         my $current_path='/';
12289:         if ($env{'form.currentpath'}) {
12290:             $current_path = $env{'form.currentpath'};
12291:         }
12292:         if ($actionurl eq '/adm/coursegrp_portfolio') {
12293:             $udom = $cdom;
12294:             $uname = $cnum;
12295:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
12296:         } else {
12297:             $udom = $env{'user.domain'};
12298:             $uname = $env{'user.name'};
12299:             $url = '/userfiles/portfolio';
12300:         }
12301:         $toplevel = $url.'/';
12302:         $url .= $current_path;
12303:         $getpropath = 1;
12304:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
12305:              ($actionurl eq '/adm/imsimport')) { 
12306:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
12307:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
12308:         $toplevel = $url;
12309:         if ($rest ne '') {
12310:             $url .= $rest;
12311:         }
12312:     } elsif ($actionurl eq '/adm/coursedocs') {
12313:         if (ref($args) eq 'HASH') {
12314:             $url = $args->{'docs_url'};
12315:             $toplevel = $url;
12316:             if ($args->{'context'} eq 'paste') {
12317:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
12318:                 ($path) = 
12319:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
12320:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
12321:                 $fileloc =~ s{^/}{};
12322:             }
12323:         }
12324:     } elsif ($actionurl eq '/adm/dependencies')  {
12325:         if ($env{'request.course.id'} ne '') {
12326:             if (ref($args) eq 'HASH') {
12327:                 $url = $args->{'docs_url'};
12328:                 $title = $args->{'docs_title'};
12329:                 $toplevel = $url; 
12330:                 unless ($toplevel =~ m{^/}) {
12331:                     $toplevel = "/$url";
12332:                 }
12333:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
12334:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
12335:                     $path = $1;
12336:                 } else {
12337:                     ($path) =
12338:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
12339:                 }
12340:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
12341:                     $fileloc = $toplevel;
12342:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
12343:                     my ($udom,$uname,$fname) =
12344:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
12345:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
12346:                 } else {
12347:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
12348:                 }
12349:                 $fileloc =~ s{^/}{};
12350:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
12351:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
12352:             }
12353:         }
12354:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
12355:         $udom = $cdom;
12356:         $uname = $cnum;
12357:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
12358:         $toplevel = $url;
12359:         $path = $url;
12360:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
12361:         $fileloc =~ s{^/}{};
12362:     }
12363:     
12364:     # parses the dependency paths to get some info
12365:     # fills $newfiles, $mapping, $subdependencies, $dependencies
12366:     # $newfiles: hash URL -> 1 for new files or external URLs
12367:     # (will be completed later)
12368:     # $mapping:
12369:     #   for external URLs: external URL -> external URL
12370:     #   for relative paths: clean path -> original path
12371:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
12372:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
12373:     foreach my $file (keys(%{$allfiles})) {
12374:         my $embed_file;
12375:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
12376:             $embed_file = $1;
12377:         } else {
12378:             $embed_file = $file;
12379:         }
12380:         my ($absolutepath,$cleaned_file);
12381:         if ($embed_file =~ m{^\w+://}) {
12382:             $cleaned_file = $embed_file;
12383:             $newfiles{$cleaned_file} = 1;
12384:             $mapping{$cleaned_file} = $embed_file;
12385:         } else {
12386:             $cleaned_file = &clean_path($embed_file);
12387:             if ($embed_file =~ m{^/}) {
12388:                 $absolutepath = $embed_file;
12389:             }
12390:             if ($cleaned_file =~ m{/}) {
12391:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
12392:                 $path = &check_for_traversal($path,$url,$toplevel);
12393:                 my $item = $fname;
12394:                 if ($path ne '') {
12395:                     $item = $path.'/'.$fname;
12396:                     $subdependencies{$path}{$fname} = 1;
12397:                 } else {
12398:                     $dependencies{$item} = 1;
12399:                 }
12400:                 if ($absolutepath) {
12401:                     $mapping{$item} = $absolutepath;
12402:                 } else {
12403:                     $mapping{$item} = $embed_file;
12404:                 }
12405:             } else {
12406:                 $dependencies{$embed_file} = 1;
12407:                 if ($absolutepath) {
12408:                     $mapping{$cleaned_file} = $absolutepath;
12409:                 } else {
12410:                     $mapping{$cleaned_file} = $embed_file;
12411:                 }
12412:             }
12413:         }
12414:     }
12415:     
12416:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
12417:     # and lists
12418:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
12419:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
12420:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
12421:     #                                    the path had to be cleaned up
12422:     # $existing: hash clean path -> 1 if the file exists
12423:     # $numexisting: number of keys in $existing
12424:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
12425:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
12426:     #                                      dependency subdirectories that are
12427:     #                                      not listed as dependencies, with some exceptions using $rem
12428:     my $dirptr = 16384;
12429:     foreach my $path (keys(%subdependencies)) {
12430:         $currsubfile{$path} = {};
12431:         if (($actionurl eq '/adm/portfolio') || 
12432:             ($actionurl eq '/adm/coursegrp_portfolio')) {
12433:             my ($sublistref,$listerror) =
12434:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
12435:             if (ref($sublistref) eq 'ARRAY') {
12436:                 foreach my $line (@{$sublistref}) {
12437:                     my ($file_name,$rest) = split(/\&/,$line,2);
12438:                     $currsubfile{$path}{$file_name} = 1;
12439:                 }
12440:             }
12441:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12442:             if (opendir(my $dir,$url.'/'.$path)) {
12443:                 my @subdir_list = grep(!/^\./,readdir($dir));
12444:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
12445:             }
12446:         } elsif (($actionurl eq '/adm/dependencies') ||
12447:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
12448:                   ($args->{'context'} eq 'paste')) ||
12449:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
12450:             if ($env{'request.course.id'} ne '') {
12451:                 my $dir;
12452:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
12453:                     $dir = $fileloc;
12454:                 } else {
12455:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
12456:                 }
12457:                 if ($dir ne '') {
12458:                     my ($sublistref,$listerror) =
12459:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
12460:                     if (ref($sublistref) eq 'ARRAY') {
12461:                         foreach my $line (@{$sublistref}) {
12462:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
12463:                                 undef,$mtime)=split(/\&/,$line,12);
12464:                             unless (($testdir&$dirptr) ||
12465:                                     ($file_name =~ /^\.\.?$/)) {
12466:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
12467:                             }
12468:                         }
12469:                     }
12470:                 }
12471:             }
12472:         }
12473:         foreach my $file (keys(%{$subdependencies{$path}})) {
12474:             if (exists($currsubfile{$path}{$file})) {
12475:                 my $item = $path.'/'.$file;
12476:                 unless ($mapping{$item} eq $item) {
12477:                     $pathchanges{$item} = 1;
12478:                 }
12479:                 $existing{$item} = 1;
12480:                 $numexisting ++;
12481:             } else {
12482:                 $newfiles{$path.'/'.$file} = 1;
12483:             }
12484:         }
12485:         if ($actionurl eq '/adm/dependencies') {
12486:             foreach my $path (keys(%currsubfile)) {
12487:                 if (ref($currsubfile{$path}) eq 'HASH') {
12488:                     foreach my $file (keys(%{$currsubfile{$path}})) {
12489:                          unless ($subdependencies{$path}{$file}) {
12490:                              next if (($rem ne '') &&
12491:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
12492:                                        (ref($navmap) &&
12493:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
12494:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
12495:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
12496:                              $unused{$path.'/'.$file} = 1; 
12497:                          }
12498:                     }
12499:                 }
12500:             }
12501:         }
12502:     }
12503:     
12504:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
12505:     # for files in $url or $fileloc (target directory) in some contexts
12506:     my %currfile;
12507:     if (($actionurl eq '/adm/portfolio') ||
12508:         ($actionurl eq '/adm/coursegrp_portfolio')) {
12509:         my ($dirlistref,$listerror) =
12510:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
12511:         if (ref($dirlistref) eq 'ARRAY') {
12512:             foreach my $line (@{$dirlistref}) {
12513:                 my ($file_name,$rest) = split(/\&/,$line,2);
12514:                 $currfile{$file_name} = 1;
12515:             }
12516:         }
12517:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12518:         if (opendir(my $dir,$url)) {
12519:             my @dir_list = grep(!/^\./,readdir($dir));
12520:             map {$currfile{$_} = 1;} @dir_list;
12521:         }
12522:     } elsif (($actionurl eq '/adm/dependencies') ||
12523:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
12524:               ($args->{'context'} eq 'paste')) ||
12525:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
12526:         if ($env{'request.course.id'} ne '') {
12527:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
12528:             if ($dir ne '') {
12529:                 my ($dirlistref,$listerror) =
12530:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
12531:                 if (ref($dirlistref) eq 'ARRAY') {
12532:                     foreach my $line (@{$dirlistref}) {
12533:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
12534:                             $size,undef,$mtime)=split(/\&/,$line,12);
12535:                         unless (($testdir&$dirptr) ||
12536:                                 ($file_name =~ /^\.\.?$/)) {
12537:                             $currfile{$file_name} = [$size,$mtime];
12538:                         }
12539:                     }
12540:                 }
12541:             }
12542:         }
12543:     }
12544:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
12545:     # are not in subdirectories, using $currfile
12546:     foreach my $file (keys(%dependencies)) {
12547:         if (exists($currfile{$file})) {
12548:             unless ($mapping{$file} eq $file) {
12549:                 $pathchanges{$file} = 1;
12550:             }
12551:             $existing{$file} = 1;
12552:             $numexisting ++;
12553:         } else {
12554:             $newfiles{$file} = 1;
12555:         }
12556:     }
12557:     foreach my $file (keys(%currfile)) {
12558:         unless (($file eq $filename) ||
12559:                 ($file eq $filename.'.bak') ||
12560:                 ($dependencies{$file})) {
12561:             if ($actionurl eq '/adm/dependencies') {
12562:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
12563:                     next if (($rem ne '') &&
12564:                              (($env{"httpref.$rem".$file} ne '') ||
12565:                               (ref($navmap) &&
12566:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
12567:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
12568:                                 ($navmap->getResourceByUrl($rem.$1)))))));
12569:                 }
12570:             }
12571:             $unused{$file} = 1;
12572:         }
12573:     }
12574:     
12575:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
12576:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
12577:         ($args->{'context'} eq 'paste')) {
12578:         $counter = scalar(keys(%existing));
12579:         $numpathchg = scalar(keys(%pathchanges));
12580:         return ($output,$counter,$numpathchg,\%existing);
12581:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
12582:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
12583:         $counter = scalar(keys(%existing));
12584:         $numpathchg = scalar(keys(%pathchanges));
12585:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
12586:     }
12587:     
12588:     # returns HTML otherwise, with dependency results and to ask for more uploads
12589:     
12590:     # $upload_output: missing dependencies (with upload form)
12591:     # $modify_output: uploaded dependencies (in use)
12592:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
12593:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
12594:         if ($actionurl eq '/adm/dependencies') {
12595:             next if ($embed_file =~ m{^\w+://});
12596:         }
12597:         $upload_output .= &start_data_table_row().
12598:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
12599:                           '<span class="LC_filename">'.$embed_file.'</span>';
12600:         unless ($mapping{$embed_file} eq $embed_file) {
12601:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
12602:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
12603:         }
12604:         $upload_output .= '</td>';
12605:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
12606:             $upload_output.='<td align="right">'.
12607:                             '<span class="LC_info LC_fontsize_medium">'.
12608:                             &mt("URL points to web address").'</span>';
12609:             $numremref++;
12610:         } elsif ($args->{'error_on_invalid_names'}
12611:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
12612:             $upload_output.='<td align="right"><span class="LC_warning">'.
12613:                             &mt('Invalid characters').'</span>';
12614:             $numinvalid++;
12615:         } else {
12616:             $upload_output .= '<td>'.
12617:                               &embedded_file_element('upload_embedded',$counter,
12618:                                                      $embed_file,\%mapping,
12619:                                                      $allfiles,$codebase,'upload');
12620:             $counter ++;
12621:             $numnew ++;
12622:         }
12623:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
12624:     }
12625:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
12626:         if ($actionurl eq '/adm/dependencies') {
12627:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
12628:             $modify_output .= &start_data_table_row().
12629:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
12630:                               '<img src="'.&icon($embed_file).'" border="0" />'.
12631:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
12632:                               '<td>'.$size.'</td>'.
12633:                               '<td>'.$mtime.'</td>'.
12634:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
12635:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
12636:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
12637:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
12638:                               &embedded_file_element('upload_embedded',$counter,
12639:                                                      $embed_file,\%mapping,
12640:                                                      $allfiles,$codebase,'modify').
12641:                               '</div></td>'.
12642:                               &end_data_table_row()."\n";
12643:             $counter ++;
12644:         } else {
12645:             $upload_output .= &start_data_table_row().
12646:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
12647:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
12648:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
12649:                               &Apache::loncommon::end_data_table_row()."\n";
12650:         }
12651:     }
12652:     my $delidx = $counter;
12653:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
12654:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
12655:         $delete_output .= &start_data_table_row().
12656:                           '<td><img src="'.&icon($oldfile).'" />'.
12657:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
12658:                           '<td>'.$size.'</td>'.
12659:                           '<td>'.$mtime.'</td>'.
12660:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
12661:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
12662:                           &embedded_file_element('upload_embedded',$delidx,
12663:                                                  $oldfile,\%mapping,$allfiles,
12664:                                                  $codebase,'delete').'</td>'.
12665:                           &end_data_table_row()."\n"; 
12666:         $numunused ++;
12667:         $delidx ++;
12668:     }
12669:     if ($upload_output) {
12670:         $upload_output = &start_data_table().
12671:                          $upload_output.
12672:                          &end_data_table()."\n";
12673:     }
12674:     if ($modify_output) {
12675:         $modify_output = &start_data_table().
12676:                          &start_data_table_header_row().
12677:                          '<th>'.&mt('File').'</th>'.
12678:                          '<th>'.&mt('Size (KB)').'</th>'.
12679:                          '<th>'.&mt('Modified').'</th>'.
12680:                          '<th>'.&mt('Upload replacement?').'</th>'.
12681:                          &end_data_table_header_row().
12682:                          $modify_output.
12683:                          &end_data_table()."\n";
12684:     }
12685:     if ($delete_output) {
12686:         $delete_output = &start_data_table().
12687:                          &start_data_table_header_row().
12688:                          '<th>'.&mt('File').'</th>'.
12689:                          '<th>'.&mt('Size (KB)').'</th>'.
12690:                          '<th>'.&mt('Modified').'</th>'.
12691:                          '<th>'.&mt('Delete?').'</th>'.
12692:                          &end_data_table_header_row().
12693:                          $delete_output.
12694:                          &end_data_table()."\n";
12695:     }
12696:     my $applies = 0;
12697:     if ($numremref) {
12698:         $applies ++;
12699:     }
12700:     if ($numinvalid) {
12701:         $applies ++;
12702:     }
12703:     if ($numexisting) {
12704:         $applies ++;
12705:     }
12706:     if ($counter || $numunused) {
12707:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
12708:                   ' method="post" enctype="multipart/form-data">'."\n".
12709:                   $state.'<h3>'.$heading.'</h3>'; 
12710:         if ($actionurl eq '/adm/dependencies') {
12711:             if ($numnew) {
12712:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
12713:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
12714:                            $upload_output.'<br />'."\n";
12715:             }
12716:             if ($numexisting) {
12717:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
12718:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
12719:                            $modify_output.'<br />'."\n";
12720:                            $buttontext = &mt('Save changes');
12721:             }
12722:             if ($numunused) {
12723:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
12724:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
12725:                            $delete_output.'<br />'."\n";
12726:                            $buttontext = &mt('Save changes');
12727:             }
12728:         } else {
12729:             $output .= $upload_output.'<br />'."\n";
12730:         }
12731:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
12732:                    $counter.'" />'."\n";
12733:         if ($actionurl eq '/adm/dependencies') { 
12734:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
12735:                        $numnew.'" />'."\n";
12736:         } elsif ($actionurl eq '') {
12737:             $output .=  '<input type="hidden" name="phase" value="three" />';
12738:         }
12739:     } elsif ($applies) {
12740:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
12741:         if ($applies > 1) {
12742:             $output .=  
12743:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
12744:             if ($numremref) {
12745:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
12746:             }
12747:             if ($numinvalid) {
12748:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
12749:             }
12750:             if ($numexisting) {
12751:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
12752:             }
12753:             $output .= '</ul><br />';
12754:         } elsif ($numremref) {
12755:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
12756:         } elsif ($numinvalid) {
12757:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
12758:         } elsif ($numexisting) {
12759:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
12760:         }
12761:         $output .= $upload_output.'<br />';
12762:     }
12763:     my ($pathchange_output,$chgcount);
12764:     $chgcount = $counter;
12765:     if (keys(%pathchanges) > 0) {
12766:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
12767:             if ($counter) {
12768:                 $output .= &embedded_file_element('pathchange',$chgcount,
12769:                                                   $embed_file,\%mapping,
12770:                                                   $allfiles,$codebase,'change');
12771:             } else {
12772:                 $pathchange_output .= 
12773:                     &start_data_table_row().
12774:                     '<td><input type ="checkbox" name="namechange" value="'.
12775:                     $chgcount.'" checked="checked" /></td>'.
12776:                     '<td>'.$mapping{$embed_file}.'</td>'.
12777:                     '<td>'.$embed_file.
12778:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
12779:                                            \%mapping,$allfiles,$codebase,'change').
12780:                     '</td>'.&end_data_table_row();
12781:             }
12782:             $numpathchg ++;
12783:             $chgcount ++;
12784:         }
12785:     }
12786:     if (($counter) || ($numunused)) {
12787:         if ($numpathchg) {
12788:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
12789:                        $numpathchg.'" />'."\n";
12790:         }
12791:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
12792:             ($actionurl eq '/adm/imsimport')) {
12793:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
12794:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
12795:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
12796:         } elsif ($actionurl eq '/adm/dependencies') {
12797:             $output .= '<input type="hidden" name="action" value="process_changes" />';
12798:         }
12799:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
12800:     } elsif ($numpathchg) {
12801:         my %pathchange = ();
12802:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
12803:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
12804:             $output .= '<p>'.&mt('or').'</p>'; 
12805:         }
12806:     }
12807:     return ($output,$counter,$numpathchg);
12808: }
12809: 
12810: =pod
12811: 
12812: =item * clean_path($name)
12813: 
12814: Performs clean-up of directories, subdirectories and filename in an
12815: embedded object, referenced in an HTML file which is being uploaded
12816: to a course or portfolio, where 
12817: "Upload embedded images/multimedia files if HTML file" checkbox was
12818: checked.
12819: 
12820: Clean-up is similar to replacements in lonnet::clean_filename()
12821: except each / between sub-directory and next level is preserved.
12822: 
12823: =cut
12824: 
12825: sub clean_path {
12826:     my ($embed_file) = @_;
12827:     $embed_file =~s{^/+}{};
12828:     my @contents;
12829:     if ($embed_file =~ m{/}) {
12830:         @contents = split(/\//,$embed_file);
12831:     } else {
12832:         @contents = ($embed_file);
12833:     }
12834:     my $lastidx = scalar(@contents)-1;
12835:     for (my $i=0; $i<=$lastidx; $i++) { 
12836:         $contents[$i]=~s{\\}{/}g;
12837:         $contents[$i]=~s/\s+/\_/g;
12838:         $contents[$i]=~s{[^/\w\.\-]}{}g;
12839:         if ($i == $lastidx) {
12840:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
12841:         }
12842:     }
12843:     if ($lastidx > 0) {
12844:         return join('/',@contents);
12845:     } else {
12846:         return $contents[0];
12847:     }
12848: }
12849: 
12850: sub embedded_file_element {
12851:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
12852:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
12853:                    (ref($codebase) eq 'HASH'));
12854:     my $output;
12855:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
12856:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
12857:     }
12858:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
12859:                &escape($embed_file).'" />';
12860:     unless (($context eq 'upload_embedded') && 
12861:             ($mapping->{$embed_file} eq $embed_file)) {
12862:         $output .='
12863:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
12864:     }
12865:     my $attrib;
12866:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
12867:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
12868:     }
12869:     $output .=
12870:         "\n\t\t".
12871:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
12872:         $attrib.'" />';
12873:     if (exists($codebase->{$mapping->{$embed_file}})) {
12874:         $output .=
12875:             "\n\t\t".
12876:             '<input name="codebase_'.$num.'" type="hidden" value="'.
12877:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
12878:     }
12879:     return $output;
12880: }
12881: 
12882: sub get_dependency_details {
12883:     my ($currfile,$currsubfile,$embed_file) = @_;
12884:     my ($size,$mtime,$showsize,$showmtime);
12885:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
12886:         if ($embed_file =~ m{/}) {
12887:             my ($path,$fname) = split(/\//,$embed_file);
12888:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
12889:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
12890:             }
12891:         } else {
12892:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
12893:                 ($size,$mtime) = @{$currfile->{$embed_file}};
12894:             }
12895:         }
12896:         $showsize = $size/1024.0;
12897:         $showsize = sprintf("%.1f",$showsize);
12898:         if ($mtime > 0) {
12899:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
12900:         }
12901:     }
12902:     return ($showsize,$showmtime);
12903: }
12904: 
12905: sub ask_embedded_js {
12906:     return <<"END";
12907: <script type="text/javascript"">
12908: // <![CDATA[
12909: function toggleBrowse(counter) {
12910:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
12911:     var fileid = document.getElementById('embedded_item_'+counter);
12912:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
12913:     if (chkboxid.checked == true) {
12914:         uploaddivid.style.display='block';
12915:     } else {
12916:         uploaddivid.style.display='none';
12917:         fileid.value = '';
12918:     }
12919: }
12920: // ]]>
12921: </script>
12922: 
12923: END
12924: }
12925: 
12926: sub upload_embedded {
12927:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
12928:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
12929:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
12930:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
12931:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
12932:         my $orig_uploaded_filename =
12933:             $env{'form.embedded_item_'.$i.'.filename'};
12934:         foreach my $type ('orig','ref','attrib','codebase') {
12935:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
12936:                 $env{'form.embedded_'.$type.'_'.$i} =
12937:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
12938:             }
12939:         }
12940:         my ($path,$fname) =
12941:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
12942:         # no path, whole string is fname
12943:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
12944:         $fname = &Apache::lonnet::clean_filename($fname);
12945:         # See if there is anything left
12946:         next if ($fname eq '');
12947: 
12948:         # Check if file already exists as a file or directory.
12949:         my ($state,$msg);
12950:         if ($context eq 'portfolio') {
12951:             my $port_path = $dirpath;
12952:             if ($group ne '') {
12953:                 $port_path = "groups/$group/$port_path";
12954:             }
12955:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
12956:                                               $fname,$group,'embedded_item_'.$i,
12957:                                               $dir_root,$port_path,$disk_quota,
12958:                                               $current_disk_usage,$uname,$udom);
12959:             if ($state eq 'will_exceed_quota'
12960:                 || $state eq 'file_locked') {
12961:                 $output .= $msg;
12962:                 next;
12963:             }
12964:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
12965:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
12966:             if ($state eq 'exists') {
12967:                 $output .= $msg;
12968:                 next;
12969:             }
12970:         }
12971:         # Check if extension is valid
12972:         if (($fname =~ /\.(\w+)$/) &&
12973:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
12974:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
12975:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
12976:             next;
12977:         } elsif (($fname =~ /\.(\w+)$/) &&
12978:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
12979:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
12980:             next;
12981:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
12982:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
12983:             next;
12984:         }
12985:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
12986:         my $subdir = $path;
12987:         $subdir =~ s{/+$}{};
12988:         if ($context eq 'portfolio') {
12989:             my $result;
12990:             if ($state eq 'existingfile') {
12991:                 $result=
12992:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
12993:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
12994:             } else {
12995:                 $result=
12996:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
12997:                                                     $dirpath.
12998:                                                     $env{'form.currentpath'}.$subdir);
12999:                 if ($result !~ m|^/uploaded/|) {
13000:                     $output .= '<span class="LC_error">'
13001:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
13002:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
13003:                                .'</span><br />';
13004:                     next;
13005:                 } else {
13006:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
13007:                                $path.$fname.'</span>').'<br />';     
13008:                 }
13009:             }
13010:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
13011:             my $extendedsubdir = $dirpath.'/'.$subdir;
13012:             $extendedsubdir =~ s{/+$}{};
13013:             my $result =
13014:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
13015:             if ($result !~ m|^/uploaded/|) {
13016:                 $output .= '<span class="LC_error">'
13017:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
13018:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
13019:                            .'</span><br />';
13020:                     next;
13021:             } else {
13022:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
13023:                            $path.$fname.'</span>').'<br />';
13024:                 if ($context eq 'syllabus') {
13025:                     &Apache::lonnet::make_public_indefinitely($result);
13026:                 }
13027:             }
13028:         } else {
13029: # Save the file
13030:             my $target = $env{'form.embedded_item_'.$i};
13031:             my $fullpath = $dir_root.$dirpath.'/'.$path;
13032:             my $dest = $fullpath.$fname;
13033:             my $url = $url_root.$dirpath.'/'.$path.$fname;
13034:             my @parts=split(/\//,"$dirpath/$path");
13035:             my $count;
13036:             my $filepath = $dir_root;
13037:             foreach my $subdir (@parts) {
13038:                 $filepath .= "/$subdir";
13039:                 if (!-e $filepath) {
13040:                     mkdir($filepath,0770);
13041:                 }
13042:             }
13043:             my $fh;
13044:             if (!open($fh,'>'.$dest)) {
13045:                 &Apache::lonnet::logthis('Failed to create '.$dest);
13046:                 $output .= '<span class="LC_error">'.
13047:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
13048:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
13049:                            '</span><br />';
13050:             } else {
13051:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
13052:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
13053:                     $output .= '<span class="LC_error">'.
13054:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
13055:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
13056:                               '</span><br />';
13057:                 } else {
13058:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
13059:                                $url.'</span>').'<br />';
13060:                     unless ($context eq 'testbank') {
13061:                         $footer .= &mt('View embedded file: [_1]',
13062:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
13063:                     }
13064:                 }
13065:                 close($fh);
13066:             }
13067:         }
13068:         if ($env{'form.embedded_ref_'.$i}) {
13069:             $pathchange{$i} = 1;
13070:         }
13071:     }
13072:     if ($output) {
13073:         $output = '<p>'.$output.'</p>';
13074:     }
13075:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
13076:     $returnflag = 'ok';
13077:     my $numpathchgs = scalar(keys(%pathchange));
13078:     if ($numpathchgs > 0) {
13079:         if ($context eq 'portfolio') {
13080:             $output .= '<p>'.&mt('or').'</p>';
13081:         } elsif ($context eq 'testbank') {
13082:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
13083:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
13084:             $returnflag = 'modify_orightml';
13085:         }
13086:     }
13087:     return ($output.$footer,$returnflag,$numpathchgs);
13088: }
13089: 
13090: sub modify_html_form {
13091:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
13092:     my $end = 0;
13093:     my $modifyform;
13094:     if ($context eq 'upload_embedded') {
13095:         return unless (ref($pathchange) eq 'HASH');
13096:         if ($env{'form.number_embedded_items'}) {
13097:             $end += $env{'form.number_embedded_items'};
13098:         }
13099:         if ($env{'form.number_pathchange_items'}) {
13100:             $end += $env{'form.number_pathchange_items'};
13101:         }
13102:         if ($end) {
13103:             for (my $i=0; $i<$end; $i++) {
13104:                 if ($i < $env{'form.number_embedded_items'}) {
13105:                     next unless($pathchange->{$i});
13106:                 }
13107:                 $modifyform .=
13108:                     &start_data_table_row().
13109:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
13110:                     'checked="checked" /></td>'.
13111:                     '<td>'.$env{'form.embedded_ref_'.$i}.
13112:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
13113:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
13114:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
13115:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
13116:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
13117:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
13118:                     '<td>'.$env{'form.embedded_orig_'.$i}.
13119:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
13120:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
13121:                     &end_data_table_row();
13122:             }
13123:         }
13124:     } else {
13125:         $modifyform = $pathchgtable;
13126:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
13127:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
13128:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
13129:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
13130:         }
13131:     }
13132:     if ($modifyform) {
13133:         if ($actionurl eq '/adm/dependencies') {
13134:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
13135:         }
13136:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
13137:                '<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".
13138:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
13139:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
13140:                '</ol></p>'."\n".'<p>'.
13141:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
13142:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
13143:                &start_data_table()."\n".
13144:                &start_data_table_header_row().
13145:                '<th>'.&mt('Change?').'</th>'.
13146:                '<th>'.&mt('Current reference').'</th>'.
13147:                '<th>'.&mt('Required reference').'</th>'.
13148:                &end_data_table_header_row()."\n".
13149:                $modifyform.
13150:                &end_data_table().'<br />'."\n".$hiddenstate.
13151:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
13152:                '</form>'."\n";
13153:     }
13154:     return;
13155: }
13156: 
13157: sub modify_html_refs {
13158:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
13159:     my $container;
13160:     if ($context eq 'portfolio') {
13161:         $container = $env{'form.container'};
13162:     } elsif ($context eq 'coursedoc') {
13163:         $container = $env{'form.primaryurl'};
13164:     } elsif ($context eq 'manage_dependencies') {
13165:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
13166:         $container = "/$container";
13167:     } elsif ($context eq 'syllabus') {
13168:         $container = $url;
13169:     } else {
13170:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
13171:     }
13172:     my (%allfiles,%codebase,$output,$content);
13173:     my @changes = &get_env_multiple('form.namechange');
13174:     unless ((@changes > 0) || ($context eq 'syllabus')) {
13175:         if (wantarray) {
13176:             return ('',0,0); 
13177:         } else {
13178:             return;
13179:         }
13180:     }
13181:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
13182:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
13183:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
13184:             if (wantarray) {
13185:                 return ('',0,0);
13186:             } else {
13187:                 return;
13188:             }
13189:         } 
13190:         $content = &Apache::lonnet::getfile($container);
13191:         if ($content eq '-1') {
13192:             if (wantarray) {
13193:                 return ('',0,0);
13194:             } else {
13195:                 return;
13196:             }
13197:         }
13198:     } else {
13199:         unless ($container =~ /^\Q$dir_root\E/) {
13200:             if (wantarray) {
13201:                 return ('',0,0);
13202:             } else {
13203:                 return;
13204:             }
13205:         } 
13206:         if (open(my $fh,'<',$container)) {
13207:             $content = join('', <$fh>);
13208:             close($fh);
13209:         } else {
13210:             if (wantarray) {
13211:                 return ('',0,0);
13212:             } else {
13213:                 return;
13214:             }
13215:         }
13216:     }
13217:     my ($count,$codebasecount) = (0,0);
13218:     my $mm = new File::MMagic;
13219:     my $mime_type = $mm->checktype_contents($content);
13220:     if ($mime_type eq 'text/html') {
13221:         my $parse_result = 
13222:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
13223:                                                     \%codebase,\$content);
13224:         if ($parse_result eq 'ok') {
13225:             foreach my $i (@changes) {
13226:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
13227:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
13228:                 if ($allfiles{$ref}) {
13229:                     my $newname =  $orig;
13230:                     my ($attrib_regexp,$codebase);
13231:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
13232:                     if ($attrib_regexp =~ /:/) {
13233:                         $attrib_regexp =~ s/\:/|/g;
13234:                     }
13235:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
13236:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
13237:                         $count += $numchg;
13238:                         $allfiles{$newname} = $allfiles{$ref};
13239:                         delete($allfiles{$ref});
13240:                     }
13241:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
13242:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
13243:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
13244:                         $codebasecount ++;
13245:                     }
13246:                 }
13247:             }
13248:             my $skiprewrites;
13249:             if ($count || $codebasecount) {
13250:                 my $saveresult;
13251:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
13252:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
13253:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
13254:                     if ($url eq $container) {
13255:                         my ($fname) = ($container =~ m{/([^/]+)$});
13256:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
13257:                                             $count,'<span class="LC_filename">'.
13258:                                             $fname.'</span>').'</p>';
13259:                     } else {
13260:                          $output = '<p class="LC_error">'.
13261:                                    &mt('Error: update failed for: [_1].',
13262:                                    '<span class="LC_filename">'.
13263:                                    $container.'</span>').'</p>';
13264:                     }
13265:                     if ($context eq 'syllabus') {
13266:                         unless ($saveresult eq 'ok') {
13267:                             $skiprewrites = 1;
13268:                         }
13269:                     }
13270:                 } else {
13271:                     if (open(my $fh,'>',$container)) {
13272:                         print $fh $content;
13273:                         close($fh);
13274:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
13275:                                   $count,'<span class="LC_filename">'.
13276:                                   $container.'</span>').'</p>';
13277:                     } else {
13278:                          $output = '<p class="LC_error">'.
13279:                                    &mt('Error: could not update [_1].',
13280:                                    '<span class="LC_filename">'.
13281:                                    $container.'</span>').'</p>';
13282:                     }
13283:                 }
13284:             }
13285:             if (($context eq 'syllabus') && (!$skiprewrites)) {
13286:                 my ($actionurl,$state);
13287:                 $actionurl = "/public/$udom/$uname/syllabus";
13288:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
13289:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
13290:                                               \%codebase,
13291:                                               {'context' => 'rewrites',
13292:                                                'ignore_remote_references' => 1,});
13293:                 if (ref($mapping) eq 'HASH') {
13294:                     my $rewrites = 0;
13295:                     foreach my $key (keys(%{$mapping})) {
13296:                         next if ($key =~ m{^https?://});
13297:                         my $ref = $mapping->{$key};
13298:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
13299:                         my $attrib;
13300:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
13301:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
13302:                         }
13303:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
13304:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
13305:                             $rewrites += $numchg;
13306:                         }
13307:                     }
13308:                     if ($rewrites) {
13309:                         my $saveresult; 
13310:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
13311:                         if ($url eq $container) {
13312:                             my ($fname) = ($container =~ m{/([^/]+)$});
13313:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
13314:                                             $count,'<span class="LC_filename">'.
13315:                                             $fname.'</span>').'</p>';
13316:                         } else {
13317:                             $output .= '<p class="LC_error">'.
13318:                                        &mt('Error: could not update links in [_1].',
13319:                                        '<span class="LC_filename">'.
13320:                                        $container.'</span>').'</p>';
13321: 
13322:                         }
13323:                     }
13324:                 }
13325:             }
13326:         } else {
13327:             &logthis('Failed to parse '.$container.
13328:                      ' to modify references: '.$parse_result);
13329:         }
13330:     }
13331:     if (wantarray) {
13332:         return ($output,$count,$codebasecount);
13333:     } else {
13334:         return $output;
13335:     }
13336: }
13337: 
13338: sub check_for_existing {
13339:     my ($path,$fname,$element) = @_;
13340:     my ($state,$msg);
13341:     if (-d $path.'/'.$fname) {
13342:         $state = 'exists';
13343:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
13344:     } elsif (-e $path.'/'.$fname) {
13345:         $state = 'exists';
13346:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
13347:     }
13348:     if ($state eq 'exists') {
13349:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
13350:     }
13351:     return ($state,$msg);
13352: }
13353: 
13354: sub check_for_upload {
13355:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
13356:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
13357:     my $filesize = length($env{'form.'.$element});
13358:     if (!$filesize) {
13359:         my $msg = '<span class="LC_error">'.
13360:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
13361:                       '<span class="LC_filename">'.$fname.'</span>',
13362:                       $filesize).'<br />'.
13363:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
13364:                   '</span>';
13365:         return ('zero_bytes',$msg);
13366:     }
13367:     $filesize =  $filesize/1000; #express in k (1024?)
13368:     my $getpropath = 1;
13369:     my ($dirlistref,$listerror) =
13370:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
13371:     my $found_file = 0;
13372:     my $locked_file = 0;
13373:     my @lockers;
13374:     my $navmap;
13375:     if ($env{'request.course.id'}) {
13376:         $navmap = Apache::lonnavmaps::navmap->new();
13377:     }
13378:     if (ref($dirlistref) eq 'ARRAY') {
13379:         foreach my $line (@{$dirlistref}) {
13380:             my ($file_name,$rest)=split(/\&/,$line,2);
13381:             if ($file_name eq $fname){
13382:                 $file_name = $path.$file_name;
13383:                 if ($group ne '') {
13384:                     $file_name = $group.$file_name;
13385:                 }
13386:                 $found_file = 1;
13387:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
13388:                     foreach my $lock (@lockers) {
13389:                         if (ref($lock) eq 'ARRAY') {
13390:                             my ($symb,$crsid) = @{$lock};
13391:                             if ($crsid eq $env{'request.course.id'}) {
13392:                                 if (ref($navmap)) {
13393:                                     my $res = $navmap->getBySymb($symb);
13394:                                     foreach my $part (@{$res->parts()}) { 
13395:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
13396:                                         unless (($slot_status == $res->RESERVED) ||
13397:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
13398:                                             $locked_file = 1;
13399:                                         }
13400:                                     }
13401:                                 } else {
13402:                                     $locked_file = 1;
13403:                                 }
13404:                             } else {
13405:                                 $locked_file = 1;
13406:                             }
13407:                         }
13408:                    }
13409:                 } else {
13410:                     my @info = split(/\&/,$rest);
13411:                     my $currsize = $info[6]/1000;
13412:                     if ($currsize < $filesize) {
13413:                         my $extra = $filesize - $currsize;
13414:                         if (($current_disk_usage + $extra) > $disk_quota) {
13415:                             my $msg = '<p class="LC_warning">'.
13416:                                       &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.',
13417:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
13418:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
13419:                                                    $disk_quota,$current_disk_usage).'</p>';
13420:                             return ('will_exceed_quota',$msg);
13421:                         }
13422:                     }
13423:                 }
13424:             }
13425:         }
13426:     }
13427:     if (($current_disk_usage + $filesize) > $disk_quota){
13428:         my $msg = '<p class="LC_warning">'.
13429:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
13430:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
13431:         return ('will_exceed_quota',$msg);
13432:     } elsif ($found_file) {
13433:         if ($locked_file) {
13434:             my $msg = '<p class="LC_warning">';
13435:             $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>');
13436:             $msg .= '</p>';
13437:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
13438:             return ('file_locked',$msg);
13439:         } else {
13440:             my $msg = '<p class="LC_error">';
13441:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
13442:             $msg .= '</p>';
13443:             return ('existingfile',$msg);
13444:         }
13445:     }
13446: }
13447: 
13448: sub check_for_traversal {
13449:     my ($path,$url,$toplevel) = @_;
13450:     my @parts=split(/\//,$path);
13451:     my $cleanpath;
13452:     my $fullpath = $url;
13453:     for (my $i=0;$i<@parts;$i++) {
13454:         next if ($parts[$i] eq '.');
13455:         if ($parts[$i] eq '..') {
13456:             $fullpath =~ s{([^/]+/)$}{};
13457:         } else {
13458:             $fullpath .= $parts[$i].'/';
13459:         }
13460:     }
13461:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
13462:         $cleanpath = $1;
13463:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
13464:         my $curr_toprel = $1;
13465:         my @parts = split(/\//,$curr_toprel);
13466:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
13467:         my @urlparts = split(/\//,$url_toprel);
13468:         my $doubledots;
13469:         my $startdiff = -1;
13470:         for (my $i=0; $i<@urlparts; $i++) {
13471:             if ($startdiff == -1) {
13472:                 unless ($urlparts[$i] eq $parts[$i]) {
13473:                     $startdiff = $i;
13474:                     $doubledots .= '../';
13475:                 }
13476:             } else {
13477:                 $doubledots .= '../';
13478:             }
13479:         }
13480:         if ($startdiff > -1) {
13481:             $cleanpath = $doubledots;
13482:             for (my $i=$startdiff; $i<@parts; $i++) {
13483:                 $cleanpath .= $parts[$i].'/';
13484:             }
13485:         }
13486:     }
13487:     $cleanpath =~ s{(/)$}{};
13488:     return $cleanpath;
13489: }
13490: 
13491: sub is_archive_file {
13492:     my ($mimetype) = @_;
13493:     if (($mimetype eq 'application/octet-stream') ||
13494:         ($mimetype eq 'application/x-stuffit') ||
13495:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
13496:         return 1;
13497:     }
13498:     return;
13499: }
13500: 
13501: sub decompress_form {
13502:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
13503:     my %lt = &Apache::lonlocal::texthash (
13504:         this => 'This file is an archive file.',
13505:         camt => 'This file is a Camtasia archive file.',
13506:         itsc => 'Its contents are as follows:',
13507:         youm => 'You may wish to extract its contents.',
13508:         extr => 'Extract contents',
13509:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
13510:         proa => 'Process automatically?',
13511:         yes  => 'Yes',
13512:         no   => 'No',
13513:         fold => 'Title for folder containing movie',
13514:         movi => 'Title for page containing embedded movie', 
13515:     );
13516:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
13517:     my ($is_camtasia,$topdir,%toplevel,@paths);
13518:     my $info = &list_archive_contents($fileloc,\@paths);
13519:     if (@paths) {
13520:         foreach my $path (@paths) {
13521:             $path =~ s{^/}{};
13522:             if ($path =~ m{^([^/]+)/$}) {
13523:                 $topdir = $1;
13524:             }
13525:             if ($path =~ m{^([^/]+)/}) {
13526:                 $toplevel{$1} = $path;
13527:             } else {
13528:                 $toplevel{$path} = $path;
13529:             }
13530:         }
13531:     }
13532:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
13533:         my @camtasia6 = ("$topdir/","$topdir/index.html",
13534:                         "$topdir/media/",
13535:                         "$topdir/media/$topdir.mp4",
13536:                         "$topdir/media/FirstFrame.png",
13537:                         "$topdir/media/player.swf",
13538:                         "$topdir/media/swfobject.js",
13539:                         "$topdir/media/expressInstall.swf");
13540:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
13541:                          "$topdir/$topdir.mp4",
13542:                          "$topdir/$topdir\_config.xml",
13543:                          "$topdir/$topdir\_controller.swf",
13544:                          "$topdir/$topdir\_embed.css",
13545:                          "$topdir/$topdir\_First_Frame.png",
13546:                          "$topdir/$topdir\_player.html",
13547:                          "$topdir/$topdir\_Thumbnails.png",
13548:                          "$topdir/playerProductInstall.swf",
13549:                          "$topdir/scripts/",
13550:                          "$topdir/scripts/config_xml.js",
13551:                          "$topdir/scripts/handlebars.js",
13552:                          "$topdir/scripts/jquery-1.7.1.min.js",
13553:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
13554:                          "$topdir/scripts/modernizr.js",
13555:                          "$topdir/scripts/player-min.js",
13556:                          "$topdir/scripts/swfobject.js",
13557:                          "$topdir/skins/",
13558:                          "$topdir/skins/configuration_express.xml",
13559:                          "$topdir/skins/express_show/",
13560:                          "$topdir/skins/express_show/player-min.css",
13561:                          "$topdir/skins/express_show/spritesheet.png");
13562:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
13563:                          "$topdir/$topdir.mp4",
13564:                          "$topdir/$topdir\_config.xml",
13565:                          "$topdir/$topdir\_controller.swf",
13566:                          "$topdir/$topdir\_embed.css",
13567:                          "$topdir/$topdir\_First_Frame.png",
13568:                          "$topdir/$topdir\_player.html",
13569:                          "$topdir/$topdir\_Thumbnails.png",
13570:                          "$topdir/playerProductInstall.swf",
13571:                          "$topdir/scripts/",
13572:                          "$topdir/scripts/config_xml.js",
13573:                          "$topdir/scripts/techsmith-smart-player.min.js",
13574:                          "$topdir/skins/",
13575:                          "$topdir/skins/configuration_express.xml",
13576:                          "$topdir/skins/express_show/",
13577:                          "$topdir/skins/express_show/spritesheet.min.css",
13578:                          "$topdir/skins/express_show/spritesheet.png",
13579:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
13580:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
13581:         if (@diffs == 0) {
13582:             $is_camtasia = 6;
13583:         } else {
13584:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
13585:             if (@diffs == 0) {
13586:                 $is_camtasia = 8;
13587:             } else {
13588:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
13589:                 if (@diffs == 0) {
13590:                     $is_camtasia = 8;
13591:                 }
13592:             }
13593:         }
13594:     }
13595:     my $output;
13596:     if ($is_camtasia) {
13597:         $output = <<"ENDCAM";
13598: <script type="text/javascript" language="Javascript">
13599: // <![CDATA[
13600: 
13601: function camtasiaToggle() {
13602:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
13603:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
13604:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
13605:                 document.getElementById('camtasia_titles').style.display='block';
13606:             } else {
13607:                 document.getElementById('camtasia_titles').style.display='none';
13608:             }
13609:         }
13610:     }
13611:     return;
13612: }
13613: 
13614: // ]]>
13615: </script>
13616: <p>$lt{'camt'}</p>
13617: ENDCAM
13618:     } else {
13619:         $output = '<p>'.$lt{'this'};
13620:         if ($info eq '') {
13621:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
13622:         } else {
13623:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
13624:                        '<div><pre>'.$info.'</pre></div>';
13625:         }
13626:     }
13627:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
13628:     my $duplicates;
13629:     my $num = 0;
13630:     if (ref($dirlist) eq 'ARRAY') {
13631:         foreach my $item (@{$dirlist}) {
13632:             if (ref($item) eq 'ARRAY') {
13633:                 if (exists($toplevel{$item->[0]})) {
13634:                     $duplicates .= 
13635:                         &start_data_table_row().
13636:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
13637:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
13638:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
13639:                         'value="1" />'.&mt('Yes').'</label>'.
13640:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
13641:                         '<td>'.$item->[0].'</td>';
13642:                     if ($item->[2]) {
13643:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
13644:                     } else {
13645:                         $duplicates .= '<td>'.&mt('File').'</td>';
13646:                     }
13647:                     $duplicates .= '<td>'.$item->[3].'</td>'.
13648:                                    '<td>'.
13649:                                    &Apache::lonlocal::locallocaltime($item->[4]).
13650:                                    '</td>'.
13651:                                    &end_data_table_row();
13652:                     $num ++;
13653:                 }
13654:             }
13655:         }
13656:     }
13657:     my $itemcount;
13658:     if (@paths > 0) {
13659:         $itemcount = scalar(@paths);
13660:     } else {
13661:         $itemcount = 1;
13662:     }
13663:     if ($is_camtasia) {
13664:         $output .= $lt{'auto'}.'<br />'.
13665:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
13666:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
13667:                    $lt{'yes'}.'</label>&nbsp;<label>'.
13668:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
13669:                    $lt{'no'}.'</label></span><br />'.
13670:                    '<div id="camtasia_titles" style="display:block">'.
13671:                    &Apache::lonhtmlcommon::start_pick_box().
13672:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
13673:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
13674:                    &Apache::lonhtmlcommon::row_closure().
13675:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
13676:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
13677:                    &Apache::lonhtmlcommon::row_closure(1).
13678:                    &Apache::lonhtmlcommon::end_pick_box().
13679:                    '</div>';
13680:     }
13681:     $output .= 
13682:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
13683:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
13684:         "\n";
13685:     if ($duplicates ne '') {
13686:         $output .= '<p><span class="LC_warning">'.
13687:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
13688:                    &start_data_table().
13689:                    &start_data_table_header_row().
13690:                    '<th>'.&mt('Overwrite?').'</th>'.
13691:                    '<th>'.&mt('Name').'</th>'.
13692:                    '<th>'.&mt('Type').'</th>'.
13693:                    '<th>'.&mt('Size').'</th>'.
13694:                    '<th>'.&mt('Last modified').'</th>'.
13695:                    &end_data_table_header_row().
13696:                    $duplicates.
13697:                    &end_data_table().
13698:                    '</p>';
13699:     }
13700:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
13701:     if (ref($hiddenelements) eq 'HASH') {
13702:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
13703:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
13704:         }
13705:     }
13706:     $output .= <<"END";
13707: <br />
13708: <input type="submit" name="decompress" value="$lt{'extr'}" />
13709: </form>
13710: $noextract
13711: END
13712:     return $output;
13713: }
13714: 
13715: sub decompression_utility {
13716:     my ($program) = @_;
13717:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
13718:     my $location;
13719:     if (grep(/^\Q$program\E$/,@utilities)) { 
13720:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
13721:                          '/usr/sbin/') {
13722:             if (-x $dir.$program) {
13723:                 $location = $dir.$program;
13724:                 last;
13725:             }
13726:         }
13727:     }
13728:     return $location;
13729: }
13730: 
13731: sub list_archive_contents {
13732:     my ($file,$pathsref) = @_;
13733:     my (@cmd,$output);
13734:     my $needsregexp;
13735:     if ($file =~ /\.zip$/) {
13736:         @cmd = (&decompression_utility('unzip'),"-l");
13737:         $needsregexp = 1;
13738:     } elsif (($file =~ m/\.tar\.gz$/) ||
13739:              ($file =~ /\.tgz$/)) {
13740:         @cmd = (&decompression_utility('tar'),"-ztf");
13741:     } elsif ($file =~ /\.tar\.bz2$/) {
13742:         @cmd = (&decompression_utility('tar'),"-jtf");
13743:     } elsif ($file =~ m|\.tar$|) {
13744:         @cmd = (&decompression_utility('tar'),"-tf");
13745:     }
13746:     if (@cmd) {
13747:         undef($!);
13748:         undef($@);
13749:         if (open(my $fh,"-|", @cmd, $file)) {
13750:             while (my $line = <$fh>) {
13751:                 $output .= $line;
13752:                 chomp($line);
13753:                 my $item;
13754:                 if ($needsregexp) {
13755:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
13756:                 } else {
13757:                     $item = $line;
13758:                 }
13759:                 if ($item ne '') {
13760:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
13761:                         push(@{$pathsref},$item);
13762:                     } 
13763:                 }
13764:             }
13765:             close($fh);
13766:         }
13767:     }
13768:     return $output;
13769: }
13770: 
13771: sub decompress_uploaded_file {
13772:     my ($file,$dir) = @_;
13773:     &Apache::lonnet::appenv({'cgi.file' => $file});
13774:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
13775:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
13776:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
13777:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
13778:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
13779:     my $decompressed = $env{'cgi.decompressed'};
13780:     &Apache::lonnet::delenv('cgi.file');
13781:     &Apache::lonnet::delenv('cgi.dir');
13782:     &Apache::lonnet::delenv('cgi.decompressed');
13783:     return ($decompressed,$result);
13784: }
13785: 
13786: sub process_decompression {
13787:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
13788:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
13789:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13790:                &mt('Unexpected file path.').'</p>'."\n";
13791:     }
13792:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
13793:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13794:                &mt('Unexpected course context.').'</p>'."\n";
13795:     }
13796:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
13797:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13798:                &mt('Filename contained unexpected characters.').'</p>'."\n";
13799:     }
13800:     my ($dir,$error,$warning,$output);
13801:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
13802:         $error = &mt('Filename not a supported archive file type.').
13803:                  '<br />'.&mt('Filename should end with one of: [_1].',
13804:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
13805:     } else {
13806:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
13807:         if ($docuhome eq 'no_host') {
13808:             $error = &mt('Could not determine home server for course.');
13809:         } else {
13810:             my @ids=&Apache::lonnet::current_machine_ids();
13811:             my $currdir = "$dir_root/$destination";
13812:             if (grep(/^\Q$docuhome\E$/,@ids)) {
13813:                 $dir = &LONCAPA::propath($docudom,$docuname).
13814:                        "$dir_root/$destination";
13815:             } else {
13816:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
13817:                        "$dir_root/$docudom/$docuname/$destination";
13818:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
13819:                     $error = &mt('Archive file not found.');
13820:                 }
13821:             }
13822:             my (@to_overwrite,@to_skip);
13823:             if ($env{'form.archive_overwrite_total'} > 0) {
13824:                 my $total = $env{'form.archive_overwrite_total'};
13825:                 for (my $i=0; $i<$total; $i++) {
13826:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
13827:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
13828:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
13829:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
13830:                     }
13831:                 }
13832:             }
13833:             my $numskip = scalar(@to_skip);
13834:             my $numoverwrite = scalar(@to_overwrite);
13835:             if (($numskip) && (!$numoverwrite)) { 
13836:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
13837:             } elsif ($dir eq '') {
13838:                 $error = &mt('Directory containing archive file unavailable.');
13839:             } elsif (!$error) {
13840:                 my ($decompressed,$display);
13841:                 if (($numskip) || ($numoverwrite)) {
13842:                     my $tempdir = time.'_'.$$.int(rand(10000));
13843:                     mkdir("$dir/$tempdir",0755);
13844:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
13845:                         ($decompressed,$display) = 
13846:                             &decompress_uploaded_file($file,"$dir/$tempdir");
13847:                         foreach my $item (@to_skip) {
13848:                             if (($item ne '') && ($item !~ /\.\./)) {
13849:                                 if (-f "$dir/$tempdir/$item") { 
13850:                                     unlink("$dir/$tempdir/$item");
13851:                                 } elsif (-d "$dir/$tempdir/$item") {
13852:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
13853:                                 }
13854:                             }
13855:                         }
13856:                         foreach my $item (@to_overwrite) {
13857:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
13858:                                 if (($item ne '') && ($item !~ /\.\./)) {
13859:                                     if (-f "$dir/$item") {
13860:                                         unlink("$dir/$item");
13861:                                     } elsif (-d "$dir/$item") {
13862:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
13863:                                     }
13864:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
13865:                                 }
13866:                             }
13867:                         }
13868:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
13869:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
13870:                         }
13871:                     }
13872:                 } else {
13873:                     ($decompressed,$display) = 
13874:                         &decompress_uploaded_file($file,$dir);
13875:                 }
13876:                 if ($decompressed eq 'ok') {
13877:                     $output = '<p class="LC_info">'.
13878:                               &mt('Files extracted successfully from archive.').
13879:                               '</p>'."\n";
13880:                     my ($warning,$result,@contents);
13881:                     my ($newdirlistref,$newlisterror) =
13882:                         &Apache::lonnet::dirlist($currdir,$docudom,
13883:                                                  $docuname,1);
13884:                     my (%is_dir,%changes,@newitems);
13885:                     my $dirptr = 16384;
13886:                     if (ref($newdirlistref) eq 'ARRAY') {
13887:                         foreach my $dir_line (@{$newdirlistref}) {
13888:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
13889:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
13890:                                 push(@newitems,$item);
13891:                                 if ($dirptr&$testdir) {
13892:                                     $is_dir{$item} = 1;
13893:                                 }
13894:                                 $changes{$item} = 1;
13895:                             }
13896:                         }
13897:                     }
13898:                     if (keys(%changes) > 0) {
13899:                         foreach my $item (sort(@newitems)) {
13900:                             if ($changes{$item}) {
13901:                                 push(@contents,$item);
13902:                             }
13903:                         }
13904:                     }
13905:                     if (@contents > 0) {
13906:                         my $wantform;
13907:                         unless ($env{'form.autoextract_camtasia'}) {
13908:                             $wantform = 1;
13909:                         }
13910:                         my (%children,%parent,%dirorder,%titles);
13911:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
13912:                                                                 $currdir,\%is_dir,
13913:                                                                 \%children,\%parent,
13914:                                                                 \@contents,\%dirorder,
13915:                                                                 \%titles,$wantform);
13916:                         if ($datatable ne '') {
13917:                             $output .= &archive_options_form('decompressed',$datatable,
13918:                                                              $count,$hiddenelem);
13919:                             my $startcount = 6;
13920:                             $output .= &archive_javascript($startcount,$count,
13921:                                                            \%titles,\%children);
13922:                         }
13923:                         if ($env{'form.autoextract_camtasia'}) {
13924:                             my $version = $env{'form.autoextract_camtasia'};
13925:                             my %displayed;
13926:                             my $total = 1;
13927:                             $env{'form.archive_directory'} = [];
13928:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
13929:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
13930:                                 $path =~ s{/$}{};
13931:                                 my $item;
13932:                                 if ($path ne '') {
13933:                                     $item = "$path/$titles{$i}";
13934:                                 } else {
13935:                                     $item = $titles{$i};
13936:                                 }
13937:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
13938:                                 if ($item eq $contents[0]) {
13939:                                     push(@{$env{'form.archive_directory'}},$i);
13940:                                     $env{'form.archive_'.$i} = 'display';
13941:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
13942:                                     $displayed{'folder'} = $i;
13943:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
13944:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
13945:                                     $env{'form.archive_'.$i} = 'display';
13946:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
13947:                                     $displayed{'web'} = $i;
13948:                                 } else {
13949:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
13950:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
13951:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
13952:                                         push(@{$env{'form.archive_directory'}},$i);
13953:                                     }
13954:                                     $env{'form.archive_'.$i} = 'dependency';
13955:                                 }
13956:                                 $total ++;
13957:                             }
13958:                             for (my $i=1; $i<$total; $i++) {
13959:                                 next if ($i == $displayed{'web'});
13960:                                 next if ($i == $displayed{'folder'});
13961:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
13962:                             }
13963:                             $env{'form.phase'} = 'decompress_cleanup';
13964:                             $env{'form.archivedelete'} = 1;
13965:                             $env{'form.archive_count'} = $total-1;
13966:                             $output .=
13967:                                 &process_extracted_files('coursedocs',$docudom,
13968:                                                          $docuname,$destination,
13969:                                                          $dir_root,$hiddenelem);
13970:                         }
13971:                     } else {
13972:                         $warning = &mt('No new items extracted from archive file.');
13973:                     }
13974:                 } else {
13975:                     $output = $display;
13976:                     $error = &mt('An error occurred during extraction from the archive file.');
13977:                 }
13978:             }
13979:         }
13980:     }
13981:     if ($error) {
13982:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13983:                    $error.'</p>'."\n";
13984:     }
13985:     if ($warning) {
13986:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
13987:     }
13988:     return $output;
13989: }
13990: 
13991: sub get_extracted {
13992:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
13993:         $titles,$wantform) = @_;
13994:     my $count = 0;
13995:     my $depth = 0;
13996:     my $datatable;
13997:     my @hierarchy;
13998:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
13999:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
14000:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
14001:     foreach my $item (@{$contents}) {
14002:         $count ++;
14003:         @{$dirorder->{$count}} = @hierarchy;
14004:         $titles->{$count} = $item;
14005:         &archive_hierarchy($depth,$count,$parent,$children);
14006:         if ($wantform) {
14007:             $datatable .= &archive_row($is_dir->{$item},$item,
14008:                                        $currdir,$depth,$count);
14009:         }
14010:         if ($is_dir->{$item}) {
14011:             $depth ++;
14012:             push(@hierarchy,$count);
14013:             $parent->{$depth} = $count;
14014:             $datatable .=
14015:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
14016:                                            \$depth,\$count,\@hierarchy,$dirorder,
14017:                                            $children,$parent,$titles,$wantform);
14018:             $depth --;
14019:             pop(@hierarchy);
14020:         }
14021:     }
14022:     return ($count,$datatable);
14023: }
14024: 
14025: sub recurse_extracted_archive {
14026:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
14027:         $children,$parent,$titles,$wantform) = @_;
14028:     my $result='';
14029:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
14030:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
14031:             (ref($dirorder) eq 'HASH')) {
14032:         return $result;
14033:     }
14034:     my $dirptr = 16384;
14035:     my ($newdirlistref,$newlisterror) =
14036:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
14037:     if (ref($newdirlistref) eq 'ARRAY') {
14038:         foreach my $dir_line (@{$newdirlistref}) {
14039:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
14040:             unless ($item =~ /^\.+$/) {
14041:                 $$count ++;
14042:                 @{$dirorder->{$$count}} = @{$hierarchy};
14043:                 $titles->{$$count} = $item;
14044:                 &archive_hierarchy($$depth,$$count,$parent,$children);
14045: 
14046:                 my $is_dir;
14047:                 if ($dirptr&$testdir) {
14048:                     $is_dir = 1;
14049:                 }
14050:                 if ($wantform) {
14051:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
14052:                 }
14053:                 if ($is_dir) {
14054:                     $$depth ++;
14055:                     push(@{$hierarchy},$$count);
14056:                     $parent->{$$depth} = $$count;
14057:                     $result .=
14058:                         &recurse_extracted_archive("$currdir/$item",$docudom,
14059:                                                    $docuname,$depth,$count,
14060:                                                    $hierarchy,$dirorder,$children,
14061:                                                    $parent,$titles,$wantform);
14062:                     $$depth --;
14063:                     pop(@{$hierarchy});
14064:                 }
14065:             }
14066:         }
14067:     }
14068:     return $result;
14069: }
14070: 
14071: sub archive_hierarchy {
14072:     my ($depth,$count,$parent,$children) =@_;
14073:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
14074:         if (exists($parent->{$depth})) {
14075:              $children->{$parent->{$depth}} .= $count.':';
14076:         }
14077:     }
14078:     return;
14079: }
14080: 
14081: sub archive_row {
14082:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
14083:     my ($name) = ($item =~ m{([^/]+)$});
14084:     my %choices = &Apache::lonlocal::texthash (
14085:                                        'display'    => 'Add as file',
14086:                                        'dependency' => 'Include as dependency',
14087:                                        'discard'    => 'Discard',
14088:                                       );
14089:     if ($is_dir) {
14090:         $choices{'display'} = &mt('Add as folder'); 
14091:     }
14092:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
14093:     my $offset = 0;
14094:     foreach my $action ('display','dependency','discard') {
14095:         $offset ++;
14096:         if ($action ne 'display') {
14097:             $offset ++;
14098:         }  
14099:         $output .= '<td><span class="LC_nobreak">'.
14100:                    '<label><input type="radio" name="archive_'.$count.
14101:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
14102:         my $text = $choices{$action};
14103:         if ($is_dir) {
14104:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
14105:             if ($action eq 'display') {
14106:                 $text = &mt('Add as folder');
14107:             }
14108:         } else {
14109:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
14110: 
14111:         }
14112:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
14113:         if ($action eq 'dependency') {
14114:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
14115:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
14116:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
14117:                        '<option value=""></option>'."\n".
14118:                        '</select>'."\n".
14119:                        '</div>';
14120:         } elsif ($action eq 'display') {
14121:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
14122:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
14123:                        '</div>';
14124:         }
14125:         $output .= '</td>';
14126:     }
14127:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
14128:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
14129:     for (my $i=0; $i<$depth; $i++) {
14130:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
14131:     }
14132:     if ($is_dir) {
14133:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
14134:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
14135:     } else {
14136:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
14137:     }
14138:     $output .= '&nbsp;'.$name.'</td>'."\n".
14139:                &end_data_table_row();
14140:     return $output;
14141: }
14142: 
14143: sub archive_options_form {
14144:     my ($form,$display,$count,$hiddenelem) = @_;
14145:     my %lt = &Apache::lonlocal::texthash(
14146:                perm => 'Permanently remove archive file?',
14147:                hows => 'How should each extracted item be incorporated in the course?',
14148:                cont => 'Content actions for all',
14149:                addf => 'Add as folder/file',
14150:                incd => 'Include as dependency for a displayed file',
14151:                disc => 'Discard',
14152:                no   => 'No',
14153:                yes  => 'Yes',
14154:                save => 'Save',
14155:     );
14156:     my $output = <<"END";
14157: <form name="$form" method="post" action="">
14158: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
14159: <label>
14160:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
14161: </label>
14162: &nbsp;
14163: <label>
14164:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
14165: </span>
14166: </p>
14167: <input type="hidden" name="phase" value="decompress_cleanup" />
14168: <br />$lt{'hows'}
14169: <div class="LC_columnSection">
14170:   <fieldset>
14171:     <legend>$lt{'cont'}</legend>
14172:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
14173:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
14174:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
14175:   </fieldset>
14176: </div>
14177: END
14178:     return $output.
14179:            &start_data_table()."\n".
14180:            $display."\n".
14181:            &end_data_table()."\n".
14182:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
14183:            $hiddenelem.
14184:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
14185:            '</form>';
14186: }
14187: 
14188: sub archive_javascript {
14189:     my ($startcount,$numitems,$titles,$children) = @_;
14190:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
14191:     my $maintitle = $env{'form.comment'};
14192:     my $scripttag = <<START;
14193: <script type="text/javascript">
14194: // <![CDATA[
14195: 
14196: function checkAll(form,prefix) {
14197:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
14198:     for (var i=0; i < form.elements.length; i++) {
14199:         var id = form.elements[i].id;
14200:         if ((id != '') && (id != undefined)) {
14201:             if (idstr.test(id)) {
14202:                 if (form.elements[i].type == 'radio') {
14203:                     form.elements[i].checked = true;
14204:                     var nostart = i-$startcount;
14205:                     var offset = nostart%7;
14206:                     var count = (nostart-offset)/7;    
14207:                     dependencyCheck(form,count,offset);
14208:                 }
14209:             }
14210:         }
14211:     }
14212: }
14213: 
14214: function propagateCheck(form,count) {
14215:     if (count > 0) {
14216:         var startelement = $startcount + ((count-1) * 7);
14217:         for (var j=1; j<6; j++) {
14218:             if ((j != 2) && (j != 4)) {
14219:                 var item = startelement + j; 
14220:                 if (form.elements[item].type == 'radio') {
14221:                     if (form.elements[item].checked) {
14222:                         containerCheck(form,count,j);
14223:                         break;
14224:                     }
14225:                 }
14226:             }
14227:         }
14228:     }
14229: }
14230: 
14231: numitems = $numitems
14232: var titles = new Array(numitems);
14233: var parents = new Array(numitems);
14234: for (var i=0; i<numitems; i++) {
14235:     parents[i] = new Array;
14236: }
14237: var maintitle = '$maintitle';
14238: 
14239: START
14240: 
14241:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
14242:         my @contents = split(/:/,$children->{$container});
14243:         for (my $i=0; $i<@contents; $i ++) {
14244:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
14245:         }
14246:     }
14247: 
14248:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
14249:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
14250:     }
14251: 
14252:     $scripttag .= <<END;
14253: 
14254: function containerCheck(form,count,offset) {
14255:     if (count > 0) {
14256:         dependencyCheck(form,count,offset);
14257:         var item = (offset+$startcount)+7*(count-1);
14258:         form.elements[item].checked = true;
14259:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
14260:             if (parents[count].length > 0) {
14261:                 for (var j=0; j<parents[count].length; j++) {
14262:                     containerCheck(form,parents[count][j],offset);
14263:                 }
14264:             }
14265:         }
14266:     }
14267: }
14268: 
14269: function dependencyCheck(form,count,offset) {
14270:     if (count > 0) {
14271:         var chosen = (offset+$startcount)+7*(count-1);
14272:         var depitem = $startcount + ((count-1) * 7) + 4;
14273:         var currtype = form.elements[depitem].type;
14274:         if (form.elements[chosen].value == 'dependency') {
14275:             document.getElementById('arc_depon_'+count).style.display='block'; 
14276:             form.elements[depitem].options.length = 0;
14277:             form.elements[depitem].options[0] = new Option('Select','',true,true);
14278:             for (var i=1; i<=numitems; i++) {
14279:                 if (i == count) {
14280:                     continue;
14281:                 }
14282:                 var startelement = $startcount + (i-1) * 7;
14283:                 for (var j=1; j<6; j++) {
14284:                     if ((j != 2) && (j!= 4)) {
14285:                         var item = startelement + j;
14286:                         if (form.elements[item].type == 'radio') {
14287:                             if (form.elements[item].checked) {
14288:                                 if (form.elements[item].value == 'display') {
14289:                                     var n = form.elements[depitem].options.length;
14290:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
14291:                                 }
14292:                             }
14293:                         }
14294:                     }
14295:                 }
14296:             }
14297:         } else {
14298:             document.getElementById('arc_depon_'+count).style.display='none';
14299:             form.elements[depitem].options.length = 0;
14300:             form.elements[depitem].options[0] = new Option('Select','',true,true);
14301:         }
14302:         titleCheck(form,count,offset);
14303:     }
14304: }
14305: 
14306: function propagateSelect(form,count,offset) {
14307:     if (count > 0) {
14308:         var item = (1+offset+$startcount)+7*(count-1);
14309:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
14310:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
14311:             if (parents[count].length > 0) {
14312:                 for (var j=0; j<parents[count].length; j++) {
14313:                     containerSelect(form,parents[count][j],offset,picked);
14314:                 }
14315:             }
14316:         }
14317:     }
14318: }
14319: 
14320: function containerSelect(form,count,offset,picked) {
14321:     if (count > 0) {
14322:         var item = (offset+$startcount)+7*(count-1);
14323:         if (form.elements[item].type == 'radio') {
14324:             if (form.elements[item].value == 'dependency') {
14325:                 if (form.elements[item+1].type == 'select-one') {
14326:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
14327:                         if (form.elements[item+1].options[i].value == picked) {
14328:                             form.elements[item+1].selectedIndex = i;
14329:                             break;
14330:                         }
14331:                     }
14332:                 }
14333:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
14334:                     if (parents[count].length > 0) {
14335:                         for (var j=0; j<parents[count].length; j++) {
14336:                             containerSelect(form,parents[count][j],offset,picked);
14337:                         }
14338:                     }
14339:                 }
14340:             }
14341:         }
14342:     }
14343: }
14344: 
14345: function titleCheck(form,count,offset) {
14346:     if (count > 0) {
14347:         var chosen = (offset+$startcount)+7*(count-1);
14348:         var depitem = $startcount + ((count-1) * 7) + 2;
14349:         var currtype = form.elements[depitem].type;
14350:         if (form.elements[chosen].value == 'display') {
14351:             document.getElementById('arc_title_'+count).style.display='block';
14352:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
14353:                 document.getElementById('archive_title_'+count).value=maintitle;
14354:             }
14355:         } else {
14356:             document.getElementById('arc_title_'+count).style.display='none';
14357:             if (currtype == 'text') { 
14358:                 document.getElementById('archive_title_'+count).value='';
14359:             }
14360:         }
14361:     }
14362:     return;
14363: }
14364: 
14365: // ]]>
14366: </script>
14367: END
14368:     return $scripttag;
14369: }
14370: 
14371: sub process_extracted_files {
14372:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
14373:     my $numitems = $env{'form.archive_count'};
14374:     return if ((!$numitems) || ($numitems =~ /\D/));
14375:     my @ids=&Apache::lonnet::current_machine_ids();
14376:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
14377:         %folders,%containers,%mapinner,%prompttofetch);
14378:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
14379:     if (grep(/^\Q$docuhome\E$/,@ids)) {
14380:         $prefix = &LONCAPA::propath($docudom,$docuname);
14381:         $pathtocheck = "$dir_root/$destination";
14382:         $dir = $dir_root;
14383:         $ishome = 1;
14384:     } else {
14385:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
14386:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
14387:         $dir = "$dir_root/$docudom/$docuname";
14388:     }
14389:     my $currdir = "$dir_root/$destination";
14390:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
14391:     if ($env{'form.folderpath'}) {
14392:         my @items = split('&',$env{'form.folderpath'});
14393:         $folders{'0'} = $items[-2];
14394:         if ($env{'form.folderpath'} =~ /\:1$/) {
14395:             $containers{'0'}='page';
14396:         } else {  
14397:             $containers{'0'}='sequence';
14398:         }
14399:     }
14400:     my @archdirs = &get_env_multiple('form.archive_directory');
14401:     if ($numitems) {
14402:         for (my $i=1; $i<=$numitems; $i++) {
14403:             my $path = $env{'form.archive_content_'.$i};
14404:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
14405:                 my $item = $1;
14406:                 $toplevelitems{$item} = $i;
14407:                 if (grep(/^\Q$i\E$/,@archdirs)) {
14408:                     $is_dir{$item} = 1;
14409:                 }
14410:             }
14411:         }
14412:     }
14413:     my ($output,%children,%parent,%titles,%dirorder,$result);
14414:     if (keys(%toplevelitems) > 0) {
14415:         my @contents = sort(keys(%toplevelitems));
14416:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
14417:                                            \%parent,\@contents,\%dirorder,\%titles);
14418:     }
14419:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
14420:     if ($numitems) {
14421:         for (my $i=1; $i<=$numitems; $i++) {
14422:             next if ($env{'form.archive_'.$i} eq 'dependency');
14423:             my $path = $env{'form.archive_content_'.$i};
14424:             if ($path =~ /^\Q$pathtocheck\E/) {
14425:                 if ($env{'form.archive_'.$i} eq 'discard') {
14426:                     if ($prefix ne '' && $path ne '') {
14427:                         if (-e $prefix.$path) {
14428:                             if ((@archdirs > 0) && 
14429:                                 (grep(/^\Q$i\E$/,@archdirs))) {
14430:                                 $todeletedir{$prefix.$path} = 1;
14431:                             } else {
14432:                                 $todelete{$prefix.$path} = 1;
14433:                             }
14434:                         }
14435:                     }
14436:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
14437:                     my ($docstitle,$title,$url,$outer);
14438:                     ($title) = ($path =~ m{/([^/]+)$});
14439:                     $docstitle = $env{'form.archive_title_'.$i};
14440:                     if ($docstitle eq '') {
14441:                         $docstitle = $title;
14442:                     }
14443:                     $outer = 0;
14444:                     if (ref($dirorder{$i}) eq 'ARRAY') {
14445:                         if (@{$dirorder{$i}} > 0) {
14446:                             foreach my $item (reverse(@{$dirorder{$i}})) {
14447:                                 if ($env{'form.archive_'.$item} eq 'display') {
14448:                                     $outer = $item;
14449:                                     last;
14450:                                 }
14451:                             }
14452:                         }
14453:                     }
14454:                     my ($errtext,$fatal) = 
14455:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
14456:                                                '/'.$folders{$outer}.'.'.
14457:                                                $containers{$outer});
14458:                     next if ($fatal);
14459:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
14460:                         if ($context eq 'coursedocs') {
14461:                             $mapinner{$i} = time;
14462:                             $folders{$i} = 'default_'.$mapinner{$i};
14463:                             $containers{$i} = 'sequence';
14464:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
14465:                                       $folders{$i}.'.'.$containers{$i};
14466:                             my $newidx = &LONCAPA::map::getresidx();
14467:                             $LONCAPA::map::resources[$newidx]=
14468:                                 $docstitle.':'.$url.':false:normal:res';
14469:                             push(@LONCAPA::map::order,$newidx);
14470:                             my ($outtext,$errtext) =
14471:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
14472:                                                         $docuname.'/'.$folders{$outer}.
14473:                                                         '.'.$containers{$outer},1,1);
14474:                             $newseqid{$i} = $newidx;
14475:                             unless ($errtext) {
14476:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
14477:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
14478:                                             '</li>'."\n";
14479:                             }
14480:                         }
14481:                     } else {
14482:                         if ($context eq 'coursedocs') {
14483:                             my $newidx=&LONCAPA::map::getresidx();
14484:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
14485:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
14486:                                       $title;
14487:                             if (($outer !~ /\D/) &&
14488:                                 (($mapinner{$outer} eq 'default') || ($mapinner{$outer} !~ /\D/)) &&
14489:                                 ($newidx !~ /\D/)) {
14490:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
14491:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
14492:                                 }
14493:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
14494:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
14495:                                 }
14496:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
14497:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
14498:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
14499:                                         unless ($ishome) {
14500:                                             my $fetch = "$newdest{$i}/$title";
14501:                                             $fetch =~ s/^\Q$prefix$dir\E//;
14502:                                             $prompttofetch{$fetch} = 1;
14503:                                         }
14504:                                     }
14505:                                 }
14506:                                 $LONCAPA::map::resources[$newidx]=
14507:                                     $docstitle.':'.$url.':false:normal:res';
14508:                                 push(@LONCAPA::map::order, $newidx);
14509:                                 my ($outtext,$errtext)=
14510:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
14511:                                                             $docuname.'/'.$folders{$outer}.
14512:                                                             '.'.$containers{$outer},1,1);
14513:                                 unless ($errtext) {
14514:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
14515:                                         $result .= '<li>'.&mt('File: [_1] added to course',
14516:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
14517:                                                    '</li>'."\n";
14518:                                     }
14519:                                 }
14520:                             } else {
14521:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
14522:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
14523:                             }
14524:                         }
14525:                     }
14526:                 }
14527:             } else {
14528:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
14529:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
14530:             }
14531:         }
14532:         for (my $i=1; $i<=$numitems; $i++) {
14533:             next unless ($env{'form.archive_'.$i} eq 'dependency');
14534:             my $path = $env{'form.archive_content_'.$i};
14535:             if ($path =~ /^\Q$pathtocheck\E/) {
14536:                 my ($title) = ($path =~ m{/([^/]+)$});
14537:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
14538:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
14539:                     if (ref($dirorder{$i}) eq 'ARRAY') {
14540:                         my ($itemidx,$fullpath,$relpath);
14541:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
14542:                             my $container = $dirorder{$referrer{$i}}->[-1];
14543:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
14544:                                 if ($dirorder{$i}->[$j] eq $container) {
14545:                                     $itemidx = $j;
14546:                                 }
14547:                             }
14548:                         }
14549:                         if ($itemidx eq '') {
14550:                             $itemidx =  0;
14551:                         } 
14552:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
14553:                             if ($mapinner{$referrer{$i}}) {
14554:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
14555:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
14556:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
14557:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
14558:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
14559:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
14560:                                             if (!-e $fullpath) {
14561:                                                 mkdir($fullpath,0755);
14562:                                             }
14563:                                         }
14564:                                     } else {
14565:                                         last;
14566:                                     }
14567:                                 }
14568:                             }
14569:                         } elsif ($newdest{$referrer{$i}}) {
14570:                             $fullpath = $newdest{$referrer{$i}};
14571:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
14572:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
14573:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
14574:                                     last;
14575:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
14576:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
14577:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
14578:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
14579:                                         if (!-e $fullpath) {
14580:                                             mkdir($fullpath,0755);
14581:                                         }
14582:                                     }
14583:                                 } else {
14584:                                     last;
14585:                                 }
14586:                             }
14587:                         }
14588:                         if ($fullpath ne '') {
14589:                             if (-e "$prefix$path") {
14590:                                 unless (rename("$prefix$path","$fullpath/$title")) {
14591:                                      $warning .= &mt('Failed to rename dependency').'<br />';
14592:                                 }
14593:                             }
14594:                             if (-e "$fullpath/$title") {
14595:                                 my $showpath;
14596:                                 if ($relpath ne '') {
14597:                                     $showpath = "$relpath/$title";
14598:                                 } else {
14599:                                     $showpath = "/$title";
14600:                                 } 
14601:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
14602:                                                       &HTML::Entities::encode($showpath,'<>&"')).
14603:                                            '</li>'."\n";
14604:                                 unless ($ishome) {
14605:                                     my $fetch = "$fullpath/$title";
14606:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
14607:                                     $prompttofetch{$fetch} = 1;
14608:                                 }
14609:                             }
14610:                         }
14611:                     }
14612:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
14613:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
14614:                                     &HTML::Entities::encode($path,'<>&"'),
14615:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
14616:                                 '<br />';
14617:                 }
14618:             } else {
14619:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
14620:                                 &HTML::Entities::encode($path)).'<br />';
14621:             }
14622:         }
14623:         if (keys(%todelete)) {
14624:             foreach my $key (keys(%todelete)) {
14625:                 unlink($key);
14626:             }
14627:         }
14628:         if (keys(%todeletedir)) {
14629:             foreach my $key (keys(%todeletedir)) {
14630:                 rmdir($key);
14631:             }
14632:         }
14633:         foreach my $dir (sort(keys(%is_dir))) {
14634:             if (($pathtocheck ne '') && ($dir ne ''))  {
14635:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
14636:             }
14637:         }
14638:         if ($result ne '') {
14639:             $output .= '<ul>'."\n".
14640:                        $result."\n".
14641:                        '</ul>';
14642:         }
14643:         unless ($ishome) {
14644:             my $replicationfail;
14645:             foreach my $item (keys(%prompttofetch)) {
14646:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
14647:                 unless ($fetchresult eq 'ok') {
14648:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
14649:                 }
14650:             }
14651:             if ($replicationfail) {
14652:                 $output .= '<p class="LC_error">'.
14653:                            &mt('Course home server failed to retrieve:').'<ul>'.
14654:                            $replicationfail.
14655:                            '</ul></p>';
14656:             }
14657:         }
14658:     } else {
14659:         $warning = &mt('No items found in archive.');
14660:     }
14661:     if ($error) {
14662:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
14663:                    $error.'</p>'."\n";
14664:     }
14665:     if ($warning) {
14666:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
14667:     }
14668:     return $output;
14669: }
14670: 
14671: sub cleanup_empty_dirs {
14672:     my ($path) = @_;
14673:     if (($path ne '') && (-d $path)) {
14674:         if (opendir(my $dirh,$path)) {
14675:             my @dircontents = grep(!/^\./,readdir($dirh));
14676:             my $numitems = 0;
14677:             foreach my $item (@dircontents) {
14678:                 if (-d "$path/$item") {
14679:                     &cleanup_empty_dirs("$path/$item");
14680:                     if (-e "$path/$item") {
14681:                         $numitems ++;
14682:                     }
14683:                 } else {
14684:                     $numitems ++;
14685:                 }
14686:             }
14687:             if ($numitems == 0) {
14688:                 rmdir($path);
14689:             }
14690:             closedir($dirh);
14691:         }
14692:     }
14693:     return;
14694: }
14695: 
14696: =pod
14697: 
14698: =item * &get_folder_hierarchy()
14699: 
14700: Provides hierarchy of names of folders/sub-folders containing the current
14701: item,
14702: 
14703: Inputs: 3
14704:      - $navmap - navmaps object
14705: 
14706:      - $map - url for map (either the trigger itself, or map containing
14707:                            the resource, which is the trigger).
14708: 
14709:      - $showitem - 1 => show title for map itself; 0 => do not show.
14710: 
14711: Outputs: 1 @pathitems - array of folder/subfolder names.
14712: 
14713: =cut
14714: 
14715: sub get_folder_hierarchy {
14716:     my ($navmap,$map,$showitem) = @_;
14717:     my @pathitems;
14718:     if (ref($navmap)) {
14719:         my $mapres = $navmap->getResourceByUrl($map);
14720:         if (ref($mapres)) {
14721:             my $pcslist = $mapres->map_hierarchy();
14722:             if ($pcslist ne '') {
14723:                 my @pcs = split(/,/,$pcslist);
14724:                 foreach my $pc (@pcs) {
14725:                     if ($pc == 1) {
14726:                         push(@pathitems,&mt('Main Content'));
14727:                     } else {
14728:                         my $res = $navmap->getByMapPc($pc);
14729:                         if (ref($res)) {
14730:                             my $title = $res->compTitle();
14731:                             $title =~ s/\W+/_/g;
14732:                             if ($title ne '') {
14733:                                 push(@pathitems,$title);
14734:                             }
14735:                         }
14736:                     }
14737:                 }
14738:             }
14739:             if ($showitem) {
14740:                 if ($mapres->{ID} eq '0.0') {
14741:                     push(@pathitems,&mt('Main Content'));
14742:                 } else {
14743:                     my $maptitle = $mapres->compTitle();
14744:                     $maptitle =~ s/\W+/_/g;
14745:                     if ($maptitle ne '') {
14746:                         push(@pathitems,$maptitle);
14747:                     }
14748:                 }
14749:             }
14750:         }
14751:     }
14752:     return @pathitems;
14753: }
14754: 
14755: =pod
14756: 
14757: =item * &get_turnedin_filepath()
14758: 
14759: Determines path in a user's portfolio file for storage of files uploaded
14760: to a specific essayresponse or dropbox item.
14761: 
14762: Inputs: 3 required + 1 optional.
14763: $symb is symb for resource, $uname and $udom are for current user (required).
14764: $caller is optional (can be "submission", if routine is called when storing
14765: an upoaded file when "Submit Answer" button was pressed).
14766: 
14767: Returns array containing $path and $multiresp. 
14768: $path is path in portfolio.  $multiresp is 1 if this resource contains more
14769: than one file upload item.  Callers of routine should append partid as a 
14770: subdirectory to $path in cases where $multiresp is 1.
14771: 
14772: Called by: homework/essayresponse.pm and homework/structuretags.pm
14773: 
14774: =cut
14775: 
14776: sub get_turnedin_filepath {
14777:     my ($symb,$uname,$udom,$caller) = @_;
14778:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
14779:     my $turnindir;
14780:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
14781:     $turnindir = $userhash{'turnindir'};
14782:     my ($path,$multiresp);
14783:     if ($turnindir eq '') {
14784:         if ($caller eq 'submission') {
14785:             $turnindir = &mt('turned in');
14786:             $turnindir =~ s/\W+/_/g;
14787:             my %newhash = (
14788:                             'turnindir' => $turnindir,
14789:                           );
14790:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
14791:         }
14792:     }
14793:     if ($turnindir ne '') {
14794:         $path = '/'.$turnindir.'/';
14795:         my ($multipart,$turnin,@pathitems);
14796:         my $navmap = Apache::lonnavmaps::navmap->new();
14797:         if (defined($navmap)) {
14798:             my $mapres = $navmap->getResourceByUrl($map);
14799:             if (ref($mapres)) {
14800:                 my $pcslist = $mapres->map_hierarchy();
14801:                 if ($pcslist ne '') {
14802:                     foreach my $pc (split(/,/,$pcslist)) {
14803:                         my $res = $navmap->getByMapPc($pc);
14804:                         if (ref($res)) {
14805:                             my $title = $res->compTitle();
14806:                             $title =~ s/\W+/_/g;
14807:                             if ($title ne '') {
14808:                                 if (($pc > 1) && (length($title) > 12)) {
14809:                                     $title = substr($title,0,12);
14810:                                 }
14811:                                 push(@pathitems,$title);
14812:                             }
14813:                         }
14814:                     }
14815:                 }
14816:                 my $maptitle = $mapres->compTitle();
14817:                 $maptitle =~ s/\W+/_/g;
14818:                 if ($maptitle ne '') {
14819:                     if (length($maptitle) > 12) {
14820:                         $maptitle = substr($maptitle,0,12);
14821:                     }
14822:                     push(@pathitems,$maptitle);
14823:                 }
14824:                 unless ($env{'request.state'} eq 'construct') {
14825:                     my $res = $navmap->getBySymb($symb);
14826:                     if (ref($res)) {
14827:                         my $partlist = $res->parts();
14828:                         my $totaluploads = 0;
14829:                         if (ref($partlist) eq 'ARRAY') {
14830:                             foreach my $part (@{$partlist}) {
14831:                                 my @types = $res->responseType($part);
14832:                                 my @ids = $res->responseIds($part);
14833:                                 for (my $i=0; $i < scalar(@ids); $i++) {
14834:                                     if ($types[$i] eq 'essay') {
14835:                                         my $partid = $part.'_'.$ids[$i];
14836:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
14837:                                             $totaluploads ++;
14838:                                         }
14839:                                     }
14840:                                 }
14841:                             }
14842:                             if ($totaluploads > 1) {
14843:                                 $multiresp = 1;
14844:                             }
14845:                         }
14846:                     }
14847:                 }
14848:             } else {
14849:                 return;
14850:             }
14851:         } else {
14852:             return;
14853:         }
14854:         my $restitle=&Apache::lonnet::gettitle($symb);
14855:         $restitle =~ s/\W+/_/g;
14856:         if ($restitle eq '') {
14857:             $restitle = ($resurl =~ m{/[^/]+$});
14858:             if ($restitle eq '') {
14859:                 $restitle = time;
14860:             }
14861:         }
14862:         if (length($restitle) > 12) {
14863:             $restitle = substr($restitle,0,12);
14864:         }
14865:         push(@pathitems,$restitle);
14866:         $path .= join('/',@pathitems);
14867:     }
14868:     return ($path,$multiresp);
14869: }
14870: 
14871: =pod
14872: 
14873: =back
14874: 
14875: =head1 CSV Upload/Handling functions
14876: 
14877: =over 4
14878: 
14879: =item * &upfile_store($r)
14880: 
14881: Store uploaded file, $r should be the HTTP Request object,
14882: needs $env{'form.upfile'}
14883: returns $datatoken to be put into hidden field
14884: 
14885: =cut
14886: 
14887: sub upfile_store {
14888:     my $r=shift;
14889:     $env{'form.upfile'}=~s/\r/\n/gs;
14890:     $env{'form.upfile'}=~s/\f/\n/gs;
14891:     $env{'form.upfile'}=~s/\n+/\n/gs;
14892:     $env{'form.upfile'}=~s/\n+$//gs;
14893: 
14894:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
14895:                                      '_enroll_'.$env{'request.course.id'}.'_'.
14896:                                      time.'_'.$$);
14897:     return if ($datatoken eq '');
14898: 
14899:     {
14900:         my $datafile = $r->dir_config('lonDaemons').
14901:                            '/tmp/'.$datatoken.'.tmp';
14902:         if ( open(my $fh,'>',$datafile) ) {
14903:             print $fh $env{'form.upfile'};
14904:             close($fh);
14905:         }
14906:     }
14907:     return $datatoken;
14908: }
14909: 
14910: =pod
14911: 
14912: =item * &load_tmp_file($r,$datatoken)
14913: 
14914: Load uploaded file from tmp, $r should be the HTTP Request object,
14915: $datatoken is the name to assign to the temporary file.
14916: sets $env{'form.upfile'} to the contents of the file
14917: 
14918: =cut
14919: 
14920: sub load_tmp_file {
14921:     my ($r,$datatoken) = @_;
14922:     return if ($datatoken eq '');
14923:     my @studentdata=();
14924:     {
14925:         my $studentfile = $r->dir_config('lonDaemons').
14926:                               '/tmp/'.$datatoken.'.tmp';
14927:         if ( open(my $fh,'<',$studentfile) ) {
14928:             @studentdata=<$fh>;
14929:             close($fh);
14930:         }
14931:     }
14932:     $env{'form.upfile'}=join('',@studentdata);
14933: }
14934: 
14935: sub valid_datatoken {
14936:     my ($datatoken) = @_;
14937:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
14938:         return $datatoken;
14939:     }
14940:     return;
14941: }
14942: 
14943: =pod
14944: 
14945: =item * &upfile_record_sep()
14946: 
14947: Separate uploaded file into records
14948: returns array of records,
14949: needs $env{'form.upfile'} and $env{'form.upfiletype'}
14950: 
14951: =cut
14952: 
14953: sub upfile_record_sep {
14954:     if ($env{'form.upfiletype'} eq 'xml') {
14955:     } else {
14956: 	my @records;
14957: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
14958: 	    if ($line=~/^\s*$/) { next; }
14959: 	    push(@records,$line);
14960: 	}
14961: 	return @records;
14962:     }
14963: }
14964: 
14965: =pod
14966: 
14967: =item * &record_sep($record)
14968: 
14969: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
14970: 
14971: =cut
14972: 
14973: sub takeleft {
14974:     my $index=shift;
14975:     return substr('0000'.$index,-4,4);
14976: }
14977: 
14978: sub record_sep {
14979:     my $record=shift;
14980:     my %components=();
14981:     if ($env{'form.upfiletype'} eq 'xml') {
14982:     } elsif ($env{'form.upfiletype'} eq 'space') {
14983:         my $i=0;
14984:         foreach my $field (split(/\s+/,$record)) {
14985:             $field=~s/^(\"|\')//;
14986:             $field=~s/(\"|\')$//;
14987:             $components{&takeleft($i)}=$field;
14988:             $i++;
14989:         }
14990:     } elsif ($env{'form.upfiletype'} eq 'tab') {
14991:         my $i=0;
14992:         foreach my $field (split(/\t/,$record)) {
14993:             $field=~s/^(\"|\')//;
14994:             $field=~s/(\"|\')$//;
14995:             $components{&takeleft($i)}=$field;
14996:             $i++;
14997:         }
14998:     } else {
14999:         my $separator=',';
15000:         if ($env{'form.upfiletype'} eq 'semisv') {
15001:             $separator=';';
15002:         }
15003:         my $i=0;
15004: # the character we are looking for to indicate the end of a quote or a record 
15005:         my $looking_for=$separator;
15006: # do not add the characters to the fields
15007:         my $ignore=0;
15008: # we just encountered a separator (or the beginning of the record)
15009:         my $just_found_separator=1;
15010: # store the field we are working on here
15011:         my $field='';
15012: # work our way through all characters in record
15013:         foreach my $character ($record=~/(.)/g) {
15014:             if ($character eq $looking_for) {
15015:                if ($character ne $separator) {
15016: # Found the end of a quote, again looking for separator
15017:                   $looking_for=$separator;
15018:                   $ignore=1;
15019:                } else {
15020: # Found a separator, store away what we got
15021:                   $components{&takeleft($i)}=$field;
15022: 	          $i++;
15023:                   $just_found_separator=1;
15024:                   $ignore=0;
15025:                   $field='';
15026:                }
15027:                next;
15028:             }
15029: # single or double quotation marks after a separator indicate beginning of a quote
15030: # we are now looking for the end of the quote and need to ignore separators
15031:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
15032:                $looking_for=$character;
15033:                next;
15034:             }
15035: # ignore would be true after we reached the end of a quote
15036:             if ($ignore) { next; }
15037:             if (($just_found_separator) && ($character=~/\s/)) { next; }
15038:             $field.=$character;
15039:             $just_found_separator=0; 
15040:         }
15041: # catch the very last entry, since we never encountered the separator
15042:         $components{&takeleft($i)}=$field;
15043:     }
15044:     return %components;
15045: }
15046: 
15047: ######################################################
15048: ######################################################
15049: 
15050: =pod
15051: 
15052: =item * &upfile_select_html()
15053: 
15054: Return HTML code to select a file from the users machine and specify 
15055: the file type.
15056: 
15057: =cut
15058: 
15059: ######################################################
15060: ######################################################
15061: sub upfile_select_html {
15062:     my %Types = (
15063:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
15064:                  semisv => &mt('Semicolon separated values'),
15065:                  space => &mt('Space separated'),
15066:                  tab   => &mt('Tabulator separated'),
15067: #                 xml   => &mt('HTML/XML'),
15068:                  );
15069:     my $Str = '<input type="file" name="upfile" size="50" />'.
15070:         '<br />'.&mt('Type').': <select name="upfiletype">';
15071:     foreach my $type (sort(keys(%Types))) {
15072:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
15073:     }
15074:     $Str .= "</select>\n";
15075:     return $Str;
15076: }
15077: 
15078: sub get_samples {
15079:     my ($records,$toget) = @_;
15080:     my @samples=({});
15081:     my $got=0;
15082:     foreach my $rec (@$records) {
15083: 	my %temp = &record_sep($rec);
15084: 	if (! grep(/\S/, values(%temp))) { next; }
15085: 	if (%temp) {
15086: 	    $samples[$got]=\%temp;
15087: 	    $got++;
15088: 	    if ($got == $toget) { last; }
15089: 	}
15090:     }
15091:     return \@samples;
15092: }
15093: 
15094: ######################################################
15095: ######################################################
15096: 
15097: =pod
15098: 
15099: =item * &csv_print_samples($r,$records)
15100: 
15101: Prints a table of sample values from each column uploaded $r is an
15102: Apache Request ref, $records is an arrayref from
15103: &Apache::loncommon::upfile_record_sep
15104: 
15105: =cut
15106: 
15107: ######################################################
15108: ######################################################
15109: sub csv_print_samples {
15110:     my ($r,$records) = @_;
15111:     my $samples = &get_samples($records,5);
15112: 
15113:     $r->print(&mt('Samples').'<br />'.&start_data_table().
15114:               &start_data_table_header_row());
15115:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
15116:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
15117:     $r->print(&end_data_table_header_row());
15118:     foreach my $hash (@$samples) {
15119: 	$r->print(&start_data_table_row());
15120: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
15121: 	    $r->print('<td>');
15122: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
15123: 	    $r->print('</td>');
15124: 	}
15125: 	$r->print(&end_data_table_row());
15126:     }
15127:     $r->print(&end_data_table().'<br />'."\n");
15128: }
15129: 
15130: ######################################################
15131: ######################################################
15132: 
15133: =pod
15134: 
15135: =item * &csv_print_select_table($r,$records,$d)
15136: 
15137: Prints a table to create associations between values and table columns.
15138: 
15139: $r is an Apache Request ref,
15140: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
15141: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
15142: 
15143: =cut
15144: 
15145: ######################################################
15146: ######################################################
15147: sub csv_print_select_table {
15148:     my ($r,$records,$d) = @_;
15149:     my $i=0;
15150:     my $samples = &get_samples($records,1);
15151:     $r->print(&mt('Associate columns with student attributes.')."\n".
15152: 	      &start_data_table().&start_data_table_header_row().
15153:               '<th>'.&mt('Attribute').'</th>'.
15154:               '<th>'.&mt('Column').'</th>'.
15155:               &end_data_table_header_row()."\n");
15156:     foreach my $array_ref (@$d) {
15157: 	my ($value,$display,$defaultcol)=@{ $array_ref };
15158: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
15159: 
15160: 	$r->print('<td><select name="f'.$i.'"'.
15161: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
15162: 	$r->print('<option value="none"></option>');
15163: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
15164: 	    $r->print('<option value="'.$sample.'"'.
15165:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
15166:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
15167: 	}
15168: 	$r->print('</select></td>'.&end_data_table_row()."\n");
15169: 	$i++;
15170:     }
15171:     $r->print(&end_data_table());
15172:     $i--;
15173:     return $i;
15174: }
15175: 
15176: ######################################################
15177: ######################################################
15178: 
15179: =pod
15180: 
15181: =item * &csv_samples_select_table($r,$records,$d)
15182: 
15183: Prints a table of sample values from the upload and can make associate samples to internal names.
15184: 
15185: $r is an Apache Request ref,
15186: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
15187: $d is an array of 2 element arrays (internal name, displayed name)
15188: 
15189: =cut
15190: 
15191: ######################################################
15192: ######################################################
15193: sub csv_samples_select_table {
15194:     my ($r,$records,$d) = @_;
15195:     my $i=0;
15196:     #
15197:     my $max_samples = 5;
15198:     my $samples = &get_samples($records,$max_samples);
15199:     $r->print(&start_data_table().
15200:               &start_data_table_header_row().'<th>'.
15201:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
15202:               &end_data_table_header_row());
15203: 
15204:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
15205: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
15206: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
15207: 	foreach my $option (@$d) {
15208: 	    my ($value,$display,$defaultcol)=@{ $option };
15209: 	    $r->print('<option value="'.$value.'"'.
15210:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
15211:                       $display.'</option>');
15212: 	}
15213: 	$r->print('</select></td><td>');
15214: 	foreach my $line (0..($max_samples-1)) {
15215: 	    if (defined($samples->[$line]{$key})) { 
15216: 		$r->print($samples->[$line]{$key}."<br />\n"); 
15217: 	    }
15218: 	}
15219: 	$r->print('</td>'.&end_data_table_row());
15220: 	$i++;
15221:     }
15222:     $r->print(&end_data_table());
15223:     $i--;
15224:     return($i);
15225: }
15226: 
15227: ######################################################
15228: ######################################################
15229: 
15230: =pod
15231: 
15232: =item * &clean_excel_name($name)
15233: 
15234: Returns a replacement for $name which does not contain any illegal characters.
15235: 
15236: =cut
15237: 
15238: ######################################################
15239: ######################################################
15240: sub clean_excel_name {
15241:     my ($name) = @_;
15242:     $name =~ s/[:\*\?\/\\]//g;
15243:     if (length($name) > 31) {
15244:         $name = substr($name,0,31);
15245:     }
15246:     return $name;
15247: }
15248: 
15249: =pod
15250: 
15251: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
15252: 
15253: Returns either 1 or undef
15254: 
15255: 1 if the part is to be hidden, undef if it is to be shown
15256: 
15257: Arguments are:
15258: 
15259: $id the id of the part to be checked
15260: $symb, optional the symb of the resource to check
15261: $udom, optional the domain of the user to check for
15262: $uname, optional the username of the user to check for
15263: 
15264: =cut
15265: 
15266: sub check_if_partid_hidden {
15267:     my ($id,$symb,$udom,$uname) = @_;
15268:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
15269: 					 $symb,$udom,$uname);
15270:     my $truth=1;
15271:     #if the string starts with !, then the list is the list to show not hide
15272:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
15273:     my @hiddenlist=split(/,/,$hiddenparts);
15274:     foreach my $checkid (@hiddenlist) {
15275: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
15276:     }
15277:     return !$truth;
15278: }
15279: 
15280: 
15281: ############################################################
15282: ############################################################
15283: 
15284: =pod
15285: 
15286: =back 
15287: 
15288: =head1 cgi-bin script and graphing routines
15289: 
15290: =over 4
15291: 
15292: =item * &get_cgi_id()
15293: 
15294: Inputs: none
15295: 
15296: Returns an id which can be used to pass environment variables
15297: to various cgi-bin scripts.  These environment variables will
15298: be removed from the users environment after a given time by
15299: the routine &Apache::lonnet::transfer_profile_to_env.
15300: 
15301: =cut
15302: 
15303: ############################################################
15304: ############################################################
15305: my $uniq=0;
15306: sub get_cgi_id {
15307:     $uniq=($uniq+1)%100000;
15308:     return (time.'_'.$$.'_'.$uniq);
15309: }
15310: 
15311: ############################################################
15312: ############################################################
15313: 
15314: =pod
15315: 
15316: =item * &DrawBarGraph()
15317: 
15318: Facilitates the plotting of data in a (stacked) bar graph.
15319: Puts plot definition data into the users environment in order for 
15320: graph.png to plot it.  Returns an <img> tag for the plot.
15321: The bars on the plot are labeled '1','2',...,'n'.
15322: 
15323: Inputs:
15324: 
15325: =over 4
15326: 
15327: =item $Title: string, the title of the plot
15328: 
15329: =item $xlabel: string, text describing the X-axis of the plot
15330: 
15331: =item $ylabel: string, text describing the Y-axis of the plot
15332: 
15333: =item $Max: scalar, the maximum Y value to use in the plot
15334: If $Max is < any data point, the graph will not be rendered.
15335: 
15336: =item $colors: array ref holding the colors to be used for the data sets when
15337: they are plotted.  If undefined, default values will be used.
15338: 
15339: =item $labels: array ref holding the labels to use on the x-axis for the bars.
15340: 
15341: =item @Values: An array of array references.  Each array reference holds data
15342: to be plotted in a stacked bar chart.
15343: 
15344: =item If the final element of @Values is a hash reference the key/value
15345: pairs will be added to the graph definition.
15346: 
15347: =back
15348: 
15349: Returns:
15350: 
15351: An <img> tag which references graph.png and the appropriate identifying
15352: information for the plot.
15353: 
15354: =cut
15355: 
15356: ############################################################
15357: ############################################################
15358: sub DrawBarGraph {
15359:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
15360:     #
15361:     if (! defined($colors)) {
15362:         $colors = ['#33ff00', 
15363:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
15364:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
15365:                   ]; 
15366:     }
15367:     my $extra_settings = {};
15368:     if (ref($Values[-1]) eq 'HASH') {
15369:         $extra_settings = pop(@Values);
15370:     }
15371:     #
15372:     my $identifier = &get_cgi_id();
15373:     my $id = 'cgi.'.$identifier;        
15374:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
15375:         return '';
15376:     }
15377:     #
15378:     my @Labels;
15379:     if (defined($labels)) {
15380:         @Labels = @$labels;
15381:     } else {
15382:         for (my $i=0;$i<@{$Values[0]};$i++) {
15383:             push(@Labels,$i+1);
15384:         }
15385:     }
15386:     #
15387:     my $NumBars = scalar(@{$Values[0]});
15388:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
15389:     my %ValuesHash;
15390:     my $NumSets=1;
15391:     foreach my $array (@Values) {
15392:         next if (! ref($array));
15393:         $ValuesHash{$id.'.data.'.$NumSets++} = 
15394:             join(',',@$array);
15395:     }
15396:     #
15397:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
15398:     if ($NumBars < 3) {
15399:         $width = 120+$NumBars*32;
15400:         $xskip = 1;
15401:         $bar_width = 30;
15402:     } elsif ($NumBars < 5) {
15403:         $width = 120+$NumBars*20;
15404:         $xskip = 1;
15405:         $bar_width = 20;
15406:     } elsif ($NumBars < 10) {
15407:         $width = 120+$NumBars*15;
15408:         $xskip = 1;
15409:         $bar_width = 15;
15410:     } elsif ($NumBars <= 25) {
15411:         $width = 120+$NumBars*11;
15412:         $xskip = 5;
15413:         $bar_width = 8;
15414:     } elsif ($NumBars <= 50) {
15415:         $width = 120+$NumBars*8;
15416:         $xskip = 5;
15417:         $bar_width = 4;
15418:     } else {
15419:         $width = 120+$NumBars*8;
15420:         $xskip = 5;
15421:         $bar_width = 4;
15422:     }
15423:     #
15424:     $Max = 1 if ($Max < 1);
15425:     if ( int($Max) < $Max ) {
15426:         $Max++;
15427:         $Max = int($Max);
15428:     }
15429:     $Title  = '' if (! defined($Title));
15430:     $xlabel = '' if (! defined($xlabel));
15431:     $ylabel = '' if (! defined($ylabel));
15432:     $ValuesHash{$id.'.title'}    = &escape($Title);
15433:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
15434:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
15435:     $ValuesHash{$id.'.y_max_value'} = $Max;
15436:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
15437:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
15438:     $ValuesHash{$id.'.PlotType'} = 'bar';
15439:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
15440:     $ValuesHash{$id.'.height'}   = $height;
15441:     $ValuesHash{$id.'.width'}    = $width;
15442:     $ValuesHash{$id.'.xskip'}    = $xskip;
15443:     $ValuesHash{$id.'.bar_width'} = $bar_width;
15444:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
15445:     #
15446:     # Deal with other parameters
15447:     while (my ($key,$value) = each(%$extra_settings)) {
15448:         $ValuesHash{$id.'.'.$key} = $value;
15449:     }
15450:     #
15451:     &Apache::lonnet::appenv(\%ValuesHash);
15452:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15453: }
15454: 
15455: ############################################################
15456: ############################################################
15457: 
15458: =pod
15459: 
15460: =item * &DrawXYGraph()
15461: 
15462: Facilitates the plotting of data in an XY graph.
15463: Puts plot definition data into the users environment in order for 
15464: graph.png to plot it.  Returns an <img> tag for the plot.
15465: 
15466: Inputs:
15467: 
15468: =over 4
15469: 
15470: =item $Title: string, the title of the plot
15471: 
15472: =item $xlabel: string, text describing the X-axis of the plot
15473: 
15474: =item $ylabel: string, text describing the Y-axis of the plot
15475: 
15476: =item $Max: scalar, the maximum Y value to use in the plot
15477: If $Max is < any data point, the graph will not be rendered.
15478: 
15479: =item $colors: Array ref containing the hex color codes for the data to be 
15480: plotted in.  If undefined, default values will be used.
15481: 
15482: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
15483: 
15484: =item $Ydata: Array ref containing Array refs.  
15485: Each of the contained arrays will be plotted as a separate curve.
15486: 
15487: =item %Values: hash indicating or overriding any default values which are 
15488: passed to graph.png.  
15489: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
15490: 
15491: =back
15492: 
15493: Returns:
15494: 
15495: An <img> tag which references graph.png and the appropriate identifying
15496: information for the plot.
15497: 
15498: =cut
15499: 
15500: ############################################################
15501: ############################################################
15502: sub DrawXYGraph {
15503:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
15504:     #
15505:     # Create the identifier for the graph
15506:     my $identifier = &get_cgi_id();
15507:     my $id = 'cgi.'.$identifier;
15508:     #
15509:     $Title  = '' if (! defined($Title));
15510:     $xlabel = '' if (! defined($xlabel));
15511:     $ylabel = '' if (! defined($ylabel));
15512:     my %ValuesHash = 
15513:         (
15514:          $id.'.title'  => &escape($Title),
15515:          $id.'.xlabel' => &escape($xlabel),
15516:          $id.'.ylabel' => &escape($ylabel),
15517:          $id.'.y_max_value'=> $Max,
15518:          $id.'.labels'     => join(',',@$Xlabels),
15519:          $id.'.PlotType'   => 'XY',
15520:          );
15521:     #
15522:     if (defined($colors) && ref($colors) eq 'ARRAY') {
15523:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
15524:     }
15525:     #
15526:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
15527:         return '';
15528:     }
15529:     my $NumSets=1;
15530:     foreach my $array (@{$Ydata}){
15531:         next if (! ref($array));
15532:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
15533:     }
15534:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
15535:     #
15536:     # Deal with other parameters
15537:     while (my ($key,$value) = each(%Values)) {
15538:         $ValuesHash{$id.'.'.$key} = $value;
15539:     }
15540:     #
15541:     &Apache::lonnet::appenv(\%ValuesHash);
15542:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15543: }
15544: 
15545: ############################################################
15546: ############################################################
15547: 
15548: =pod
15549: 
15550: =item * &DrawXYYGraph()
15551: 
15552: Facilitates the plotting of data in an XY graph with two Y axes.
15553: Puts plot definition data into the users environment in order for 
15554: graph.png to plot it.  Returns an <img> tag for the plot.
15555: 
15556: Inputs:
15557: 
15558: =over 4
15559: 
15560: =item $Title: string, the title of the plot
15561: 
15562: =item $xlabel: string, text describing the X-axis of the plot
15563: 
15564: =item $ylabel: string, text describing the Y-axis of the plot
15565: 
15566: =item $colors: Array ref containing the hex color codes for the data to be 
15567: plotted in.  If undefined, default values will be used.
15568: 
15569: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
15570: 
15571: =item $Ydata1: The first data set
15572: 
15573: =item $Min1: The minimum value of the left Y-axis
15574: 
15575: =item $Max1: The maximum value of the left Y-axis
15576: 
15577: =item $Ydata2: The second data set
15578: 
15579: =item $Min2: The minimum value of the right Y-axis
15580: 
15581: =item $Max2: The maximum value of the left Y-axis
15582: 
15583: =item %Values: hash indicating or overriding any default values which are 
15584: passed to graph.png.  
15585: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
15586: 
15587: =back
15588: 
15589: Returns:
15590: 
15591: An <img> tag which references graph.png and the appropriate identifying
15592: information for the plot.
15593: 
15594: =cut
15595: 
15596: ############################################################
15597: ############################################################
15598: sub DrawXYYGraph {
15599:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
15600:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
15601:     #
15602:     # Create the identifier for the graph
15603:     my $identifier = &get_cgi_id();
15604:     my $id = 'cgi.'.$identifier;
15605:     #
15606:     $Title  = '' if (! defined($Title));
15607:     $xlabel = '' if (! defined($xlabel));
15608:     $ylabel = '' if (! defined($ylabel));
15609:     my %ValuesHash = 
15610:         (
15611:          $id.'.title'  => &escape($Title),
15612:          $id.'.xlabel' => &escape($xlabel),
15613:          $id.'.ylabel' => &escape($ylabel),
15614:          $id.'.labels' => join(',',@$Xlabels),
15615:          $id.'.PlotType' => 'XY',
15616:          $id.'.NumSets' => 2,
15617:          $id.'.two_axes' => 1,
15618:          $id.'.y1_max_value' => $Max1,
15619:          $id.'.y1_min_value' => $Min1,
15620:          $id.'.y2_max_value' => $Max2,
15621:          $id.'.y2_min_value' => $Min2,
15622:          );
15623:     #
15624:     if (defined($colors) && ref($colors) eq 'ARRAY') {
15625:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
15626:     }
15627:     #
15628:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
15629:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
15630:         return '';
15631:     }
15632:     my $NumSets=1;
15633:     foreach my $array ($Ydata1,$Ydata2){
15634:         next if (! ref($array));
15635:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
15636:     }
15637:     #
15638:     # Deal with other parameters
15639:     while (my ($key,$value) = each(%Values)) {
15640:         $ValuesHash{$id.'.'.$key} = $value;
15641:     }
15642:     #
15643:     &Apache::lonnet::appenv(\%ValuesHash);
15644:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15645: }
15646: 
15647: ############################################################
15648: ############################################################
15649: 
15650: =pod
15651: 
15652: =back 
15653: 
15654: =head1 Statistics helper routines?  
15655: 
15656: Bad place for them but what the hell.
15657: 
15658: =over 4
15659: 
15660: =item * &chartlink()
15661: 
15662: Returns a link to the chart for a specific student.  
15663: 
15664: Inputs:
15665: 
15666: =over 4
15667: 
15668: =item $linktext: The text of the link
15669: 
15670: =item $sname: The students username
15671: 
15672: =item $sdomain: The students domain
15673: 
15674: =back
15675: 
15676: =back
15677: 
15678: =cut
15679: 
15680: ############################################################
15681: ############################################################
15682: sub chartlink {
15683:     my ($linktext, $sname, $sdomain) = @_;
15684:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
15685:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
15686:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
15687:        '">'.$linktext.'</a>';
15688: }
15689: 
15690: #######################################################
15691: #######################################################
15692: 
15693: =pod
15694: 
15695: =head1 Course Environment Routines
15696: 
15697: =over 4
15698: 
15699: =item * &restore_course_settings()
15700: 
15701: =item * &store_course_settings()
15702: 
15703: Restores/Store indicated form parameters from the course environment.
15704: Will not overwrite existing values of the form parameters.
15705: 
15706: Inputs: 
15707: a scalar describing the data (e.g. 'chart', 'problem_analysis')
15708: 
15709: a hash ref describing the data to be stored.  For example:
15710:    
15711: %Save_Parameters = ('Status' => 'scalar',
15712:     'chartoutputmode' => 'scalar',
15713:     'chartoutputdata' => 'scalar',
15714:     'Section' => 'array',
15715:     'Group' => 'array',
15716:     'StudentData' => 'array',
15717:     'Maps' => 'array');
15718: 
15719: Returns: both routines return nothing
15720: 
15721: =back
15722: 
15723: =cut
15724: 
15725: #######################################################
15726: #######################################################
15727: sub store_course_settings {
15728:     return &store_settings($env{'request.course.id'},@_);
15729: }
15730: 
15731: sub store_settings {
15732:     # save to the environment
15733:     # appenv the same items, just to be safe
15734:     my $udom  = $env{'user.domain'};
15735:     my $uname = $env{'user.name'};
15736:     my ($context,$prefix,$Settings) = @_;
15737:     my %SaveHash;
15738:     my %AppHash;
15739:     while (my ($setting,$type) = each(%$Settings)) {
15740:         my $basename = join('.','internal',$context,$prefix,$setting);
15741:         my $envname = 'environment.'.$basename;
15742:         if (exists($env{'form.'.$setting})) {
15743:             # Save this value away
15744:             if ($type eq 'scalar' &&
15745:                 (! exists($env{$envname}) || 
15746:                  $env{$envname} ne $env{'form.'.$setting})) {
15747:                 $SaveHash{$basename} = $env{'form.'.$setting};
15748:                 $AppHash{$envname}   = $env{'form.'.$setting};
15749:             } elsif ($type eq 'array') {
15750:                 my $stored_form;
15751:                 if (ref($env{'form.'.$setting})) {
15752:                     $stored_form = join(',',
15753:                                         map {
15754:                                             &escape($_);
15755:                                         } sort(@{$env{'form.'.$setting}}));
15756:                 } else {
15757:                     $stored_form = 
15758:                         &escape($env{'form.'.$setting});
15759:                 }
15760:                 # Determine if the array contents are the same.
15761:                 if ($stored_form ne $env{$envname}) {
15762:                     $SaveHash{$basename} = $stored_form;
15763:                     $AppHash{$envname}   = $stored_form;
15764:                 }
15765:             }
15766:         }
15767:     }
15768:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
15769:                                           $udom,$uname);
15770:     if ($put_result !~ /^(ok|delayed)/) {
15771:         &Apache::lonnet::logthis('unable to save form parameters, '.
15772:                                  'got error:'.$put_result);
15773:     }
15774:     # Make sure these settings stick around in this session, too
15775:     &Apache::lonnet::appenv(\%AppHash);
15776:     return;
15777: }
15778: 
15779: sub restore_course_settings {
15780:     return &restore_settings($env{'request.course.id'},@_);
15781: }
15782: 
15783: sub restore_settings {
15784:     my ($context,$prefix,$Settings) = @_;
15785:     while (my ($setting,$type) = each(%$Settings)) {
15786:         next if (exists($env{'form.'.$setting}));
15787:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
15788:             '.'.$setting;
15789:         if (exists($env{$envname})) {
15790:             if ($type eq 'scalar') {
15791:                 $env{'form.'.$setting} = $env{$envname};
15792:             } elsif ($type eq 'array') {
15793:                 $env{'form.'.$setting} = [ 
15794:                                            map { 
15795:                                                &unescape($_); 
15796:                                            } split(',',$env{$envname})
15797:                                            ];
15798:             }
15799:         }
15800:     }
15801: }
15802: 
15803: #######################################################
15804: #######################################################
15805: 
15806: =pod
15807: 
15808: =head1 Domain E-mail Routines  
15809: 
15810: =over 4
15811: 
15812: =item * &build_recipient_list()
15813: 
15814: Build recipient lists for following types of e-mail:
15815: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
15816: (d) Help requests, (e) Course requests needing approval, (f) loncapa
15817: module change checking, student/employee ID conflict checks, as
15818: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
15819: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
15820: 
15821: Inputs:
15822: defmail (scalar - email address of default recipient), 
15823: mailing type (scalar: errormail, packagesmail, helpdeskmail,
15824: requestsmail, updatesmail, or idconflictsmail).
15825: 
15826: defdom (domain for which to retrieve configuration settings),
15827: 
15828: origmail (scalar - email address of recipient from loncapa.conf, 
15829: i.e., predates configuration by DC via domainprefs.pm
15830: 
15831: $requname username of requester (if mailing type is helpdeskmail)
15832: 
15833: $requdom domain of requester (if mailing type is helpdeskmail)
15834: 
15835: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
15836: 
15837: 
15838: Returns: comma separated list of addresses to which to send e-mail.
15839: 
15840: =back
15841: 
15842: =cut
15843: 
15844: ############################################################
15845: ############################################################
15846: sub build_recipient_list {
15847:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
15848:     my @recipients;
15849:     my ($otheremails,$lastresort,$allbcc,$addtext);
15850:     my %domconfig =
15851:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
15852:     if (ref($domconfig{'contacts'}) eq 'HASH') {
15853:         if (exists($domconfig{'contacts'}{$mailing})) {
15854:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
15855:                 my @contacts = ('adminemail','supportemail');
15856:                 foreach my $item (@contacts) {
15857:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
15858:                         my $addr = $domconfig{'contacts'}{$item}; 
15859:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
15860:                             push(@recipients,$addr);
15861:                         }
15862:                     }
15863:                 }
15864:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
15865:                 if ($mailing eq 'helpdeskmail') {
15866:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
15867:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
15868:                         my @ok_bccs;
15869:                         foreach my $bcc (@bccs) {
15870:                             $bcc =~ s/^\s+//g;
15871:                             $bcc =~ s/\s+$//g;
15872:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15873:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15874:                                     push(@ok_bccs,$bcc);
15875:                                 }
15876:                             }
15877:                         }
15878:                         if (@ok_bccs > 0) {
15879:                             $allbcc = join(', ',@ok_bccs);
15880:                         }
15881:                     }
15882:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
15883:                 }
15884:             }
15885:         } elsif ($origmail ne '') {
15886:             $lastresort = $origmail;
15887:         }
15888:         if ($mailing eq 'helpdeskmail') {
15889:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
15890:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
15891:                 my ($inststatus,$inststatus_checked);
15892:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
15893:                     ($env{'user.domain'} ne 'public')) {
15894:                     $inststatus_checked = 1;
15895:                     $inststatus = $env{'environment.inststatus'};
15896:                 }
15897:                 unless ($inststatus_checked) {
15898:                     if (($requname ne '') && ($requdom ne '')) {
15899:                         if (($requname =~ /^$match_username$/) &&
15900:                             ($requdom =~ /^$match_domain$/) &&
15901:                             (&Apache::lonnet::domain($requdom))) {
15902:                             my $requhome = &Apache::lonnet::homeserver($requname,
15903:                                                                       $requdom);
15904:                             unless ($requhome eq 'no_host') {
15905:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
15906:                                 $inststatus = $userenv{'inststatus'};
15907:                                 $inststatus_checked = 1;
15908:                             }
15909:                         }
15910:                     }
15911:                 }
15912:                 unless ($inststatus_checked) {
15913:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
15914:                         my %srch = (srchby     => 'email',
15915:                                     srchdomain => $defdom,
15916:                                     srchterm   => $reqemail,
15917:                                     srchtype   => 'exact');
15918:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
15919:                         foreach my $uname (keys(%srch_results)) {
15920:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
15921:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
15922:                                 $inststatus_checked = 1;
15923:                                 last;
15924:                             }
15925:                         }
15926:                         unless ($inststatus_checked) {
15927:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
15928:                             if ($dirsrchres eq 'ok') {
15929:                                 foreach my $uname (keys(%srch_results)) {
15930:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
15931:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
15932:                                         $inststatus_checked = 1;
15933:                                         last;
15934:                                     }
15935:                                 }
15936:                             }
15937:                         }
15938:                     }
15939:                 }
15940:                 if ($inststatus ne '') {
15941:                     foreach my $status (split(/\:/,$inststatus)) {
15942:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
15943:                             my @contacts = ('adminemail','supportemail');
15944:                             foreach my $item (@contacts) {
15945:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
15946:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
15947:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
15948:                                         push(@recipients,$addr);
15949:                                     }
15950:                                 }
15951:                             }
15952:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
15953:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
15954:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
15955:                                 my @ok_bccs;
15956:                                 foreach my $bcc (@bccs) {
15957:                                     $bcc =~ s/^\s+//g;
15958:                                     $bcc =~ s/\s+$//g;
15959:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15960:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15961:                                             push(@ok_bccs,$bcc);
15962:                                         }
15963:                                     }
15964:                                 }
15965:                                 if (@ok_bccs > 0) {
15966:                                     $allbcc = join(', ',@ok_bccs);
15967:                                 }
15968:                             }
15969:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
15970:                             last;
15971:                         }
15972:                     }
15973:                 }
15974:             }
15975:         }
15976:     } elsif ($origmail ne '') {
15977:         $lastresort = $origmail;
15978:     }
15979:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
15980:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
15981:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
15982:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
15983:             my %what = (
15984:                           perlvar => 1,
15985:                        );
15986:             my $primary = &Apache::lonnet::domain($defdom,'primary');
15987:             if ($primary) {
15988:                 my $gotaddr;
15989:                 my ($result,$returnhash) =
15990:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
15991:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
15992:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
15993:                         $lastresort = $returnhash->{'lonSupportEMail'};
15994:                         $gotaddr = 1;
15995:                     }
15996:                 }
15997:                 unless ($gotaddr) {
15998:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
15999:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
16000:                     unless ($uintdom eq $intdom) {
16001:                         my %domconfig =
16002:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
16003:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
16004:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
16005:                                 my @contacts = ('adminemail','supportemail');
16006:                                 foreach my $item (@contacts) {
16007:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
16008:                                         my $addr = $domconfig{'contacts'}{$item};
16009:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
16010:                                             push(@recipients,$addr);
16011:                                         }
16012:                                     }
16013:                                 }
16014:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
16015:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
16016:                                 }
16017:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
16018:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
16019:                                     my @ok_bccs;
16020:                                     foreach my $bcc (@bccs) {
16021:                                         $bcc =~ s/^\s+//g;
16022:                                         $bcc =~ s/\s+$//g;
16023:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
16024:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
16025:                                                 push(@ok_bccs,$bcc);
16026:                                             }
16027:                                         }
16028:                                     }
16029:                                     if (@ok_bccs > 0) {
16030:                                         $allbcc = join(', ',@ok_bccs);
16031:                                     }
16032:                                 }
16033:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
16034:                             }
16035:                         }
16036:                     }
16037:                 }
16038:             }
16039:         }
16040:     }
16041:     if (defined($defmail)) {
16042:         if ($defmail ne '') {
16043:             push(@recipients,$defmail);
16044:         }
16045:     }
16046:     if ($otheremails) {
16047:         my @others;
16048:         if ($otheremails =~ /,/) {
16049:             @others = split(/,/,$otheremails);
16050:         } else {
16051:             push(@others,$otheremails);
16052:         }
16053:         foreach my $addr (@others) {
16054:             if (!grep(/^\Q$addr\E$/,@recipients)) {
16055:                 push(@recipients,$addr);
16056:             }
16057:         }
16058:     }
16059:     if ($mailing eq 'helpdeskmail') {
16060:         if ((!@recipients) && ($lastresort ne '')) {
16061:             push(@recipients,$lastresort);
16062:         }
16063:     } elsif ($lastresort ne '') {
16064:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
16065:             push(@recipients,$lastresort);
16066:         }
16067:     }
16068:     my $recipientlist = join(',',@recipients);
16069:     if (wantarray) {
16070:         return ($recipientlist,$allbcc,$addtext);
16071:     } else {
16072:         return $recipientlist;
16073:     }
16074: }
16075: 
16076: ############################################################
16077: ############################################################
16078: 
16079: =pod
16080: 
16081: =over 4
16082: 
16083: =item * &mime_email()
16084: 
16085: Sends an email with a possible attachment
16086: 
16087: Inputs:
16088: 
16089: =over 4
16090: 
16091: from -              Sender's email address
16092: 
16093: replyto -           Reply-To email address
16094: 
16095: to -                Email address of recipient
16096: 
16097: subject -           Subject of email
16098: 
16099: body -              Body of email
16100: 
16101: cc_string -         Carbon copy email address
16102: 
16103: bcc -               Blind carbon copy email address
16104: 
16105: attachment_path -   Path of file to be attached
16106: 
16107: file_name -         Name of file to be attached
16108: 
16109: attachment_text -   The body of an attachment of type "TEXT"
16110: 
16111: =back
16112: 
16113: =back
16114: 
16115: =cut
16116: 
16117: ############################################################
16118: ############################################################
16119: 
16120: sub mime_email {
16121:     my ($from,$replyto,$to,$subject,$body,$cc_string,$bcc,$attachment_path, 
16122:         $file_name,$attachment_text) = @_;
16123:  
16124:     my $msg = MIME::Lite->new(
16125:              From    => $from,
16126:              To      => $to,
16127:              Subject => $subject,
16128:              Type    =>'TEXT',
16129:              Data    => $body,
16130:              );
16131:     if ($replyto ne '') {
16132:         $msg->add("Reply-To" => $replyto);
16133:     }
16134:     if ($cc_string ne '') {
16135:         $msg->add("Cc" => $cc_string);
16136:     }
16137:     if ($bcc ne '') {
16138:         $msg->add("Bcc" => $bcc);
16139:     }
16140:     $msg->attr("content-type"         => "text/plain");
16141:     $msg->attr("content-type.charset" => "UTF-8");
16142:     # Attach file if given
16143:     if ($attachment_path) {
16144:         unless ($file_name) {
16145:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
16146:         }
16147:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
16148:         $msg->attach(Type     => $type,
16149:                      Path     => $attachment_path,
16150:                      Filename => $file_name
16151:                      );
16152:     # Otherwise attach text if given
16153:     } elsif ($attachment_text) {
16154:         $msg->attach(Type => 'TEXT',
16155:                      Data => $attachment_text);
16156:     }
16157:     # Send it
16158:     $msg->send('sendmail');
16159: }
16160: 
16161: ############################################################
16162: ############################################################
16163: 
16164: =pod
16165: 
16166: =head1 Course Catalog Routines
16167: 
16168: =over 4
16169: 
16170: =item * &gather_categories()
16171: 
16172: Converts category definitions - keys of categories hash stored in  
16173: coursecategories in configuration.db on the primary library server in a 
16174: domain - to an array.  Also generates javascript and idx hash used to 
16175: generate Domain Coordinator interface for editing Course Categories.
16176: 
16177: Inputs:
16178: 
16179: categories (reference to hash of category definitions).
16180: 
16181: cats (reference to array of arrays/hashes which encapsulates hierarchy of
16182:       categories and subcategories).
16183: 
16184: idx (reference to hash of counters used in Domain Coordinator interface for 
16185:       editing Course Categories).
16186: 
16187: jsarray (reference to array of categories used to create Javascript arrays for
16188:          Domain Coordinator interface for editing Course Categories).
16189: 
16190: Returns: nothing
16191: 
16192: Side effects: populates cats, idx and jsarray. 
16193: 
16194: =cut
16195: 
16196: sub gather_categories {
16197:     my ($categories,$cats,$idx,$jsarray) = @_;
16198:     my %counters;
16199:     my $num = 0;
16200:     foreach my $item (keys(%{$categories})) {
16201:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
16202:         if ($container eq '' && $depth == 0) {
16203:             $cats->[$depth][$categories->{$item}] = $cat;
16204:         } else {
16205:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
16206:         }
16207:         my ($escitem,$tail) = split(/:/,$item,2);
16208:         if ($counters{$tail} eq '') {
16209:             $counters{$tail} = $num;
16210:             $num ++;
16211:         }
16212:         if (ref($idx) eq 'HASH') {
16213:             $idx->{$item} = $counters{$tail};
16214:         }
16215:         if (ref($jsarray) eq 'ARRAY') {
16216:             push(@{$jsarray->[$counters{$tail}]},$item);
16217:         }
16218:     }
16219:     return;
16220: }
16221: 
16222: =pod
16223: 
16224: =item * &extract_categories()
16225: 
16226: Used to generate breadcrumb trails for course categories.
16227: 
16228: Inputs:
16229: 
16230: categories (reference to hash of category definitions).
16231: 
16232: cats (reference to array of arrays/hashes which encapsulates hierarchy of
16233:       categories and subcategories).
16234: 
16235: trails (reference to array of breacrumb trails for each category).
16236: 
16237: allitems (reference to hash - key is category key 
16238:          (format: escaped(name):escaped(parent category):depth in hierarchy).
16239: 
16240: idx (reference to hash of counters used in Domain Coordinator interface for
16241:       editing Course Categories).
16242: 
16243: jsarray (reference to array of categories used to create Javascript arrays for
16244:          Domain Coordinator interface for editing Course Categories).
16245: 
16246: subcats (reference to hash of arrays containing all subcategories within each 
16247:          category, -recursive)
16248: 
16249: maxd (reference to hash used to hold max depth for all top-level categories).
16250: 
16251: Returns: nothing
16252: 
16253: Side effects: populates trails and allitems hash references.
16254: 
16255: =cut
16256: 
16257: sub extract_categories {
16258:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
16259:     if (ref($categories) eq 'HASH') {
16260:         &gather_categories($categories,$cats,$idx,$jsarray);
16261:         if (ref($cats->[0]) eq 'ARRAY') {
16262:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
16263:                 my $name = $cats->[0][$i];
16264:                 my $item = &escape($name).'::0';
16265:                 my $trailstr;
16266:                 if ($name eq 'instcode') {
16267:                     $trailstr = &mt('Official courses (with institutional codes)');
16268:                 } elsif ($name eq 'communities') {
16269:                     $trailstr = &mt('Communities');
16270:                 } elsif ($name eq 'placement') {
16271:                     $trailstr = &mt('Placement Tests');
16272:                 } else {
16273:                     $trailstr = $name;
16274:                 }
16275:                 if ($allitems->{$item} eq '') {
16276:                     push(@{$trails},$trailstr);
16277:                     $allitems->{$item} = scalar(@{$trails})-1;
16278:                 }
16279:                 my @parents = ($name);
16280:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
16281:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
16282:                         my $category = $cats->[1]{$name}[$j];
16283:                         if (ref($subcats) eq 'HASH') {
16284:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
16285:                         }
16286:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
16287:                     }
16288:                 } else {
16289:                     if (ref($subcats) eq 'HASH') {
16290:                         $subcats->{$item} = [];
16291:                     }
16292:                     if (ref($maxd) eq 'HASH') {
16293:                         $maxd->{$name} = 1;
16294:                     }
16295:                 }
16296:             }
16297:         }
16298:     }
16299:     return;
16300: }
16301: 
16302: =pod
16303: 
16304: =item * &recurse_categories()
16305: 
16306: Recursively used to generate breadcrumb trails for course categories.
16307: 
16308: Inputs:
16309: 
16310: cats (reference to array of arrays/hashes which encapsulates hierarchy of
16311:       categories and subcategories).
16312: 
16313: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
16314: 
16315: category (current course category, for which breadcrumb trail is being generated).
16316: 
16317: trails (reference to array of breadcrumb trails for each category).
16318: 
16319: allitems (reference to hash - key is category key
16320:          (format: escaped(name):escaped(parent category):depth in hierarchy).
16321: 
16322: parents (array containing containers directories for current category, 
16323:          back to top level). 
16324: 
16325: Returns: nothing
16326: 
16327: Side effects: populates trails and allitems hash references
16328: 
16329: =cut
16330: 
16331: sub recurse_categories {
16332:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
16333:     my $shallower = $depth - 1;
16334:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
16335:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
16336:             my $name = $cats->[$depth]{$category}[$k];
16337:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
16338:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
16339:             if ($allitems->{$item} eq '') {
16340:                 push(@{$trails},$trailstr);
16341:                 $allitems->{$item} = scalar(@{$trails})-1;
16342:             }
16343:             my $deeper = $depth+1;
16344:             push(@{$parents},$category);
16345:             if (ref($subcats) eq 'HASH') {
16346:                 my $subcat = &escape($name).':'.$category.':'.$depth;
16347:                 for (my $j=@{$parents}; $j>=0; $j--) {
16348:                     my $higher;
16349:                     if ($j > 0) {
16350:                         $higher = &escape($parents->[$j]).':'.
16351:                                   &escape($parents->[$j-1]).':'.$j;
16352:                     } else {
16353:                         $higher = &escape($parents->[$j]).'::'.$j;
16354:                     }
16355:                     push(@{$subcats->{$higher}},$subcat);
16356:                 }
16357:             }
16358:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
16359:                                 $subcats,$maxd);
16360:             pop(@{$parents});
16361:         }
16362:     } else {
16363:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
16364:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
16365:         if ($allitems->{$item} eq '') {
16366:             push(@{$trails},$trailstr);
16367:             $allitems->{$item} = scalar(@{$trails})-1;
16368:         }
16369:         if (ref($maxd) eq 'HASH') {
16370:             if ($depth > $maxd->{$parents->[0]}) {
16371:                 $maxd->{$parents->[0]} = $depth;
16372:             }
16373:         }
16374:     }
16375:     return;
16376: }
16377: 
16378: =pod
16379: 
16380: =item * &assign_categories_table()
16381: 
16382: Create a datatable for display of hierarchical categories in a domain,
16383: with checkboxes to allow a course to be categorized. 
16384: 
16385: Inputs:
16386: 
16387: cathash - reference to hash of categories defined for the domain (from
16388:           configuration.db)
16389: 
16390: currcat - scalar with an & separated list of categories assigned to a course. 
16391: 
16392: type    - scalar contains course type (Course or Community).
16393: 
16394: disabled - scalar (optional) contains disabled="disabled" if input elements are
16395:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
16396: 
16397: Returns: $output (markup to be displayed) 
16398: 
16399: =cut
16400: 
16401: sub assign_categories_table {
16402:     my ($cathash,$currcat,$type,$disabled) = @_;
16403:     my $output;
16404:     if (ref($cathash) eq 'HASH') {
16405:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
16406:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
16407:         $maxdepth = scalar(@cats);
16408:         if (@cats > 0) {
16409:             my $itemcount = 0;
16410:             if (ref($cats[0]) eq 'ARRAY') {
16411:                 my @currcategories;
16412:                 if ($currcat ne '') {
16413:                     @currcategories = split('&',$currcat);
16414:                 }
16415:                 my $table;
16416:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
16417:                     my $parent = $cats[0][$i];
16418:                     next if ($parent eq 'instcode');
16419:                     if ($type eq 'Community') {
16420:                         next unless ($parent eq 'communities');
16421:                     } elsif ($type eq 'Placement') {
16422:                         next unless ($parent eq 'placement');
16423:                     } else {
16424:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
16425:                     }
16426:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
16427:                     my $item = &escape($parent).'::0';
16428:                     my $checked = '';
16429:                     if (@currcategories > 0) {
16430:                         if (grep(/^\Q$item\E$/,@currcategories)) {
16431:                             $checked = ' checked="checked"';
16432:                         }
16433:                     }
16434:                     my $parent_title = $parent;
16435:                     if ($parent eq 'communities') {
16436:                         $parent_title = &mt('Communities');
16437:                     } elsif ($parent eq 'placement') {
16438:                         $parent_title = &mt('Placement Tests');
16439:                     }
16440:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
16441:                               '<input type="checkbox" name="usecategory" value="'.
16442:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
16443:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
16444:                     my $depth = 1;
16445:                     push(@path,$parent);
16446:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
16447:                     pop(@path);
16448:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
16449:                     $itemcount ++;
16450:                 }
16451:                 if ($itemcount) {
16452:                     $output = &Apache::loncommon::start_data_table().
16453:                               $table.
16454:                               &Apache::loncommon::end_data_table();
16455:                 }
16456:             }
16457:         }
16458:     }
16459:     return $output;
16460: }
16461: 
16462: =pod
16463: 
16464: =item * &assign_category_rows()
16465: 
16466: Create a datatable row for display of nested categories in a domain,
16467: with checkboxes to allow a course to be categorized,called recursively.
16468: 
16469: Inputs:
16470: 
16471: itemcount - track row number for alternating colors
16472: 
16473: cats - reference to array of arrays/hashes which encapsulates hierarchy of
16474:       categories and subcategories.
16475: 
16476: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
16477: 
16478: parent - parent of current category item
16479: 
16480: path - Array containing all categories back up through the hierarchy from the
16481:        current category to the top level.
16482: 
16483: currcategories - reference to array of current categories assigned to the course
16484: 
16485: disabled - scalar (optional) contains disabled="disabled" if input elements are
16486:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
16487: 
16488: Returns: $output (markup to be displayed).
16489: 
16490: =cut
16491: 
16492: sub assign_category_rows {
16493:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
16494:     my ($text,$name,$item,$chgstr);
16495:     if (ref($cats) eq 'ARRAY') {
16496:         my $maxdepth = scalar(@{$cats});
16497:         if (ref($cats->[$depth]) eq 'HASH') {
16498:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
16499:                 my $numchildren = @{$cats->[$depth]{$parent}};
16500:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
16501:                 $text .= '<td><table class="LC_data_table">';
16502:                 for (my $j=0; $j<$numchildren; $j++) {
16503:                     $name = $cats->[$depth]{$parent}[$j];
16504:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
16505:                     my $deeper = $depth+1;
16506:                     my $checked = '';
16507:                     if (ref($currcategories) eq 'ARRAY') {
16508:                         if (@{$currcategories} > 0) {
16509:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
16510:                                 $checked = ' checked="checked"';
16511:                             }
16512:                         }
16513:                     }
16514:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
16515:                              '<input type="checkbox" name="usecategory" value="'.
16516:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
16517:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
16518:                              '</td><td>';
16519:                     if (ref($path) eq 'ARRAY') {
16520:                         push(@{$path},$name);
16521:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
16522:                         pop(@{$path});
16523:                     }
16524:                     $text .= '</td></tr>';
16525:                 }
16526:                 $text .= '</table></td>';
16527:             }
16528:         }
16529:     }
16530:     return $text;
16531: }
16532: 
16533: =pod
16534: 
16535: =back
16536: 
16537: =cut
16538: 
16539: ############################################################
16540: ############################################################
16541: 
16542: 
16543: sub commit_customrole {
16544:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context,$othdomby,$requester) = @_;
16545:     my $result = &Apache::lonnet::assigncustomrole(
16546:                      $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,
16547:                      $context,$othdomby,$requester);
16548:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
16549:                          ($start?', '.&mt('starting').' '.localtime($start):'').
16550:                          ($end?', ending '.localtime($end):'').': <b>'.$result.'</b><br />';
16551:     if (wantarray) {
16552:         return ($output,$result);
16553:     } else {
16554:         return $output;
16555:     }
16556: }
16557: 
16558: sub commit_standardrole {
16559:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits,
16560:         $othdomby,$requester) = @_;
16561:     my ($output,$logmsg,$linefeed,$result);
16562:     if ($context eq 'auto') {
16563:         $linefeed = "\n";
16564:     } else {
16565:         $linefeed = "<br />\n";
16566:     }  
16567:     if ($three eq 'st') {
16568:         $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
16569:                                       $one,$two,$sec,$context,$credits,$othdomby,
16570:                                       $requester);
16571:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
16572:             ($result eq 'unknown_course') || ($result eq 'refused')) {
16573:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
16574:         } else {
16575:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
16576:                ($start?', '.&mt('starting').' '.localtime($start):'').
16577:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
16578:             if ($context eq 'auto') {
16579:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
16580:             } else {
16581:                $output .= '<b>'.$result.'</b>'.$linefeed.
16582:                &mt('Add to classlist').': <b>ok</b>';
16583:             }
16584:             $output .= $linefeed;
16585:         }
16586:     } else {
16587:         $output = &mt('Assigning').' '.$three.' in '.$url.
16588:                ($start?', '.&mt('starting').' '.localtime($start):'').
16589:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
16590:         $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,
16591:                                               '','',$context,$othdomby,$requester);
16592:         if ($context eq 'auto') {
16593:             $output .= $result.$linefeed;
16594:         } else {
16595:             $output .= '<b>'.$result.'</b>'.$linefeed;
16596:         }
16597:     }
16598:     if (wantarray) {
16599:         return ($output,$result);
16600:     } else {
16601:         return $output;
16602:     }
16603: }
16604: 
16605: sub commit_studentrole {
16606:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
16607:         $credits,$othdomby,$requester) = @_;
16608:     my ($result,$linefeed,$oldsecurl,$newsecurl);
16609:     if ($context eq 'auto') {
16610:         $linefeed = "\n";
16611:     } else {
16612:         $linefeed = '<br />'."\n";
16613:     }
16614:     if (defined($one) && defined($two)) {
16615:         my $cid=$one.'_'.$two;
16616:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
16617:         my $secchange = 0;
16618:         my $expire_role_result;
16619:         my $modify_section_result;
16620:         if ($oldsec ne '-1') { 
16621:             if ($oldsec ne $sec) {
16622:                 $secchange = 1;
16623:                 my $now = time;
16624:                 my $uurl='/'.$cid;
16625:                 $uurl=~s/\_/\//g;
16626:                 if ($oldsec) {
16627:                     $uurl.='/'.$oldsec;
16628:                 }
16629:                 $oldsecurl = $uurl;
16630:                 $expire_role_result = 
16631:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,
16632:                                                 '','','',$context,$othdomby,$requester);
16633:                 if ($env{'request.course.sec'} ne '') {
16634:                     if ($expire_role_result eq 'refused') {
16635:                         my @roles = ('st');
16636:                         my @statuses = ('previous');
16637:                         my @roledoms = ($one);
16638:                         my $withsec = 1;
16639:                         my %roleshash = 
16640:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
16641:                                               \@statuses,\@roles,\@roledoms,$withsec);
16642:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
16643:                             my ($oldstart,$oldend) = 
16644:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
16645:                             if ($oldend > 0 && $oldend <= $now) {
16646:                                 $expire_role_result = 'ok';
16647:                             }
16648:                         }
16649:                     }
16650:                 }
16651:                 $result = $expire_role_result;
16652:             }
16653:         }
16654:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
16655:             $modify_section_result = 
16656:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
16657:                                                            undef,undef,undef,$sec,
16658:                                                            $end,$start,'','',$cid,
16659:                                                            '',$context,$credits,'',
16660:                                                            $othdomby,$requester);
16661:             if ($modify_section_result =~ /^ok/) {
16662:                 if ($secchange == 1) {
16663:                     if ($sec eq '') {
16664:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
16665:                     } else {
16666:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
16667:                     }
16668:                 } elsif ($oldsec eq '-1') {
16669:                     if ($sec eq '') {
16670:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
16671:                     } else {
16672:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
16673:                     }
16674:                 } else {
16675:                     if ($sec eq '') {
16676:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
16677:                     } else {
16678:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
16679:                     }
16680:                 }
16681:             } else {
16682:                 if ($secchange) { 
16683:                     $$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;
16684:                 } else {
16685:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
16686:                 }
16687:             }
16688:             $result = $modify_section_result;
16689:         } elsif ($secchange == 1) {
16690:             if ($oldsec eq '') {
16691:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
16692:             } else {
16693:                 $$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;
16694:             }
16695:             if ($expire_role_result eq 'refused') {
16696:                 my $newsecurl = '/'.$cid;
16697:                 $newsecurl =~ s/\_/\//g;
16698:                 if ($sec ne '') {
16699:                     $newsecurl.='/'.$sec;
16700:                 }
16701:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
16702:                     if ($sec eq '') {
16703:                         $$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;
16704:                     } else {
16705:                         $$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;
16706:                     }
16707:                 }
16708:             }
16709:         }
16710:     } else {
16711:         $$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;
16712:         $result = "error: incomplete course id\n";
16713:     }
16714:     return $result;
16715: }
16716: 
16717: sub show_role_extent {
16718:     my ($scope,$context,$role) = @_;
16719:     $scope =~ s{^/}{};
16720:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
16721:     push(@courseroles,'co');
16722:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
16723:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
16724:         $scope =~ s{/}{_};
16725:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
16726:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
16727:         my ($audom,$auname) = split(/\//,$scope);
16728:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
16729:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
16730:     } else {
16731:         $scope =~ s{/$}{};
16732:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
16733:                    &Apache::lonnet::domain($scope,'description').'</span>');
16734:     }
16735: }
16736: 
16737: ############################################################
16738: ############################################################
16739: 
16740: sub check_clone {
16741:     my ($args,$linefeed) = @_;
16742:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
16743:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
16744:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
16745:     my $clonetitle;
16746:     my @clonemsg;
16747:     my $can_clone = 0;
16748:     my $lctype = lc($args->{'crstype'});
16749:     if ($lctype ne 'community') {
16750:         $lctype = 'course';
16751:     }
16752:     if ($clonehome eq 'no_host') {
16753:         if ($args->{'crstype'} eq 'Community') {
16754:             push(@clonemsg,({
16755:                               mt => 'No new community created.',
16756:                               args => [],
16757:                             },
16758:                             {
16759:                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
16760:                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
16761:                             }));
16762:         } else {
16763:             push(@clonemsg,({
16764:                               mt => 'No new course created.',
16765:                               args => [],
16766:                             },
16767:                             {
16768:                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
16769:                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
16770:                             }));
16771:         }
16772:     } else {
16773: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
16774:         $clonetitle = $clonedesc{'description'};
16775:         if ($args->{'crstype'} eq 'Community') {
16776:             if ($clonedesc{'type'} ne 'Community') {
16777:                 push(@clonemsg,({
16778:                                   mt => 'No new community created.',
16779:                                   args => [],
16780:                                 },
16781:                                 {
16782:                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
16783:                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
16784:                                 }));
16785:                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
16786:             }
16787:         }
16788: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
16789:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
16790: 	    $can_clone = 1;
16791: 	} else {
16792: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
16793: 						 $args->{'clonedomain'},$args->{'clonecourse'});
16794:             if ($clonehash{'cloners'} eq '') {
16795:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
16796:                 if ($domdefs{'canclone'}) {
16797:                     unless ($domdefs{'canclone'} eq 'none') {
16798:                         if ($domdefs{'canclone'} eq 'domain') {
16799:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
16800:                                 $can_clone = 1;
16801:                             }
16802:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
16803:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
16804:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
16805:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
16806:                                 $can_clone = 1;
16807:                             }
16808:                         }
16809:                     }
16810:                 }
16811:             } else {
16812: 	        my @cloners = split(/,/,$clonehash{'cloners'});
16813:                 if (grep(/^\*$/,@cloners)) {
16814:                     $can_clone = 1;
16815:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
16816:                     $can_clone = 1;
16817:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
16818:                     $can_clone = 1;
16819:                 }
16820:                 unless ($can_clone) {
16821:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
16822:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
16823:                         my (%gotdomdefaults,%gotcodedefaults);
16824:                         foreach my $cloner (@cloners) {
16825:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
16826:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
16827:                                 my (%codedefaults,@code_order);
16828:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
16829:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
16830:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
16831:                                     }
16832:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
16833:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
16834:                                     }
16835:                                 } else {
16836:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
16837:                                                                             \%codedefaults,
16838:                                                                             \@code_order);
16839:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
16840:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
16841:                                 }
16842:                                 if (@code_order > 0) {
16843:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
16844:                                                                                 $cloner,$clonehash{'internal.coursecode'},
16845:                                                                                 $args->{'crscode'})) {
16846:                                         $can_clone = 1;
16847:                                         last;
16848:                                     }
16849:                                 }
16850:                             }
16851:                         }
16852:                     }
16853:                 }
16854:             }
16855:             unless ($can_clone) {
16856:                 my $ccrole = 'cc';
16857:                 if ($args->{'crstype'} eq 'Community') {
16858:                     $ccrole = 'co';
16859:                 }
16860: 	        my %roleshash =
16861: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
16862: 					          $args->{'ccdomain'},
16863:                                                   'userroles',['active'],[$ccrole],
16864: 					          [$args->{'clonedomain'}]);
16865: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
16866:                     $can_clone = 1;
16867:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
16868:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
16869:                     $can_clone = 1;
16870:                 }
16871:             }
16872:             unless ($can_clone) {
16873:                 if ($args->{'crstype'} eq 'Community') {
16874:                     push(@clonemsg,({
16875:                                       mt => 'No new community created.',
16876:                                       args => [],
16877:                                     },
16878:                                     {
16879:                                       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]).',
16880:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
16881:                                     }));
16882:                 } else {
16883:                     push(@clonemsg,({
16884:                                       mt => 'No new course created.',
16885:                                       args => [],
16886:                                     },
16887:                                     {
16888:                                       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]).',
16889:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
16890:                                     }));
16891:                 }
16892: 	    }
16893:         }
16894:     }
16895:     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
16896: }
16897: 
16898: sub construct_course {
16899:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
16900:         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
16901:     my ($outcome,$msgref,$clonemsgref);
16902:     my $linefeed =  '<br />'."\n";
16903:     if ($context eq 'auto') {
16904:         $linefeed = "\n";
16905:     }
16906: 
16907: #
16908: # Are we cloning?
16909: #
16910:     my ($can_clone,$cloneid,$clonehome,$clonetitle);
16911:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
16912: 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
16913:         if (!$can_clone) {
16914: 	    return (0,$outcome,$clonemsgref);
16915: 	}
16916:     }
16917: 
16918: #
16919: # Open course
16920: #
16921:     my $showncrstype;
16922:     if ($args->{'crstype'} eq 'Placement') {
16923:         $showncrstype = 'placement test'; 
16924:     } else {  
16925:         $showncrstype = lc($args->{'crstype'});
16926:     }
16927:     my %cenv=();
16928:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
16929:                                              $args->{'cdescr'},
16930:                                              $args->{'curl'},
16931:                                              $args->{'course_home'},
16932:                                              $args->{'nonstandard'},
16933:                                              $args->{'crscode'},
16934:                                              $args->{'ccuname'}.':'.
16935:                                              $args->{'ccdomain'},
16936:                                              $args->{'crstype'},
16937:                                              $cnum,$context,$category,
16938:                                              $callercontext);
16939: 
16940:     # Note: The testing routines depend on this being output; see 
16941:     # Utils::Course. This needs to at least be output as a comment
16942:     # if anyone ever decides to not show this, and Utils::Course::new
16943:     # will need to be suitably modified.
16944:     if (($callercontext eq 'auto') && ($user_lh ne '')) {
16945:         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
16946:     } else {
16947:         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
16948:     }
16949:     if ($$courseid =~ /^error:/) {
16950:         return (0,$outcome,$clonemsgref);
16951:     }
16952: 
16953: #
16954: # Check if created correctly
16955: #
16956:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
16957:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
16958:     if ($crsuhome eq 'no_host') {
16959:         if (($callercontext eq 'auto') && ($user_lh ne '')) {
16960:             $outcome .= &mt_user($user_lh,
16961:                             'Course creation failed, unrecognized course home server.');
16962:         } else {
16963:             $outcome .= &mt('Course creation failed, unrecognized course home server.');
16964:         }
16965:         $outcome .= $linefeed;
16966:         return (0,$outcome,$clonemsgref);
16967:     }
16968:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
16969: 
16970: #
16971: # Do the cloning
16972: #   
16973:     my @clonemsg;
16974:     if ($can_clone && $cloneid) {
16975:         push(@clonemsg,
16976:                       {
16977:                           mt => 'Created [_1] by cloning from [_2]',
16978:                           args => [$showncrstype,$clonetitle],
16979:                       });
16980: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
16981: # Copy all files
16982:         my @info =
16983: 	    &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
16984: 	                                             $args->{'dateshift'},$args->{'crscode'},
16985:                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
16986:                                                      $args->{'tinyurls'});
16987:         if (@info) {
16988:             push(@clonemsg,@info);
16989:         }
16990: # Restore URL
16991: 	$cenv{'url'}=$oldcenv{'url'};
16992: # Restore title
16993: 	$cenv{'description'}=$oldcenv{'description'};
16994: # Restore creation date, creator and creation context.
16995:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
16996:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
16997:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
16998: # Mark as cloned
16999: 	$cenv{'clonedfrom'}=$cloneid;
17000: # Need to clone grading mode
17001:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
17002:         $cenv{'grading'}=$newenv{'grading'};
17003: # Do not clone these environment entries
17004:         &Apache::lonnet::del('environment',
17005:                   ['default_enrollment_start_date',
17006:                    'default_enrollment_end_date',
17007:                    'question.email',
17008:                    'policy.email',
17009:                    'comment.email',
17010:                    'pch.users.denied',
17011:                    'plc.users.denied',
17012:                    'hidefromcat',
17013:                    'checkforpriv',
17014:                    'categories'],
17015:                    $$crsudom,$$crsunum);
17016:         if ($args->{'textbook'}) {
17017:             $cenv{'internal.textbook'} = $args->{'textbook'};
17018:         }
17019:     }
17020: 
17021: #
17022: # Set environment (will override cloned, if existing)
17023: #
17024:     my @sections = ();
17025:     my @xlists = ();
17026:     if ($args->{'crstype'}) {
17027:         $cenv{'type'}=$args->{'crstype'};
17028:     }
17029:     if ($args->{'lti'}) {
17030:         $cenv{'internal.lti'}=$args->{'lti'};
17031:     }
17032:     if ($args->{'crsid'}) {
17033:         $cenv{'courseid'}=$args->{'crsid'};
17034:     }
17035:     if ($args->{'crscode'}) {
17036:         $cenv{'internal.coursecode'}=$args->{'crscode'};
17037:     }
17038:     if ($args->{'crsquota'} ne '') {
17039:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
17040:     } else {
17041:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
17042:     }
17043:     if ($args->{'ccuname'}) {
17044:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
17045:                                         ':'.$args->{'ccdomain'};
17046:     } else {
17047:         $cenv{'internal.courseowner'} = $args->{'curruser'};
17048:     }
17049:     if ($args->{'defaultcredits'}) {
17050:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
17051:     }
17052:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
17053:     if ($args->{'crssections'}) {
17054:         $cenv{'internal.sectionnums'} = '';
17055:         if ($args->{'crssections'} =~ m/,/) {
17056:             @sections = split/,/,$args->{'crssections'};
17057:         } else {
17058:             $sections[0] = $args->{'crssections'};
17059:         }
17060:         if (@sections > 0) {
17061:             foreach my $item (@sections) {
17062:                 my ($sec,$gp) = split/:/,$item;
17063:                 my $class = $args->{'crscode'}.$sec;
17064:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
17065:                 $cenv{'internal.sectionnums'} .= $item.',';
17066:                 unless ($addcheck eq 'ok') {
17067:                     push(@badclasses,$class);
17068:                 }
17069:             }
17070:             $cenv{'internal.sectionnums'} =~ s/,$//;
17071:         }
17072:     }
17073: # do not hide course coordinator from staff listing, 
17074: # even if privileged
17075:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
17076: # add course coordinator's domain to domains to check for privileged users
17077: # if different to course domain
17078:     if ($$crsudom ne $args->{'ccdomain'}) {
17079:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
17080:     }
17081: # add crosslistings
17082:     if ($args->{'crsxlist'}) {
17083:         $cenv{'internal.crosslistings'}='';
17084:         if ($args->{'crsxlist'} =~ m/,/) {
17085:             @xlists = split/,/,$args->{'crsxlist'};
17086:         } else {
17087:             $xlists[0] = $args->{'crsxlist'};
17088:         }
17089:         if (@xlists > 0) {
17090:             foreach my $item (@xlists) {
17091:                 my ($xl,$gp) = split/:/,$item;
17092:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
17093:                 $cenv{'internal.crosslistings'} .= $item.',';
17094:                 unless ($addcheck eq 'ok') {
17095:                     push(@badclasses,$xl);
17096:                 }
17097:             }
17098:             $cenv{'internal.crosslistings'} =~ s/,$//;
17099:         }
17100:     }
17101:     if ($args->{'autoadds'}) {
17102:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
17103:     }
17104:     if ($args->{'autodrops'}) {
17105:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
17106:     }
17107: # check for notification of enrollment changes
17108:     my @notified = ();
17109:     if ($args->{'notify_owner'}) {
17110:         if ($args->{'ccuname'} ne '') {
17111:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
17112:         }
17113:     }
17114:     if ($args->{'notify_dc'}) {
17115:         if ($uname ne '') { 
17116:             push(@notified,$uname.':'.$udom);
17117:         }
17118:     }
17119:     if (@notified > 0) {
17120:         my $notifylist;
17121:         if (@notified > 1) {
17122:             $notifylist = join(',',@notified);
17123:         } else {
17124:             $notifylist = $notified[0];
17125:         }
17126:         $cenv{'internal.notifylist'} = $notifylist;
17127:     }
17128:     if (@badclasses > 0) {
17129:         my %lt=&Apache::lonlocal::texthash(
17130:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
17131:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
17132:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
17133:         );
17134:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
17135:                            &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'};
17136:         if ($context eq 'auto') {
17137:             $outcome .= $badclass_msg.$linefeed;
17138:         } else {
17139:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
17140:         }
17141:         foreach my $item (@badclasses) {
17142:             if ($context eq 'auto') {
17143:                 $outcome .= " - $item\n";
17144:             } else {
17145:                 $outcome .= "<li>$item</li>\n";
17146:             }
17147:         }
17148:         if ($context eq 'auto') {
17149:             $outcome .= $linefeed;
17150:         } else {
17151:             $outcome .= "</ul><br /><br /></div>\n";
17152:         } 
17153:     }
17154:     if ($args->{'no_end_date'}) {
17155:         $args->{'endaccess'} = 0;
17156:     }
17157:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
17158:     $cenv{'internal.autoend'}=$args->{'enrollend'};
17159:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
17160:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
17161:     if ($args->{'showphotos'}) {
17162:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
17163:     }
17164:     $cenv{'internal.authtype'} = $args->{'authtype'};
17165:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
17166:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
17167:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
17168:             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'); 
17169:             if ($context eq 'auto') {
17170:                 $outcome .= $krb_msg;
17171:             } else {
17172:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
17173:             }
17174:             $outcome .= $linefeed;
17175:         }
17176:     }
17177:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
17178:        if ($args->{'setpolicy'}) {
17179:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
17180:        }
17181:        if ($args->{'setcontent'}) {
17182:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
17183:        }
17184:        if ($args->{'setcomment'}) {
17185:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
17186:        }
17187:     }
17188:     if ($args->{'reshome'}) {
17189: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
17190: 	$cenv{'reshome'}=~s/\/+$/\//;
17191:     }
17192: #
17193: # course has keyed access
17194: #
17195:     if ($args->{'setkeys'}) {
17196:        $cenv{'keyaccess'}='yes';
17197:     }
17198: # if specified, key authority is not course, but user
17199: # only active if keyaccess is yes
17200:     if ($args->{'keyauth'}) {
17201: 	my ($user,$domain) = split(':',$args->{'keyauth'});
17202: 	$user = &LONCAPA::clean_username($user);
17203: 	$domain = &LONCAPA::clean_username($domain);
17204: 	if ($user ne '' && $domain ne '') {
17205: 	    $cenv{'keyauth'}=$user.':'.$domain;
17206: 	}
17207:     }
17208: 
17209: #
17210: #  generate and store uniquecode (available to course requester), if course should have one.
17211: #
17212:     if ($args->{'uniquecode'}) {
17213:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
17214:         if ($code) {
17215:             $cenv{'internal.uniquecode'} = $code;
17216:             my %crsinfo =
17217:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
17218:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
17219:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
17220:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
17221:             } 
17222:             if (ref($coderef)) {
17223:                 $$coderef = $code;
17224:             }
17225:         }
17226:     }
17227: 
17228:     if ($args->{'disresdis'}) {
17229:         $cenv{'pch.roles.denied'}='st';
17230:     }
17231:     if ($args->{'disablechat'}) {
17232:         $cenv{'plc.roles.denied'}='st';
17233:     }
17234: 
17235:     # Record we've not yet viewed the Course Initialization Helper for this 
17236:     # course
17237:     $cenv{'course.helper.not.run'} = 1;
17238:     #
17239:     # Use new Randomseed
17240:     #
17241:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
17242:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
17243:     #
17244:     # The encryption code and receipt prefix for this course
17245:     #
17246:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
17247:     $cenv{'internal.encpref'}=100+int(9*rand(99));
17248:     #
17249:     # By default, use standard grading
17250:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
17251: 
17252:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
17253:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
17254: #
17255: # Open all assignments
17256: #
17257:     if ($args->{'openall'}) {
17258:        my $opendate = time;
17259:        if ($args->{'openallfrom'} =~ /^\d+$/) {
17260:            $opendate = $args->{'openallfrom'};
17261:        }
17262:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
17263:        my %storecontent = ($storeunder         => $opendate,
17264:                            $storeunder.'.type' => 'date_start');
17265:        $outcome .= &mt('All assignments open starting [_1]',
17266:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
17267:                    &Apache::lonnet::cput
17268:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
17269:    }
17270: #
17271: # Set first page
17272: #
17273:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
17274: 	    || ($cloneid)) {
17275: 	$outcome .= &mt('Setting first resource').': ';
17276: 
17277: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
17278:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
17279: 
17280:         $outcome .= ($fatal?$errtext:'read ok').' - ';
17281:         my $title; my $url;
17282:         if ($args->{'firstres'} eq 'syl') {
17283: 	    $title=&mt('Syllabus');
17284:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
17285:         } else {
17286:             $title=&mt('Table of Contents');
17287:             $url='/adm/navmaps';
17288:         }
17289: 
17290:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
17291: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
17292: 
17293: 	if ($errtext) { $fatal=2; }
17294:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
17295:     }
17296: 
17297: # 
17298: # Set params for Placement Tests
17299: #
17300:     if ($args->{'crstype'} eq 'Placement') {
17301:        my %storecontent; 
17302:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
17303:        my %defaults = (
17304:                         buttonshide   => { value => 'yes',
17305:                                            type => 'string_yesno',},
17306:                         type          => { value => 'randomizetry',
17307:                                            type  => 'string_questiontype',},
17308:                         maxtries      => { value => 1,
17309:                                            type => 'int_pos',},
17310:                         problemstatus => { value => 'no',
17311:                                            type  => 'string_problemstatus',},
17312:                       );
17313:        foreach my $key (keys(%defaults)) {
17314:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
17315:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
17316:        }
17317:        &Apache::lonnet::cput
17318:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
17319:     }
17320: 
17321:     return (1,$outcome,\@clonemsg);
17322: }
17323: 
17324: sub make_unique_code {
17325:     my ($cdom,$cnum) = @_;
17326:     # get lock on uniquecodes db
17327:     my $lockhash = {
17328:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
17329:                                                   ':'.$env{'user.domain'},
17330:                    };
17331:     my $tries = 0;
17332:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
17333:     my ($code,$error);
17334:   
17335:     while (($gotlock ne 'ok') && ($tries<3)) {
17336:         $tries ++;
17337:         sleep 1;
17338:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
17339:     }
17340:     if ($gotlock eq 'ok') {
17341:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
17342:         my $gotcode;
17343:         my $attempts = 0;
17344:         while ((!$gotcode) && ($attempts < 100)) {
17345:             $code = &generate_code();
17346:             if (!exists($currcodes{$code})) {
17347:                 $gotcode = 1;
17348:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
17349:                     $error = 'nostore';
17350:                 }
17351:             }
17352:             $attempts ++;
17353:         }
17354:         my @del_lock = ($cnum."\0".'uniquecodes');
17355:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
17356:     } else {
17357:         $error = 'nolock';
17358:     }
17359:     return ($code,$error);
17360: }
17361: 
17362: sub generate_code {
17363:     my $code;
17364:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
17365:     for (my $i=0; $i<6; $i++) {
17366:         my $lettnum = int (rand 2);
17367:         my $item = '';
17368:         if ($lettnum) {
17369:             $item = $letts[int( rand(18) )];
17370:         } else {
17371:             $item = 1+int( rand(8) );
17372:         }
17373:         $code .= $item;
17374:     }
17375:     return $code;
17376: }
17377: 
17378: ############################################################
17379: ############################################################
17380: 
17381: # Community, Course and Placement Test
17382: sub course_type {
17383:     my ($cid) = @_;
17384:     if (!defined($cid)) {
17385:         $cid = $env{'request.course.id'};
17386:     }
17387:     if (defined($env{'course.'.$cid.'.type'})) {
17388:         return $env{'course.'.$cid.'.type'};
17389:     } else {
17390:         return 'Course';
17391:     }
17392: }
17393: 
17394: sub group_term {
17395:     my $crstype = &course_type();
17396:     my %names = (
17397:                   'Course' => 'group',
17398:                   'Community' => 'group',
17399:                   'Placement' => 'group',
17400:                 );
17401:     return $names{$crstype};
17402: }
17403: 
17404: sub course_types {
17405:     my @types = ('official','unofficial','community','textbook','placement','lti');
17406:     my %typename = (
17407:                          official   => 'Official course',
17408:                          unofficial => 'Unofficial course',
17409:                          community  => 'Community',
17410:                          textbook   => 'Textbook course',
17411:                          placement  => 'Placement test',
17412:                          lti        => 'LTI provider',
17413:                    );
17414:     return (\@types,\%typename);
17415: }
17416: 
17417: sub icon {
17418:     my ($file)=@_;
17419:     my $curfext = lc((split(/\./,$file))[-1]);
17420:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
17421:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
17422:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
17423: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
17424: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
17425: 	            $curfext.".gif") {
17426: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
17427: 		$curfext.".gif";
17428: 	}
17429:     }
17430:     return &lonhttpdurl($iconname);
17431: } 
17432: 
17433: sub lonhttpdurl {
17434: #
17435: # Had been used for "small fry" static images on separate port 8080.
17436: # Modify here if lightweight http functionality desired again.
17437: # Currently eliminated due to increasing firewall issues.
17438: #
17439:     my ($url)=@_;
17440:     return $url;
17441: }
17442: 
17443: sub connection_aborted {
17444:     my ($r)=@_;
17445:     $r->print(" ");$r->rflush();
17446:     my $c = $r->connection;
17447:     return $c->aborted();
17448: }
17449: 
17450: #    Escapes strings that may have embedded 's that will be put into
17451: #    strings as 'strings'.
17452: sub escape_single {
17453:     my ($input) = @_;
17454:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
17455:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
17456:     return $input;
17457: }
17458: 
17459: #  Same as escape_single, but escape's "'s  This 
17460: #  can be used for  "strings"
17461: sub escape_double {
17462:     my ($input) = @_;
17463:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
17464:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
17465:     return $input;
17466: }
17467:  
17468: #   Escapes the last element of a full URL.
17469: sub escape_url {
17470:     my ($url)   = @_;
17471:     my @urlslices = split(/\//, $url,-1);
17472:     my $lastitem = &escape(pop(@urlslices));
17473:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
17474: }
17475: 
17476: sub compare_arrays {
17477:     my ($arrayref1,$arrayref2) = @_;
17478:     my (@difference,%count);
17479:     @difference = ();
17480:     %count = ();
17481:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
17482:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
17483:         foreach my $element (keys(%count)) {
17484:             if ($count{$element} == 1) {
17485:                 push(@difference,$element);
17486:             }
17487:         }
17488:     }
17489:     return @difference;
17490: }
17491: 
17492: sub lon_status_items {
17493:     my %defaults = (
17494:                      E         => 100,
17495:                      W         => 4,
17496:                      N         => 1,
17497:                      U         => 5,
17498:                      threshold => 200,
17499:                      sysmail   => 2500,
17500:                    );
17501:     my %names = (
17502:                    E => 'Errors',
17503:                    W => 'Warnings',
17504:                    N => 'Notices',
17505:                    U => 'Unsent',
17506:                 );
17507:     return (\%defaults,\%names);
17508: }
17509: 
17510: # -------------------------------------------------------- Initialize user login
17511: sub init_user_environment {
17512:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
17513:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
17514: 
17515:     my $public=($username eq 'public' && $domain eq 'public');
17516: 
17517:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
17518:     my $now=time;
17519: 
17520:     if ($public) {
17521: 	my $max_public=100;
17522: 	my $oldest;
17523: 	my $oldest_time=0;
17524: 	for(my $next=1;$next<=$max_public;$next++) {
17525: 	    if (-e $lonids."/publicuser_$next.id") {
17526: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
17527: 		if ($mtime<$oldest_time || !$oldest_time) {
17528: 		    $oldest_time=$mtime;
17529: 		    $oldest=$next;
17530: 		}
17531: 	    } else {
17532: 		$cookie="publicuser_$next";
17533: 		last;
17534: 	    }
17535: 	}
17536: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
17537:     } else {
17538: 	# See if old ID present, if so, remove if this isn't a robot,
17539: 	# killing any existing non-robot sessions
17540: 	if (!$args->{'robot'}) {
17541: 	    opendir(DIR,$lonids);
17542: 	    while ($filename=readdir(DIR)) {
17543: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
17544:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
17545:                             &GDBM_READER(),0640)) {
17546:                         my $linkedfile;
17547:                         if (exists($oldenv{'user.linkedenv'})) {
17548:                             $linkedfile = $oldenv{'user.linkedenv'};
17549:                         }
17550:                         untie(%oldenv);
17551:                         if (unlink("$lonids/$filename")) {
17552:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
17553:                                 if (-l "$lonids/$linkedfile.id") {
17554:                                     unlink("$lonids/$linkedfile.id");
17555:                                 }
17556:                             }
17557:                         }
17558:                     } else {
17559:                         unlink($lonids.'/'.$filename);
17560:                     }
17561: 		}
17562: 	    }
17563: 	    closedir(DIR);
17564: # If there is a undeleted lockfile for the user's paste buffer remove it.
17565:             my $namespace = 'nohist_courseeditor';
17566:             my $lockingkey = 'paste'."\0".'locked_num';
17567:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
17568:                                                 $domain,$username);
17569:             if (exists($lockhash{$lockingkey})) {
17570:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
17571:                 unless ($delresult eq 'ok') {
17572:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
17573:                 }
17574:             }
17575: 	}
17576: # Give them a new cookie
17577: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
17578: 		                   : $now.$$.int(rand(10000)));
17579: 	$cookie="$username\_$id\_$domain\_$authhost";
17580:     
17581: # Initialize roles
17582: 
17583: 	($userroles,$firstaccenv,$timerintenv) = 
17584:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
17585:     }
17586: # ------------------------------------ Check browser type and MathML capability
17587: 
17588:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
17589:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
17590: 
17591: # ------------------------------------------------------------- Get environment
17592: 
17593:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
17594:     my ($tmp) = keys(%userenv);
17595:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
17596: 	undef(%userenv);
17597:     }
17598:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
17599: 	$form->{'interface'}=$userenv{'interface'};
17600:     }
17601:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
17602: 
17603: # --------------- Do not trust query string to be put directly into environment
17604:     foreach my $option ('interface','localpath','localres') {
17605:         $form->{$option}=~s/[\n\r\=]//gs;
17606:     }
17607: # --------------------------------------------------------- Write first profile
17608: 
17609:     {
17610:         my $ip = &Apache::lonnet::get_requestor_ip($r);
17611: 	my %initial_env = 
17612: 	    ("user.name"          => $username,
17613: 	     "user.domain"        => $domain,
17614: 	     "user.home"          => $authhost,
17615: 	     "browser.type"       => $clientbrowser,
17616: 	     "browser.version"    => $clientversion,
17617: 	     "browser.mathml"     => $clientmathml,
17618: 	     "browser.unicode"    => $clientunicode,
17619: 	     "browser.os"         => $clientos,
17620:              "browser.mobile"     => $clientmobile,
17621:              "browser.info"       => $clientinfo,
17622:              "browser.osversion"  => $clientosversion,
17623: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
17624: 	     "request.course.fn"  => '',
17625: 	     "request.course.uri" => '',
17626: 	     "request.course.sec" => '',
17627: 	     "request.role"       => 'cm',
17628: 	     "request.role.adv"   => $env{'user.adv'},
17629: 	     "request.host"       => $ip,);
17630: 
17631:         if ($form->{'localpath'}) {
17632: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
17633: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
17634:         }
17635: 	
17636: 	if ($form->{'interface'}) {
17637: 	    $form->{'interface'}=~s/\W//gs;
17638: 	    $initial_env{"browser.interface"} = $form->{'interface'};
17639: 	    $env{'browser.interface'}=$form->{'interface'};
17640: 	}
17641: 
17642:         if ($form->{'iptoken'}) {
17643:             my $lonhost = $r->dir_config('lonHostID');
17644:             $initial_env{"user.noloadbalance"} = $lonhost;
17645:             $env{'user.noloadbalance'} = $lonhost;
17646:         }
17647: 
17648:         if ($form->{'noloadbalance'}) {
17649:             my @hosts = &Apache::lonnet::current_machine_ids();
17650:             my $hosthere = $form->{'noloadbalance'};
17651:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
17652:                 $initial_env{"user.noloadbalance"} = $hosthere;
17653:                 $env{'user.noloadbalance'} = $hosthere;
17654:             }
17655:         }
17656: 
17657:         unless ($domain eq 'public') {
17658:             my %is_adv = ( is_adv => $env{'user.adv'} );
17659:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
17660: 
17661:             foreach my $tool ('aboutme','blog','webdav','portfolio','timezone') {
17662:                 $userenv{'availabletools.'.$tool} = 
17663:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
17664:                                                       undef,\%userenv,\%domdef,\%is_adv);
17665:             }
17666: 
17667:             foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
17668:                 $userenv{'canrequest.'.$crstype} =
17669:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
17670:                                                       'reload','requestcourses',
17671:                                                       \%userenv,\%domdef,\%is_adv);
17672:             }
17673: 
17674:             $userenv{'canrequest.author'} =
17675:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
17676:                                                   'reload','requestauthor',
17677:                                                   \%userenv,\%domdef,\%is_adv);
17678:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
17679:                                                  $domain,$username);
17680:             my $reqstatus = $reqauthor{'author_status'};
17681:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
17682:                 if (ref($reqauthor{'author'}) eq 'HASH') {
17683:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
17684:                                                       $reqauthor{'author'}{'timestamp'};
17685:                 }
17686:             }
17687:             my ($types,$typename) = &course_types();
17688:             if (ref($types) eq 'ARRAY') {
17689:                 my @options = ('approval','validate','autolimit');
17690:                 my $optregex = join('|',@options);
17691:                 my (%willtrust,%trustchecked);
17692:                 foreach my $type (@{$types}) {
17693:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
17694:                     if ($dom_str ne '') {
17695:                         my $updatedstr = '';
17696:                         my @possdomains = split(',',$dom_str);
17697:                         foreach my $entry (@possdomains) {
17698:                             my ($extdom,$extopt) = split(':',$entry);
17699:                             unless ($trustchecked{$extdom}) {
17700:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
17701:                                 $trustchecked{$extdom} = 1;
17702:                             }
17703:                             if ($willtrust{$extdom}) {
17704:                                 $updatedstr .= $entry.',';
17705:                             }
17706:                         }
17707:                         $updatedstr =~ s/,$//;
17708:                         if ($updatedstr) {
17709:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
17710:                         } else {
17711:                             delete($userenv{'reqcrsotherdom.'.$type});
17712:                         }
17713:                     }
17714:                 }
17715:             }
17716:         }
17717: 	$env{'user.environment'} = "$lonids/$cookie.id";
17718: 
17719: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
17720: 		 &GDBM_WRCREAT(),0640)) {
17721: 	    &_add_to_env(\%disk_env,\%initial_env);
17722: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
17723: 	    &_add_to_env(\%disk_env,$userroles);
17724:             if (ref($firstaccenv) eq 'HASH') {
17725:                 &_add_to_env(\%disk_env,$firstaccenv);
17726:             }
17727:             if (ref($timerintenv) eq 'HASH') {
17728:                 &_add_to_env(\%disk_env,$timerintenv);
17729:             }
17730: 	    if (ref($args->{'extra_env'})) {
17731: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
17732: 	    }
17733: 	    untie(%disk_env);
17734: 	} else {
17735: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
17736: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
17737: 	    return 'error: '.$!;
17738: 	}
17739:     }
17740:     $env{'request.role'}='cm';
17741:     $env{'request.role.adv'}=$env{'user.adv'};
17742:     $env{'browser.type'}=$clientbrowser;
17743: 
17744:     return $cookie;
17745: 
17746: }
17747: 
17748: sub _add_to_env {
17749:     my ($idf,$env_data,$prefix) = @_;
17750:     if (ref($env_data) eq 'HASH') {
17751:         while (my ($key,$value) = each(%$env_data)) {
17752: 	    $idf->{$prefix.$key} = $value;
17753: 	    $env{$prefix.$key}   = $value;
17754:         }
17755:     }
17756: }
17757: 
17758: # --- Get the symbolic name of a problem and the url
17759: sub get_symb {
17760:     my ($request,$silent) = @_;
17761:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
17762:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
17763:     if ($symb eq '') {
17764:         if (!$silent) {
17765:             if (ref($request)) { 
17766:                 $request->print("Unable to handle ambiguous references:$url:.");
17767:             }
17768:             return ();
17769:         }
17770:     }
17771:     &Apache::lonenc::check_decrypt(\$symb);
17772:     return ($symb);
17773: }
17774: 
17775: # --------------------------------------------------------------Get annotation
17776: 
17777: sub get_annotation {
17778:     my ($symb,$enc) = @_;
17779: 
17780:     my $key = $symb;
17781:     if (!$enc) {
17782:         $key =
17783:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
17784:     }
17785:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
17786:     return $annotation{$key};
17787: }
17788: 
17789: sub clean_symb {
17790:     my ($symb,$delete_enc) = @_;
17791: 
17792:     &Apache::lonenc::check_decrypt(\$symb);
17793:     my $enc = $env{'request.enc'};
17794:     if ($delete_enc) {
17795:         delete($env{'request.enc'});
17796:     }
17797: 
17798:     return ($symb,$enc);
17799: }
17800: 
17801: ############################################################
17802: ############################################################
17803: 
17804: =pod
17805: 
17806: =head1 Routines for building display used to search for courses
17807: 
17808: 
17809: =over 4
17810: 
17811: =item * &build_filters()
17812: 
17813: Create markup for a table used to set filters to use when selecting
17814: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
17815: and quotacheck.pl
17816: 
17817: 
17818: Inputs:
17819: 
17820: filterlist - anonymous array of fields to include as potential filters 
17821: 
17822: crstype - course type
17823: 
17824: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
17825:               to pop-open a course selector (will contain "extra element"). 
17826: 
17827: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
17828: 
17829: filter - anonymous hash of criteria and their values
17830: 
17831: action - form action
17832: 
17833: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
17834: 
17835: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
17836: 
17837: cloneruname - username of owner of new course who wants to clone
17838: 
17839: clonerudom - domain of owner of new course who wants to clone
17840: 
17841: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
17842: 
17843: codetitlesref - reference to array of titles of components in institutional codes (official courses)
17844: 
17845: codedom - domain
17846: 
17847: formname - value of form element named "form". 
17848: 
17849: fixeddom - domain, if fixed.
17850: 
17851: prevphase - value to assign to form element named "phase" when going back to the previous screen  
17852: 
17853: cnameelement - name of form element in form on opener page which will receive title of selected course 
17854: 
17855: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
17856: 
17857: cdomelement - name of form element in form on opener page which will receive domain of selected course
17858: 
17859: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
17860: 
17861: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
17862: 
17863: clonewarning - warning message about missing information for intended course owner when DC creates a course
17864: 
17865: 
17866: Returns: $output - HTML for display of search criteria, and hidden form elements.
17867: 
17868: 
17869: Side Effects: None
17870: 
17871: =cut
17872: 
17873: # ---------------------------------------------- search for courses based on last activity etc.
17874: 
17875: sub build_filters {
17876:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
17877:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
17878:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
17879:         $cnameelement,$cnumelement,$cdomelement,$setroles,
17880:         $clonetext,$clonewarning) = @_;
17881:     my ($list,$jscript);
17882:     my $onchange = 'javascript:updateFilters(this)';
17883:     my ($domainselectform,$sincefilterform,$createdfilterform,
17884:         $ownerdomselectform,$persondomselectform,$instcodeform,
17885:         $typeselectform,$instcodetitle);
17886:     if ($formname eq '') {
17887:         $formname = $caller;
17888:     }
17889:     foreach my $item (@{$filterlist}) {
17890:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
17891:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
17892:             if ($item eq 'domainfilter') {
17893:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
17894:             } elsif ($item eq 'coursefilter') {
17895:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
17896:             } elsif ($item eq 'ownerfilter') {
17897:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
17898:             } elsif ($item eq 'ownerdomfilter') {
17899:                 $filter->{'ownerdomfilter'} =
17900:                     &LONCAPA::clean_domain($filter->{$item});
17901:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
17902:                                                        'ownerdomfilter',1);
17903:             } elsif ($item eq 'personfilter') {
17904:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
17905:             } elsif ($item eq 'persondomfilter') {
17906:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
17907:                                                         'persondomfilter',1);
17908:             } else {
17909:                 $filter->{$item} =~ s/\W//g;
17910:             }
17911:             if (!$filter->{$item}) {
17912:                 $filter->{$item} = '';
17913:             }
17914:         }
17915:         if ($item eq 'domainfilter') {
17916:             my $allow_blank = 1;
17917:             if ($formname eq 'portform') {
17918:                 $allow_blank=0;
17919:             } elsif ($formname eq 'studentform') {
17920:                 $allow_blank=0;
17921:             }
17922:             if ($fixeddom) {
17923:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
17924:                                     ' value="'.$codedom.'" />'.
17925:                                     &Apache::lonnet::domain($codedom,'description');
17926:             } else {
17927:                 $domainselectform = &select_dom_form($filter->{$item},
17928:                                                      'domainfilter',
17929:                                                       $allow_blank,'',$onchange);
17930:             }
17931:         } else {
17932:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
17933:         }
17934:     }
17935: 
17936:     # last course activity filter and selection
17937:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
17938: 
17939:     # course created filter and selection
17940:     if (exists($filter->{'createdfilter'})) {
17941:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
17942:     }
17943: 
17944:     my $prefix = $crstype;
17945:     if ($crstype eq 'Placement') {
17946:         $prefix = 'Placement Test'
17947:     }
17948:     my %lt = &Apache::lonlocal::texthash(
17949:                 'cac' => "$prefix Activity",
17950:                 'ccr' => "$prefix Created",
17951:                 'cde' => "$prefix Title",
17952:                 'cdo' => "$prefix Domain",
17953:                 'ins' => 'Institutional Code',
17954:                 'inc' => 'Institutional Categorization',
17955:                 'cow' => "$prefix Owner/Co-owner",
17956:                 'cop' => "$prefix Personnel Includes",
17957:                 'cog' => 'Type',
17958:              );
17959: 
17960:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
17961:         my $typeval = 'Course';
17962:         if ($crstype eq 'Community') {
17963:             $typeval = 'Community';
17964:         } elsif ($crstype eq 'Placement') {
17965:             $typeval = 'Placement';
17966:         }
17967:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
17968:     } else {
17969:         $typeselectform =  '<select name="type" size="1"';
17970:         if ($onchange) {
17971:             $typeselectform .= ' onchange="'.$onchange.'"';
17972:         }
17973:         $typeselectform .= '>'."\n";
17974:         foreach my $posstype ('Course','Community','Placement') {
17975:             my $shown;
17976:             if ($posstype eq 'Placement') {
17977:                 $shown = &mt('Placement Test');
17978:             } else {
17979:                 $shown = &mt($posstype);
17980:             }
17981:             $typeselectform.='<option value="'.$posstype.'"'.
17982:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
17983:         }
17984:         $typeselectform.="</select>";
17985:     }
17986: 
17987:     my ($cloneableonlyform,$cloneabletitle);
17988:     if (exists($filter->{'cloneableonly'})) {
17989:         my $cloneableon = '';
17990:         my $cloneableoff = ' checked="checked"';
17991:         if ($filter->{'cloneableonly'}) {
17992:             $cloneableon = $cloneableoff;
17993:             $cloneableoff = '';
17994:         }
17995:         $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>';
17996:         if ($formname eq 'ccrs') {
17997:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
17998:         } else {
17999:             $cloneabletitle = &mt('Cloneable by you');
18000:         }
18001:     }
18002:     my $officialjs;
18003:     if ($crstype eq 'Course') {
18004:         if (exists($filter->{'instcodefilter'})) {
18005: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
18006: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
18007:             if ($codedom) { 
18008:                 $officialjs = 1;
18009:                 ($instcodeform,$jscript,$$numtitlesref) =
18010:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
18011:                                                                   $officialjs,$codetitlesref);
18012:                 if ($jscript) {
18013:                     $jscript = '<script type="text/javascript">'."\n".
18014:                                '// <![CDATA['."\n".
18015:                                $jscript."\n".
18016:                                '// ]]>'."\n".
18017:                                '</script>'."\n";
18018:                 }
18019:             }
18020:             if ($instcodeform eq '') {
18021:                 $instcodeform =
18022:                     '<input type="text" name="instcodefilter" size="10" value="'.
18023:                     $list->{'instcodefilter'}.'" />';
18024:                 $instcodetitle = $lt{'ins'};
18025:             } else {
18026:                 $instcodetitle = $lt{'inc'};
18027:             }
18028:             if ($fixeddom) {
18029:                 $instcodetitle .= '<br />('.$codedom.')';
18030:             }
18031:         }
18032:     }
18033:     my $output = qq|
18034: <form method="post" name="filterpicker" action="$action">
18035: <input type="hidden" name="form" value="$formname" />
18036: |;
18037:     if ($formname eq 'modifycourse') {
18038:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
18039:                    '<input type="hidden" name="prevphase" value="'.
18040:                    $prevphase.'" />'."\n";
18041:     } elsif ($formname eq 'quotacheck') {
18042:         $output .= qq|
18043: <input type="hidden" name="sortby" value="" />
18044: <input type="hidden" name="sortorder" value="" />
18045: |;
18046:     } else {
18047:         my $name_input;
18048:         if ($cnameelement ne '') {
18049:             $name_input = '<input type="hidden" name="cnameelement" value="'.
18050:                           $cnameelement.'" />';
18051:         }
18052:         $output .= qq|
18053: <input type="hidden" name="cnumelement" value="$cnumelement" />
18054: <input type="hidden" name="cdomelement" value="$cdomelement" />
18055: $name_input
18056: $roleelement
18057: $multelement
18058: $typeelement
18059: |;
18060:         if ($formname eq 'portform') {
18061:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
18062:         }
18063:     }
18064:     if ($fixeddom) {
18065:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
18066:     }
18067:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
18068:     if ($sincefilterform) {
18069:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
18070:                   .$sincefilterform
18071:                   .&Apache::lonhtmlcommon::row_closure();
18072:     }
18073:     if ($createdfilterform) {
18074:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
18075:                   .$createdfilterform
18076:                   .&Apache::lonhtmlcommon::row_closure();
18077:     }
18078:     if ($domainselectform) {
18079:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
18080:                   .$domainselectform
18081:                   .&Apache::lonhtmlcommon::row_closure();
18082:     }
18083:     if ($typeselectform) {
18084:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
18085:             $output .= $typeselectform;
18086:         } else {
18087:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
18088:                       .$typeselectform
18089:                       .&Apache::lonhtmlcommon::row_closure();
18090:         }
18091:     }
18092:     if ($instcodeform) {
18093:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
18094:                   .$instcodeform
18095:                   .&Apache::lonhtmlcommon::row_closure();
18096:     }
18097:     if (exists($filter->{'ownerfilter'})) {
18098:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
18099:                    '<table><tr><td>'.&mt('Username').'<br />'.
18100:                    '<input type="text" name="ownerfilter" size="20" value="'.
18101:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
18102:                    $ownerdomselectform.'</td></tr></table>'.
18103:                    &Apache::lonhtmlcommon::row_closure();
18104:     }
18105:     if (exists($filter->{'personfilter'})) {
18106:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
18107:                    '<table><tr><td>'.&mt('Username').'<br />'.
18108:                    '<input type="text" name="personfilter" size="20" value="'.
18109:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
18110:                    $persondomselectform.'</td></tr></table>'.
18111:                    &Apache::lonhtmlcommon::row_closure();
18112:     }
18113:     if (exists($filter->{'coursefilter'})) {
18114:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
18115:                   .'<input type="text" name="coursefilter" size="25" value="'
18116:                   .$list->{'coursefilter'}.'" />'
18117:                   .&Apache::lonhtmlcommon::row_closure();
18118:     }
18119:     if ($cloneableonlyform) {
18120:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
18121:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
18122:     }
18123:     if (exists($filter->{'descriptfilter'})) {
18124:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
18125:                   .'<input type="text" name="descriptfilter" size="40" value="'
18126:                   .$list->{'descriptfilter'}.'" />'
18127:                   .&Apache::lonhtmlcommon::row_closure(1);
18128:     }
18129:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
18130:                '<input type="hidden" name="updater" value="" />'."\n".
18131:                '<input type="submit" name="gosearch" value="'.
18132:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
18133:     return $jscript.$clonewarning.$output;
18134: }
18135: 
18136: =pod 
18137: 
18138: =item * &timebased_select_form()
18139: 
18140: Create markup for a dropdown list used to select a time-based
18141: filter e.g., Course Activity, Course Created, when searching for courses
18142: or communities
18143: 
18144: Inputs:
18145: 
18146: item - name of form element (sincefilter or createdfilter)
18147: 
18148: filter - anonymous hash of criteria and their values
18149: 
18150: Returns: HTML for a select box contained a blank, then six time selections,
18151:          with value set in incoming form variables currently selected. 
18152: 
18153: Side Effects: None
18154: 
18155: =cut
18156: 
18157: sub timebased_select_form {
18158:     my ($item,$filter) = @_;
18159:     if (ref($filter) eq 'HASH') {
18160:         $filter->{$item} =~ s/[^\d-]//g;
18161:         if (!$filter->{$item}) { $filter->{$item}=-1; }
18162:         return &select_form(
18163:                             $filter->{$item},
18164:                             $item,
18165:                             {      '-1' => '',
18166:                                 '86400' => &mt('today'),
18167:                                '604800' => &mt('last week'),
18168:                               '2592000' => &mt('last month'),
18169:                               '7776000' => &mt('last three months'),
18170:                              '15552000' => &mt('last six months'),
18171:                              '31104000' => &mt('last year'),
18172:                     'select_form_order' =>
18173:                            ['-1','86400','604800','2592000','7776000',
18174:                             '15552000','31104000']});
18175:     }
18176: }
18177: 
18178: =pod
18179: 
18180: =item * &js_changer()
18181: 
18182: Create script tag containing Javascript used to submit course search form
18183: when course type or domain is changed, and also to hide 'Searching ...' on
18184: page load completion for page showing search result.
18185: 
18186: Inputs: None
18187: 
18188: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
18189: 
18190: Side Effects: None
18191: 
18192: =cut
18193: 
18194: sub js_changer {
18195:     return <<ENDJS;
18196: <script type="text/javascript">
18197: // <![CDATA[
18198: function updateFilters(caller) {
18199:     if (typeof(caller) != "undefined") {
18200:         document.filterpicker.updater.value = caller.name;
18201:     }
18202:     document.filterpicker.submit();
18203: }
18204: 
18205: function hideSearching() {
18206:     if (document.getElementById('searching')) {
18207:         document.getElementById('searching').style.display = 'none';
18208:     }
18209:     return;
18210: }
18211: 
18212: // ]]>
18213: </script>
18214: 
18215: ENDJS
18216: }
18217: 
18218: =pod
18219: 
18220: =item * &search_courses()
18221: 
18222: Process selected filters form course search form and pass to lonnet::courseiddump
18223: to retrieve a hash for which keys are courseIDs which match the selected filters.
18224: 
18225: Inputs:
18226: 
18227: dom - domain being searched 
18228: 
18229: type - course type ('Course' or 'Community' or '.' if any).
18230: 
18231: filter - anonymous hash of criteria and their values
18232: 
18233: numtitles - for institutional codes - number of categories
18234: 
18235: cloneruname - optional username of new course owner
18236: 
18237: clonerudom - optional domain of new course owner
18238: 
18239: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
18240:             (used when DC is using course creation form)
18241: 
18242: codetitles - reference to array of titles of components in institutional codes (official courses).
18243: 
18244: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
18245:            (and so can clone automatically)
18246: 
18247: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
18248: 
18249: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
18250:               courses to clone 
18251: 
18252: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
18253: 
18254: 
18255: Side Effects: None
18256: 
18257: =cut
18258: 
18259: 
18260: sub search_courses {
18261:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
18262:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
18263:     my (%courses,%showcourses,$cloner);
18264:     if (($filter->{'ownerfilter'} ne '') ||
18265:         ($filter->{'ownerdomfilter'} ne '')) {
18266:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
18267:                                        $filter->{'ownerdomfilter'};
18268:     }
18269:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
18270:         if (!$filter->{$item}) {
18271:             $filter->{$item}='.';
18272:         }
18273:     }
18274:     my $now = time;
18275:     my $timefilter =
18276:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
18277:     my ($createdbefore,$createdafter);
18278:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
18279:         $createdbefore = $now;
18280:         $createdafter = $now-$filter->{'createdfilter'};
18281:     }
18282:     my ($instcodefilter,$regexpok);
18283:     if ($numtitles) {
18284:         if ($env{'form.official'} eq 'on') {
18285:             $instcodefilter =
18286:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
18287:             $regexpok = 1;
18288:         } elsif ($env{'form.official'} eq 'off') {
18289:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
18290:             unless ($instcodefilter eq '') {
18291:                 $regexpok = -1;
18292:             }
18293:         }
18294:     } else {
18295:         $instcodefilter = $filter->{'instcodefilter'};
18296:     }
18297:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
18298:     if ($type eq '') { $type = '.'; }
18299: 
18300:     if (($clonerudom ne '') && ($cloneruname ne '')) {
18301:         $cloner = $cloneruname.':'.$clonerudom;
18302:     }
18303:     %courses = &Apache::lonnet::courseiddump($dom,
18304:                                              $filter->{'descriptfilter'},
18305:                                              $timefilter,
18306:                                              $instcodefilter,
18307:                                              $filter->{'combownerfilter'},
18308:                                              $filter->{'coursefilter'},
18309:                                              undef,undef,$type,$regexpok,undef,undef,
18310:                                              undef,undef,$cloner,$cc_clone,
18311:                                              $filter->{'cloneableonly'},
18312:                                              $createdbefore,$createdafter,undef,
18313:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
18314:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
18315:         my $ccrole;
18316:         if ($type eq 'Community') {
18317:             $ccrole = 'co';
18318:         } else {
18319:             $ccrole = 'cc';
18320:         }
18321:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
18322:                                                      $filter->{'persondomfilter'},
18323:                                                      'userroles',undef,
18324:                                                      [$ccrole,'in','ad','ep','ta','cr'],
18325:                                                      $dom);
18326:         foreach my $role (keys(%rolehash)) {
18327:             my ($cnum,$cdom,$courserole) = split(':',$role);
18328:             my $cid = $cdom.'_'.$cnum;
18329:             if (exists($courses{$cid})) {
18330:                 if (ref($courses{$cid}) eq 'HASH') {
18331:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
18332:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
18333:                             push(@{$courses{$cid}{roles}},$courserole);
18334:                         }
18335:                     } else {
18336:                         $courses{$cid}{roles} = [$courserole];
18337:                     }
18338:                     $showcourses{$cid} = $courses{$cid};
18339:                 }
18340:             }
18341:         }
18342:         %courses = %showcourses;
18343:     }
18344:     return %courses;
18345: }
18346: 
18347: =pod
18348: 
18349: =back
18350: 
18351: =head1 Routines for version requirements for current course.
18352: 
18353: =over 4
18354: 
18355: =item * &check_release_required()
18356: 
18357: Compares required LON-CAPA version with version on server, and
18358: if required version is newer looks for a server with the required version.
18359: 
18360: Looks first at servers in user's owen domain; if none suitable, looks at
18361: servers in course's domain are permitted to host sessions for user's domain.
18362: 
18363: Inputs:
18364: 
18365: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
18366: 
18367: $courseid - Course ID of current course
18368: 
18369: $rolecode - User's current role in course (for switchserver query string).
18370: 
18371: $required - LON-CAPA version needed by course (format: Major.Minor).
18372: 
18373: 
18374: Returns:
18375: 
18376: $switchserver - query string tp append to /adm/switchserver call (if 
18377:                 current server's LON-CAPA version is too old. 
18378: 
18379: $warning - Message is displayed if no suitable server could be found.
18380: 
18381: =cut
18382: 
18383: sub check_release_required {
18384:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
18385:     my ($switchserver,$warning);
18386:     if ($required ne '') {
18387:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
18388:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
18389:         if ($reqdmajor ne '' && $reqdminor ne '') {
18390:             my $otherserver;
18391:             if (($major eq '' && $minor eq '') ||
18392:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
18393:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
18394:                 my $switchlcrev =
18395:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
18396:                                                            $userdomserver);
18397:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
18398:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
18399:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
18400:                     my $cdom = $env{'course.'.$courseid.'.domain'};
18401:                     if ($cdom ne $env{'user.domain'}) {
18402:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
18403:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
18404:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
18405:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
18406:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
18407:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
18408:                         my $canhost =
18409:                             &Apache::lonnet::can_host_session($env{'user.domain'},
18410:                                                               $coursedomserver,
18411:                                                               $remoterev,
18412:                                                               $udomdefaults{'remotesessions'},
18413:                                                               $defdomdefaults{'hostedsessions'});
18414: 
18415:                         if ($canhost) {
18416:                             $otherserver = $coursedomserver;
18417:                         } else {
18418:                             $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.");
18419:                         }
18420:                     } else {
18421:                         $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).");
18422:                     }
18423:                 } else {
18424:                     $otherserver = $userdomserver;
18425:                 }
18426:             }
18427:             if ($otherserver ne '') {
18428:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
18429:             }
18430:         }
18431:     }
18432:     return ($switchserver,$warning);
18433: }
18434: 
18435: =pod
18436: 
18437: =item * &check_release_result()
18438: 
18439: Inputs:
18440: 
18441: $switchwarning - Warning message if no suitable server found to host session.
18442: 
18443: $switchserver - query string to append to /adm/switchserver containing lonHostID
18444:                 and current role.
18445: 
18446: Returns: HTML to display with information about requirement to switch server.
18447:          Either displaying warning with link to Roles/Courses screen or
18448:          display link to switchserver.
18449: 
18450: =cut
18451: 
18452: sub check_release_result {
18453:     my ($switchwarning,$switchserver) = @_;
18454:     my $output = &start_page('Selected course unavailable on this server').
18455:                  '<p class="LC_warning">';
18456:     if ($switchwarning) {
18457:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
18458:         if (&show_course()) {
18459:             $output .= &mt('Display courses');
18460:         } else {
18461:             $output .= &mt('Display roles');
18462:         }
18463:         $output .= '</a>';
18464:     } elsif ($switchserver) {
18465:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
18466:                    '<br />'.
18467:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
18468:                    &mt('Switch Server').
18469:                    '</a>';
18470:     }
18471:     $output .= '</p>'.&end_page();
18472:     return $output;
18473: }
18474: 
18475: =pod
18476: 
18477: =item * &needs_coursereinit()
18478: 
18479: Determine if course contents stored for user's session needs to be
18480: refreshed, because content has changed since "Big Hash" last tied.
18481: 
18482: Check for change is made if time last checked is more than 10 minutes ago
18483: (by default).
18484: 
18485: Inputs:
18486: 
18487: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
18488: 
18489: $interval (optional) - Time which may elapse (in s) between last check for content
18490:                        change in current course. (default: 600 s).  
18491: 
18492: Returns: an array; first element is:
18493: 
18494: =over 4
18495: 
18496: 'switch' - if content updates mean user's session
18497:            needs to be switched to a server running a newer LON-CAPA version
18498:  
18499: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
18500:            on current server hosting user's session                
18501: 
18502: ''       - if no action required.
18503: 
18504: =back
18505: 
18506: If first item element is 'switch':
18507: 
18508: second item is $switchwarning - Warning message if no suitable server found to host session. 
18509: 
18510: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
18511:                               and current role. 
18512: 
18513: otherwise: no other elements returned.
18514: 
18515: =back
18516: 
18517: =cut
18518: 
18519: sub needs_coursereinit {
18520:     my ($loncaparev,$interval) = @_;
18521:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
18522:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
18523:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
18524:     my $now = time;
18525:     if ($interval eq '') {
18526:         $interval = 600;
18527:     }
18528:     if (($now-$env{'request.course.timechecked'})>$interval) {
18529:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
18530:         my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
18531:         if ($blocked) {
18532:             return ();
18533:         }
18534:         my $update;
18535:         my $lastmainchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
18536:         my $lastsuppchange = &Apache::lonnet::get_suppchange($cdom,$cnum);
18537:         if ($lastmainchange > $env{'request.course.tied'}) {
18538:             my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
18539:             if ($needswitch) {
18540:                 return ('switch',$switchwarning,$switchserver);
18541:             }
18542:             $update = 'main';
18543:         }
18544:         if ($lastsuppchange > $env{'request.course.suppupdated'}) {
18545:             if ($update) {
18546:                 $update = 'both';
18547:             } else {
18548:                 my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
18549:                 if ($needswitch) {
18550:                     return ('switch',$switchwarning,$switchserver);
18551:                 } else {
18552:                     $update = 'supp';
18553:                 }
18554:             }
18555:             return ($update);
18556:         }
18557:     }
18558:     return ();
18559: }
18560: 
18561: sub switch_for_update {
18562:     my ($loncaparev,$cdom,$cnum) = @_;
18563:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
18564:     if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
18565:         my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
18566:         if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
18567:             &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
18568:                                     $curr_reqd_hash{'internal.releaserequired'}});
18569:             my ($switchserver,$switchwarning) =
18570:                 &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
18571:                                         $curr_reqd_hash{'internal.releaserequired'});
18572:             if ($switchwarning ne '' || $switchserver ne '') {
18573:                 return ('switch',$switchwarning,$switchserver);
18574:             }
18575:         }
18576:     }
18577:     return ();
18578: }
18579: 
18580: sub update_content_constraints {
18581:     my ($cdom,$cnum,$chome,$cid) = @_;
18582:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
18583:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
18584:     my (%checkresponsetypes,%checkcrsrestypes);
18585:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
18586:         my ($item,$name,$value) = split(/:/,$key);
18587:         if ($item eq 'resourcetag') {
18588:             if ($name eq 'responsetype') {
18589:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
18590:             }
18591:         } elsif ($item eq 'course') {
18592:             if ($name eq 'courserestype') {
18593:                 $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
18594:             }
18595:         }
18596:     }
18597:     my $navmap = Apache::lonnavmaps::navmap->new();
18598:     if (defined($navmap)) {
18599:         my (%allresponses,%allcrsrestypes);
18600:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
18601:             if ($res->is_tool()) {
18602:                 if ($allcrsrestypes{'exttool'}) {
18603:                     $allcrsrestypes{'exttool'} ++;
18604:                 } else {
18605:                     $allcrsrestypes{'exttool'} = 1;
18606:                 }
18607:                 next;
18608:             }
18609:             my %responses = $res->responseTypes();
18610:             foreach my $key (keys(%responses)) {
18611:                 next unless(exists($checkresponsetypes{$key}));
18612:                 $allresponses{$key} += $responses{$key};
18613:             }
18614:         }
18615:         foreach my $key (keys(%allresponses)) {
18616:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
18617:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
18618:                 ($reqdmajor,$reqdminor) = ($major,$minor);
18619:             }
18620:         }
18621:         foreach my $key (keys(%allcrsrestypes)) {
18622:             my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
18623:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
18624:                 ($reqdmajor,$reqdminor) = ($major,$minor);
18625:             }
18626:         }
18627:         undef($navmap);
18628:     }
18629:     if (&Apache::lonnet::count_supptools($cnum,$cdom,1)) {
18630:         my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
18631:         if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
18632:             ($reqdmajor,$reqdminor) = ($major,$minor);
18633:         }
18634:     }
18635:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
18636:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
18637:     }
18638:     return;
18639: }
18640: 
18641: sub allmaps_incourse {
18642:     my ($cdom,$cnum,$chome,$cid) = @_;
18643:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
18644:         $cid = $env{'request.course.id'};
18645:         $cdom = $env{'course.'.$cid.'.domain'};
18646:         $cnum = $env{'course.'.$cid.'.num'};
18647:         $chome = $env{'course.'.$cid.'.home'};
18648:     }
18649:     my %allmaps = ();
18650:     my $lastchange =
18651:         &Apache::lonnet::get_coursechange($cdom,$cnum);
18652:     if ($lastchange > $env{'request.course.tied'}) {
18653:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
18654:         unless ($ferr) {
18655:             &update_content_constraints($cdom,$cnum,$chome,$cid);
18656:         }
18657:     }
18658:     my $navmap = Apache::lonnavmaps::navmap->new();
18659:     if (defined($navmap)) {
18660:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
18661:             $allmaps{$res->src()} = 1;
18662:         }
18663:     }
18664:     return \%allmaps;
18665: }
18666: 
18667: sub parse_supplemental_title {
18668:     my ($title) = @_;
18669: 
18670:     my ($foldertitle,$renametitle);
18671:     if ($title =~ /&amp;&amp;&amp;/) {
18672:         $title = &HTML::Entites::decode($title);
18673:     }
18674:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
18675:         $renametitle=$4;
18676:         my ($time,$uname,$udom) = ($1,$2,$3);
18677:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
18678:         my $name =  &plainname($uname,$udom);
18679:         $name = &HTML::Entities::encode($name,'"<>&\'');
18680:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
18681:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.$name;
18682:         if ($foldertitle ne '') {
18683:             $title .= ': <br />'.$foldertitle;
18684:         }
18685:     }
18686:     if (wantarray) {
18687:         return ($title,$foldertitle,$renametitle);
18688:     }
18689:     return $title;
18690: }
18691: 
18692: sub get_supplemental {
18693:     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
18694:     my $hashid=$cnum.':'.$cdom;
18695:     my ($supplemental,$cached,$set_httprefs);
18696:     unless ($ignorecache) {
18697:         ($supplemental,$cached) = &Apache::lonnet::is_cached_new('supplemental',$hashid);
18698:     }
18699:     unless (defined($cached)) {
18700:         my $chome=&Apache::lonnet::homeserver($cnum,$cdom);
18701:         unless ($chome eq 'no_host') {
18702:             my @order = @LONCAPA::map::order;
18703:             my @resources = @LONCAPA::map::resources;
18704:             my @resparms = @LONCAPA::map::resparms;
18705:             my @zombies = @LONCAPA::map::zombies;
18706:             my ($errors,%ids,%hidden);
18707:             $errors =
18708:                 &recurse_supplemental($cnum,$cdom,'supplemental.sequence',
18709:                                       $errors,$possdel,\%ids,\%hidden);
18710:             @LONCAPA::map::order = @order;
18711:             @LONCAPA::map::resources = @resources;
18712:             @LONCAPA::map::resparms = @resparms;
18713:             @LONCAPA::map::zombies = @zombies;
18714:             $set_httprefs = 1;
18715:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
18716:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
18717:             }
18718:             $supplemental = {
18719:                                ids => \%ids,
18720:                                hidden => \%hidden,
18721:                             };
18722:             &Apache::lonnet::do_cache_new('supplemental',$hashid,$supplemental,600);
18723:         }
18724:     }
18725:     return ($supplemental,$set_httprefs);
18726: }
18727: 
18728: sub recurse_supplemental {
18729:     my ($cnum,$cdom,$suppmap,$errors,$possdel,$suppids,$hiddensupp,$hidden) = @_;
18730:     if (($suppmap) && (ref($suppids) eq 'HASH') && (ref($hiddensupp) eq 'HASH')) {
18731:         my $mapnum;
18732:         if ($suppmap eq 'supplemental.sequence') {
18733:             $mapnum = 0;
18734:         } else {
18735:             ($mapnum) = ($suppmap =~ /^supplemental_(\d+)\.sequence$/);
18736:         }
18737:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
18738:         if ($fatal) {
18739:             $errors ++;
18740:         } else {
18741:             my @order = @LONCAPA::map::order;
18742:             if (@order > 0) {
18743:                 my @resources = @LONCAPA::map::resources;
18744:                 my @resparms = @LONCAPA::map::resparms;
18745:                 foreach my $idx (@order) {
18746:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$resources[$idx]);
18747:                     if (($src ne '') && ($status eq 'res')) {
18748:                         my $id = $mapnum.':'.$idx;
18749:                         push(@{$suppids->{$src}},$id);
18750:                         if (($hidden) || (&get_supp_parameter($resparms[$idx],'parameter_hiddenresource') =~ /^yes/i)) {
18751:                             $hiddensupp->{$id} = 1;
18752:                         }
18753:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
18754:                             $errors = &recurse_supplemental($cnum,$cdom,$1,$errors,$possdel,$suppids,
18755:                                                             $hiddensupp,$hiddensupp->{$id});
18756:                         } else {
18757:                             my $allowed;
18758:                             if (($env{'request.role.adv'}) || (!$hiddensupp->{$id})) {
18759:                                 $allowed = 1;
18760:                             } elsif ($possdel) {
18761:                                 foreach my $item (@{$suppids->{$src}}) {
18762:                                     next if ($item eq $id);
18763:                                     unless ($hiddensupp->{$item}) {
18764:                                        $allowed = 1;
18765:                                        last;
18766:                                     }
18767:                                 }
18768:                                 if ((!$allowed) && (exists($env{'httpref.'.$src}))) {
18769:                                     &Apache::lonnet::delenv('httpref.'.$src);
18770:                                 }
18771:                             }
18772:                             if ($allowed && (!exists($env{'httpref.'.$src}))) {
18773:                                 &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
18774:                             }
18775:                         }
18776:                     }
18777:                 }
18778:             }
18779:         }
18780:     }
18781:     return $errors;
18782: }
18783: 
18784: sub set_supp_httprefs {
18785:     my ($cnum,$cdom,$supplemental,$possdel) = @_;
18786:     if (ref($supplemental) eq 'HASH') {
18787:         if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
18788:             foreach my $src (keys(%{$supplemental->{'ids'}})) {
18789:                 next if ($src =~ /\.sequence$/);
18790:                 if (ref($supplemental->{'ids'}->{$src}) eq 'ARRAY') {
18791:                     my $allowed;
18792:                     if ($env{'request.role.adv'}) {
18793:                         $allowed = 1;
18794:                     } else {
18795:                         foreach my $id (@{$supplemental->{'ids'}->{$src}}) {
18796:                             unless ($supplemental->{'hidden'}->{$id}) {
18797:                                 $allowed = 1;
18798:                                 last;
18799:                             }
18800:                         }
18801:                     }
18802:                     if (exists($env{'httpref.'.$src})) {
18803:                         if ($possdel) {
18804:                             unless ($allowed) {
18805:                                 &Apache::lonnet::delenv('httpref.'.$src);
18806:                             }
18807:                         }
18808:                     } elsif ($allowed) {
18809:                         &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
18810:                     }
18811:                 }
18812:             }
18813:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
18814:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
18815:             }
18816:         }
18817:     }
18818: }
18819: 
18820: sub get_supp_parameter {
18821:     my ($resparm,$name)=@_;
18822:     return if ($resparm eq '');
18823:     my $value=undef;
18824:     my $ptype=undef;
18825:     foreach (split('&&&',$resparm)) {
18826:         my ($thistype,$thisname,$thisvalue)=split('___',$_);
18827:         if ($thisname eq $name) {
18828:             $value=$thisvalue;
18829:             $ptype=$thistype;
18830:         }
18831:     }
18832:     return $value;
18833: }
18834: 
18835: sub symb_to_docspath {
18836:     my ($symb,$navmapref) = @_;
18837:     return unless ($symb && ref($navmapref));
18838:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
18839:     if ($resurl=~/\.(sequence|page)$/) {
18840:         $mapurl=$resurl;
18841:     } elsif ($resurl eq 'adm/navmaps') {
18842:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
18843:     }
18844:     my $mapresobj;
18845:     unless (ref($$navmapref)) {
18846:         $$navmapref = Apache::lonnavmaps::navmap->new();
18847:     }
18848:     if (ref($$navmapref)) {
18849:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
18850:     }
18851:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
18852:     my $type=$2;
18853:     my $path;
18854:     if (ref($mapresobj)) {
18855:         my $pcslist = $mapresobj->map_hierarchy();
18856:         if ($pcslist ne '') {
18857:             foreach my $pc (split(/,/,$pcslist)) {
18858:                 next if ($pc <= 1);
18859:                 my $res = $$navmapref->getByMapPc($pc);
18860:                 if (ref($res)) {
18861:                     my $thisurl = $res->src();
18862:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
18863:                     my $thistitle = $res->title();
18864:                     $path .= '&'.
18865:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
18866:                              &escape($thistitle).
18867:                              ':'.$res->randompick().
18868:                              ':'.$res->randomout().
18869:                              ':'.$res->encrypted().
18870:                              ':'.$res->randomorder().
18871:                              ':'.$res->is_page();
18872:                 }
18873:             }
18874:         }
18875:         $path =~ s/^\&//;
18876:         my $maptitle = $mapresobj->title();
18877:         if ($mapurl eq 'default') {
18878:             $maptitle = 'Main Content';
18879:         }
18880:         $path .= (($path ne '')? '&' : '').
18881:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
18882:                  &escape($maptitle).
18883:                  ':'.$mapresobj->randompick().
18884:                  ':'.$mapresobj->randomout().
18885:                  ':'.$mapresobj->encrypted().
18886:                  ':'.$mapresobj->randomorder().
18887:                  ':'.$mapresobj->is_page();
18888:     } else {
18889:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
18890:         my $ispage = (($type eq 'page')? 1 : '');
18891:         if ($mapurl eq 'default') {
18892:             $maptitle = 'Main Content';
18893:         }
18894:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
18895:                 &escape($maptitle).':::::'.$ispage;
18896:     }
18897:     unless ($mapurl eq 'default') {
18898:         $path = 'default&'.
18899:                 &escape('Main Content').
18900:                 ':::::&'.$path;
18901:     }
18902:     return $path;
18903: }
18904: 
18905: sub validate_folderpath {
18906:     my ($supplementalflag,$allowed,$coursenum,$coursedom) = @_;
18907:     if ($env{'form.folderpath'} ne '') {
18908:         my @items = split(/\&/,$env{'form.folderpath'});
18909:         my ($badpath,$changed,$got_supp,$supppath,%supphidden,%suppids);
18910:         for (my $i=0; $i<@items; $i++) {
18911:             my $odd = $i%2;
18912:             if (($odd) && (!$supplementalflag) && ($items[$i] !~ /^[^:]*:(|\d+):(|1):(|1):(|1):(|1)$/)) {
18913:                 $badpath = 1;
18914:             } elsif ($odd && $supplementalflag) {
18915:                 my $idx = $i-1;
18916:                 if ($items[$i] =~ /^([^:]*)::(|1):::$/) {
18917:                     my $esc_name = $1;
18918:                     if ((!$allowed) || ($items[$idx] eq 'supplemental')) {
18919:                         $supppath .= '&'.$esc_name;
18920:                         $changed = 1;
18921:                     } else {
18922:                         $supppath .= '&'.$items[$i];
18923:                     }
18924:                 } elsif (($allowed) && ($items[$idx] ne 'supplemental')) {
18925:                     $changed = 1;
18926:                     my $is_hidden;
18927:                     unless ($got_supp) {
18928:                         my ($supplemental) = &get_supplemental($coursenum,$coursedom);
18929:                         if (ref($supplemental) eq 'HASH') {
18930:                             if (ref($supplemental->{'hidden'}) eq 'HASH') {
18931:                                 %supphidden = %{$supplemental->{'hidden'}};
18932:                             }
18933:                             if (ref($supplemental->{'ids'}) eq 'HASH') {
18934:                                 %suppids = %{$supplemental->{'ids'}};
18935:                             }
18936:                         }
18937:                         $got_supp = 1;
18938:                     }
18939:                     if (ref($suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}) eq 'ARRAY') {
18940:                         my $mapid = $suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}->[0];
18941:                         if ($supphidden{$mapid}) {
18942:                             $is_hidden = 1;
18943:                         }
18944:                     }
18945:                     $supppath .= '&'.$items[$i].'::'.$is_hidden.':::';
18946:                 } else {
18947:                     $supppath .= '&'.$items[$i];
18948:                 }
18949:             } elsif ((!$odd) && ($items[$i] !~ /^(default|supplemental)(|_\d+)$/)) {
18950:                 $badpath = 1;
18951:             } elsif ($supplementalflag) {
18952:                 $supppath .= '&'.$items[$i];
18953:             }
18954:             last if ($badpath);
18955:         }
18956:         if ($badpath) {
18957:             delete($env{'form.folderpath'});
18958:         } elsif ($changed && $supplementalflag) {
18959:             $supppath =~ s/^\&//;
18960:             $env{'form.folderpath'} = $supppath;
18961:         }
18962:     }
18963:     return;
18964: }
18965: 
18966: sub captcha_display {
18967:     my ($context,$lonhost,$defdom) = @_;
18968:     my ($output,$error);
18969:     my ($captcha,$pubkey,$privkey,$version) = 
18970:         &get_captcha_config($context,$lonhost,$defdom);
18971:     if ($captcha eq 'original') {
18972:         $output = &create_captcha();
18973:         unless ($output) {
18974:             $error = 'captcha';
18975:         }
18976:     } elsif ($captcha eq 'recaptcha') {
18977:         $output = &create_recaptcha($pubkey,$version);
18978:         unless ($output) {
18979:             $error = 'recaptcha';
18980:         }
18981:     }
18982:     return ($output,$error,$captcha,$version);
18983: }
18984: 
18985: sub captcha_response {
18986:     my ($context,$lonhost,$defdom) = @_;
18987:     my ($captcha_chk,$captcha_error);
18988:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
18989:     if ($captcha eq 'original') {
18990:         ($captcha_chk,$captcha_error) = &check_captcha();
18991:     } elsif ($captcha eq 'recaptcha') {
18992:         $captcha_chk = &check_recaptcha($privkey,$version);
18993:     } else {
18994:         $captcha_chk = 1;
18995:     }
18996:     return ($captcha_chk,$captcha_error);
18997: }
18998: 
18999: sub get_captcha_config {
19000:     my ($context,$lonhost,$dom_in_effect) = @_;
19001:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
19002:     my $hostname = &Apache::lonnet::hostname($lonhost);
19003:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
19004:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
19005:     if ($context eq 'usercreation') {
19006:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
19007:         if (ref($domconfig{$context}) eq 'HASH') {
19008:             $hashtocheck = $domconfig{$context}{'cancreate'};
19009:             if (ref($hashtocheck) eq 'HASH') {
19010:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
19011:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
19012:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
19013:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
19014:                     }
19015:                     if ($privkey && $pubkey) {
19016:                         $captcha = 'recaptcha';
19017:                         $version = $hashtocheck->{'recaptchaversion'};
19018:                         if ($version ne '2') {
19019:                             $version = 1;
19020:                         }
19021:                     } else {
19022:                         $captcha = 'original';
19023:                     }
19024:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
19025:                     $captcha = 'original';
19026:                 }
19027:             }
19028:         } else {
19029:             $captcha = 'captcha';
19030:         }
19031:     } elsif ($context eq 'login') {
19032:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
19033:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
19034:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
19035:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
19036:             if ($privkey && $pubkey) {
19037:                 $captcha = 'recaptcha';
19038:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
19039:                 if ($version ne '2') {
19040:                     $version = 1; 
19041:                 }
19042:             } else {
19043:                 $captcha = 'original';
19044:             }
19045:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
19046:             $captcha = 'original';
19047:         }
19048:     } elsif ($context eq 'passwords') {
19049:         if ($dom_in_effect) {
19050:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
19051:             if ($passwdconf{'captcha'} eq 'recaptcha') {
19052:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
19053:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
19054:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
19055:                 }
19056:                 if ($privkey && $pubkey) {
19057:                     $captcha = 'recaptcha';
19058:                     $version = $passwdconf{'recaptchaversion'};
19059:                     if ($version ne '2') {
19060:                         $version = 1;
19061:                     }
19062:                 } else {
19063:                     $captcha = 'original';
19064:                 }
19065:             } elsif ($passwdconf{'captcha'} ne 'notused') {
19066:                 $captcha = 'original';
19067:             }
19068:         }
19069:     } 
19070:     return ($captcha,$pubkey,$privkey,$version);
19071: }
19072: 
19073: sub create_captcha {
19074:     my %captcha_params = &captcha_settings();
19075:     my ($output,$maxtries,$tries) = ('',10,0);
19076:     while ($tries < $maxtries) {
19077:         $tries ++;
19078:         my $captcha = Authen::Captcha->new (
19079:                                            output_folder => $captcha_params{'output_dir'},
19080:                                            data_folder   => $captcha_params{'db_dir'},
19081:                                           );
19082:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
19083: 
19084:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
19085:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
19086:                       '<span class="LC_nobreak">'.
19087:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
19088:                       '<input type="text" size="5" name="code" value="" autocomplete="new-password" />'.
19089:                       '</span><br />'.
19090:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
19091:             last;
19092:         }
19093:     }
19094:     if ($output eq '') {
19095:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
19096:     }
19097:     return $output;
19098: }
19099: 
19100: sub captcha_settings {
19101:     my %captcha_params = (
19102:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
19103:                            www_output_dir => "/captchaspool",
19104:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
19105:                            numchars       => '5',
19106:                          );
19107:     return %captcha_params;
19108: }
19109: 
19110: sub check_captcha {
19111:     my ($captcha_chk,$captcha_error);
19112:     my $code = $env{'form.code'};
19113:     my $md5sum = $env{'form.crypt'};
19114:     my %captcha_params = &captcha_settings();
19115:     my $captcha = Authen::Captcha->new(
19116:                       output_folder => $captcha_params{'output_dir'},
19117:                       data_folder   => $captcha_params{'db_dir'},
19118:                   );
19119:     $captcha_chk = $captcha->check_code($code,$md5sum);
19120:     my %captcha_hash = (
19121:                         0       => 'Code not checked (file error)',
19122:                        -1      => 'Failed: code expired',
19123:                        -2      => 'Failed: invalid code (not in database)',
19124:                        -3      => 'Failed: invalid code (code does not match crypt)',
19125:     );
19126:     if ($captcha_chk != 1) {
19127:         $captcha_error = $captcha_hash{$captcha_chk}
19128:     }
19129:     return ($captcha_chk,$captcha_error);
19130: }
19131: 
19132: sub create_recaptcha {
19133:     my ($pubkey,$version) = @_;
19134:     if ($version >= 2) {
19135:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
19136:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
19137:     } else {
19138:         my $use_ssl;
19139:         if ($ENV{'SERVER_PORT'} == 443) {
19140:             $use_ssl = 1;
19141:         }
19142:         my $captcha = Captcha::reCAPTCHA->new;
19143:         return $captcha->get_options_setter({theme => 'white'})."\n".
19144:                $captcha->get_html($pubkey,undef,$use_ssl).
19145:                &mt('If the text is hard to read, [_1] will replace them.',
19146:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
19147:                '<br /><br />';
19148:     }
19149: }
19150: 
19151: sub check_recaptcha {
19152:     my ($privkey,$version) = @_;
19153:     my $captcha_chk;
19154:     my $ip = &Apache::lonnet::get_requestor_ip();
19155:     if ($version >= 2) {
19156:         my %info = (
19157:                      secret   => $privkey, 
19158:                      response => $env{'form.g-recaptcha-response'},
19159:                      remoteip => $ip,
19160:                    );
19161:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
19162:         $request->content(join('&',map {
19163:                          my $name = escape($_);
19164:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
19165:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
19166:                          : &escape($info{$_}) );
19167:         } keys(%info)));
19168:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
19169:         if ($response->is_success)  {
19170:             my $data = JSON::DWIW->from_json($response->decoded_content);
19171:             if (ref($data) eq 'HASH') {
19172:                 if ($data->{'success'}) {
19173:                     $captcha_chk = 1;
19174:                 }
19175:             }
19176:         }
19177:     } else {
19178:         my $captcha = Captcha::reCAPTCHA->new;
19179:         my $captcha_result =
19180:             $captcha->check_answer(
19181:                                     $privkey,
19182:                                     $ip,
19183:                                     $env{'form.recaptcha_challenge_field'},
19184:                                     $env{'form.recaptcha_response_field'},
19185:                                   );
19186:         if ($captcha_result->{is_valid}) {
19187:             $captcha_chk = 1;
19188:         }
19189:     }
19190:     return $captcha_chk;
19191: }
19192: 
19193: sub emailusername_info {
19194:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
19195:     my %titles = &Apache::lonlocal::texthash (
19196:                      lastname      => 'Last Name',
19197:                      firstname     => 'First Name',
19198:                      institution   => 'School/college/university',
19199:                      location      => "School's city, state/province, country",
19200:                      web           => "School's web address",
19201:                      officialemail => 'E-mail address at institution (if different)',
19202:                      id            => 'Student/Employee ID',
19203:                  );
19204:     return (\@fields,\%titles);
19205: }
19206: 
19207: sub cleanup_html {
19208:     my ($incoming) = @_;
19209:     my $outgoing;
19210:     if ($incoming ne '') {
19211:         $outgoing = $incoming;
19212:         $outgoing =~ s/;/&#059;/g;
19213:         $outgoing =~ s/\#/&#035;/g;
19214:         $outgoing =~ s/\&/&#038;/g;
19215:         $outgoing =~ s/</&#060;/g;
19216:         $outgoing =~ s/>/&#062;/g;
19217:         $outgoing =~ s/\(/&#040/g;
19218:         $outgoing =~ s/\)/&#041;/g;
19219:         $outgoing =~ s/"/&#034;/g;
19220:         $outgoing =~ s/'/&#039;/g;
19221:         $outgoing =~ s/\$/&#036;/g;
19222:         $outgoing =~ s{/}{&#047;}g;
19223:         $outgoing =~ s/=/&#061;/g;
19224:         $outgoing =~ s/\\/&#092;/g
19225:     }
19226:     return $outgoing;
19227: }
19228: 
19229: # Checks for critical messages and returns a redirect url if one exists.
19230: # $interval indicates how often to check for messages.
19231: # $context is the calling context -- roles, grades, contents, menu or flip. 
19232: sub critical_redirect {
19233:     my ($interval,$context) = @_;
19234:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
19235:         return ();
19236:     }
19237:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
19238:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
19239:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
19240:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
19241:             my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
19242:             if ($blocked) {
19243:                 my $checkrole = "cm./$cdom/$cnum";
19244:                 if ($env{'request.course.sec'} ne '') {
19245:                     $checkrole .= "/$env{'request.course.sec'}";
19246:                 }
19247:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
19248:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
19249:                     return;
19250:                 }
19251:             }
19252:         }
19253:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
19254:                                         $env{'user.name'});
19255:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
19256:         my $redirecturl;
19257:         if ($what[0]) {
19258: 	    if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
19259: 	        $redirecturl='/adm/email?critical=display';
19260: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
19261:                 return (1, $url);
19262:             }
19263:         }
19264:     } 
19265:     return ();
19266: }
19267: 
19268: # Use:
19269: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
19270: #
19271: ##################################################
19272: #          password associated functions         #
19273: ##################################################
19274: sub des_keys {
19275:     # Make a new key for DES encryption.
19276:     # Each key has two parts which are returned separately.
19277:     # Please note:  Each key must be passed through the &hex function
19278:     # before it is output to the web browser.  The hex versions cannot
19279:     # be used to decrypt.
19280:     my @hexstr=('0','1','2','3','4','5','6','7',
19281:                 '8','9','a','b','c','d','e','f');
19282:     my $lkey='';
19283:     for (0..7) {
19284:         $lkey.=$hexstr[rand(15)];
19285:     }
19286:     my $ukey='';
19287:     for (0..7) {
19288:         $ukey.=$hexstr[rand(15)];
19289:     }
19290:     return ($lkey,$ukey);
19291: }
19292: 
19293: sub des_decrypt {
19294:     my ($key,$cyphertext) = @_;
19295:     my $keybin=pack("H16",$key);
19296:     my $cypher;
19297:     if ($Crypt::DES::VERSION>=2.03) {
19298:         $cypher=new Crypt::DES $keybin;
19299:     } else {
19300:         $cypher=new DES $keybin;
19301:     }
19302:     my $plaintext='';
19303:     my $cypherlength = length($cyphertext);
19304:     my $numchunks = int($cypherlength/32);
19305:     for (my $j=0; $j<$numchunks; $j++) {
19306:         my $start = $j*32;
19307:         my $cypherblock = substr($cyphertext,$start,32);
19308:         my $chunk =
19309:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
19310:         $chunk .=
19311:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
19312:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
19313:         $plaintext .= $chunk;
19314:     }
19315:     return $plaintext;
19316: }
19317: 
19318: sub get_requested_shorturls {
19319:     my ($cdom,$cnum,$navmap) = @_;
19320:     return unless (ref($navmap));
19321:     my ($numnew,$errors);
19322:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
19323:     if (@toshorten) {
19324:         my (%maps,%resources,%titles);
19325:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
19326:                                                                'shorturls',$cdom,$cnum);
19327:         if (keys(%resources)) {
19328:             my %tocreate;
19329:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
19330:                 my $symb = $resources{$item};
19331:                 if ($symb) {
19332:                     $tocreate{$cnum.'&'.$symb} = 1;
19333:                 }
19334:             }
19335:             if (keys(%tocreate)) {
19336:                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
19337:                                                       \%tocreate);
19338:             }
19339:         }
19340:     }
19341:     return ($numnew,$errors);
19342: }
19343: 
19344: sub make_short_symbs {
19345:     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
19346:     my ($numnew,@errors);
19347:     if (ref($tocreateref) eq 'HASH') {
19348:         my %tocreate = %{$tocreateref};
19349:         if (keys(%tocreate)) {
19350:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
19351:             my $su = Short::URL->new(no_vowels => 1);
19352:             my $init = '';
19353:             my (%newunique,%addcourse,%courseonly,%failed);
19354:             # get lock on tiny db
19355:             my $now = time;
19356:             if ($lockuser eq '') {
19357:                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
19358:             }
19359:             my $lockhash = {
19360:                                 "lock\0$now" => $lockuser,
19361:                             };
19362:             my $tries = 0;
19363:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
19364:             my ($code,$error);
19365:             while (($gotlock ne 'ok') && ($tries<3)) {
19366:                 $tries ++;
19367:                 sleep 1;
19368:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
19369:             }
19370:             if ($gotlock eq 'ok') {
19371:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
19372:                                        \%addcourse,\%courseonly,\%failed);
19373:                 if (keys(%failed)) {
19374:                     my $numfailed = scalar(keys(%failed));
19375:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
19376:                 }
19377:                 if (keys(%newunique)) {
19378:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
19379:                     if ($putres eq 'ok') {
19380:                         $numnew = scalar(keys(%newunique));
19381:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
19382:                         unless ($newputres eq 'ok') {
19383:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
19384:                         }
19385:                     } else {
19386:                         push(@errors,&mt('error: could not store unique six character URLs'));
19387:                     }
19388:                 }
19389:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
19390:                 unless ($dellockres eq 'ok') {
19391:                     push(@errors,&mt('error: could not release lockfile'));
19392:                 }
19393:             } else {
19394:                 push(@errors,&mt('error: could not obtain lockfile'));
19395:             }
19396:             if (keys(%courseonly)) {
19397:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
19398:                 if ($result ne 'ok') {
19399:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
19400:                 }
19401:             }
19402:         }
19403:     }
19404:     return ($numnew,\@errors);
19405: }
19406: 
19407: sub shorten_symbs {
19408:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
19409:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
19410:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
19411:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
19412:     my (%possibles,%collisions);
19413:     foreach my $key (keys(%{$tocreate})) {
19414:         my $num = String::CRC32::crc32($key);
19415:         my $tiny = $su->encode($num,$init);
19416:         if ($tiny) {
19417:             $possibles{$tiny} = $key;
19418:         }
19419:     }
19420:     if (!$init) {
19421:         $init = 1;
19422:     } else {
19423:         $init ++;
19424:     }
19425:     if (keys(%possibles)) {
19426:         my @posstiny = keys(%possibles);
19427:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
19428:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
19429:         if (keys(%currtiny)) {
19430:             foreach my $key (keys(%currtiny)) {
19431:                 next if ($currtiny{$key} eq '');
19432:                 if ($currtiny{$key} eq $possibles{$key}) {
19433:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
19434:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
19435:                         $courseonly->{$tsymb} = $key;
19436:                     }
19437:                 } else {
19438:                     $collisions{$possibles{$key}} = 1;
19439:                 }
19440:                 delete($possibles{$key});
19441:             }
19442:         }
19443:         foreach my $key (keys(%possibles)) {
19444:             $newunique->{$key} = $possibles{$key};
19445:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
19446:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
19447:                 $addcourse->{$tsymb} = $key;
19448:             }
19449:         }
19450:     }
19451:     if (keys(%collisions)) {
19452:         if ($init <5) {
19453:             if (!$init) {
19454:                 $init = 1;
19455:             } else {
19456:                 $init ++;
19457:             }
19458:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
19459:                                    $newunique,$addcourse,$courseonly,$failed);
19460:         } else {
19461:             foreach my $key (keys(%collisions)) {
19462:                 $failed->{$key} = 1;
19463:             }
19464:         }
19465:     }
19466:     return $init;
19467: }
19468: 
19469: sub is_nonframeable {
19470:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
19471:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
19472:     return if (($remprotocol eq '') || ($remhost eq ''));
19473: 
19474:     $remprotocol = lc($remprotocol);
19475:     $remhost = lc($remhost);
19476:     my $remport = 80;
19477:     if ($remprotocol eq 'https') {
19478:         $remport = 443;
19479:     }
19480:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
19481:     if ($cached) {
19482:         unless ($nocache) {
19483:             if ($result) {
19484:                 return 1;
19485:             } else {
19486:                 return 0;
19487:             }
19488:         }
19489:     }
19490:     my $uselink;
19491:     my $request = new HTTP::Request('HEAD',$url);
19492:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
19493:     if ($response->is_success()) {
19494:         my $secpolicy = lc($response->header('content-security-policy'));
19495:         my $xframeop = lc($response->header('x-frame-options'));
19496:         $secpolicy =~ s/^\s+|\s+$//g;
19497:         $xframeop =~ s/^\s+|\s+$//g;
19498:         if (($secpolicy ne '') || ($xframeop ne '')) {
19499:             my $remotehost = $remprotocol.'://'.$remhost;
19500:             my ($origin,$protocol,$port);
19501:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
19502:                 $port = $ENV{'SERVER_PORT'};
19503:             } else {
19504:                 $port = 80;
19505:             }
19506:             if ($absolute eq '') {
19507:                 $protocol = 'http:';
19508:                 if ($port == 443) {
19509:                     $protocol = 'https:';
19510:                 }
19511:                 $origin = $protocol.'//'.lc($hostname);
19512:             } else {
19513:                 $origin = lc($absolute);
19514:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
19515:             }
19516:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
19517:                 my $framepolicy = $1;
19518:                 $framepolicy =~ s/^\s+|\s+$//g;
19519:                 my @policies = split(/\s+/,$framepolicy);
19520:                 if (@policies) {
19521:                     if (grep(/^\Q'none'\E$/,@policies)) {
19522:                         $uselink = 1;
19523:                     } else {
19524:                         $uselink = 1;
19525:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
19526:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
19527:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
19528:                             undef($uselink);
19529:                         }
19530:                         if ($uselink) {
19531:                             if (grep(/^\Q'self'\E$/,@policies)) {
19532:                                 if (($origin ne '') && ($remotehost eq $origin)) {
19533:                                     undef($uselink);
19534:                                 }
19535:                             }
19536:                         }
19537:                         if ($uselink) {
19538:                             my @possok;
19539:                             if ($ip ne '') {
19540:                                 push(@possok,$ip);
19541:                             }
19542:                             my $hoststr = '';
19543:                             foreach my $part (reverse(split(/\./,$hostname))) {
19544:                                 if ($hoststr eq '') {
19545:                                     $hoststr = $part;
19546:                                 } else {
19547:                                     $hoststr = "$part.$hoststr";
19548:                                 }
19549:                                 if ($hoststr eq $hostname) {
19550:                                     push(@possok,$hostname);
19551:                                 } else {
19552:                                     push(@possok,"*.$hoststr");
19553:                                 }
19554:                             }
19555:                             if (@possok) {
19556:                                 foreach my $poss (@possok) {
19557:                                     last if (!$uselink);
19558:                                     foreach my $policy (@policies) {
19559:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
19560:                                             undef($uselink);
19561:                                             last;
19562:                                         }
19563:                                     }
19564:                                 }
19565:                             }
19566:                         }
19567:                     }
19568:                 }
19569:             } elsif ($xframeop ne '') {
19570:                 $uselink = 1;
19571:                 my @policies = split(/\s*,\s*/,$xframeop);
19572:                 if (@policies) {
19573:                     unless (grep(/^deny$/,@policies)) {
19574:                         if ($origin ne '') {
19575:                             if (grep(/^sameorigin$/,@policies)) {
19576:                                 if ($remotehost eq $origin) {
19577:                                     undef($uselink);
19578:                                 }
19579:                             }
19580:                             if ($uselink) {
19581:                                 foreach my $policy (@policies) {
19582:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
19583:                                         my $allowfrom = $1;
19584:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
19585:                                             undef($uselink);
19586:                                             last;
19587:                                         }
19588:                                     }
19589:                                 }
19590:                             }
19591:                         }
19592:                     }
19593:                 }
19594:             }
19595:         }
19596:     }
19597:     if ($nocache) {
19598:         if ($cached) {
19599:             my $devalidate;
19600:             if ($uselink && !$result) {
19601:                 $devalidate = 1;
19602:             } elsif (!$uselink && $result) {
19603:                 $devalidate = 1;
19604:             }
19605:             if ($devalidate) {
19606:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
19607:             }
19608:         }
19609:     } else {
19610:         if ($uselink) {
19611:             $result = 1;
19612:         } else {
19613:             $result = 0;
19614:         }
19615:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
19616:     }
19617:     return $uselink;
19618: }
19619: 
19620: sub page_menu {
19621:     my ($menucolls,$menunum) = @_;
19622:     my %menu;
19623:     foreach my $item (split(/;/,$menucolls)) {
19624:         my ($num,$value) = split(/\%/,$item);
19625:         if ($num eq $menunum) {
19626:             my @entries = split(/\&/,$value);
19627:             foreach my $entry (@entries) {
19628:                 my ($name,$fields) = split(/=/,$entry);
19629:                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
19630:                     $menu{$name} = $fields;
19631:                 } else {
19632:                     my @shown;
19633:                     if ($fields =~ /,/) {
19634:                         @shown = split(/,/,$fields);
19635:                     } else {
19636:                         @shown = ($fields);
19637:                     }
19638:                     if (@shown) {
19639:                         foreach my $field (@shown) {
19640:                             next if ($field eq '');
19641:                             $menu{$field} = 1;
19642:                         }
19643:                     }
19644:                 }
19645:             }
19646:         }
19647:     }
19648:     return %menu;
19649: }
19650: 
19651: 1;
19652: __END__;
19653: 

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