File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1075.2.141: download - view: text, annotated - select for diffs
Fri Jan 10 05:15:29 2020 UTC (4 years, 4 months ago) by raeburn
Branches: version_2_11_X
CVS tags: version_2_11_3_msu
- For 2.11
  Backport 1.1335

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1075.2.141 2020/01/10 05:15:29 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: # Makes a table out of the previous attempts
   30: # Inputs result_from_symbread, user, domain, course_id
   31: # Reads in non-network-related .tab files
   32: 
   33: # POD header:
   34: 
   35: =pod
   36: 
   37: =head1 NAME
   38: 
   39: Apache::loncommon - pile of common routines
   40: 
   41: =head1 SYNOPSIS
   42: 
   43: Common routines for manipulating connections, student answers,
   44:     domains, common Javascript fragments, etc.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: A collection of commonly used subroutines that don't have a natural
   49: home anywhere else. This collection helps remove
   50: redundancy from other modules and increase efficiency of memory usage.
   51: 
   52: =cut 
   53: 
   54: # End of POD header
   55: package Apache::loncommon;
   56: 
   57: use strict;
   58: use Apache::lonnet;
   59: use GDBM_File;
   60: use POSIX qw(strftime mktime);
   61: use Apache::lonmenu();
   62: use Apache::lonenc();
   63: use Apache::lonlocal;
   64: use Apache::lonnet();
   65: use HTML::Entities;
   66: use Apache::lonhtmlcommon();
   67: use Apache::loncoursedata();
   68: use Apache::lontexconvert();
   69: use Apache::lonclonecourse();
   70: use Apache::lonuserutils();
   71: use Apache::lonuserstate();
   72: use Apache::courseclassifier();
   73: use LONCAPA qw(:DEFAULT :match);
   74: use HTTP::Request;
   75: use DateTime::TimeZone;
   76: use DateTime::Locale;
   77: use Encode();
   78: use Authen::Captcha;
   79: use Captcha::reCAPTCHA;
   80: use JSON::DWIW;
   81: use LWP::UserAgent;
   82: use Crypt::DES;
   83: use DynaLoader; # for Crypt::DES version
   84: use File::Copy();
   85: use File::Path();
   86: 
   87: # ---------------------------------------------- Designs
   88: use vars qw(%defaultdesign);
   89: 
   90: my $readit;
   91: 
   92: 
   93: ##
   94: ## Global Variables
   95: ##
   96: 
   97: 
   98: # ----------------------------------------------- SSI with retries:
   99: #
  100: 
  101: =pod
  102: 
  103: =head1 Server Side include with retries:
  104: 
  105: =over 4
  106: 
  107: =item * &ssi_with_retries(resource,retries form)
  108: 
  109: Performs an ssi with some number of retries.  Retries continue either
  110: until the result is ok or until the retry count supplied by the
  111: caller is exhausted.  
  112: 
  113: Inputs:
  114: 
  115: =over 4
  116: 
  117: resource   - Identifies the resource to insert.
  118: 
  119: retries    - Count of the number of retries allowed.
  120: 
  121: form       - Hash that identifies the rendering options.
  122: 
  123: =back
  124: 
  125: Returns:
  126: 
  127: =over 4
  128: 
  129: content    - The content of the response.  If retries were exhausted this is empty.
  130: 
  131: response   - The response from the last attempt (which may or may not have been successful.
  132: 
  133: =back
  134: 
  135: =back
  136: 
  137: =cut
  138: 
  139: sub ssi_with_retries {
  140:     my ($resource, $retries, %form) = @_;
  141: 
  142: 
  143:     my $ok = 0;			# True if we got a good response.
  144:     my $content;
  145:     my $response;
  146: 
  147:     # Try to get the ssi done. within the retries count:
  148: 
  149:     do {
  150: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  151: 	$ok      = $response->is_success;
  152:         if (!$ok) {
  153:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  154:         }
  155: 	$retries--;
  156:     } while (!$ok && ($retries > 0));
  157: 
  158:     if (!$ok) {
  159: 	$content = '';		# On error return an empty content.
  160:     }
  161:     return ($content, $response);
  162: 
  163: }
  164: 
  165: 
  166: 
  167: # ----------------------------------------------- Filetypes/Languages/Copyright
  168: my %language;
  169: my %supported_language;
  170: my %latex_language;		# For choosing hyphenation in <transl..>
  171: my %latex_language_bykey;	# for choosing hyphenation from metadata
  172: my %cprtag;
  173: my %scprtag;
  174: my %fe; my %fd; my %fm;
  175: my %category_extensions;
  176: 
  177: # ---------------------------------------------- Thesaurus variables
  178: #
  179: # %Keywords:
  180: #      A hash used by &keyword to determine if a word is considered a keyword.
  181: # $thesaurus_db_file 
  182: #      Scalar containing the full path to the thesaurus database.
  183: 
  184: my %Keywords;
  185: my $thesaurus_db_file;
  186: 
  187: #
  188: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  189: # thesaurus.tab, and filecategories.tab.
  190: #
  191: BEGIN {
  192:     # Variable initialization
  193:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  194:     #
  195:     unless ($readit) {
  196: # ------------------------------------------------------------------- languages
  197:     {
  198:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  199:                                    '/language.tab';
  200:         if ( open(my $fh,'<',$langtabfile) ) {
  201:             while (my $line = <$fh>) {
  202:                 next if ($line=~/^\#/);
  203:                 chomp($line);
  204:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  205:                 $language{$key}=$val.' - '.$enc;
  206:                 if ($sup) {
  207:                     $supported_language{$key}=$sup;
  208:                 }
  209: 		if ($latex) {
  210: 		    $latex_language_bykey{$key} = $latex;
  211: 		    $latex_language{$two} = $latex;
  212: 		}
  213:             }
  214:             close($fh);
  215:         }
  216:     }
  217: # ------------------------------------------------------------------ copyrights
  218:     {
  219:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  220:                                   '/copyright.tab';
  221:         if ( open (my $fh,'<',$copyrightfile) ) {
  222:             while (my $line = <$fh>) {
  223:                 next if ($line=~/^\#/);
  224:                 chomp($line);
  225:                 my ($key,$val)=(split(/\s+/,$line,2));
  226:                 $cprtag{$key}=$val;
  227:             }
  228:             close($fh);
  229:         }
  230:     }
  231: # ----------------------------------------------------------- source copyrights
  232:     {
  233:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  234:                                   '/source_copyright.tab';
  235:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
  236:             while (my $line = <$fh>) {
  237:                 next if ($line =~ /^\#/);
  238:                 chomp($line);
  239:                 my ($key,$val)=(split(/\s+/,$line,2));
  240:                 $scprtag{$key}=$val;
  241:             }
  242:             close($fh);
  243:         }
  244:     }
  245: 
  246: # -------------------------------------------------------------- default domain designs
  247:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  248:     my $designfile = $designdir.'/default.tab';
  249:     if ( open (my $fh,'<',$designfile) ) {
  250:         while (my $line = <$fh>) {
  251:             next if ($line =~ /^\#/);
  252:             chomp($line);
  253:             my ($key,$val)=(split(/\=/,$line));
  254:             if ($val) { $defaultdesign{$key}=$val; }
  255:         }
  256:         close($fh);
  257:     }
  258: 
  259: # ------------------------------------------------------------- file categories
  260:     {
  261:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  262:                                   '/filecategories.tab';
  263:         if ( open (my $fh,'<',$categoryfile) ) {
  264: 	    while (my $line = <$fh>) {
  265: 		next if ($line =~ /^\#/);
  266: 		chomp($line);
  267:                 my ($extension,$category)=(split(/\s+/,$line,2));
  268:                 push(@{$category_extensions{lc($category)}},$extension);
  269:             }
  270:             close($fh);
  271:         }
  272: 
  273:     }
  274: # ------------------------------------------------------------------ file types
  275:     {
  276:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  277:                '/filetypes.tab';
  278:         if ( open (my $fh,'<',$typesfile) ) {
  279:             while (my $line = <$fh>) {
  280: 		next if ($line =~ /^\#/);
  281: 		chomp($line);
  282:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  283:                 if ($descr ne '') {
  284:                     $fe{$ending}=lc($emb);
  285:                     $fd{$ending}=$descr;
  286:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  287:                 }
  288:             }
  289:             close($fh);
  290:         }
  291:     }
  292:     &Apache::lonnet::logthis(
  293:              "<span style='color:yellow;'>INFO: Read file types</span>");
  294:     $readit=1;
  295:     }  # end of unless($readit) 
  296:     
  297: }
  298: 
  299: ###############################################################
  300: ##           HTML and Javascript Helper Functions            ##
  301: ###############################################################
  302: 
  303: =pod 
  304: 
  305: =head1 HTML and Javascript Functions
  306: 
  307: =over 4
  308: 
  309: =item * &browser_and_searcher_javascript()
  310: 
  311: X<browsing, javascript>X<searching, javascript>Returns a string
  312: containing javascript with two functions, C<openbrowser> and
  313: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  314: tags.
  315: 
  316: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  317: 
  318: inputs: formname, elementname, only, omit
  319: 
  320: formname and elementname indicate the name of the html form and name of
  321: the element that the results of the browsing selection are to be placed in. 
  322: 
  323: Specifying 'only' will restrict the browser to displaying only files
  324: with the given extension.  Can be a comma separated list.
  325: 
  326: Specifying 'omit' will restrict the browser to NOT displaying files
  327: with the given extension.  Can be a comma separated list.
  328: 
  329: =item * &opensearcher(formname,elementname) [javascript]
  330: 
  331: Inputs: formname, elementname
  332: 
  333: formname and elementname specify the name of the html form and the name
  334: of the element the selection from the search results will be placed in.
  335: 
  336: =cut
  337: 
  338: sub browser_and_searcher_javascript {
  339:     my ($mode)=@_;
  340:     if (!defined($mode)) { $mode='edit'; }
  341:     my $resurl=&escape_single(&lastresurl());
  342:     return <<END;
  343: // <!-- BEGIN LON-CAPA Internal
  344:     var editbrowser = null;
  345:     function openbrowser(formname,elementname,only,omit,titleelement) {
  346:         var url = '$resurl/?';
  347:         if (editbrowser == null) {
  348:             url += 'launch=1&';
  349:         }
  350:         url += 'catalogmode=interactive&';
  351:         url += 'mode=$mode&';
  352:         url += 'inhibitmenu=yes&';
  353:         url += 'form=' + formname + '&';
  354:         if (only != null) {
  355:             url += 'only=' + only + '&';
  356:         } else {
  357:             url += 'only=&';
  358: 	}
  359:         if (omit != null) {
  360:             url += 'omit=' + omit + '&';
  361:         } else {
  362:             url += 'omit=&';
  363: 	}
  364:         if (titleelement != null) {
  365:             url += 'titleelement=' + titleelement + '&';
  366:         } else {
  367: 	    url += 'titleelement=&';
  368: 	}
  369:         url += 'element=' + elementname + '';
  370:         var title = 'Browser';
  371:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  372:         options += ',width=700,height=600';
  373:         editbrowser = open(url,title,options,'1');
  374:         editbrowser.focus();
  375:     }
  376:     var editsearcher;
  377:     function opensearcher(formname,elementname,titleelement) {
  378:         var url = '/adm/searchcat?';
  379:         if (editsearcher == null) {
  380:             url += 'launch=1&';
  381:         }
  382:         url += 'catalogmode=interactive&';
  383:         url += 'mode=$mode&';
  384:         url += 'form=' + formname + '&';
  385:         if (titleelement != null) {
  386:             url += 'titleelement=' + titleelement + '&';
  387:         } else {
  388: 	    url += 'titleelement=&';
  389: 	}
  390:         url += 'element=' + elementname + '';
  391:         var title = 'Search';
  392:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  393:         options += ',width=700,height=600';
  394:         editsearcher = open(url,title,options,'1');
  395:         editsearcher.focus();
  396:     }
  397: // END LON-CAPA Internal -->
  398: END
  399: }
  400: 
  401: sub lastresurl {
  402:     if ($env{'environment.lastresurl'}) {
  403: 	return $env{'environment.lastresurl'}
  404:     } else {
  405: 	return '/res';
  406:     }
  407: }
  408: 
  409: sub storeresurl {
  410:     my $resurl=&Apache::lonnet::clutter(shift);
  411:     unless ($resurl=~/^\/res/) { return 0; }
  412:     $resurl=~s/\/$//;
  413:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  414:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  415:     return 1;
  416: }
  417: 
  418: sub studentbrowser_javascript {
  419:    unless (
  420:             (($env{'request.course.id'}) && 
  421:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  422: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  423: 					  '/'.$env{'request.course.sec'})
  424: 	      ))
  425:          || ($env{'request.role'}=~/^(au|dc|su)/)
  426:           ) { return ''; }  
  427:    return (<<'ENDSTDBRW');
  428: <script type="text/javascript" language="Javascript">
  429: // <![CDATA[
  430:     var stdeditbrowser;
  431:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
  432:         var url = '/adm/pickstudent?';
  433:         var filter;
  434: 	if (!ignorefilter) {
  435: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  436: 	}
  437:         if (filter != null) {
  438:            if (filter != '') {
  439:                url += 'filter='+filter+'&';
  440: 	   }
  441:         }
  442:         url += 'form=' + formname + '&unameelement='+uname+
  443:                                     '&udomelement='+udom+
  444:                                     '&clicker='+clicker;
  445: 	if (roleflag) { url+="&roles=1"; }
  446:         if (courseadvonly) { url+="&courseadvonly=1"; }
  447:         var title = 'Student_Browser';
  448:         var options = 'scrollbars=1,resizable=1,menubar=0';
  449:         options += ',width=700,height=600';
  450:         stdeditbrowser = open(url,title,options,'1');
  451:         stdeditbrowser.focus();
  452:     }
  453: // ]]>
  454: </script>
  455: ENDSTDBRW
  456: }
  457: 
  458: sub resourcebrowser_javascript {
  459:    unless ($env{'request.course.id'}) { return ''; }
  460:    return (<<'ENDRESBRW');
  461: <script type="text/javascript" language="Javascript">
  462: // <![CDATA[
  463:     var reseditbrowser;
  464:     function openresbrowser(formname,reslink) {
  465:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  466:         var title = 'Resource_Browser';
  467:         var options = 'scrollbars=1,resizable=1,menubar=0';
  468:         options += ',width=700,height=500';
  469:         reseditbrowser = open(url,title,options,'1');
  470:         reseditbrowser.focus();
  471:     }
  472: // ]]>
  473: </script>
  474: ENDRESBRW
  475: }
  476: 
  477: sub selectstudent_link {
  478:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
  479:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  480:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  481:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  482:    if ($env{'request.course.id'}) {  
  483:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  484: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  485: 					'/'.$env{'request.course.sec'})) {
  486: 	   return '';
  487:        }
  488:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  489:        if ($courseadvonly)  {
  490:            $callargs .= ",'',1,1";
  491:        }
  492:        return '<span class="LC_nobreak">'.
  493:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  494:               &mt('Select User').'</a></span>';
  495:    }
  496:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  497:        $callargs .= ",'',1"; 
  498:        return '<span class="LC_nobreak">'.
  499:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  500:               &mt('Select User').'</a></span>';
  501:    }
  502:    return '';
  503: }
  504: 
  505: sub selectresource_link {
  506:    my ($form,$reslink,$arg)=@_;
  507:    
  508:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  509:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  510:    unless ($env{'request.course.id'}) { return $arg; }
  511:    return '<span class="LC_nobreak">'.
  512:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  513:               $arg.'</a></span>';
  514: }
  515: 
  516: 
  517: 
  518: sub authorbrowser_javascript {
  519:     return <<"ENDAUTHORBRW";
  520: <script type="text/javascript" language="JavaScript">
  521: // <![CDATA[
  522: var stdeditbrowser;
  523: 
  524: function openauthorbrowser(formname,udom) {
  525:     var url = '/adm/pickauthor?';
  526:     url += 'form='+formname+'&roledom='+udom;
  527:     var title = 'Author_Browser';
  528:     var options = 'scrollbars=1,resizable=1,menubar=0';
  529:     options += ',width=700,height=600';
  530:     stdeditbrowser = open(url,title,options,'1');
  531:     stdeditbrowser.focus();
  532: }
  533: 
  534: // ]]>
  535: </script>
  536: ENDAUTHORBRW
  537: }
  538: 
  539: sub coursebrowser_javascript {
  540:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
  541:         $credits_element,$instcode) = @_;
  542:     my $wintitle = 'Course_Browser';
  543:     if ($crstype eq 'Community') {
  544:         $wintitle = 'Community_Browser';
  545:     }
  546:     my $id_functions = &javascript_index_functions();
  547:     my $output = '
  548: <script type="text/javascript" language="JavaScript">
  549: // <![CDATA[
  550:     var stdeditbrowser;'."\n";
  551: 
  552:     $output .= <<"ENDSTDBRW";
  553:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  554:         var url = '/adm/pickcourse?';
  555:         var formid = getFormIdByName(formname);
  556:         var domainfilter = getDomainFromSelectbox(formname,udom);
  557:         if (domainfilter != null) {
  558:            if (domainfilter != '') {
  559:                url += 'domainfilter='+domainfilter+'&';
  560: 	   }
  561:         }
  562:         url += 'form=' + formname + '&cnumelement='+uname+
  563: 	                            '&cdomelement='+udom+
  564:                                     '&cnameelement='+desc;
  565:         if (extra_element !=null && extra_element != '') {
  566:             if (formname == 'rolechoice' || formname == 'studentform') {
  567:                 url += '&roleelement='+extra_element;
  568:                 if (domainfilter == null || domainfilter == '') {
  569:                     url += '&domainfilter='+extra_element;
  570:                 }
  571:             }
  572:             else {
  573:                 if (formname == 'portform') {
  574:                     url += '&setroles='+extra_element;
  575:                 } else {
  576:                     if (formname == 'rules') {
  577:                         url += '&fixeddom='+extra_element; 
  578:                     }
  579:                 }
  580:             }     
  581:         }
  582:         if (type != null && type != '') {
  583:             url += '&type='+type;
  584:         }
  585:         if (type_elem != null && type_elem != '') {
  586:             url += '&typeelement='+type_elem;
  587:         }
  588:         if (formname == 'ccrs') {
  589:             var ownername = document.forms[formid].ccuname.value;
  590:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  591:             url += '&cloner='+ownername+':'+ownerdom;
  592:             if (type == 'Course') {
  593:                 url += '&crscode='+document.forms[formid].crscode.value;
  594:             }
  595:         }
  596:         if (formname == 'requestcrs') {
  597:             url += '&crsdom=$domainfilter&crscode=$instcode';
  598:         }
  599:         if (multflag !=null && multflag != '') {
  600:             url += '&multiple='+multflag;
  601:         }
  602:         var title = '$wintitle';
  603:         var options = 'scrollbars=1,resizable=1,menubar=0';
  604:         options += ',width=700,height=600';
  605:         stdeditbrowser = open(url,title,options,'1');
  606:         stdeditbrowser.focus();
  607:     }
  608: $id_functions
  609: ENDSTDBRW
  610:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
  611:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
  612:                                       $credits_element);
  613:     }
  614:     $output .= '
  615: // ]]>
  616: </script>';
  617:     return $output;
  618: }
  619: 
  620: sub javascript_index_functions {
  621:     return <<"ENDJS";
  622: 
  623: function getFormIdByName(formname) {
  624:     for (var i=0;i<document.forms.length;i++) {
  625:         if (document.forms[i].name == formname) {
  626:             return i;
  627:         }
  628:     }
  629:     return -1;
  630: }
  631: 
  632: function getIndexByName(formid,item) {
  633:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  634:         if (document.forms[formid].elements[i].name == item) {
  635:             return i;
  636:         }
  637:     }
  638:     return -1;
  639: }
  640: 
  641: function getDomainFromSelectbox(formname,udom) {
  642:     var userdom;
  643:     var formid = getFormIdByName(formname);
  644:     if (formid > -1) {
  645:         var domid = getIndexByName(formid,udom);
  646:         if (domid > -1) {
  647:             if (document.forms[formid].elements[domid].type == 'select-one') {
  648:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  649:             }
  650:             if (document.forms[formid].elements[domid].type == 'hidden') {
  651:                 userdom=document.forms[formid].elements[domid].value;
  652:             }
  653:         }
  654:     }
  655:     return userdom;
  656: }
  657: 
  658: ENDJS
  659: 
  660: }
  661: 
  662: sub javascript_array_indexof {
  663:     return <<ENDJS;
  664: <script type="text/javascript" language="JavaScript">
  665: // <![CDATA[
  666: 
  667: if (!Array.prototype.indexOf) {
  668:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  669:         "use strict";
  670:         if (this === void 0 || this === null) {
  671:             throw new TypeError();
  672:         }
  673:         var t = Object(this);
  674:         var len = t.length >>> 0;
  675:         if (len === 0) {
  676:             return -1;
  677:         }
  678:         var n = 0;
  679:         if (arguments.length > 0) {
  680:             n = Number(arguments[1]);
  681:             if (n !== n) { // shortcut for verifying if it's NaN
  682:                 n = 0;
  683:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  684:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  685:             }
  686:         }
  687:         if (n >= len) {
  688:             return -1;
  689:         }
  690:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  691:         for (; k < len; k++) {
  692:             if (k in t && t[k] === searchElement) {
  693:                 return k;
  694:             }
  695:         }
  696:         return -1;
  697:     }
  698: }
  699: 
  700: // ]]>
  701: </script>
  702: 
  703: ENDJS
  704: 
  705: }
  706: 
  707: sub userbrowser_javascript {
  708:     my $id_functions = &javascript_index_functions();
  709:     return <<"ENDUSERBRW";
  710: 
  711: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  712:     var url = '/adm/pickuser?';
  713:     var userdom = getDomainFromSelectbox(formname,udom);
  714:     if (userdom != null) {
  715:        if (userdom != '') {
  716:            url += 'srchdom='+userdom+'&';
  717:        }
  718:     }
  719:     url += 'form=' + formname + '&unameelement='+uname+
  720:                                 '&udomelement='+udom+
  721:                                 '&ulastelement='+ulast+
  722:                                 '&ufirstelement='+ufirst+
  723:                                 '&uemailelement='+uemail+
  724:                                 '&hideudomelement='+hideudom+
  725:                                 '&coursedom='+crsdom;
  726:     if ((caller != null) && (caller != undefined)) {
  727:         url += '&caller='+caller;
  728:     }
  729:     var title = 'User_Browser';
  730:     var options = 'scrollbars=1,resizable=1,menubar=0';
  731:     options += ',width=700,height=600';
  732:     var stdeditbrowser = open(url,title,options,'1');
  733:     stdeditbrowser.focus();
  734: }
  735: 
  736: function fix_domain (formname,udom,origdom,uname) {
  737:     var formid = getFormIdByName(formname);
  738:     if (formid > -1) {
  739:         var unameid = getIndexByName(formid,uname);
  740:         var domid = getIndexByName(formid,udom);
  741:         var hidedomid = getIndexByName(formid,origdom);
  742:         if (hidedomid > -1) {
  743:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  744:             var unameval = document.forms[formid].elements[unameid].value;
  745:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  746:                 if (domid > -1) {
  747:                     var slct = document.forms[formid].elements[domid];
  748:                     if (slct.type == 'select-one') {
  749:                         var i;
  750:                         for (i=0;i<slct.length;i++) {
  751:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  752:                         }
  753:                     }
  754:                     if (slct.type == 'hidden') {
  755:                         slct.value = fixeddom;
  756:                     }
  757:                 }
  758:             }
  759:         }
  760:     }
  761:     return;
  762: }
  763: 
  764: $id_functions
  765: ENDUSERBRW
  766: }
  767: 
  768: sub setsec_javascript {
  769:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
  770:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  771:         $communityrolestr);
  772:     if ($role_element ne '') {
  773:         my @allroles = ('st','ta','ep','in','ad');
  774:         foreach my $crstype ('Course','Community') {
  775:             if ($crstype eq 'Community') {
  776:                 foreach my $role (@allroles) {
  777:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  778:                 }
  779:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  780:             } else {
  781:                 foreach my $role (@allroles) {
  782:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  783:                 }
  784:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  785:             }
  786:         }
  787:         $rolestr = '"'.join('","',@allroles).'"';
  788:         $courserolestr = '"'.join('","',@courserolenames).'"';
  789:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  790:     }
  791:     my $setsections = qq|
  792: function setSect(sectionlist) {
  793:     var sectionsArray = new Array();
  794:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  795:         sectionsArray = sectionlist.split(",");
  796:     }
  797:     var numSections = sectionsArray.length;
  798:     document.$formname.$sec_element.length = 0;
  799:     if (numSections == 0) {
  800:         document.$formname.$sec_element.multiple=false;
  801:         document.$formname.$sec_element.size=1;
  802:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  803:     } else {
  804:         if (numSections == 1) {
  805:             document.$formname.$sec_element.multiple=false;
  806:             document.$formname.$sec_element.size=1;
  807:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  808:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  809:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  810:         } else {
  811:             for (var i=0; i<numSections; i++) {
  812:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  813:             }
  814:             document.$formname.$sec_element.multiple=true
  815:             if (numSections < 3) {
  816:                 document.$formname.$sec_element.size=numSections;
  817:             } else {
  818:                 document.$formname.$sec_element.size=3;
  819:             }
  820:             document.$formname.$sec_element.options[0].selected = false
  821:         }
  822:     }
  823: }
  824: 
  825: function setRole(crstype) {
  826: |;
  827:     if ($role_element eq '') {
  828:         $setsections .= '    return;
  829: }
  830: ';
  831:     } else {
  832:         $setsections .= qq|
  833:     var elementLength = document.$formname.$role_element.length;
  834:     var allroles = Array($rolestr);
  835:     var courserolenames = Array($courserolestr);
  836:     var communityrolenames = Array($communityrolestr);
  837:     if (elementLength != undefined) {
  838:         if (document.$formname.$role_element.options[5].value == 'cc') {
  839:             if (crstype == 'Course') {
  840:                 return;
  841:             } else {
  842:                 allroles[5] = 'co';
  843:                 for (var i=0; i<6; i++) {
  844:                     document.$formname.$role_element.options[i].value = allroles[i];
  845:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  846:                 }
  847:             }
  848:         } else {
  849:             if (crstype == 'Community') {
  850:                 return;
  851:             } else {
  852:                 allroles[5] = 'cc';
  853:                 for (var i=0; i<6; i++) {
  854:                     document.$formname.$role_element.options[i].value = allroles[i];
  855:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  856:                 }
  857:             }
  858:         }
  859:     }
  860:     return;
  861: }
  862: |;
  863:     }
  864:     if ($credits_element) {
  865:         $setsections .= qq|
  866: function setCredits(defaultcredits) {
  867:     document.$formname.$credits_element.value = defaultcredits;
  868:     return;
  869: }
  870: |;
  871:     }
  872:     return $setsections;
  873: }
  874: 
  875: sub selectcourse_link {
  876:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  877:        $typeelement) = @_;
  878:    my $type = $selecttype;
  879:    my $linktext = &mt('Select Course');
  880:    if ($selecttype eq 'Community') {
  881:        $linktext = &mt('Select Community');
  882:    } elsif ($selecttype eq 'Course/Community') {
  883:        $linktext = &mt('Select Course/Community');
  884:        $type = '';
  885:    } elsif ($selecttype eq 'Select') {
  886:        $linktext = &mt('Select');
  887:        $type = '';
  888:    }
  889:    return '<span class="LC_nobreak">'
  890:          ."<a href='"
  891:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  892:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  893:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  894:          ."'>".$linktext.'</a>'
  895:          .'</span>';
  896: }
  897: 
  898: sub selectauthor_link {
  899:    my ($form,$udom)=@_;
  900:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  901:           &mt('Select Author').'</a>';
  902: }
  903: 
  904: sub selectuser_link {
  905:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  906:         $coursedom,$linktext,$caller) = @_;
  907:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  908:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  909:            ');">'.$linktext.'</a>';
  910: }
  911: 
  912: sub check_uncheck_jscript {
  913:     my $jscript = <<"ENDSCRT";
  914: function checkAll(field) {
  915:     if (field.length > 0) {
  916:         for (i = 0; i < field.length; i++) {
  917:             if (!field[i].disabled) {
  918:                 field[i].checked = true;
  919:             }
  920:         }
  921:     } else {
  922:         if (!field.disabled) {
  923:             field.checked = true;
  924:         }
  925:     }
  926: }
  927:  
  928: function uncheckAll(field) {
  929:     if (field.length > 0) {
  930:         for (i = 0; i < field.length; i++) {
  931:             field[i].checked = false ;
  932:         }
  933:     } else {
  934:         field.checked = false ;
  935:     }
  936: }
  937: ENDSCRT
  938:     return $jscript;
  939: }
  940: 
  941: sub select_timezone {
  942:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  943:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  944:    if ($includeempty) {
  945:        $output .= '<option value=""';
  946:        if (($selected eq '') || ($selected eq 'local')) {
  947:            $output .= ' selected="selected" ';
  948:        }
  949:        $output .= '> </option>';
  950:    }
  951:    my @timezones = DateTime::TimeZone->all_names;
  952:    foreach my $tzone (@timezones) {
  953:        $output.= '<option value="'.$tzone.'"';
  954:        if ($tzone eq $selected) {
  955:            $output.=' selected="selected"';
  956:        }
  957:        $output.=">$tzone</option>\n";
  958:    }
  959:    $output.="</select>";
  960:    return $output;
  961: }
  962: 
  963: sub select_datelocale {
  964:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  965:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  966:     if ($includeempty) {
  967:         $output .= '<option value=""';
  968:         if ($selected eq '') {
  969:             $output .= ' selected="selected" ';
  970:         }
  971:         $output .= '> </option>';
  972:     }
  973:     my @languages = &Apache::lonlocal::preferred_languages();
  974:     my (@possibles,%locale_names);
  975:     my @locales = DateTime::Locale->ids();
  976:     foreach my $id (@locales) {
  977:         if ($id ne '') {
  978:             my ($en_terr,$native_terr);
  979:             my $loc = DateTime::Locale->load($id);
  980:             if (ref($loc)) {
  981:                 $en_terr = $loc->name();
  982:                 $native_terr = $loc->native_name();
  983:                 if (grep(/^en$/,@languages) || !@languages) {
  984:                     if ($en_terr ne '') {
  985:                         $locale_names{$id} = '('.$en_terr.')';
  986:                     } elsif ($native_terr ne '') {
  987:                         $locale_names{$id} = $native_terr;
  988:                     }
  989:                 } else {
  990:                     if ($native_terr ne '') {
  991:                         $locale_names{$id} = $native_terr.' ';
  992:                     } elsif ($en_terr ne '') {
  993:                         $locale_names{$id} = '('.$en_terr.')';
  994:                     }
  995:                 }
  996:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
  997:                 push(@possibles,$id);
  998:             }
  999:         }
 1000:     }
 1001:     foreach my $item (sort(@possibles)) {
 1002:         $output.= '<option value="'.$item.'"';
 1003:         if ($item eq $selected) {
 1004:             $output.=' selected="selected"';
 1005:         }
 1006:         $output.=">$item";
 1007:         if ($locale_names{$item} ne '') {
 1008:             $output.='  '.$locale_names{$item};
 1009:         }
 1010:         $output.="</option>\n";
 1011:     }
 1012:     $output.="</select>";
 1013:     return $output;
 1014: }
 1015: 
 1016: sub select_language {
 1017:     my ($name,$selected,$includeempty,$noedit) = @_;
 1018:     my %langchoices;
 1019:     if ($includeempty) {
 1020:         %langchoices = ('' => 'No language preference');
 1021:     }
 1022:     foreach my $id (&languageids()) {
 1023:         my $code = &supportedlanguagecode($id);
 1024:         if ($code) {
 1025:             $langchoices{$code} = &plainlanguagedescription($id);
 1026:         }
 1027:     }
 1028:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
 1029:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
 1030: }
 1031: 
 1032: =pod
 1033: 
 1034: =item * &linked_select_forms(...)
 1035: 
 1036: linked_select_forms returns a string containing a <script></script> block
 1037: and html for two <select> menus.  The select menus will be linked in that
 1038: changing the value of the first menu will result in new values being placed
 1039: in the second menu.  The values in the select menu will appear in alphabetical
 1040: order unless a defined order is provided.
 1041: 
 1042: linked_select_forms takes the following ordered inputs:
 1043: 
 1044: =over 4
 1045: 
 1046: =item * $formname, the name of the <form> tag
 1047: 
 1048: =item * $middletext, the text which appears between the <select> tags
 1049: 
 1050: =item * $firstdefault, the default value for the first menu
 1051: 
 1052: =item * $firstselectname, the name of the first <select> tag
 1053: 
 1054: =item * $secondselectname, the name of the second <select> tag
 1055: 
 1056: =item * $hashref, a reference to a hash containing the data for the menus.
 1057: 
 1058: =item * $menuorder, the order of values in the first menu
 1059: 
 1060: =item * $onchangefirst, additional javascript call to execute for an onchange
 1061:         event for the first <select> tag
 1062: 
 1063: =item * $onchangesecond, additional javascript call to execute for an onchange
 1064:         event for the second <select> tag
 1065: 
 1066: =back 
 1067: 
 1068: Below is an example of such a hash.  Only the 'text', 'default', and 
 1069: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1070: values for the first select menu.  The text that coincides with the 
 1071: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1072: and text for the second menu are given in the hash pointed to by 
 1073: $menu{$choice1}->{'select2'}.  
 1074: 
 1075:  my %menu = ( A1 => { text =>"Choice A1" ,
 1076:                        default => "B3",
 1077:                        select2 => { 
 1078:                            B1 => "Choice B1",
 1079:                            B2 => "Choice B2",
 1080:                            B3 => "Choice B3",
 1081:                            B4 => "Choice B4"
 1082:                            },
 1083:                        order => ['B4','B3','B1','B2'],
 1084:                    },
 1085:                A2 => { text =>"Choice A2" ,
 1086:                        default => "C2",
 1087:                        select2 => { 
 1088:                            C1 => "Choice C1",
 1089:                            C2 => "Choice C2",
 1090:                            C3 => "Choice C3"
 1091:                            },
 1092:                        order => ['C2','C1','C3'],
 1093:                    },
 1094:                A3 => { text =>"Choice A3" ,
 1095:                        default => "D6",
 1096:                        select2 => { 
 1097:                            D1 => "Choice D1",
 1098:                            D2 => "Choice D2",
 1099:                            D3 => "Choice D3",
 1100:                            D4 => "Choice D4",
 1101:                            D5 => "Choice D5",
 1102:                            D6 => "Choice D6",
 1103:                            D7 => "Choice D7"
 1104:                            },
 1105:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1106:                    }
 1107:                );
 1108: 
 1109: =cut
 1110: 
 1111: sub linked_select_forms {
 1112:     my ($formname,
 1113:         $middletext,
 1114:         $firstdefault,
 1115:         $firstselectname,
 1116:         $secondselectname, 
 1117:         $hashref,
 1118:         $menuorder,
 1119:         $onchangefirst,
 1120:         $onchangesecond
 1121:         ) = @_;
 1122:     my $second = "document.$formname.$secondselectname";
 1123:     my $first = "document.$formname.$firstselectname";
 1124:     # output the javascript to do the changing
 1125:     my $result = '';
 1126:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1127:     $result.="// <![CDATA[\n";
 1128:     $result.="var select2data = new Object();\n";
 1129:     $" = '","';
 1130:     my $debug = '';
 1131:     foreach my $s1 (sort(keys(%$hashref))) {
 1132:         $result.="select2data.d_$s1 = new Object();\n";        
 1133:         $result.="select2data.d_$s1.def = new String('".
 1134:             $hashref->{$s1}->{'default'}."');\n";
 1135:         $result.="select2data.d_$s1.values = new Array(";
 1136:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1137:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1138:             @s2values = @{$hashref->{$s1}->{'order'}};
 1139:         }
 1140:         $result.="\"@s2values\");\n";
 1141:         $result.="select2data.d_$s1.texts = new Array(";        
 1142:         my @s2texts;
 1143:         foreach my $value (@s2values) {
 1144:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
 1145:         }
 1146:         $result.="\"@s2texts\");\n";
 1147:     }
 1148:     $"=' ';
 1149:     $result.= <<"END";
 1150: 
 1151: function select1_changed() {
 1152:     // Determine new choice
 1153:     var newvalue = "d_" + $first.value;
 1154:     // update select2
 1155:     var values     = select2data[newvalue].values;
 1156:     var texts      = select2data[newvalue].texts;
 1157:     var select2def = select2data[newvalue].def;
 1158:     var i;
 1159:     // out with the old
 1160:     for (i = 0; i < $second.options.length; i++) {
 1161:         $second.options[i] = null;
 1162:     }
 1163:     // in with the nuclear
 1164:     for (i=0;i<values.length; i++) {
 1165:         $second.options[i] = new Option(values[i]);
 1166:         $second.options[i].value = values[i];
 1167:         $second.options[i].text = texts[i];
 1168:         if (values[i] == select2def) {
 1169:             $second.options[i].selected = true;
 1170:         }
 1171:     }
 1172: }
 1173: // ]]>
 1174: </script>
 1175: END
 1176:     # output the initial values for the selection lists
 1177:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
 1178:     my @order = sort(keys(%{$hashref}));
 1179:     if (ref($menuorder) eq 'ARRAY') {
 1180:         @order = @{$menuorder};
 1181:     }
 1182:     foreach my $value (@order) {
 1183:         $result.="    <option value=\"$value\" ";
 1184:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1185:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1186:     }
 1187:     $result .= "</select>\n";
 1188:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1189:     $result .= $middletext;
 1190:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
 1191:     if ($onchangesecond) {
 1192:         $result .= ' onchange="'.$onchangesecond.'"';
 1193:     }
 1194:     $result .= ">\n";
 1195:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1196:     
 1197:     my @secondorder = sort(keys(%select2));
 1198:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1199:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1200:     }
 1201:     foreach my $value (@secondorder) {
 1202:         $result.="    <option value=\"$value\" ";        
 1203:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1204:         $result.=">".&mt($select2{$value})."</option>\n";
 1205:     }
 1206:     $result .= "</select>\n";
 1207:     #    return $debug;
 1208:     return $result;
 1209: }   #  end of sub linked_select_forms {
 1210: 
 1211: =pod
 1212: 
 1213: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1214: 
 1215: Returns a string corresponding to an HTML link to the given help
 1216: $topic, where $topic corresponds to the name of a .tex file in
 1217: /home/httpd/html/adm/help/tex, with underscores replaced by
 1218: spaces. 
 1219: 
 1220: $text will optionally be linked to the same topic, allowing you to
 1221: link text in addition to the graphic. If you do not want to link
 1222: text, but wish to specify one of the later parameters, pass an
 1223: empty string. 
 1224: 
 1225: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1226: the link will not open a new window. If false, the link will open
 1227: a new window using Javascript. (Default is false.) 
 1228: 
 1229: $width and $height are optional numerical parameters that will
 1230: override the width and height of the popped up window, which may
 1231: be useful for certain help topics with big pictures included.
 1232: 
 1233: $imgid is the id of the img tag used for the help icon. This may be
 1234: used in a javascript call to switch the image src.  See 
 1235: lonhtmlcommon::htmlareaselectactive() for an example.
 1236: 
 1237: =cut
 1238: 
 1239: sub help_open_topic {
 1240:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1241:     $text = "" if (not defined $text);
 1242:     $stayOnPage = 0 if (not defined $stayOnPage);
 1243:     $width = 500 if (not defined $width);
 1244:     $height = 400 if (not defined $height);
 1245:     my $filename = $topic;
 1246:     $filename =~ s/ /_/g;
 1247: 
 1248:     my $template = "";
 1249:     my $link;
 1250:     
 1251:     $topic=~s/\W/\_/g;
 1252: 
 1253:     if (!$stayOnPage) {
 1254:         if ($env{'browser.mobile'}) {
 1255: 	    $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1256:         } else {
 1257:             $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1258:         }
 1259:     } elsif ($stayOnPage eq 'popup') {
 1260:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1261:     } else {
 1262: 	$link = "/adm/help/${filename}.hlp";
 1263:     }
 1264: 
 1265:     # Add the text
 1266:     if ($text ne "") {	
 1267: 	$template.='<span class="LC_help_open_topic">'
 1268:                   .'<a target="_top" href="'.$link.'">'
 1269:                   .$text.'</a>';
 1270:     }
 1271: 
 1272:     # (Always) Add the graphic
 1273:     my $title = &mt('Online Help');
 1274:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1275:     if ($imgid ne '') {
 1276:         $imgid = ' id="'.$imgid.'"';
 1277:     }
 1278:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
 1279:               .'<img src="'.$helpicon.'" border="0"'
 1280:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1281:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1282:               .' /></a>';
 1283:     if ($text ne "") {	
 1284:         $template.='</span>';
 1285:     }
 1286:     return $template;
 1287: 
 1288: }
 1289: 
 1290: # This is a quicky function for Latex cheatsheet editing, since it 
 1291: # appears in at least four places
 1292: sub helpLatexCheatsheet {
 1293:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1294:     my $out;
 1295:     my $addOther = '';
 1296:     if ($topic) {
 1297: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1298:     }
 1299:     $out = '<span>' # Start cheatsheet
 1300: 	  .$addOther
 1301:           .'<span>'
 1302: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1303: 	  .'</span> <span>'
 1304: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1305: 	  .'</span>';
 1306:     unless ($not_author) {
 1307:         $out .= ' <span>'
 1308: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1309: 	       .'</span> <span>'
 1310:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
 1311:                .'</span>';
 1312:     }
 1313:     $out .= '</span>'; # End cheatsheet
 1314:     return $out;
 1315: }
 1316: 
 1317: sub general_help {
 1318:     my $helptopic='Student_Intro';
 1319:     if ($env{'request.role'}=~/^(ca|au)/) {
 1320: 	$helptopic='Authoring_Intro';
 1321:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1322: 	$helptopic='Course_Coordination_Intro';
 1323:     } elsif ($env{'request.role'}=~/^dc/) {
 1324:         $helptopic='Domain_Coordination_Intro';
 1325:     }
 1326:     return $helptopic;
 1327: }
 1328: 
 1329: sub update_help_link {
 1330:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1331:     my $origurl = $ENV{'REQUEST_URI'};
 1332:     $origurl=~s|^/~|/priv/|;
 1333:     my $timestamp = time;
 1334:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1335:         $$datum = &escape($$datum);
 1336:     }
 1337: 
 1338:     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";
 1339:     my $output .= <<"ENDOUTPUT";
 1340: <script type="text/javascript">
 1341: // <![CDATA[
 1342: banner_link = '$banner_link';
 1343: // ]]>
 1344: </script>
 1345: ENDOUTPUT
 1346:     return $output;
 1347: }
 1348: 
 1349: # now just updates the help link and generates a blue icon
 1350: sub help_open_menu {
 1351:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1352: 	= @_;    
 1353:     $stayOnPage = 1;
 1354:     my $output;
 1355:     if ($component_help) {
 1356: 	if (!$text) {
 1357: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1358: 				       $width,$height);
 1359: 	} else {
 1360: 	    my $help_text;
 1361: 	    $help_text=&unescape($topic);
 1362: 	    $output='<table><tr><td>'.
 1363: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1364: 				 $width,$height).'</td></tr></table>';
 1365: 	}
 1366:     }
 1367:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1368:     return $output.$banner_link;
 1369: }
 1370: 
 1371: sub top_nav_help {
 1372:     my ($text) = @_;
 1373:     $text = &mt($text);
 1374:     my $stay_on_page;
 1375:     unless ($env{'environment.remote'} eq 'on') {
 1376:         $stay_on_page = 1;
 1377:     }
 1378:     my ($link,$banner_link);
 1379:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
 1380:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1381: 	                         : "javascript:helpMenu('open')";
 1382:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1383:     }
 1384:     my $title = &mt('Get help');
 1385:     if ($link) {
 1386:         return <<"END";
 1387: $banner_link
 1388: <a href="$link" title="$title">$text</a>
 1389: END
 1390:     } else {
 1391:         return '&nbsp;'.$text.'&nbsp;';
 1392:     }
 1393: }
 1394: 
 1395: sub help_menu_js {
 1396:     my ($httphost) = @_;
 1397:     my $stayOnPage = 1;
 1398:     my $width = 620;
 1399:     my $height = 600;
 1400:     my $helptopic=&general_help();
 1401:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
 1402:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1403:     my $start_page =
 1404:         &Apache::loncommon::start_page('Help Menu', undef,
 1405: 				       {'frameset'    => 1,
 1406: 					'js_ready'    => 1,
 1407:                                         'use_absolute' => $httphost,
 1408: 					'add_entries' => {
 1409: 					    'border' => '0',
 1410: 					    'rows'   => "110,*",},});
 1411:     my $end_page =
 1412:         &Apache::loncommon::end_page({'frameset' => 1,
 1413: 				      'js_ready' => 1,});
 1414: 
 1415:     my $template .= <<"ENDTEMPLATE";
 1416: <script type="text/javascript">
 1417: // <![CDATA[
 1418: // <!-- BEGIN LON-CAPA Internal
 1419: var banner_link = '';
 1420: function helpMenu(target) {
 1421:     var caller = this;
 1422:     if (target == 'open') {
 1423:         var newWindow = null;
 1424:         try {
 1425:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1426:         }
 1427:         catch(error) {
 1428:             writeHelp(caller);
 1429:             return;
 1430:         }
 1431:         if (newWindow) {
 1432:             caller = newWindow;
 1433:         }
 1434:     }
 1435:     writeHelp(caller);
 1436:     return;
 1437: }
 1438: function writeHelp(caller) {
 1439:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
 1440:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
 1441:     caller.document.close();
 1442:     caller.focus();
 1443: }
 1444: // END LON-CAPA Internal -->
 1445: // ]]>
 1446: </script>
 1447: ENDTEMPLATE
 1448:     return $template;
 1449: }
 1450: 
 1451: sub help_open_bug {
 1452:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1453:     unless ($env{'user.adv'}) { return ''; }
 1454:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1455:     $text = "" if (not defined $text);
 1456: 	$stayOnPage=1;
 1457:     $width = 600 if (not defined $width);
 1458:     $height = 600 if (not defined $height);
 1459: 
 1460:     $topic=~s/\W+/\+/g;
 1461:     my $link='';
 1462:     my $template='';
 1463:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1464: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1465:     if (!$stayOnPage)
 1466:     {
 1467: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1468:     }
 1469:     else
 1470:     {
 1471: 	$link = $url;
 1472:     }
 1473:     # Add the text
 1474:     if ($text ne "")
 1475:     {
 1476: 	$template .= 
 1477:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1478:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1479:     }
 1480: 
 1481:     # Add the graphic
 1482:     my $title = &mt('Report a Bug');
 1483:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1484:     $template .= <<"ENDTEMPLATE";
 1485:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1486: ENDTEMPLATE
 1487:     if ($text ne '') { $template.='</td></tr></table>' };
 1488:     return $template;
 1489: 
 1490: }
 1491: 
 1492: sub help_open_faq {
 1493:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1494:     unless ($env{'user.adv'}) { return ''; }
 1495:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1496:     $text = "" if (not defined $text);
 1497: 	$stayOnPage=1;
 1498:     $width = 350 if (not defined $width);
 1499:     $height = 400 if (not defined $height);
 1500: 
 1501:     $topic=~s/\W+/\+/g;
 1502:     my $link='';
 1503:     my $template='';
 1504:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1505:     if (!$stayOnPage)
 1506:     {
 1507: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1508:     }
 1509:     else
 1510:     {
 1511: 	$link = $url;
 1512:     }
 1513: 
 1514:     # Add the text
 1515:     if ($text ne "")
 1516:     {
 1517: 	$template .= 
 1518:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1519:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1520:     }
 1521: 
 1522:     # Add the graphic
 1523:     my $title = &mt('View the FAQ');
 1524:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1525:     $template .= <<"ENDTEMPLATE";
 1526:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1527: ENDTEMPLATE
 1528:     if ($text ne '') { $template.='</td></tr></table>' };
 1529:     return $template;
 1530: 
 1531: }
 1532: 
 1533: ###############################################################
 1534: ###############################################################
 1535: 
 1536: =pod
 1537: 
 1538: =item * &change_content_javascript():
 1539: 
 1540: This and the next function allow you to create small sections of an
 1541: otherwise static HTML page that you can update on the fly with
 1542: Javascript, even in Netscape 4.
 1543: 
 1544: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1545: must be written to the HTML page once. It will prove the Javascript
 1546: function "change(name, content)". Calling the change function with the
 1547: name of the section 
 1548: you want to update, matching the name passed to C<changable_area>, and
 1549: the new content you want to put in there, will put the content into
 1550: that area.
 1551: 
 1552: B<Note>: Netscape 4 only reserves enough space for the changable area
 1553: to contain room for the original contents. You need to "make space"
 1554: for whatever changes you wish to make, and be B<sure> to check your
 1555: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1556: it's adequate for updating a one-line status display, but little more.
 1557: This script will set the space to 100% width, so you only need to
 1558: worry about height in Netscape 4.
 1559: 
 1560: Modern browsers are much less limiting, and if you can commit to the
 1561: user not using Netscape 4, this feature may be used freely with
 1562: pretty much any HTML.
 1563: 
 1564: =cut
 1565: 
 1566: sub change_content_javascript {
 1567:     # If we're on Netscape 4, we need to use Layer-based code
 1568:     if ($env{'browser.type'} eq 'netscape' &&
 1569: 	$env{'browser.version'} =~ /^4\./) {
 1570: 	return (<<NETSCAPE4);
 1571: 	function change(name, content) {
 1572: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1573: 	    doc.open();
 1574: 	    doc.write(content);
 1575: 	    doc.close();
 1576: 	}
 1577: NETSCAPE4
 1578:     } else {
 1579: 	# Otherwise, we need to use semi-standards-compliant code
 1580: 	# (technically, "innerHTML" isn't standard but the equivalent
 1581: 	# is really scary, and every useful browser supports it
 1582: 	return (<<DOMBASED);
 1583: 	function change(name, content) {
 1584: 	    element = document.getElementById(name);
 1585: 	    element.innerHTML = content;
 1586: 	}
 1587: DOMBASED
 1588:     }
 1589: }
 1590: 
 1591: =pod
 1592: 
 1593: =item * &changable_area($name,$origContent):
 1594: 
 1595: This provides a "changable area" that can be modified on the fly via
 1596: the Javascript code provided in C<change_content_javascript>. $name is
 1597: the name you will use to reference the area later; do not repeat the
 1598: same name on a given HTML page more then once. $origContent is what
 1599: the area will originally contain, which can be left blank.
 1600: 
 1601: =cut
 1602: 
 1603: sub changable_area {
 1604:     my ($name, $origContent) = @_;
 1605: 
 1606:     if ($env{'browser.type'} eq 'netscape' &&
 1607: 	$env{'browser.version'} =~ /^4\./) {
 1608: 	# If this is netscape 4, we need to use the Layer tag
 1609: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1610:     } else {
 1611: 	return "<span id='$name'>$origContent</span>";
 1612:     }
 1613: }
 1614: 
 1615: =pod
 1616: 
 1617: =item * &viewport_geometry_js 
 1618: 
 1619: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1620: 
 1621: =cut
 1622: 
 1623: 
 1624: sub viewport_geometry_js { 
 1625:     return <<"GEOMETRY";
 1626: var Geometry = {};
 1627: function init_geometry() {
 1628:     if (Geometry.init) { return };
 1629:     Geometry.init=1;
 1630:     if (window.innerHeight) {
 1631:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1632:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1633:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1634:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1635:     }
 1636:     else if (document.documentElement && document.documentElement.clientHeight) {
 1637:         Geometry.getViewportHeight =
 1638:             function() { return document.documentElement.clientHeight; };
 1639:         Geometry.getViewportWidth =
 1640:             function() { return document.documentElement.clientWidth; };
 1641: 
 1642:         Geometry.getHorizontalScroll =
 1643:             function() { return document.documentElement.scrollLeft; };
 1644:         Geometry.getVerticalScroll =
 1645:             function() { return document.documentElement.scrollTop; };
 1646:     }
 1647:     else if (document.body.clientHeight) {
 1648:         Geometry.getViewportHeight =
 1649:             function() { return document.body.clientHeight; };
 1650:         Geometry.getViewportWidth =
 1651:             function() { return document.body.clientWidth; };
 1652:         Geometry.getHorizontalScroll =
 1653:             function() { return document.body.scrollLeft; };
 1654:         Geometry.getVerticalScroll =
 1655:             function() { return document.body.scrollTop; };
 1656:     }
 1657: }
 1658: 
 1659: GEOMETRY
 1660: }
 1661: 
 1662: =pod
 1663: 
 1664: =item * &viewport_size_js()
 1665: 
 1666: 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. 
 1667: 
 1668: =cut
 1669: 
 1670: sub viewport_size_js {
 1671:     my $geometry = &viewport_geometry_js();
 1672:     return <<"DIMS";
 1673: 
 1674: $geometry
 1675: 
 1676: function getViewportDims(width,height) {
 1677:     init_geometry();
 1678:     width.value = Geometry.getViewportWidth();
 1679:     height.value = Geometry.getViewportHeight();
 1680:     return;
 1681: }
 1682: 
 1683: DIMS
 1684: }
 1685: 
 1686: =pod
 1687: 
 1688: =item * &resize_textarea_js()
 1689: 
 1690: emits the needed javascript to resize a textarea to be as big as possible
 1691: 
 1692: creates a function resize_textrea that takes two IDs first should be
 1693: the id of the element to resize, second should be the id of a div that
 1694: surrounds everything that comes after the textarea, this routine needs
 1695: to be attached to the <body> for the onload and onresize events.
 1696: 
 1697: =back
 1698: 
 1699: =cut
 1700: 
 1701: sub resize_textarea_js {
 1702:     my $geometry = &viewport_geometry_js();
 1703:     return <<"RESIZE";
 1704:     <script type="text/javascript">
 1705: // <![CDATA[
 1706: $geometry
 1707: 
 1708: function getX(element) {
 1709:     var x = 0;
 1710:     while (element) {
 1711: 	x += element.offsetLeft;
 1712: 	element = element.offsetParent;
 1713:     }
 1714:     return x;
 1715: }
 1716: function getY(element) {
 1717:     var y = 0;
 1718:     while (element) {
 1719: 	y += element.offsetTop;
 1720: 	element = element.offsetParent;
 1721:     }
 1722:     return y;
 1723: }
 1724: 
 1725: 
 1726: function resize_textarea(textarea_id,bottom_id) {
 1727:     init_geometry();
 1728:     var textarea        = document.getElementById(textarea_id);
 1729:     //alert(textarea);
 1730: 
 1731:     var textarea_top    = getY(textarea);
 1732:     var textarea_height = textarea.offsetHeight;
 1733:     var bottom          = document.getElementById(bottom_id);
 1734:     var bottom_top      = getY(bottom);
 1735:     var bottom_height   = bottom.offsetHeight;
 1736:     var window_height   = Geometry.getViewportHeight();
 1737:     var fudge           = 23;
 1738:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1739:     if (new_height < 300) {
 1740: 	new_height = 300;
 1741:     }
 1742:     textarea.style.height=new_height+'px';
 1743: }
 1744: // ]]>
 1745: </script>
 1746: RESIZE
 1747: 
 1748: }
 1749: 
 1750: sub colorfuleditor_js {
 1751:     return <<"COLORFULEDIT"
 1752: <script type="text/javascript">
 1753: // <![CDATA[>
 1754:     function fold_box(curDepth, lastresource){
 1755: 
 1756:     // we need a list because there can be several blocks you need to fold in one tag
 1757:         var block = document.getElementsByName('foldblock_'+curDepth);
 1758:     // but there is only one folding button per tag
 1759:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
 1760: 
 1761:         if(block.item(0).style.display == 'none'){
 1762: 
 1763:             foldbutton.value = '@{[&mt("Hide")]}';
 1764:             for (i = 0; i < block.length; i++){
 1765:                 block.item(i).style.display = '';
 1766:             }
 1767:         }else{
 1768: 
 1769:             foldbutton.value = '@{[&mt("Show")]}';
 1770:             for (i = 0; i < block.length; i++){
 1771:                 // block.item(i).style.visibility = 'collapse';
 1772:                 block.item(i).style.display = 'none';
 1773:             }
 1774:         };
 1775:         saveState(lastresource);
 1776:     }
 1777: 
 1778:     function saveState (lastresource) {
 1779: 
 1780:         var tag_list = getTagList();
 1781:         if(tag_list != null){
 1782:             var timestamp = new Date().getTime();
 1783:             var key = lastresource;
 1784: 
 1785:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
 1786:             // starting with timestamp
 1787:             var value = timestamp+';';
 1788: 
 1789:             // building the list of key-value pairs
 1790:             for(var i = 0; i < tag_list.length; i++){
 1791:                 value += tag_list[i]+',';
 1792:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
 1793:             }
 1794: 
 1795:             // only iterate whole storage if nothing to override
 1796:             if(localStorage.getItem(key) == null){
 1797: 
 1798:                 // prevent storage from growing large
 1799:                 if(localStorage.length > 50){
 1800:                     var regex_getTimestamp = /^(?:\d)+;/;
 1801:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
 1802:                     var oldest_key;
 1803: 
 1804:                     for(var i = 1; i < localStorage.length; i++){
 1805:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
 1806:                             oldest_key = localStorage.key(i);
 1807:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
 1808:                         }
 1809:                     }
 1810:                     localStorage.removeItem(oldest_key);
 1811:                 }
 1812:             }
 1813:             localStorage.setItem(key,value);
 1814:         }
 1815:     }
 1816: 
 1817:     // restore folding status of blocks (on page load)
 1818:     function restoreState (lastresource) {
 1819:         if(localStorage.getItem(lastresource) != null){
 1820:             var key = lastresource;
 1821:             var value = localStorage.getItem(key);
 1822:             var regex_delTimestamp = /^\d+;/;
 1823: 
 1824:             value.replace(regex_delTimestamp, '');
 1825: 
 1826:             var valueArr = value.split(';');
 1827:             var pairs;
 1828:             var elements;
 1829:             for (var i = 0; i < valueArr.length; i++){
 1830:                 pairs = valueArr[i].split(',');
 1831:                 elements = document.getElementsByName(pairs[0]);
 1832: 
 1833:                 for (var j = 0; j < elements.length; j++){
 1834:                     elements[j].style.display = pairs[1];
 1835:                     if (pairs[1] == "none"){
 1836:                         var regex_id = /([_\\d]+)\$/;
 1837:                         regex_id.exec(pairs[0]);
 1838:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
 1839:                     }
 1840:                 }
 1841:             }
 1842:         }
 1843:     }
 1844: 
 1845:     function getTagList () {
 1846: 
 1847:         var stringToSearch = document.lonhomework.innerHTML;
 1848: 
 1849:         var ret = new Array();
 1850:         var regex_findBlock = /(foldblock_.*?)"/g;
 1851:         var tag_list = stringToSearch.match(regex_findBlock);
 1852: 
 1853:         if(tag_list != null){
 1854:             for(var i = 0; i < tag_list.length; i++){
 1855:                 ret.push(tag_list[i].replace(/"/, ''));
 1856:             }
 1857:         }
 1858:         return ret;
 1859:     }
 1860: 
 1861:     function saveScrollPosition (resource) {
 1862:         var tag_list = getTagList();
 1863: 
 1864:         // we dont always want to jump to the first block
 1865:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
 1866:         if(\$(window).scrollTop() > 170){
 1867:             if(tag_list != null){
 1868:                 var result;
 1869:                 for(var i = 0; i < tag_list.length; i++){
 1870:                     if(isElementInViewport(tag_list[i])){
 1871:                         result += tag_list[i]+';';
 1872:                     }
 1873:                 }
 1874:                 sessionStorage.setItem('anchor_'+resource, result);
 1875:             }
 1876:         } else {
 1877:             // we dont need to save zero, just delete the item to leave everything tidy
 1878:             sessionStorage.removeItem('anchor_'+resource);
 1879:         }
 1880:     }
 1881: 
 1882:     function restoreScrollPosition(resource){
 1883: 
 1884:         var elem = sessionStorage.getItem('anchor_'+resource);
 1885:         if(elem != null){
 1886:             var tag_list = elem.split(';');
 1887:             var elem_list;
 1888: 
 1889:             for(var i = 0; i < tag_list.length; i++){
 1890:                 elem_list = document.getElementsByName(tag_list[i]);
 1891: 
 1892:                 if(elem_list.length > 0){
 1893:                     elem = elem_list[0];
 1894:                     break;
 1895:                 }
 1896:             }
 1897:             elem.scrollIntoView();
 1898:         }
 1899:     }
 1900: 
 1901:     function isElementInViewport(el) {
 1902: 
 1903:         // change to last element instead of first
 1904:         var elem = document.getElementsByName(el);
 1905:         var rect = elem[0].getBoundingClientRect();
 1906: 
 1907:         return (
 1908:             rect.top >= 0 &&
 1909:             rect.left >= 0 &&
 1910:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
 1911:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
 1912:         );
 1913:     }
 1914: 
 1915:     function autosize(depth){
 1916:         var cmInst = window['cm'+depth];
 1917:         var fitsizeButton = document.getElementById('fitsize'+depth);
 1918: 
 1919:         // is fixed size, switching to dynamic
 1920:         if (sessionStorage.getItem("autosized_"+depth) == null) {
 1921:             cmInst.setSize("","auto");
 1922:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
 1923:             sessionStorage.setItem("autosized_"+depth, "yes");
 1924: 
 1925:         // is dynamic size, switching to fixed
 1926:         } else {
 1927:             cmInst.setSize("","300px");
 1928:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
 1929:             sessionStorage.removeItem("autosized_"+depth);
 1930:         }
 1931:     }
 1932: 
 1933: 
 1934: 
 1935: // ]]>
 1936: </script>
 1937: COLORFULEDIT
 1938: }
 1939: 
 1940: sub xmleditor_js {
 1941:     return <<XMLEDIT
 1942: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
 1943: <script type="text/javascript">
 1944: // <![CDATA[>
 1945: 
 1946:     function saveScrollPosition (resource) {
 1947: 
 1948:         var scrollPos = \$(window).scrollTop();
 1949:         sessionStorage.setItem(resource,scrollPos);
 1950:     }
 1951: 
 1952:     function restoreScrollPosition(resource){
 1953: 
 1954:         var scrollPos = sessionStorage.getItem(resource);
 1955:         \$(window).scrollTop(scrollPos);
 1956:     }
 1957: 
 1958:     // unless internet explorer
 1959:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
 1960: 
 1961:         \$(document).ready(function() {
 1962:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
 1963:         });
 1964:     }
 1965: 
 1966:     // inserts text at cursor position into codemirror (xml editor only)
 1967:     function insertText(text){
 1968:         cm.focus();
 1969:         var curPos = cm.getCursor();
 1970:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
 1971:     }
 1972: // ]]>
 1973: </script>
 1974: XMLEDIT
 1975: }
 1976: 
 1977: sub insert_folding_button {
 1978:     my $curDepth = $Apache::lonxml::curdepth;
 1979:     my $lastresource = $env{'request.ambiguous'};
 1980: 
 1981:     return "<input type=\"button\" id=\"folding_btn_$curDepth\"
 1982:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
 1983: }
 1984: 
 1985: 
 1986: =pod
 1987: 
 1988: =head1 Excel and CSV file utility routines
 1989: 
 1990: =cut
 1991: 
 1992: ###############################################################
 1993: ###############################################################
 1994: 
 1995: =pod
 1996: 
 1997: =over 4
 1998: 
 1999: =item * &csv_translate($text) 
 2000: 
 2001: Translate $text to allow it to be output as a 'comma separated values' 
 2002: format.
 2003: 
 2004: =cut
 2005: 
 2006: ###############################################################
 2007: ###############################################################
 2008: sub csv_translate {
 2009:     my $text = shift;
 2010:     $text =~ s/\"/\"\"/g;
 2011:     $text =~ s/\n/ /g;
 2012:     return $text;
 2013: }
 2014: 
 2015: ###############################################################
 2016: ###############################################################
 2017: 
 2018: =pod
 2019: 
 2020: =item * &define_excel_formats()
 2021: 
 2022: Define some commonly used Excel cell formats.
 2023: 
 2024: Currently supported formats:
 2025: 
 2026: =over 4
 2027: 
 2028: =item header
 2029: 
 2030: =item bold
 2031: 
 2032: =item h1
 2033: 
 2034: =item h2
 2035: 
 2036: =item h3
 2037: 
 2038: =item h4
 2039: 
 2040: =item i
 2041: 
 2042: =item date
 2043: 
 2044: =back
 2045: 
 2046: Inputs: $workbook
 2047: 
 2048: Returns: $format, a hash reference.
 2049: 
 2050: 
 2051: =cut
 2052: 
 2053: ###############################################################
 2054: ###############################################################
 2055: sub define_excel_formats {
 2056:     my ($workbook) = @_;
 2057:     my $format;
 2058:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 2059:                                                 bottom    => 1,
 2060:                                                 align     => 'center');
 2061:     $format->{'bold'} = $workbook->add_format(bold=>1);
 2062:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 2063:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 2064:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 2065:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 2066:     $format->{'i'}    = $workbook->add_format(italic=>1);
 2067:     $format->{'date'} = $workbook->add_format(num_format=>
 2068:                                             'mm/dd/yyyy hh:mm:ss');
 2069:     return $format;
 2070: }
 2071: 
 2072: ###############################################################
 2073: ###############################################################
 2074: 
 2075: =pod
 2076: 
 2077: =item * &create_workbook()
 2078: 
 2079: Create an Excel worksheet.  If it fails, output message on the
 2080: request object and return undefs.
 2081: 
 2082: Inputs: Apache request object
 2083: 
 2084: Returns (undef) on failure, 
 2085:     Excel worksheet object, scalar with filename, and formats 
 2086:     from &Apache::loncommon::define_excel_formats on success
 2087: 
 2088: =cut
 2089: 
 2090: ###############################################################
 2091: ###############################################################
 2092: sub create_workbook {
 2093:     my ($r) = @_;
 2094:         #
 2095:     # Create the excel spreadsheet
 2096:     my $filename = '/prtspool/'.
 2097:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2098:         time.'_'.rand(1000000000).'.xls';
 2099:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 2100:     if (! defined($workbook)) {
 2101:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 2102:         $r->print(
 2103:             '<p class="LC_error">'
 2104:            .&mt('Problems occurred in creating the new Excel file.')
 2105:            .' '.&mt('This error has been logged.')
 2106:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2107:            .'</p>'
 2108:         );
 2109:         return (undef);
 2110:     }
 2111:     #
 2112:     $workbook->set_tempdir(LONCAPA::tempdir());
 2113:     #
 2114:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 2115:     return ($workbook,$filename,$format);
 2116: }
 2117: 
 2118: ###############################################################
 2119: ###############################################################
 2120: 
 2121: =pod
 2122: 
 2123: =item * &create_text_file()
 2124: 
 2125: Create a file to write to and eventually make available to the user.
 2126: If file creation fails, outputs an error message on the request object and 
 2127: return undefs.
 2128: 
 2129: Inputs: Apache request object, and file suffix
 2130: 
 2131: Returns (undef) on failure, 
 2132:     Filehandle and filename on success.
 2133: 
 2134: =cut
 2135: 
 2136: ###############################################################
 2137: ###############################################################
 2138: sub create_text_file {
 2139:     my ($r,$suffix) = @_;
 2140:     if (! defined($suffix)) { $suffix = 'txt'; };
 2141:     my $fh;
 2142:     my $filename = '/prtspool/'.
 2143:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2144:         time.'_'.rand(1000000000).'.'.$suffix;
 2145:     $fh = Apache::File->new('>/home/httpd'.$filename);
 2146:     if (! defined($fh)) {
 2147:         $r->log_error("Couldn't open $filename for output $!");
 2148:         $r->print(
 2149:             '<p class="LC_error">'
 2150:            .&mt('Problems occurred in creating the output file.')
 2151:            .' '.&mt('This error has been logged.')
 2152:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2153:            .'</p>'
 2154:         );
 2155:     }
 2156:     return ($fh,$filename)
 2157: }
 2158: 
 2159: 
 2160: =pod 
 2161: 
 2162: =back
 2163: 
 2164: =cut
 2165: 
 2166: ###############################################################
 2167: ##        Home server <option> list generating code          ##
 2168: ###############################################################
 2169: 
 2170: # ------------------------------------------
 2171: 
 2172: sub domain_select {
 2173:     my ($name,$value,$multiple)=@_;
 2174:     my %domains=map { 
 2175: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 2176:     } &Apache::lonnet::all_domains();
 2177:     if ($multiple) {
 2178: 	$domains{''}=&mt('Any domain');
 2179: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2180: 	return &multiple_select_form($name,$value,4,\%domains);
 2181:     } else {
 2182: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2183: 	return &select_form($name,$value,\%domains);
 2184:     }
 2185: }
 2186: 
 2187: #-------------------------------------------
 2188: 
 2189: =pod
 2190: 
 2191: =head1 Routines for form select boxes
 2192: 
 2193: =over 4
 2194: 
 2195: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 2196: 
 2197: Returns a string containing a <select> element int multiple mode
 2198: 
 2199: 
 2200: Args:
 2201:   $name - name of the <select> element
 2202:   $value - scalar or array ref of values that should already be selected
 2203:   $size - number of rows long the select element is
 2204:   $hash - the elements should be 'option' => 'shown text'
 2205:           (shown text should already have been &mt())
 2206:   $order - (optional) array ref of the order to show the elements in
 2207: 
 2208: =cut
 2209: 
 2210: #-------------------------------------------
 2211: sub multiple_select_form {
 2212:     my ($name,$value,$size,$hash,$order)=@_;
 2213:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 2214:     my $output='';
 2215:     if (! defined($size)) {
 2216:         $size = 4;
 2217:         if (scalar(keys(%$hash))<4) {
 2218:             $size = scalar(keys(%$hash));
 2219:         }
 2220:     }
 2221:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 2222:     my @order;
 2223:     if (ref($order) eq 'ARRAY')  {
 2224:         @order = @{$order};
 2225:     } else {
 2226:         @order = sort(keys(%$hash));
 2227:     }
 2228:     if (exists($$hash{'select_form_order'})) {
 2229:         @order = @{$$hash{'select_form_order'}};
 2230:     }
 2231:         
 2232:     foreach my $key (@order) {
 2233:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 2234:         $output.='selected="selected" ' if ($selected{$key});
 2235:         $output.='>'.$hash->{$key}."</option>\n";
 2236:     }
 2237:     $output.="</select>\n";
 2238:     return $output;
 2239: }
 2240: 
 2241: #-------------------------------------------
 2242: 
 2243: =pod
 2244: 
 2245: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
 2246: 
 2247: Returns a string containing a <select name='$name' size='1'> form to 
 2248: allow a user to select options from a ref to a hash containing:
 2249: option_name => displayed text. An optional $onchange can include
 2250: a javascript onchange item, e.g., onchange="this.form.submit();".
 2251: An optional arg -- $readonly -- if true will cause the select form
 2252: to be disabled, e.g., for the case where an instructor has a section-
 2253: specific role, and is viewing/modifying parameters.  
 2254: 
 2255: See lonrights.pm for an example invocation and use.
 2256: 
 2257: =cut
 2258: 
 2259: #-------------------------------------------
 2260: sub select_form {
 2261:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
 2262:     return unless (ref($hashref) eq 'HASH');
 2263:     if ($onchange) {
 2264:         $onchange = ' onchange="'.$onchange.'"';
 2265:     }
 2266:     my $disabled;
 2267:     if ($readonly) {
 2268:         $disabled = ' disabled="disabled"';
 2269:     }
 2270:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2271:     my @keys;
 2272:     if (exists($hashref->{'select_form_order'})) {
 2273: 	@keys=@{$hashref->{'select_form_order'}};
 2274:     } else {
 2275: 	@keys=sort(keys(%{$hashref}));
 2276:     }
 2277:     foreach my $key (@keys) {
 2278:         $selectform.=
 2279: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2280:             ($key eq $def ? 'selected="selected" ' : '').
 2281:                 ">".$hashref->{$key}."</option>\n";
 2282:     }
 2283:     $selectform.="</select>";
 2284:     return $selectform;
 2285: }
 2286: 
 2287: # For display filters
 2288: 
 2289: sub display_filter {
 2290:     my ($context) = @_;
 2291:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2292:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2293:     my $phraseinput = 'hidden';
 2294:     my $includeinput = 'hidden';
 2295:     my ($checked,$includetypestext);
 2296:     if ($env{'form.displayfilter'} eq 'containing') {
 2297:         $phraseinput = 'text'; 
 2298:         if ($context eq 'parmslog') {
 2299:             $includeinput = 'checkbox';
 2300:             if ($env{'form.includetypes'}) {
 2301:                 $checked = ' checked="checked"';
 2302:             }
 2303:             $includetypestext = &mt('Include parameter types');
 2304:         }
 2305:     } else {
 2306:         $includetypestext = '&nbsp;';
 2307:     }
 2308:     my ($additional,$secondid,$thirdid);
 2309:     if ($context eq 'parmslog') {
 2310:         $additional = 
 2311:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2312:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2313:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2314:             '</label>';
 2315:         $secondid = 'includetypes';
 2316:         $thirdid = 'includetypestext';
 2317:     }
 2318:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2319:                                                     '$secondid','$thirdid')";
 2320:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2321: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 2322: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2323: 	   '</label></span> <span class="LC_nobreak">'.
 2324:            &mt('Filter: [_1]',
 2325: 	   &select_form($env{'form.displayfilter'},
 2326: 			'displayfilter',
 2327: 			{'currentfolder' => 'Current folder/page',
 2328: 			 'containing' => 'Containing phrase',
 2329: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2330: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2331:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2332:                          '" />'.$additional;
 2333: }
 2334: 
 2335: sub display_filter_js {
 2336:     my $includetext = &mt('Include parameter types');
 2337:     return <<"ENDJS";
 2338:   
 2339: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2340:     var firstType = 'hidden';
 2341:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2342:         firstType = 'text';
 2343:     }
 2344:     firstObject = document.getElementById(firstid);
 2345:     if (typeof(firstObject) == 'object') {
 2346:         if (firstObject.type != firstType) {
 2347:             changeInputType(firstObject,firstType);
 2348:         }
 2349:     }
 2350:     if (context == 'parmslog') {
 2351:         var secondType = 'hidden';
 2352:         if (firstType == 'text') {
 2353:             secondType = 'checkbox';
 2354:         }
 2355:         secondObject = document.getElementById(secondid);  
 2356:         if (typeof(secondObject) == 'object') {
 2357:             if (secondObject.type != secondType) {
 2358:                 changeInputType(secondObject,secondType);
 2359:             }
 2360:         }
 2361:         var textItem = document.getElementById(thirdid);
 2362:         var currtext = textItem.innerHTML;
 2363:         var newtext;
 2364:         if (firstType == 'text') {
 2365:             newtext = '$includetext';
 2366:         } else {
 2367:             newtext = '&nbsp;';
 2368:         }
 2369:         if (currtext != newtext) {
 2370:             textItem.innerHTML = newtext;
 2371:         }
 2372:     }
 2373:     return;
 2374: }
 2375: 
 2376: function changeInputType(oldObject,newType) {
 2377:     var newObject = document.createElement('input');
 2378:     newObject.type = newType;
 2379:     if (oldObject.size) {
 2380:         newObject.size = oldObject.size;
 2381:     }
 2382:     if (oldObject.value) {
 2383:         newObject.value = oldObject.value;
 2384:     }
 2385:     if (oldObject.name) {
 2386:         newObject.name = oldObject.name;
 2387:     }
 2388:     if (oldObject.id) {
 2389:         newObject.id = oldObject.id;
 2390:     }
 2391:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2392:     return;
 2393: }
 2394: 
 2395: ENDJS
 2396: }
 2397: 
 2398: sub gradeleveldescription {
 2399:     my $gradelevel=shift;
 2400:     my %gradelevels=(0 => 'Not specified',
 2401: 		     1 => 'Grade 1',
 2402: 		     2 => 'Grade 2',
 2403: 		     3 => 'Grade 3',
 2404: 		     4 => 'Grade 4',
 2405: 		     5 => 'Grade 5',
 2406: 		     6 => 'Grade 6',
 2407: 		     7 => 'Grade 7',
 2408: 		     8 => 'Grade 8',
 2409: 		     9 => 'Grade 9',
 2410: 		     10 => 'Grade 10',
 2411: 		     11 => 'Grade 11',
 2412: 		     12 => 'Grade 12',
 2413: 		     13 => 'Grade 13',
 2414: 		     14 => '100 Level',
 2415: 		     15 => '200 Level',
 2416: 		     16 => '300 Level',
 2417: 		     17 => '400 Level',
 2418: 		     18 => 'Graduate Level');
 2419:     return &mt($gradelevels{$gradelevel});
 2420: }
 2421: 
 2422: sub select_level_form {
 2423:     my ($deflevel,$name)=@_;
 2424:     unless ($deflevel) { $deflevel=0; }
 2425:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2426:     for (my $i=0; $i<=18; $i++) {
 2427:         $selectform.="<option value=\"$i\" ".
 2428:             ($i==$deflevel ? 'selected="selected" ' : '').
 2429:                 ">".&gradeleveldescription($i)."</option>\n";
 2430:     }
 2431:     $selectform.="</select>";
 2432:     return $selectform;
 2433: }
 2434: 
 2435: #-------------------------------------------
 2436: 
 2437: =pod
 2438: 
 2439: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
 2440: 
 2441: Returns a string containing a <select name='$name' size='1'> form to 
 2442: allow a user to select the domain to preform an operation in.  
 2443: See loncreateuser.pm for an example invocation and use.
 2444: 
 2445: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2446: selected");
 2447: 
 2448: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2449: 
 2450: 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.
 2451: 
 2452: The optional $incdoms is a reference to an array of domains which will be the only available options.
 2453: 
 2454: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
 2455: 
 2456: The optional $disabled argument, if true, adds the disabled attribute to the select tag. 
 2457: 
 2458: =cut
 2459: 
 2460: #-------------------------------------------
 2461: sub select_dom_form {
 2462:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
 2463:     if ($onchange) {
 2464:         $onchange = ' onchange="'.$onchange.'"';
 2465:     }
 2466:     if ($disabled) {
 2467:         $disabled = ' disabled="disabled"';
 2468:     }
 2469:     my (@domains,%exclude);
 2470:     if (ref($incdoms) eq 'ARRAY') {
 2471:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2472:     } else {
 2473:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2474:     }
 2475:     if ($includeempty) { @domains=('',@domains); }
 2476:     if (ref($excdoms) eq 'ARRAY') {
 2477:         map { $exclude{$_} = 1; } @{$excdoms};
 2478:     }
 2479:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2480:     foreach my $dom (@domains) {
 2481:         next if ($exclude{$dom});
 2482:         $selectdomain.="<option value=\"$dom\" ".
 2483:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2484:         if ($showdomdesc) {
 2485:             if ($dom ne '') {
 2486:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2487:                 if ($domdesc ne '') {
 2488:                     $selectdomain .= ' ('.$domdesc.')';
 2489:                 }
 2490:             } 
 2491:         }
 2492:         $selectdomain .= "</option>\n";
 2493:     }
 2494:     $selectdomain.="</select>";
 2495:     return $selectdomain;
 2496: }
 2497: 
 2498: #-------------------------------------------
 2499: 
 2500: =pod
 2501: 
 2502: =item * &home_server_form_item($domain,$name,$defaultflag)
 2503: 
 2504: input: 4 arguments (two required, two optional) - 
 2505:     $domain - domain of new user
 2506:     $name - name of form element
 2507:     $default - Value of 'default' causes a default item to be first 
 2508:                             option, and selected by default. 
 2509:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2510:                             if 1 server found, or default, if 0 found.
 2511: output: returns 2 items: 
 2512: (a) form element which contains either:
 2513:    (i) <select name="$name">
 2514:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2515:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2516:        </select>
 2517:        form item if there are multiple library servers in $domain, or
 2518:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2519:        if there is only one library server in $domain.
 2520: 
 2521: (b) number of library servers found.
 2522: 
 2523: See loncreateuser.pm for example of use.
 2524: 
 2525: =cut
 2526: 
 2527: #-------------------------------------------
 2528: sub home_server_form_item {
 2529:     my ($domain,$name,$default,$hide) = @_;
 2530:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2531:     my $result;
 2532:     my $numlib = keys(%servers);
 2533:     if ($numlib > 1) {
 2534:         $result .= '<select name="'.$name.'" />'."\n";
 2535:         if ($default) {
 2536:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2537:                        '</option>'."\n";
 2538:         }
 2539:         foreach my $hostid (sort(keys(%servers))) {
 2540:             $result.= '<option value="'.$hostid.'">'.
 2541: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2542:         }
 2543:         $result .= '</select>'."\n";
 2544:     } elsif ($numlib == 1) {
 2545:         my $hostid;
 2546:         foreach my $item (keys(%servers)) {
 2547:             $hostid = $item;
 2548:         }
 2549:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2550:                    $hostid.'" />';
 2551:                    if (!$hide) {
 2552:                        $result .= $hostid.' '.$servers{$hostid};
 2553:                    }
 2554:                    $result .= "\n";
 2555:     } elsif ($default) {
 2556:         $result .= '<input type="hidden" name="'.$name.
 2557:                    '" value="default" />';
 2558:                    if (!$hide) {
 2559:                        $result .= &mt('default');
 2560:                    }
 2561:                    $result .= "\n";
 2562:     }
 2563:     return ($result,$numlib);
 2564: }
 2565: 
 2566: =pod
 2567: 
 2568: =back 
 2569: 
 2570: =cut
 2571: 
 2572: ###############################################################
 2573: ##                  Decoding User Agent                      ##
 2574: ###############################################################
 2575: 
 2576: =pod
 2577: 
 2578: =head1 Decoding the User Agent
 2579: 
 2580: =over 4
 2581: 
 2582: =item * &decode_user_agent()
 2583: 
 2584: Inputs: $r
 2585: 
 2586: Outputs:
 2587: 
 2588: =over 4
 2589: 
 2590: =item * $httpbrowser
 2591: 
 2592: =item * $clientbrowser
 2593: 
 2594: =item * $clientversion
 2595: 
 2596: =item * $clientmathml
 2597: 
 2598: =item * $clientunicode
 2599: 
 2600: =item * $clientos
 2601: 
 2602: =item * $clientmobile
 2603: 
 2604: =item * $clientinfo
 2605: 
 2606: =item * $clientosversion
 2607: 
 2608: =back
 2609: 
 2610: =back 
 2611: 
 2612: =cut
 2613: 
 2614: ###############################################################
 2615: ###############################################################
 2616: sub decode_user_agent {
 2617:     my ($r)=@_;
 2618:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2619:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2620:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2621:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2622:     my $clientbrowser='unknown';
 2623:     my $clientversion='0';
 2624:     my $clientmathml='';
 2625:     my $clientunicode='0';
 2626:     my $clientmobile=0;
 2627:     my $clientosversion='';
 2628:     for (my $i=0;$i<=$#browsertype;$i++) {
 2629:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
 2630: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2631: 	    $clientbrowser=$bname;
 2632:             $httpbrowser=~/$vreg/i;
 2633: 	    $clientversion=$1;
 2634:             $clientmathml=($clientversion>=$minv);
 2635:             $clientunicode=($clientversion>=$univ);
 2636: 	}
 2637:     }
 2638:     my $clientos='unknown';
 2639:     my $clientinfo;
 2640:     if (($httpbrowser=~/linux/i) ||
 2641:         ($httpbrowser=~/unix/i) ||
 2642:         ($httpbrowser=~/ux/i) ||
 2643:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2644:     if (($httpbrowser=~/vax/i) ||
 2645:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2646:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2647:     if (($httpbrowser=~/mac/i) ||
 2648:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2649:     if ($httpbrowser=~/win/i) {
 2650:         $clientos='win';
 2651:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
 2652:             $clientosversion = $1;
 2653:         }
 2654:     }
 2655:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2656:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 2657:         $clientmobile=lc($1);
 2658:     }
 2659:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 2660:         $clientinfo = 'firefox-'.$1;
 2661:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 2662:         $clientinfo = 'chromeframe-'.$1;
 2663:     }
 2664:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2665:             $clientunicode,$clientos,$clientmobile,$clientinfo,
 2666:             $clientosversion);
 2667: }
 2668: 
 2669: ###############################################################
 2670: ##    Authentication changing form generation subroutines    ##
 2671: ###############################################################
 2672: ##
 2673: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2674: ## hash, and have reasonable default values.
 2675: ##
 2676: ##    formname = the name given in the <form> tag.
 2677: #-------------------------------------------
 2678: 
 2679: =pod
 2680: 
 2681: =head1 Authentication Routines
 2682: 
 2683: =over 4
 2684: 
 2685: =item * &authform_xxxxxx()
 2686: 
 2687: The authform_xxxxxx subroutines provide javascript and html forms which 
 2688: handle some of the conveniences required for authentication forms.  
 2689: This is not an optimal method, but it works.  
 2690: 
 2691: =over 4
 2692: 
 2693: =item * authform_header
 2694: 
 2695: =item * authform_authorwarning
 2696: 
 2697: =item * authform_nochange
 2698: 
 2699: =item * authform_kerberos
 2700: 
 2701: =item * authform_internal
 2702: 
 2703: =item * authform_filesystem
 2704: 
 2705: =back
 2706: 
 2707: See loncreateuser.pm for invocation and use examples.
 2708: 
 2709: =cut
 2710: 
 2711: #-------------------------------------------
 2712: sub authform_header{  
 2713:     my %in = (
 2714:         formname => 'cu',
 2715:         kerb_def_dom => '',
 2716:         @_,
 2717:     );
 2718:     $in{'formname'} = 'document.' . $in{'formname'};
 2719:     my $result='';
 2720: 
 2721: #---------------------------------------------- Code for upper case translation
 2722:     my $Javascript_toUpperCase;
 2723:     unless ($in{kerb_def_dom}) {
 2724:         $Javascript_toUpperCase =<<"END";
 2725:         switch (choice) {
 2726:            case 'krb': currentform.elements[choicearg].value =
 2727:                currentform.elements[choicearg].value.toUpperCase();
 2728:                break;
 2729:            default:
 2730:         }
 2731: END
 2732:     } else {
 2733:         $Javascript_toUpperCase = "";
 2734:     }
 2735: 
 2736:     my $radioval = "'nochange'";
 2737:     if (defined($in{'curr_authtype'})) {
 2738:         if ($in{'curr_authtype'} ne '') {
 2739:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2740:         }
 2741:     }
 2742:     my $argfield = 'null';
 2743:     if (defined($in{'mode'})) {
 2744:         if ($in{'mode'} eq 'modifycourse')  {
 2745:             if (defined($in{'curr_autharg'})) {
 2746:                 if ($in{'curr_autharg'} ne '') {
 2747:                     $argfield = "'$in{'curr_autharg'}'";
 2748:                 }
 2749:             }
 2750:         }
 2751:     }
 2752: 
 2753:     $result.=<<"END";
 2754: var current = new Object();
 2755: current.radiovalue = $radioval;
 2756: current.argfield = $argfield;
 2757: 
 2758: function changed_radio(choice,currentform) {
 2759:     var choicearg = choice + 'arg';
 2760:     // If a radio button in changed, we need to change the argfield
 2761:     if (current.radiovalue != choice) {
 2762:         current.radiovalue = choice;
 2763:         if (current.argfield != null) {
 2764:             currentform.elements[current.argfield].value = '';
 2765:         }
 2766:         if (choice == 'nochange') {
 2767:             current.argfield = null;
 2768:         } else {
 2769:             current.argfield = choicearg;
 2770:             switch(choice) {
 2771:                 case 'krb': 
 2772:                     currentform.elements[current.argfield].value = 
 2773:                         "$in{'kerb_def_dom'}";
 2774:                 break;
 2775:               default:
 2776:                 break;
 2777:             }
 2778:         }
 2779:     }
 2780:     return;
 2781: }
 2782: 
 2783: function changed_text(choice,currentform) {
 2784:     var choicearg = choice + 'arg';
 2785:     if (currentform.elements[choicearg].value !='') {
 2786:         $Javascript_toUpperCase
 2787:         // clear old field
 2788:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2789:             currentform.elements[current.argfield].value = '';
 2790:         }
 2791:         current.argfield = choicearg;
 2792:     }
 2793:     set_auth_radio_buttons(choice,currentform);
 2794:     return;
 2795: }
 2796: 
 2797: function set_auth_radio_buttons(newvalue,currentform) {
 2798:     var numauthchoices = currentform.login.length;
 2799:     if (typeof numauthchoices  == "undefined") {
 2800:         return;
 2801:     } 
 2802:     var i=0;
 2803:     while (i < numauthchoices) {
 2804:         if (currentform.login[i].value == newvalue) { break; }
 2805:         i++;
 2806:     }
 2807:     if (i == numauthchoices) {
 2808:         return;
 2809:     }
 2810:     current.radiovalue = newvalue;
 2811:     currentform.login[i].checked = true;
 2812:     return;
 2813: }
 2814: END
 2815:     return $result;
 2816: }
 2817: 
 2818: sub authform_authorwarning {
 2819:     my $result='';
 2820:     $result='<i>'.
 2821:         &mt('As a general rule, only authors or co-authors should be '.
 2822:             'filesystem authenticated '.
 2823:             '(which allows access to the server filesystem).')."</i>\n";
 2824:     return $result;
 2825: }
 2826: 
 2827: sub authform_nochange {
 2828:     my %in = (
 2829:               formname => 'document.cu',
 2830:               kerb_def_dom => 'MSU.EDU',
 2831:               @_,
 2832:           );
 2833:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
 2834:     my $result;
 2835:     if (!$authnum) {
 2836:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 2837:     } else {
 2838:         $result = '<label>'.&mt('[_1] Do not change login data',
 2839:                   '<input type="radio" name="login" value="nochange" '.
 2840:                   'checked="checked" onclick="'.
 2841:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2842: 	    '</label>';
 2843:     }
 2844:     return $result;
 2845: }
 2846: 
 2847: sub authform_kerberos {
 2848:     my %in = (
 2849:               formname => 'document.cu',
 2850:               kerb_def_dom => 'MSU.EDU',
 2851:               kerb_def_auth => 'krb4',
 2852:               @_,
 2853:               );
 2854:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2855:         $autharg,$jscall,$disabled);
 2856:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2857:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2858:        $check5 = ' checked="checked"';
 2859:     } else {
 2860:        $check4 = ' checked="checked"';
 2861:     }
 2862:     if ($in{'readonly'}) {
 2863:         $disabled = ' disabled="disabled"';
 2864:     }
 2865:     $krbarg = $in{'kerb_def_dom'};
 2866:     if (defined($in{'curr_authtype'})) {
 2867:         if ($in{'curr_authtype'} eq 'krb') {
 2868:             $krbcheck = ' checked="checked"';
 2869:             if (defined($in{'mode'})) {
 2870:                 if ($in{'mode'} eq 'modifyuser') {
 2871:                     $krbcheck = '';
 2872:                 }
 2873:             }
 2874:             if (defined($in{'curr_kerb_ver'})) {
 2875:                 if ($in{'curr_krb_ver'} eq '5') {
 2876:                     $check5 = ' checked="checked"';
 2877:                     $check4 = '';
 2878:                 } else {
 2879:                     $check4 = ' checked="checked"';
 2880:                     $check5 = '';
 2881:                 }
 2882:             }
 2883:             if (defined($in{'curr_autharg'})) {
 2884:                 $krbarg = $in{'curr_autharg'};
 2885:             }
 2886:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2887:                 if (defined($in{'curr_autharg'})) {
 2888:                     $result = 
 2889:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2890:         $in{'curr_autharg'},$krbver);
 2891:                 } else {
 2892:                     $result =
 2893:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2894:                 }
 2895:                 return $result; 
 2896:             }
 2897:         }
 2898:     } else {
 2899:         if ($authnum == 1) {
 2900:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2901:         }
 2902:     }
 2903:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2904:         return;
 2905:     } elsif ($authtype eq '') {
 2906:         if (defined($in{'mode'})) {
 2907:             if ($in{'mode'} eq 'modifycourse') {
 2908:                 if ($authnum == 1) {
 2909:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
 2910:                 }
 2911:             }
 2912:         }
 2913:     }
 2914:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2915:     if ($authtype eq '') {
 2916:         $authtype = '<input type="radio" name="login" value="krb" '.
 2917:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2918:                     $krbcheck.$disabled.' />';
 2919:     }
 2920:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2921:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 2922:          $in{'curr_authtype'} eq 'krb5') ||
 2923:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 2924:          $in{'curr_authtype'} eq 'krb4')) {
 2925:         $result .= &mt
 2926:         ('[_1] Kerberos authenticated with domain [_2] '.
 2927:          '[_3] Version 4 [_4] Version 5 [_5]',
 2928:          '<label>'.$authtype,
 2929:          '</label><input type="text" size="10" name="krbarg" '.
 2930:              'value="'.$krbarg.'" '.
 2931:              'onchange="'.$jscall.'"'.$disabled.' />',
 2932:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
 2933:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
 2934: 	 '</label>');
 2935:     } elsif ($can_assign{'krb4'}) {
 2936:         $result .= &mt
 2937:         ('[_1] Kerberos authenticated with domain [_2] '.
 2938:          '[_3] Version 4 [_4]',
 2939:          '<label>'.$authtype,
 2940:          '</label><input type="text" size="10" name="krbarg" '.
 2941:              'value="'.$krbarg.'" '.
 2942:              'onchange="'.$jscall.'"'.$disabled.' />',
 2943:          '<label><input type="hidden" name="krbver" value="4" />',
 2944:          '</label>');
 2945:     } elsif ($can_assign{'krb5'}) {
 2946:         $result .= &mt
 2947:         ('[_1] Kerberos authenticated with domain [_2] '.
 2948:          '[_3] Version 5 [_4]',
 2949:          '<label>'.$authtype,
 2950:          '</label><input type="text" size="10" name="krbarg" '.
 2951:              'value="'.$krbarg.'" '.
 2952:              'onchange="'.$jscall.'"'.$disabled.' />',
 2953:          '<label><input type="hidden" name="krbver" value="5" />',
 2954:          '</label>');
 2955:     }
 2956:     return $result;
 2957: }
 2958: 
 2959: sub authform_internal {
 2960:     my %in = (
 2961:                 formname => 'document.cu',
 2962:                 kerb_def_dom => 'MSU.EDU',
 2963:                 @_,
 2964:                 );
 2965:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
 2966:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2967:     if ($in{'readonly'}) {
 2968:         $disabled = ' disabled="disabled"';
 2969:     }
 2970:     if (defined($in{'curr_authtype'})) {
 2971:         if ($in{'curr_authtype'} eq 'int') {
 2972:             if ($can_assign{'int'}) {
 2973:                 $intcheck = 'checked="checked" ';
 2974:                 if (defined($in{'mode'})) {
 2975:                     if ($in{'mode'} eq 'modifyuser') {
 2976:                         $intcheck = '';
 2977:                     }
 2978:                 }
 2979:                 if (defined($in{'curr_autharg'})) {
 2980:                     $intarg = $in{'curr_autharg'};
 2981:                 }
 2982:             } else {
 2983:                 $result = &mt('Currently internally authenticated.');
 2984:                 return $result;
 2985:             }
 2986:         }
 2987:     } else {
 2988:         if ($authnum == 1) {
 2989:             $authtype = '<input type="hidden" name="login" value="int" />';
 2990:         }
 2991:     }
 2992:     if (!$can_assign{'int'}) {
 2993:         return;
 2994:     } elsif ($authtype eq '') {
 2995:         if (defined($in{'mode'})) {
 2996:             if ($in{'mode'} eq 'modifycourse') {
 2997:                 if ($authnum == 1) {
 2998:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
 2999:                 }
 3000:             }
 3001:         }
 3002:     }
 3003:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 3004:     if ($authtype eq '') {
 3005:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 3006:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
 3007:     }
 3008:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 3009:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3010:     $result = &mt
 3011:         ('[_1] Internally authenticated (with initial password [_2])',
 3012:          '<label>'.$authtype,'</label>'.$autharg);
 3013:     $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>';
 3014:     return $result;
 3015: }
 3016: 
 3017: sub authform_local {
 3018:     my %in = (
 3019:               formname => 'document.cu',
 3020:               kerb_def_dom => 'MSU.EDU',
 3021:               @_,
 3022:               );
 3023:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
 3024:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3025:     if ($in{'readonly'}) {
 3026:         $disabled = ' disabled="disabled"';
 3027:     }
 3028:     if (defined($in{'curr_authtype'})) {
 3029:         if ($in{'curr_authtype'} eq 'loc') {
 3030:             if ($can_assign{'loc'}) {
 3031:                 $loccheck = 'checked="checked" ';
 3032:                 if (defined($in{'mode'})) {
 3033:                     if ($in{'mode'} eq 'modifyuser') {
 3034:                         $loccheck = '';
 3035:                     }
 3036:                 }
 3037:                 if (defined($in{'curr_autharg'})) {
 3038:                     $locarg = $in{'curr_autharg'};
 3039:                 }
 3040:             } else {
 3041:                 $result = &mt('Currently using local (institutional) authentication.');
 3042:                 return $result;
 3043:             }
 3044:         }
 3045:     } else {
 3046:         if ($authnum == 1) {
 3047:             $authtype = '<input type="hidden" name="login" value="loc" />';
 3048:         }
 3049:     }
 3050:     if (!$can_assign{'loc'}) {
 3051:         return;
 3052:     } elsif ($authtype eq '') {
 3053:         if (defined($in{'mode'})) {
 3054:             if ($in{'mode'} eq 'modifycourse') {
 3055:                 if ($authnum == 1) {
 3056:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
 3057:                 }
 3058:             }
 3059:         }
 3060:     }
 3061:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 3062:     if ($authtype eq '') {
 3063:         $authtype = '<input type="radio" name="login" value="loc" '.
 3064:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 3065:                     $jscall.'"'.$disabled.' />';
 3066:     }
 3067:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 3068:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3069:     $result = &mt('[_1] Local Authentication with argument [_2]',
 3070:                   '<label>'.$authtype,'</label>'.$autharg);
 3071:     return $result;
 3072: }
 3073: 
 3074: sub authform_filesystem {
 3075:     my %in = (
 3076:               formname => 'document.cu',
 3077:               kerb_def_dom => 'MSU.EDU',
 3078:               @_,
 3079:               );
 3080:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
 3081:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3082:     if ($in{'readonly'}) {
 3083:         $disabled = ' disabled="disabled"';
 3084:     }
 3085:     if (defined($in{'curr_authtype'})) {
 3086:         if ($in{'curr_authtype'} eq 'fsys') {
 3087:             if ($can_assign{'fsys'}) {
 3088:                 $fsyscheck = 'checked="checked" ';
 3089:                 if (defined($in{'mode'})) {
 3090:                     if ($in{'mode'} eq 'modifyuser') {
 3091:                         $fsyscheck = '';
 3092:                     }
 3093:                 }
 3094:             } else {
 3095:                 $result = &mt('Currently Filesystem Authenticated.');
 3096:                 return $result;
 3097:             }           
 3098:         }
 3099:     } else {
 3100:         if ($authnum == 1) {
 3101:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 3102:         }
 3103:     }
 3104:     if (!$can_assign{'fsys'}) {
 3105:         return;
 3106:     } elsif ($authtype eq '') {
 3107:         if (defined($in{'mode'})) {
 3108:             if ($in{'mode'} eq 'modifycourse') {
 3109:                 if ($authnum == 1) {
 3110:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
 3111:                 }
 3112:             }
 3113:         }
 3114:     }
 3115:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 3116:     if ($authtype eq '') {
 3117:         $authtype = '<input type="radio" name="login" value="fsys" '.
 3118:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 3119:                     $jscall.'"'.$disabled.' />';
 3120:     }
 3121:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 3122:                ' onchange="'.$jscall.'"'.$disabled.' />';
 3123:     $result = &mt
 3124:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 3125:          '<label><input type="radio" name="login" value="fsys" '.
 3126:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />',
 3127:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 3128:                   'onchange="'.$jscall.'"'.$disabled.' />');
 3129:     return $result;
 3130: }
 3131: 
 3132: sub get_assignable_auth {
 3133:     my ($dom) = @_;
 3134:     if ($dom eq '') {
 3135:         $dom = $env{'request.role.domain'};
 3136:     }
 3137:     my %can_assign = (
 3138:                           krb4 => 1,
 3139:                           krb5 => 1,
 3140:                           int  => 1,
 3141:                           loc  => 1,
 3142:                      );
 3143:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 3144:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 3145:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 3146:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 3147:             my $context;
 3148:             if ($env{'request.role'} =~ /^au/) {
 3149:                 $context = 'author';
 3150:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
 3151:                 $context = 'domain';
 3152:             } elsif ($env{'request.course.id'}) {
 3153:                 $context = 'course';
 3154:             }
 3155:             if ($context) {
 3156:                 if (ref($authhash->{$context}) eq 'HASH') {
 3157:                    %can_assign = %{$authhash->{$context}}; 
 3158:                 }
 3159:             }
 3160:         }
 3161:     }
 3162:     my $authnum = 0;
 3163:     foreach my $key (keys(%can_assign)) {
 3164:         if ($can_assign{$key}) {
 3165:             $authnum ++;
 3166:         }
 3167:     }
 3168:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 3169:         $authnum --;
 3170:     }
 3171:     return ($authnum,%can_assign);
 3172: }
 3173: 
 3174: sub check_passwd_rules {
 3175:     my ($domain,$plainpass) = @_;
 3176:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
 3177:     my ($min,$max,@chars,@brokerule,$warning);
 3178:     $min = $Apache::lonnet::passwdmin;
 3179:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
 3180:         if ($passwdconf{'min'} =~ /^\d+$/) {
 3181:             if ($passwdconf{'min'} > $min) {
 3182:                 $min = $passwdconf{'min'};
 3183:             }
 3184:         }
 3185:         if ($passwdconf{'max'} =~ /^\d+$/) {
 3186:             $max = $passwdconf{'max'};
 3187:         }
 3188:         @chars = @{$passwdconf{'chars'}};
 3189:     }
 3190:     if (($min) && (length($plainpass) < $min)) {
 3191:         push(@brokerule,'min');
 3192:     }
 3193:     if (($max) && (length($plainpass) > $max)) {
 3194:         push(@brokerule,'max');
 3195:     }
 3196:     if (@chars) {
 3197:         my %rules;
 3198:         map { $rules{$_} = 1; } @chars;
 3199:         if ($rules{'uc'}) {
 3200:             unless ($plainpass =~ /[A-Z]/) {
 3201:                 push(@brokerule,'uc');
 3202:             }
 3203:         }
 3204:         if ($rules{'lc'}) {
 3205:             unless ($plainpass =~ /[a-z]/) {
 3206:                 push(@brokerule,'lc');
 3207:             }
 3208:         }
 3209:         if ($rules{'num'}) {
 3210:             unless ($plainpass =~ /\d/) {
 3211:                 push(@brokerule,'num');
 3212:             }
 3213:         }
 3214:         if ($rules{'spec'}) {
 3215:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
 3216:                 push(@brokerule,'spec');
 3217:             }
 3218:         }
 3219:     }
 3220:     if (@brokerule) {
 3221:         my %rulenames = &Apache::lonlocal::texthash(
 3222:             uc   => 'At least one upper case letter',
 3223:             lc   => 'At least one lower case letter',
 3224:             num  => 'At least one number',
 3225:             spec => 'At least one non-alphanumeric',
 3226:         );
 3227:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
 3228:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
 3229:         $rulenames{'num'} .= ': 0123456789';
 3230:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
 3231:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
 3232:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
 3233:         $warning = &mt('Password did not satisfy the following:').'<ul>';
 3234:         foreach my $rule ('min','max','uc','ls','num','spec') {
 3235:             if (grep(/^$rule$/,@brokerule)) {
 3236:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
 3237:             }
 3238:         }
 3239:         $warning .= '</ul>';
 3240:     }
 3241:     if (wantarray) {
 3242:         return @brokerule;
 3243:     }
 3244:     return $warning;
 3245: }
 3246: 
 3247: ###############################################################
 3248: ##    Get Kerberos Defaults for Domain                 ##
 3249: ###############################################################
 3250: ##
 3251: ## Returns default kerberos version and an associated argument
 3252: ## as listed in file domain.tab. If not listed, provides
 3253: ## appropriate default domain and kerberos version.
 3254: ##
 3255: #-------------------------------------------
 3256: 
 3257: =pod
 3258: 
 3259: =item * &get_kerberos_defaults()
 3260: 
 3261: get_kerberos_defaults($target_domain) returns the default kerberos
 3262: version and domain. If not found, it defaults to version 4 and the 
 3263: domain of the server.
 3264: 
 3265: =over 4
 3266: 
 3267: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 3268: 
 3269: =back
 3270: 
 3271: =back
 3272: 
 3273: =cut
 3274: 
 3275: #-------------------------------------------
 3276: sub get_kerberos_defaults {
 3277:     my $domain=shift;
 3278:     my ($krbdef,$krbdefdom);
 3279:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 3280:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 3281:         $krbdef = $domdefaults{'auth_def'};
 3282:         $krbdefdom = $domdefaults{'auth_arg_def'};
 3283:     } else {
 3284:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 3285:         my $krbdefdom=$1;
 3286:         $krbdefdom=~tr/a-z/A-Z/;
 3287:         $krbdef = "krb4";
 3288:     }
 3289:     return ($krbdef,$krbdefdom);
 3290: }
 3291: 
 3292: 
 3293: ###############################################################
 3294: ##                Thesaurus Functions                        ##
 3295: ###############################################################
 3296: 
 3297: =pod
 3298: 
 3299: =head1 Thesaurus Functions
 3300: 
 3301: =over 4
 3302: 
 3303: =item * &initialize_keywords()
 3304: 
 3305: Initializes the package variable %Keywords if it is empty.  Uses the
 3306: package variable $thesaurus_db_file.
 3307: 
 3308: =cut
 3309: 
 3310: ###################################################
 3311: 
 3312: sub initialize_keywords {
 3313:     return 1 if (scalar keys(%Keywords));
 3314:     # If we are here, %Keywords is empty, so fill it up
 3315:     #   Make sure the file we need exists...
 3316:     if (! -e $thesaurus_db_file) {
 3317:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 3318:                                  " failed because it does not exist");
 3319:         return 0;
 3320:     }
 3321:     #   Set up the hash as a database
 3322:     my %thesaurus_db;
 3323:     if (! tie(%thesaurus_db,'GDBM_File',
 3324:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3325:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 3326:                                  $thesaurus_db_file);
 3327:         return 0;
 3328:     } 
 3329:     #  Get the average number of appearances of a word.
 3330:     my $avecount = $thesaurus_db{'average.count'};
 3331:     #  Put keywords (those that appear > average) into %Keywords
 3332:     while (my ($word,$data)=each (%thesaurus_db)) {
 3333:         my ($count,undef) = split /:/,$data;
 3334:         $Keywords{$word}++ if ($count > $avecount);
 3335:     }
 3336:     untie %thesaurus_db;
 3337:     # Remove special values from %Keywords.
 3338:     foreach my $value ('total.count','average.count') {
 3339:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 3340:   }
 3341:     return 1;
 3342: }
 3343: 
 3344: ###################################################
 3345: 
 3346: =pod
 3347: 
 3348: =item * &keyword($word)
 3349: 
 3350: Returns true if $word is a keyword.  A keyword is a word that appears more 
 3351: than the average number of times in the thesaurus database.  Calls 
 3352: &initialize_keywords
 3353: 
 3354: =cut
 3355: 
 3356: ###################################################
 3357: 
 3358: sub keyword {
 3359:     return if (!&initialize_keywords());
 3360:     my $word=lc(shift());
 3361:     $word=~s/\W//g;
 3362:     return exists($Keywords{$word});
 3363: }
 3364: 
 3365: ###############################################################
 3366: 
 3367: =pod 
 3368: 
 3369: =item * &get_related_words()
 3370: 
 3371: Look up a word in the thesaurus.  Takes a scalar argument and returns
 3372: an array of words.  If the keyword is not in the thesaurus, an empty array
 3373: will be returned.  The order of the words returned is determined by the
 3374: database which holds them.
 3375: 
 3376: Uses global $thesaurus_db_file.
 3377: 
 3378: 
 3379: =cut
 3380: 
 3381: ###############################################################
 3382: sub get_related_words {
 3383:     my $keyword = shift;
 3384:     my %thesaurus_db;
 3385:     if (! -e $thesaurus_db_file) {
 3386:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 3387:                                  "failed because the file does not exist");
 3388:         return ();
 3389:     }
 3390:     if (! tie(%thesaurus_db,'GDBM_File',
 3391:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3392:         return ();
 3393:     } 
 3394:     my @Words=();
 3395:     my $count=0;
 3396:     if (exists($thesaurus_db{$keyword})) {
 3397: 	# The first element is the number of times
 3398: 	# the word appears.  We do not need it now.
 3399: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 3400: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 3401: 	my $threshold=$mostfrequentcount/10;
 3402:         foreach my $possibleword (@RelatedWords) {
 3403:             my ($word,$wordcount)=split(/\,/,$possibleword);
 3404:             if ($wordcount>$threshold) {
 3405: 		push(@Words,$word);
 3406:                 $count++;
 3407:                 if ($count>10) { last; }
 3408: 	    }
 3409:         }
 3410:     }
 3411:     untie %thesaurus_db;
 3412:     return @Words;
 3413: }
 3414: 
 3415: =pod
 3416: 
 3417: =back
 3418: 
 3419: =cut
 3420: 
 3421: # -------------------------------------------------------------- Plaintext name
 3422: =pod
 3423: 
 3424: =head1 User Name Functions
 3425: 
 3426: =over 4
 3427: 
 3428: =item * &plainname($uname,$udom,$first)
 3429: 
 3430: Takes a users logon name and returns it as a string in
 3431: "first middle last generation" form 
 3432: if $first is set to 'lastname' then it returns it as
 3433: 'lastname generation, firstname middlename' if their is a lastname
 3434: 
 3435: =cut
 3436: 
 3437: 
 3438: ###############################################################
 3439: sub plainname {
 3440:     my ($uname,$udom,$first)=@_;
 3441:     return if (!defined($uname) || !defined($udom));
 3442:     my %names=&getnames($uname,$udom);
 3443:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 3444: 					  $names{'middlename'},
 3445: 					  $names{'lastname'},
 3446: 					  $names{'generation'},$first);
 3447:     $name=~s/^\s+//;
 3448:     $name=~s/\s+$//;
 3449:     $name=~s/\s+/ /g;
 3450:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 3451:     return $name;
 3452: }
 3453: 
 3454: # -------------------------------------------------------------------- Nickname
 3455: =pod
 3456: 
 3457: =item * &nickname($uname,$udom)
 3458: 
 3459: Gets a users name and returns it as a string as
 3460: 
 3461: "&quot;nickname&quot;"
 3462: 
 3463: if the user has a nickname or
 3464: 
 3465: "first middle last generation"
 3466: 
 3467: if the user does not
 3468: 
 3469: =cut
 3470: 
 3471: sub nickname {
 3472:     my ($uname,$udom)=@_;
 3473:     return if (!defined($uname) || !defined($udom));
 3474:     my %names=&getnames($uname,$udom);
 3475:     my $name=$names{'nickname'};
 3476:     if ($name) {
 3477:        $name='&quot;'.$name.'&quot;'; 
 3478:     } else {
 3479:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 3480: 	     $names{'lastname'}.' '.$names{'generation'};
 3481:        $name=~s/\s+$//;
 3482:        $name=~s/\s+/ /g;
 3483:     }
 3484:     return $name;
 3485: }
 3486: 
 3487: sub getnames {
 3488:     my ($uname,$udom)=@_;
 3489:     return if (!defined($uname) || !defined($udom));
 3490:     if ($udom eq 'public' && $uname eq 'public') {
 3491: 	return ('lastname' => &mt('Public'));
 3492:     }
 3493:     my $id=$uname.':'.$udom;
 3494:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 3495:     if ($cached) {
 3496: 	return %{$names};
 3497:     } else {
 3498: 	my %loadnames=&Apache::lonnet::get('environment',
 3499:                     ['firstname','middlename','lastname','generation','nickname'],
 3500: 					 $udom,$uname);
 3501: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 3502: 	return %loadnames;
 3503:     }
 3504: }
 3505: 
 3506: # -------------------------------------------------------------------- getemails
 3507: 
 3508: =pod
 3509: 
 3510: =item * &getemails($uname,$udom)
 3511: 
 3512: Gets a user's email information and returns it as a hash with keys:
 3513: notification, critnotification, permanentemail
 3514: 
 3515: For notification and critnotification, values are comma-separated lists 
 3516: of e-mail addresses; for permanentemail, value is a single e-mail address.
 3517:  
 3518: 
 3519: =cut
 3520: 
 3521: 
 3522: sub getemails {
 3523:     my ($uname,$udom)=@_;
 3524:     if ($udom eq 'public' && $uname eq 'public') {
 3525: 	return;
 3526:     }
 3527:     if (!$udom) { $udom=$env{'user.domain'}; }
 3528:     if (!$uname) { $uname=$env{'user.name'}; }
 3529:     my $id=$uname.':'.$udom;
 3530:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 3531:     if ($cached) {
 3532: 	return %{$names};
 3533:     } else {
 3534: 	my %loadnames=&Apache::lonnet::get('environment',
 3535:                     			   ['notification','critnotification',
 3536: 					    'permanentemail'],
 3537: 					   $udom,$uname);
 3538: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 3539: 	return %loadnames;
 3540:     }
 3541: }
 3542: 
 3543: sub flush_email_cache {
 3544:     my ($uname,$udom)=@_;
 3545:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3546:     if (!$uname) { $uname=$env{'user.name'};   }
 3547:     return if ($udom eq 'public' && $uname eq 'public');
 3548:     my $id=$uname.':'.$udom;
 3549:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 3550: }
 3551: 
 3552: # -------------------------------------------------------------------- getlangs
 3553: 
 3554: =pod
 3555: 
 3556: =item * &getlangs($uname,$udom)
 3557: 
 3558: Gets a user's language preference and returns it as a hash with key:
 3559: language.
 3560: 
 3561: =cut
 3562: 
 3563: 
 3564: sub getlangs {
 3565:     my ($uname,$udom) = @_;
 3566:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3567:     if (!$uname) { $uname=$env{'user.name'};   }
 3568:     my $id=$uname.':'.$udom;
 3569:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 3570:     if ($cached) {
 3571:         return %{$langs};
 3572:     } else {
 3573:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 3574:                                            $udom,$uname);
 3575:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 3576:         return %loadlangs;
 3577:     }
 3578: }
 3579: 
 3580: sub flush_langs_cache {
 3581:     my ($uname,$udom)=@_;
 3582:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3583:     if (!$uname) { $uname=$env{'user.name'};   }
 3584:     return if ($udom eq 'public' && $uname eq 'public');
 3585:     my $id=$uname.':'.$udom;
 3586:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 3587: }
 3588: 
 3589: # ------------------------------------------------------------------ Screenname
 3590: 
 3591: =pod
 3592: 
 3593: =item * &screenname($uname,$udom)
 3594: 
 3595: Gets a users screenname and returns it as a string
 3596: 
 3597: =cut
 3598: 
 3599: sub screenname {
 3600:     my ($uname,$udom)=@_;
 3601:     if ($uname eq $env{'user.name'} &&
 3602: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 3603:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 3604:     return $names{'screenname'};
 3605: }
 3606: 
 3607: 
 3608: # ------------------------------------------------------------- Confirm Wrapper
 3609: =pod
 3610: 
 3611: =item * &confirmwrapper($message)
 3612: 
 3613: Wrap messages about completion of operation in box
 3614: 
 3615: =cut
 3616: 
 3617: sub confirmwrapper {
 3618:     my ($message)=@_;
 3619:     if ($message) {
 3620:         return "\n".'<div class="LC_confirm_box">'."\n"
 3621:                .$message."\n"
 3622:                .'</div>'."\n";
 3623:     } else {
 3624:         return $message;
 3625:     }
 3626: }
 3627: 
 3628: # ------------------------------------------------------------- Message Wrapper
 3629: 
 3630: sub messagewrapper {
 3631:     my ($link,$username,$domain,$subject,$text)=@_;
 3632:     return 
 3633:         '<a href="/adm/email?compose=individual&amp;'.
 3634:         'recname='.$username.'&amp;recdom='.$domain.
 3635: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3636:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3637: }
 3638: 
 3639: # --------------------------------------------------------------- Notes Wrapper
 3640: 
 3641: sub noteswrapper {
 3642:     my ($link,$un,$do)=@_;
 3643:     return 
 3644: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3645: }
 3646: 
 3647: # ------------------------------------------------------------- Aboutme Wrapper
 3648: 
 3649: sub aboutmewrapper {
 3650:     my ($link,$username,$domain,$target,$class)=@_;
 3651:     if (!defined($username)  && !defined($domain)) {
 3652:         return;
 3653:     }
 3654:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 3655: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3656: }
 3657: 
 3658: # ------------------------------------------------------------ Syllabus Wrapper
 3659: 
 3660: sub syllabuswrapper {
 3661:     my ($linktext,$coursedir,$domain)=@_;
 3662:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3663: }
 3664: 
 3665: # -----------------------------------------------------------------------------
 3666: 
 3667: sub track_student_link {
 3668:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3669:     my $link ="/adm/trackstudent?";
 3670:     my $title = 'View recent activity';
 3671:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3672:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3673:         $link .= "selected_student=$sname:$sdom";
 3674:         $title .= ' of this student';
 3675:     } 
 3676:     if (defined($target) && $target !~ /^\s*$/) {
 3677:         $target = qq{target="$target"};
 3678:     } else {
 3679:         $target = '';
 3680:     }
 3681:     if ($start) { $link.='&amp;start='.$start; }
 3682:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3683:     $title = &mt($title);
 3684:     $linktext = &mt($linktext);
 3685:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3686: 	&help_open_topic('View_recent_activity');
 3687: }
 3688: 
 3689: sub slot_reservations_link {
 3690:     my ($linktext,$sname,$sdom,$target) = @_;
 3691:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3692:     my $title = 'View slot reservation history';
 3693:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3694:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3695:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3696:         $title .= ' of this student';
 3697:     }
 3698:     if (defined($target) && $target !~ /^\s*$/) {
 3699:         $target = qq{target="$target"};
 3700:     } else {
 3701:         $target = '';
 3702:     }
 3703:     $title = &mt($title);
 3704:     $linktext = &mt($linktext);
 3705:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3706: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3707: 
 3708: }
 3709: 
 3710: # ===================================================== Display a student photo
 3711: 
 3712: 
 3713: sub student_image_tag {
 3714:     my ($domain,$user)=@_;
 3715:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3716:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3717: 	return '<img src="'.$imgsrc.'" align="right" />';
 3718:     } else {
 3719: 	return '';
 3720:     }
 3721: }
 3722: 
 3723: =pod
 3724: 
 3725: =back
 3726: 
 3727: =head1 Access .tab File Data
 3728: 
 3729: =over 4
 3730: 
 3731: =item * &languageids() 
 3732: 
 3733: returns list of all language ids
 3734: 
 3735: =cut
 3736: 
 3737: sub languageids {
 3738:     return sort(keys(%language));
 3739: }
 3740: 
 3741: =pod
 3742: 
 3743: =item * &languagedescription() 
 3744: 
 3745: returns description of a specified language id
 3746: 
 3747: =cut
 3748: 
 3749: sub languagedescription {
 3750:     my $code=shift;
 3751:     return  ($supported_language{$code}?'* ':'').
 3752:             $language{$code}.
 3753: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 3754: }
 3755: 
 3756: =pod
 3757: 
 3758: =item * &plainlanguagedescription
 3759: 
 3760: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 3761: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 3762: 
 3763: =cut
 3764: 
 3765: sub plainlanguagedescription {
 3766:     my $code=shift;
 3767:     return $language{$code};
 3768: }
 3769: 
 3770: =pod
 3771: 
 3772: =item * &supportedlanguagecode
 3773: 
 3774: Returns the supported language code (e.g. sptutf maps to pt) given a language
 3775: code.
 3776: 
 3777: =cut
 3778: 
 3779: sub supportedlanguagecode {
 3780:     my $code=shift;
 3781:     return $supported_language{$code};
 3782: }
 3783: 
 3784: =pod
 3785: 
 3786: =item * &latexlanguage()
 3787: 
 3788: Given a language key code returns the correspondnig language to use
 3789: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 3790: is no supported hyphenation for the language code.
 3791: 
 3792: =cut
 3793: 
 3794: sub latexlanguage {
 3795:     my $code = shift;
 3796:     return $latex_language{$code};
 3797: }
 3798: 
 3799: =pod
 3800: 
 3801: =item * &latexhyphenation()
 3802: 
 3803: Same as above but what's supplied is the language as it might be stored
 3804: in the metadata.
 3805: 
 3806: =cut
 3807: 
 3808: sub latexhyphenation {
 3809:     my $key = shift;
 3810:     return $latex_language_bykey{$key};
 3811: }
 3812: 
 3813: =pod
 3814: 
 3815: =item * &copyrightids() 
 3816: 
 3817: returns list of all copyrights
 3818: 
 3819: =cut
 3820: 
 3821: sub copyrightids {
 3822:     return sort(keys(%cprtag));
 3823: }
 3824: 
 3825: =pod
 3826: 
 3827: =item * &copyrightdescription() 
 3828: 
 3829: returns description of a specified copyright id
 3830: 
 3831: =cut
 3832: 
 3833: sub copyrightdescription {
 3834:     return &mt($cprtag{shift(@_)});
 3835: }
 3836: 
 3837: =pod
 3838: 
 3839: =item * &source_copyrightids() 
 3840: 
 3841: returns list of all source copyrights
 3842: 
 3843: =cut
 3844: 
 3845: sub source_copyrightids {
 3846:     return sort(keys(%scprtag));
 3847: }
 3848: 
 3849: =pod
 3850: 
 3851: =item * &source_copyrightdescription() 
 3852: 
 3853: returns description of a specified source copyright id
 3854: 
 3855: =cut
 3856: 
 3857: sub source_copyrightdescription {
 3858:     return &mt($scprtag{shift(@_)});
 3859: }
 3860: 
 3861: =pod
 3862: 
 3863: =item * &filecategories() 
 3864: 
 3865: returns list of all file categories
 3866: 
 3867: =cut
 3868: 
 3869: sub filecategories {
 3870:     return sort(keys(%category_extensions));
 3871: }
 3872: 
 3873: =pod
 3874: 
 3875: =item * &filecategorytypes() 
 3876: 
 3877: returns list of file types belonging to a given file
 3878: category
 3879: 
 3880: =cut
 3881: 
 3882: sub filecategorytypes {
 3883:     my ($cat) = @_;
 3884:     return @{$category_extensions{lc($cat)}};
 3885: }
 3886: 
 3887: =pod
 3888: 
 3889: =item * &fileembstyle() 
 3890: 
 3891: returns embedding style for a specified file type
 3892: 
 3893: =cut
 3894: 
 3895: sub fileembstyle {
 3896:     return $fe{lc(shift(@_))};
 3897: }
 3898: 
 3899: sub filemimetype {
 3900:     return $fm{lc(shift(@_))};
 3901: }
 3902: 
 3903: 
 3904: sub filecategoryselect {
 3905:     my ($name,$value)=@_;
 3906:     return &select_form($value,$name,
 3907:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 3908: }
 3909: 
 3910: =pod
 3911: 
 3912: =item * &filedescription() 
 3913: 
 3914: returns description for a specified file type
 3915: 
 3916: =cut
 3917: 
 3918: sub filedescription {
 3919:     my $file_description = $fd{lc(shift())};
 3920:     $file_description =~ s:([\[\]]):~$1:g;
 3921:     return &mt($file_description);
 3922: }
 3923: 
 3924: =pod
 3925: 
 3926: =item * &filedescriptionex() 
 3927: 
 3928: returns description for a specified file type with
 3929: extra formatting
 3930: 
 3931: =cut
 3932: 
 3933: sub filedescriptionex {
 3934:     my $ex=shift;
 3935:     my $file_description = $fd{lc($ex)};
 3936:     $file_description =~ s:([\[\]]):~$1:g;
 3937:     return '.'.$ex.' '.&mt($file_description);
 3938: }
 3939: 
 3940: # End of .tab access
 3941: =pod
 3942: 
 3943: =back
 3944: 
 3945: =cut
 3946: 
 3947: # ------------------------------------------------------------------ File Types
 3948: sub fileextensions {
 3949:     return sort(keys(%fe));
 3950: }
 3951: 
 3952: # ----------------------------------------------------------- Display Languages
 3953: # returns a hash with all desired display languages
 3954: #
 3955: 
 3956: sub display_languages {
 3957:     my %languages=();
 3958:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3959: 	$languages{$lang}=1;
 3960:     }
 3961:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3962:     if ($env{'form.displaylanguage'}) {
 3963: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3964: 	    $languages{$lang}=1;
 3965:         }
 3966:     }
 3967:     return %languages;
 3968: }
 3969: 
 3970: sub languages {
 3971:     my ($possible_langs) = @_;
 3972:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3973:     if (!ref($possible_langs)) {
 3974: 	if( wantarray ) {
 3975: 	    return @preferred_langs;
 3976: 	} else {
 3977: 	    return $preferred_langs[0];
 3978: 	}
 3979:     }
 3980:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3981:     my @preferred_possibilities;
 3982:     foreach my $preferred_lang (@preferred_langs) {
 3983: 	if (exists($possibilities{$preferred_lang})) {
 3984: 	    push(@preferred_possibilities, $preferred_lang);
 3985: 	}
 3986:     }
 3987:     if( wantarray ) {
 3988: 	return @preferred_possibilities;
 3989:     }
 3990:     return $preferred_possibilities[0];
 3991: }
 3992: 
 3993: sub user_lang {
 3994:     my ($touname,$toudom,$fromcid) = @_;
 3995:     my @userlangs;
 3996:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3997:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3998:                     $env{'course.'.$fromcid.'.languages'}));
 3999:     } else {
 4000:         my %langhash = &getlangs($touname,$toudom);
 4001:         if ($langhash{'languages'} ne '') {
 4002:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 4003:         } else {
 4004:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 4005:             if ($domdefs{'lang_def'} ne '') {
 4006:                 @userlangs = ($domdefs{'lang_def'});
 4007:             }
 4008:         }
 4009:     }
 4010:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 4011:     my $user_lh = Apache::localize->get_handle(@languages);
 4012:     return $user_lh;
 4013: }
 4014: 
 4015: 
 4016: ###############################################################
 4017: ##               Student Answer Attempts                     ##
 4018: ###############################################################
 4019: 
 4020: =pod
 4021: 
 4022: =head1 Alternate Problem Views
 4023: 
 4024: =over 4
 4025: 
 4026: =item * &get_previous_attempt($symb, $username, $domain, $course,
 4027:     $getattempt, $regexp, $gradesub, $usec, $identifier)
 4028: 
 4029: Return string with previous attempt on problem. Arguments:
 4030: 
 4031: =over 4
 4032: 
 4033: =item * $symb: Problem, including path
 4034: 
 4035: =item * $username: username of the desired student
 4036: 
 4037: =item * $domain: domain of the desired student
 4038: 
 4039: =item * $course: Course ID
 4040: 
 4041: =item * $getattempt: Leave blank for all attempts, otherwise put
 4042:     something
 4043: 
 4044: =item * $regexp: if string matches this regexp, the string will be
 4045:     sent to $gradesub
 4046: 
 4047: =item * $gradesub: routine that processes the string if it matches $regexp
 4048: 
 4049: =item * $usec: section of the desired student
 4050: 
 4051: =item * $identifier: counter for student (multiple students one problem) or
 4052:     problem (one student; whole sequence).
 4053: 
 4054: =back
 4055: 
 4056: The output string is a table containing all desired attempts, if any.
 4057: 
 4058: =cut
 4059: 
 4060: sub get_previous_attempt {
 4061:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
 4062:   my $prevattempts='';
 4063:   no strict 'refs';
 4064:   if ($symb) {
 4065:     my (%returnhash)=
 4066:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 4067:     if ($returnhash{'version'}) {
 4068:       my %lasthash=();
 4069:       my $version;
 4070:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 4071:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
 4072:             if ($key =~ /\.rawrndseed$/) {
 4073:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
 4074:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
 4075:             } else {
 4076:                 $lasthash{$key}=$returnhash{$version.':'.$key};
 4077:             }
 4078:         }
 4079:       }
 4080:       $prevattempts=&start_data_table().&start_data_table_header_row();
 4081:       $prevattempts.='<th>'.&mt('History').'</th>';
 4082:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
 4083:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 4084:       foreach my $key (sort(keys(%lasthash))) {
 4085: 	my ($ign,@parts) = split(/\./,$key);
 4086: 	if ($#parts > 0) {
 4087: 	  my $data=$parts[-1];
 4088:           next if ($data eq 'foilorder');
 4089: 	  pop(@parts);
 4090:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 4091:           if ($data eq 'type') {
 4092:               unless ($showsurv) {
 4093:                   my $id = join(',',@parts);
 4094:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 4095:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 4096:                       $lasthidden{$ign.'.'.$id} = 1;
 4097:                   }
 4098:               }
 4099:               if ($identifier ne '') {
 4100:                   my $id = join(',',@parts);
 4101:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
 4102:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
 4103:                       $hidestatus{$ign.'.'.$id} = 1;
 4104:                   }
 4105:               }
 4106:           } elsif ($data eq 'regrader') {
 4107:               if (($identifier ne '') && (@parts)) {
 4108:                   my $id = join(',',@parts);
 4109:                   $regraded{$ign.'.'.$id} = 1;
 4110:               }
 4111:           } 
 4112: 	} else {
 4113: 	  if ($#parts == 0) {
 4114: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 4115: 	  } else {
 4116: 	    $prevattempts.='<th>'.$ign.'</th>';
 4117: 	  }
 4118: 	}
 4119:       }
 4120:       $prevattempts.=&end_data_table_header_row();
 4121:       if ($getattempt eq '') {
 4122:         my (%solved,%resets,%probstatus);
 4123:         if (($identifier ne '') && (keys(%regraded) > 0)) {
 4124:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 4125:                 foreach my $id (keys(%regraded)) {
 4126:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
 4127:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
 4128:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
 4129:                         push(@{$resets{$id}},$version);
 4130:                     }
 4131:                 }
 4132:             }
 4133:         }
 4134: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 4135:             my (@hidden,@unsolved);
 4136:             if (%typeparts) {
 4137:                 foreach my $id (keys(%typeparts)) {
 4138:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
 4139:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 4140:                         push(@hidden,$id);
 4141:                     } elsif ($identifier ne '') {
 4142:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
 4143:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
 4144:                                 ($hidestatus{$id})) {
 4145:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
 4146:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
 4147:                                 push(@{$solved{$id}},$version);
 4148:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
 4149:                                      (ref($solved{$id}) eq 'ARRAY')) {
 4150:                                 my $skip;
 4151:                                 if (ref($resets{$id}) eq 'ARRAY') {
 4152:                                     foreach my $reset (@{$resets{$id}}) {
 4153:                                         if ($reset > $solved{$id}[-1]) {
 4154:                                             $skip=1;
 4155:                                             last;
 4156:                                         }
 4157:                                     }
 4158:                                 }
 4159:                                 unless ($skip) {
 4160:                                     my ($ign,$partslist) = split(/\./,$id,2);
 4161:                                     push(@unsolved,$partslist);
 4162:                                 }
 4163:                             }
 4164:                         }
 4165:                     }
 4166:                 }
 4167:             }
 4168:             $prevattempts.=&start_data_table_row().
 4169:                            '<td>'.&mt('Transaction [_1]',$version);
 4170:             if (@unsolved) {
 4171:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
 4172:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
 4173:                                  &mt('Hide').'</label></span>';
 4174:             }
 4175:             $prevattempts .= '</td>';
 4176:             if (@hidden) {
 4177:                 foreach my $key (sort(keys(%lasthash))) {
 4178:                     next if ($key =~ /\.foilorder$/);
 4179:                     my $hide;
 4180:                     foreach my $id (@hidden) {
 4181:                         if ($key =~ /^\Q$id\E/) {
 4182:                             $hide = 1;
 4183:                             last;
 4184:                         }
 4185:                     }
 4186:                     if ($hide) {
 4187:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4188:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 4189:                             my $value = &format_previous_attempt_value($key,
 4190:                                              $returnhash{$version.':'.$key});
 4191:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4192:                         } else {
 4193:                             $prevattempts.='<td>&nbsp;</td>';
 4194:                         }
 4195:                     } else {
 4196:                         if ($key =~ /\./) {
 4197:                             my $value = $returnhash{$version.':'.$key};
 4198:                             if ($key =~ /\.rndseed$/) {
 4199:                                 my ($id) = ($key =~ /^(.+)\.rndseed$/);
 4200:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4201:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4202:                                 }
 4203:                             }
 4204:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4205:                                            '&nbsp;</td>';
 4206:                         } else {
 4207:                             $prevattempts.='<td>&nbsp;</td>';
 4208:                         }
 4209:                     }
 4210:                 }
 4211:             } else {
 4212: 	        foreach my $key (sort(keys(%lasthash))) {
 4213:                     next if ($key =~ /\.foilorder$/);
 4214:                     my $value = $returnhash{$version.':'.$key};
 4215:                     if ($key =~ /\.rndseed$/) {
 4216:                         my ($id) = ($key =~ /^(.+)\.rndseed$/);
 4217:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4218:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4219:                         }
 4220:                     }
 4221:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4222:                                    '&nbsp;</td>';
 4223: 	        }
 4224:             }
 4225: 	    $prevattempts.=&end_data_table_row();
 4226: 	 }
 4227:       }
 4228:       my @currhidden = keys(%lasthidden);
 4229:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 4230:       foreach my $key (sort(keys(%lasthash))) {
 4231:           next if ($key =~ /\.foilorder$/);
 4232:           if (%typeparts) {
 4233:               my $hidden;
 4234:               foreach my $id (@currhidden) {
 4235:                   if ($key =~ /^\Q$id\E/) {
 4236:                       $hidden = 1;
 4237:                       last;
 4238:                   }
 4239:               }
 4240:               if ($hidden) {
 4241:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4242:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 4243:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4244:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4245:                           $value = &$gradesub($value);
 4246:                       }
 4247:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4248:                   } else {
 4249:                       $prevattempts.='<td>&nbsp;</td>';
 4250:                   }
 4251:               } else {
 4252:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4253:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4254:                       $value = &$gradesub($value);
 4255:                   }
 4256:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4257:               }
 4258:           } else {
 4259: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4260: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4261:                   $value = &$gradesub($value);
 4262:               }
 4263: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4264:           }
 4265:       }
 4266:       $prevattempts.= &end_data_table_row().&end_data_table();
 4267:     } else {
 4268:       $prevattempts=
 4269: 	  &start_data_table().&start_data_table_row().
 4270: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 4271: 	  &end_data_table_row().&end_data_table();
 4272:     }
 4273:   } else {
 4274:     $prevattempts=
 4275: 	  &start_data_table().&start_data_table_row().
 4276: 	  '<td>'.&mt('No data.').'</td>'.
 4277: 	  &end_data_table_row().&end_data_table();
 4278:   }
 4279: }
 4280: 
 4281: sub format_previous_attempt_value {
 4282:     my ($key,$value) = @_;
 4283:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 4284: 	$value = &Apache::lonlocal::locallocaltime($value);
 4285:     } elsif (ref($value) eq 'ARRAY') {
 4286: 	$value = '('.join(', ', @{ $value }).')';
 4287:     } elsif ($key =~ /answerstring$/) {
 4288:         my %answers = &Apache::lonnet::str2hash($value);
 4289:         my @anskeys = sort(keys(%answers));
 4290:         if (@anskeys == 1) {
 4291:             my $answer = $answers{$anskeys[0]};
 4292:             if ($answer =~ m{\0}) {
 4293:                 $answer =~ s{\0}{,}g;
 4294:             }
 4295:             my $tag_internal_answer_name = 'INTERNAL';
 4296:             if ($anskeys[0] eq $tag_internal_answer_name) {
 4297:                 $value = $answer; 
 4298:             } else {
 4299:                 $value = $anskeys[0].'='.$answer;
 4300:             }
 4301:         } else {
 4302:             foreach my $ans (@anskeys) {
 4303:                 my $answer = $answers{$ans};
 4304:                 if ($answer =~ m{\0}) {
 4305:                     $answer =~ s{\0}{,}g;
 4306:                 }
 4307:                 $value .=  $ans.'='.$answer.'<br />';;
 4308:             } 
 4309:         }
 4310:     } else {
 4311: 	$value = &unescape($value);
 4312:     }
 4313:     return $value;
 4314: }
 4315: 
 4316: 
 4317: sub relative_to_absolute {
 4318:     my ($url,$output)=@_;
 4319:     my $parser=HTML::TokeParser->new(\$output);
 4320:     my $token;
 4321:     my $thisdir=$url;
 4322:     my @rlinks=();
 4323:     while ($token=$parser->get_token) {
 4324: 	if ($token->[0] eq 'S') {
 4325: 	    if ($token->[1] eq 'a') {
 4326: 		if ($token->[2]->{'href'}) {
 4327: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 4328: 		}
 4329: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 4330: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 4331: 	    } elsif ($token->[1] eq 'base') {
 4332: 		$thisdir=$token->[2]->{'href'};
 4333: 	    }
 4334: 	}
 4335:     }
 4336:     $thisdir=~s-/[^/]*$--;
 4337:     foreach my $link (@rlinks) {
 4338: 	unless (($link=~/^https?\:\/\//i) ||
 4339: 		($link=~/^\//) ||
 4340: 		($link=~/^javascript:/i) ||
 4341: 		($link=~/^mailto:/i) ||
 4342: 		($link=~/^\#/)) {
 4343: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 4344: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 4345: 	}
 4346:     }
 4347: # -------------------------------------------------- Deal with Applet codebases
 4348:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 4349:     return $output;
 4350: }
 4351: 
 4352: =pod
 4353: 
 4354: =item * &get_student_view()
 4355: 
 4356: show a snapshot of what student was looking at
 4357: 
 4358: =cut
 4359: 
 4360: sub get_student_view {
 4361:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 4362:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4363:   my (%form);
 4364:   my @elements=('symb','courseid','domain','username');
 4365:   foreach my $element (@elements) {
 4366:       $form{'grade_'.$element}=eval '$'.$element #'
 4367:   }
 4368:   if (defined($moreenv)) {
 4369:       %form=(%form,%{$moreenv});
 4370:   }
 4371:   if (defined($target)) { $form{'grade_target'} = $target; }
 4372:   $feedurl=&Apache::lonnet::clutter($feedurl);
 4373:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 4374:   $userview=~s/\<body[^\>]*\>//gi;
 4375:   $userview=~s/\<\/body\>//gi;
 4376:   $userview=~s/\<html\>//gi;
 4377:   $userview=~s/\<\/html\>//gi;
 4378:   $userview=~s/\<head\>//gi;
 4379:   $userview=~s/\<\/head\>//gi;
 4380:   $userview=~s/action\s*\=/would_be_action\=/gi;
 4381:   $userview=&relative_to_absolute($feedurl,$userview);
 4382:   if (wantarray) {
 4383:      return ($userview,$response);
 4384:   } else {
 4385:      return $userview;
 4386:   }
 4387: }
 4388: 
 4389: sub get_student_view_with_retries {
 4390:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 4391: 
 4392:     my $ok = 0;                 # True if we got a good response.
 4393:     my $content;
 4394:     my $response;
 4395: 
 4396:     # Try to get the student_view done. within the retries count:
 4397:     
 4398:     do {
 4399:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 4400:          $ok      = $response->is_success;
 4401:          if (!$ok) {
 4402:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 4403:          }
 4404:          $retries--;
 4405:     } while (!$ok && ($retries > 0));
 4406:     
 4407:     if (!$ok) {
 4408:        $content = '';          # On error return an empty content.
 4409:     }
 4410:     if (wantarray) {
 4411:        return ($content, $response);
 4412:     } else {
 4413:        return $content;
 4414:     }
 4415: }
 4416: 
 4417: =pod
 4418: 
 4419: =item * &get_student_answers() 
 4420: 
 4421: show a snapshot of how student was answering problem
 4422: 
 4423: =cut
 4424: 
 4425: sub get_student_answers {
 4426:   my ($symb,$username,$domain,$courseid,%form) = @_;
 4427:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4428:   my (%moreenv);
 4429:   my @elements=('symb','courseid','domain','username');
 4430:   foreach my $element (@elements) {
 4431:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 4432:   }
 4433:   $moreenv{'grade_target'}='answer';
 4434:   %moreenv=(%form,%moreenv);
 4435:   $feedurl = &Apache::lonnet::clutter($feedurl);
 4436:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 4437:   return $userview;
 4438: }
 4439: 
 4440: =pod
 4441: 
 4442: =item * &submlink()
 4443: 
 4444: Inputs: $text $uname $udom $symb $target
 4445: 
 4446: Returns: A link to grades.pm such as to see the SUBM view of a student
 4447: 
 4448: =cut
 4449: 
 4450: ###############################################
 4451: sub submlink {
 4452:     my ($text,$uname,$udom,$symb,$target)=@_;
 4453:     if (!($uname && $udom)) {
 4454: 	(my $cursymb, my $courseid,$udom,$uname)=
 4455: 	    &Apache::lonnet::whichuser($symb);
 4456: 	if (!$symb) { $symb=$cursymb; }
 4457:     }
 4458:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4459:     $symb=&escape($symb);
 4460:     if ($target) { $target=" target=\"$target\""; }
 4461:     return
 4462:         '<a href="/adm/grades?command=submission'.
 4463:         '&amp;symb='.$symb.
 4464:         '&amp;student='.$uname.
 4465:         '&amp;userdom='.$udom.'"'.
 4466:         $target.'>'.$text.'</a>';
 4467: }
 4468: ##############################################
 4469: 
 4470: =pod
 4471: 
 4472: =item * &pgrdlink()
 4473: 
 4474: Inputs: $text $uname $udom $symb $target
 4475: 
 4476: Returns: A link to grades.pm such as to see the PGRD view of a student
 4477: 
 4478: =cut
 4479: 
 4480: ###############################################
 4481: sub pgrdlink {
 4482:     my $link=&submlink(@_);
 4483:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 4484:     return $link;
 4485: }
 4486: ##############################################
 4487: 
 4488: =pod
 4489: 
 4490: =item * &pprmlink()
 4491: 
 4492: Inputs: $text $uname $udom $symb $target
 4493: 
 4494: Returns: A link to parmset.pm such as to see the PPRM view of a
 4495: student and a specific resource
 4496: 
 4497: =cut
 4498: 
 4499: ###############################################
 4500: sub pprmlink {
 4501:     my ($text,$uname,$udom,$symb,$target)=@_;
 4502:     if (!($uname && $udom)) {
 4503: 	(my $cursymb, my $courseid,$udom,$uname)=
 4504: 	    &Apache::lonnet::whichuser($symb);
 4505: 	if (!$symb) { $symb=$cursymb; }
 4506:     }
 4507:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4508:     $symb=&escape($symb);
 4509:     if ($target) { $target="target=\"$target\""; }
 4510:     return '<a href="/adm/parmset?command=set&amp;'.
 4511: 	'symb='.$symb.'&amp;uname='.$uname.
 4512: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 4513: }
 4514: ##############################################
 4515: 
 4516: =pod
 4517: 
 4518: =back
 4519: 
 4520: =cut
 4521: 
 4522: ###############################################
 4523: 
 4524: 
 4525: sub timehash {
 4526:     my ($thistime) = @_;
 4527:     my $timezone = &Apache::lonlocal::gettimezone();
 4528:     my $dt = DateTime->from_epoch(epoch => $thistime)
 4529:                      ->set_time_zone($timezone);
 4530:     my $wday = $dt->day_of_week();
 4531:     if ($wday == 7) { $wday = 0; }
 4532:     return ( 'second' => $dt->second(),
 4533:              'minute' => $dt->minute(),
 4534:              'hour'   => $dt->hour(),
 4535:              'day'     => $dt->day_of_month(),
 4536:              'month'   => $dt->month(),
 4537:              'year'    => $dt->year(),
 4538:              'weekday' => $wday,
 4539:              'dayyear' => $dt->day_of_year(),
 4540:              'dlsav'   => $dt->is_dst() );
 4541: }
 4542: 
 4543: sub utc_string {
 4544:     my ($date)=@_;
 4545:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 4546: }
 4547: 
 4548: sub maketime {
 4549:     my %th=@_;
 4550:     my ($epoch_time,$timezone,$dt);
 4551:     $timezone = &Apache::lonlocal::gettimezone();
 4552:     eval {
 4553:         $dt = DateTime->new( year   => $th{'year'},
 4554:                              month  => $th{'month'},
 4555:                              day    => $th{'day'},
 4556:                              hour   => $th{'hour'},
 4557:                              minute => $th{'minute'},
 4558:                              second => $th{'second'},
 4559:                              time_zone => $timezone,
 4560:                          );
 4561:     };
 4562:     if (!$@) {
 4563:         $epoch_time = $dt->epoch;
 4564:         if ($epoch_time) {
 4565:             return $epoch_time;
 4566:         }
 4567:     }
 4568:     return POSIX::mktime(
 4569:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 4570:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 4571: }
 4572: 
 4573: #########################################
 4574: 
 4575: sub findallcourses {
 4576:     my ($roles,$uname,$udom) = @_;
 4577:     my %roles;
 4578:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 4579:     my %courses;
 4580:     my $now=time;
 4581:     if (!defined($uname)) {
 4582:         $uname = $env{'user.name'};
 4583:     }
 4584:     if (!defined($udom)) {
 4585:         $udom = $env{'user.domain'};
 4586:     }
 4587:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 4588:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 4589:         if (!%roles) {
 4590:             %roles = (
 4591:                        cc => 1,
 4592:                        co => 1,
 4593:                        in => 1,
 4594:                        ep => 1,
 4595:                        ta => 1,
 4596:                        cr => 1,
 4597:                        st => 1,
 4598:              );
 4599:         }
 4600:         foreach my $entry (keys(%roleshash)) {
 4601:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 4602:             if ($trole =~ /^cr/) { 
 4603:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 4604:             } else {
 4605:                 next if (!exists($roles{$trole}));
 4606:             }
 4607:             if ($tend) {
 4608:                 next if ($tend < $now);
 4609:             }
 4610:             if ($tstart) {
 4611:                 next if ($tstart > $now);
 4612:             }
 4613:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 4614:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 4615:             my $value = $trole.'/'.$cdom.'/';
 4616:             if ($secpart eq '') {
 4617:                 ($cnum,$role) = split(/_/,$cnumpart); 
 4618:                 $sec = 'none';
 4619:                 $value .= $cnum.'/';
 4620:             } else {
 4621:                 $cnum = $cnumpart;
 4622:                 ($sec,$role) = split(/_/,$secpart);
 4623:                 $value .= $cnum.'/'.$sec;
 4624:             }
 4625:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4626:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4627:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4628:                 }
 4629:             } else {
 4630:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4631:             }
 4632:         }
 4633:     } else {
 4634:         foreach my $key (keys(%env)) {
 4635: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 4636:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 4637: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 4638: 	        next if ($role eq 'ca' || $role eq 'aa');
 4639: 	        next if (%roles && !exists($roles{$role}));
 4640: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 4641:                 my $active=1;
 4642:                 if ($starttime) {
 4643: 		    if ($now<$starttime) { $active=0; }
 4644:                 }
 4645:                 if ($endtime) {
 4646:                     if ($now>$endtime) { $active=0; }
 4647:                 }
 4648:                 if ($active) {
 4649:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 4650:                     if ($sec eq '') {
 4651:                         $sec = 'none';
 4652:                     } else {
 4653:                         $value .= $sec;
 4654:                     }
 4655:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4656:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4657:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4658:                         }
 4659:                     } else {
 4660:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4661:                     }
 4662:                 }
 4663:             }
 4664:         }
 4665:     }
 4666:     return %courses;
 4667: }
 4668: 
 4669: ###############################################
 4670: 
 4671: sub blockcheck {
 4672:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
 4673: 
 4674:     if (defined($udom) && defined($uname)) {
 4675:         # If uname and udom are for a course, check for blocks in the course.
 4676:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
 4677:             my ($startblock,$endblock,$triggerblock) =
 4678:                 &get_blocks($setters,$activity,$udom,$uname,$url);
 4679:             return ($startblock,$endblock,$triggerblock);
 4680:         }
 4681:     } else {
 4682:         $udom = $env{'user.domain'};
 4683:         $uname = $env{'user.name'};
 4684:     }
 4685: 
 4686:     my $startblock = 0;
 4687:     my $endblock = 0;
 4688:     my $triggerblock = '';
 4689:     my %live_courses = &findallcourses(undef,$uname,$udom);
 4690: 
 4691:     # If uname is for a user, and activity is course-specific, i.e.,
 4692:     # boards, chat or groups, check for blocking in current course only.
 4693: 
 4694:     if (($activity eq 'boards' || $activity eq 'chat' ||
 4695:          $activity eq 'groups' || $activity eq 'printout') &&
 4696:         ($env{'request.course.id'})) {
 4697:         foreach my $key (keys(%live_courses)) {
 4698:             if ($key ne $env{'request.course.id'}) {
 4699:                 delete($live_courses{$key});
 4700:             }
 4701:         }
 4702:     }
 4703: 
 4704:     my $otheruser = 0;
 4705:     my %own_courses;
 4706:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 4707:         # Resource belongs to user other than current user.
 4708:         $otheruser = 1;
 4709:         # Gather courses for current user
 4710:         %own_courses = 
 4711:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 4712:     }
 4713: 
 4714:     # Gather active course roles - course coordinator, instructor, 
 4715:     # exam proctor, ta, student, or custom role.
 4716: 
 4717:     foreach my $course (keys(%live_courses)) {
 4718:         my ($cdom,$cnum);
 4719:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 4720:             $cdom = $env{'course.'.$course.'.domain'};
 4721:             $cnum = $env{'course.'.$course.'.num'};
 4722:         } else {
 4723:             ($cdom,$cnum) = split(/_/,$course); 
 4724:         }
 4725:         my $no_ownblock = 0;
 4726:         my $no_userblock = 0;
 4727:         if ($otheruser && $activity ne 'com') {
 4728:             # Check if current user has 'evb' priv for this
 4729:             if (defined($own_courses{$course})) {
 4730:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 4731:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4732:                     if ($sec ne 'none') {
 4733:                         $checkrole .= '/'.$sec;
 4734:                     }
 4735:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4736:                         $no_ownblock = 1;
 4737:                         last;
 4738:                     }
 4739:                 }
 4740:             }
 4741:             # if they have 'evb' priv and are currently not playing student
 4742:             next if (($no_ownblock) &&
 4743:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 4744:         }
 4745:         foreach my $sec (keys(%{$live_courses{$course}})) {
 4746:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4747:             if ($sec ne 'none') {
 4748:                 $checkrole .= '/'.$sec;
 4749:             }
 4750:             if ($otheruser) {
 4751:                 # Resource belongs to user other than current user.
 4752:                 # Assemble privs for that user, and check for 'evb' priv.
 4753:                 my (%allroles,%userroles);
 4754:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 4755:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 4756:                         my ($trole,$tdom,$tnum,$tsec);
 4757:                         if ($entry =~ /^cr/) {
 4758:                             ($trole,$tdom,$tnum,$tsec) = 
 4759:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 4760:                         } else {
 4761:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 4762:                         }
 4763:                         my ($spec,$area,$trest);
 4764:                         $area = '/'.$tdom.'/'.$tnum;
 4765:                         $trest = $tnum;
 4766:                         if ($tsec ne '') {
 4767:                             $area .= '/'.$tsec;
 4768:                             $trest .= '/'.$tsec;
 4769:                         }
 4770:                         $spec = $trole.'.'.$area;
 4771:                         if ($trole =~ /^cr/) {
 4772:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 4773:                                                               $tdom,$spec,$trest,$area);
 4774:                         } else {
 4775:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 4776:                                                                 $tdom,$spec,$trest,$area);
 4777:                         }
 4778:                     }
 4779:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 4780:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 4781:                         if ($1) {
 4782:                             $no_userblock = 1;
 4783:                             last;
 4784:                         }
 4785:                     }
 4786:                 }
 4787:             } else {
 4788:                 # Resource belongs to current user
 4789:                 # Check for 'evb' priv via lonnet::allowed().
 4790:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4791:                     $no_ownblock = 1;
 4792:                     last;
 4793:                 }
 4794:             }
 4795:         }
 4796:         # if they have the evb priv and are currently not playing student
 4797:         next if (($no_ownblock) &&
 4798:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 4799:         next if ($no_userblock);
 4800: 
 4801:         # Retrieve blocking times and identity of blocker for course
 4802:         # of specified user, unless user has 'evb' privilege.
 4803:         
 4804:         my ($start,$end,$trigger) = 
 4805:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
 4806:         if (($start != 0) && 
 4807:             (($startblock == 0) || ($startblock > $start))) {
 4808:             $startblock = $start;
 4809:             if ($trigger ne '') {
 4810:                 $triggerblock = $trigger;
 4811:             }
 4812:         }
 4813:         if (($end != 0)  &&
 4814:             (($endblock == 0) || ($endblock < $end))) {
 4815:             $endblock = $end;
 4816:             if ($trigger ne '') {
 4817:                 $triggerblock = $trigger;
 4818:             }
 4819:         }
 4820:     }
 4821:     return ($startblock,$endblock,$triggerblock);
 4822: }
 4823: 
 4824: sub get_blocks {
 4825:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
 4826:     my $startblock = 0;
 4827:     my $endblock = 0;
 4828:     my $triggerblock = '';
 4829:     my $course = $cdom.'_'.$cnum;
 4830:     $setters->{$course} = {};
 4831:     $setters->{$course}{'staff'} = [];
 4832:     $setters->{$course}{'times'} = [];
 4833:     $setters->{$course}{'triggers'} = [];
 4834:     my (@blockers,%triggered);
 4835:     my $now = time;
 4836:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 4837:     if ($activity eq 'docs') {
 4838:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
 4839:         foreach my $block (@blockers) {
 4840:             if ($block =~ /^firstaccess____(.+)$/) {
 4841:                 my $item = $1;
 4842:                 my $type = 'map';
 4843:                 my $timersymb = $item;
 4844:                 if ($item eq 'course') {
 4845:                     $type = 'course';
 4846:                 } elsif ($item =~ /___\d+___/) {
 4847:                     $type = 'resource';
 4848:                 } else {
 4849:                     $timersymb = &Apache::lonnet::symbread($item);
 4850:                 }
 4851:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4852:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 4853:                 $triggered{$block} = {
 4854:                                        start => $start,
 4855:                                        end   => $end,
 4856:                                        type  => $type,
 4857:                                      };
 4858:             }
 4859:         }
 4860:     } else {
 4861:         foreach my $block (keys(%commblocks)) {
 4862:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 4863:                 my ($start,$end) = ($1,$2);
 4864:                 if ($start <= time && $end >= time) {
 4865:                     if (ref($commblocks{$block}) eq 'HASH') {
 4866:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 4867:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 4868:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 4869:                                     push(@blockers,$block);
 4870:                                 }
 4871:                             }
 4872:                         }
 4873:                     }
 4874:                 }
 4875:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 4876:                 my $item = $1;
 4877:                 my $timersymb = $item; 
 4878:                 my $type = 'map';
 4879:                 if ($item eq 'course') {
 4880:                     $type = 'course';
 4881:                 } elsif ($item =~ /___\d+___/) {
 4882:                     $type = 'resource';
 4883:                 } else {
 4884:                     $timersymb = &Apache::lonnet::symbread($item);
 4885:                 }
 4886:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4887:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 4888:                 if ($start && $end) {
 4889:                     if (($start <= time) && ($end >= time)) {
 4890:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 4891:                             push(@blockers,$block);
 4892:                             $triggered{$block} = {
 4893:                                                    start => $start,
 4894:                                                    end   => $end,
 4895:                                                    type  => $type,
 4896:                                                  };
 4897:                         }
 4898:                     }
 4899:                 }
 4900:             }
 4901:         }
 4902:     }
 4903:     foreach my $blocker (@blockers) {
 4904:         my ($staff_name,$staff_dom,$title,$blocks) =
 4905:             &parse_block_record($commblocks{$blocker});
 4906:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 4907:         my ($start,$end,$triggertype);
 4908:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 4909:             ($start,$end) = ($1,$2);
 4910:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 4911:             $start = $triggered{$blocker}{'start'};
 4912:             $end = $triggered{$blocker}{'end'};
 4913:             $triggertype = $triggered{$blocker}{'type'};
 4914:         }
 4915:         if ($start) {
 4916:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 4917:             if ($triggertype) {
 4918:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 4919:             } else {
 4920:                 push(@{$$setters{$course}{'triggers'}},0);
 4921:             }
 4922:             if ( ($startblock == 0) || ($startblock > $start) ) {
 4923:                 $startblock = $start;
 4924:                 if ($triggertype) {
 4925:                     $triggerblock = $blocker;
 4926:                 }
 4927:             }
 4928:             if ( ($endblock == 0) || ($endblock < $end) ) {
 4929:                $endblock = $end;
 4930:                if ($triggertype) {
 4931:                    $triggerblock = $blocker;
 4932:                }
 4933:             }
 4934:         }
 4935:     }
 4936:     return ($startblock,$endblock,$triggerblock);
 4937: }
 4938: 
 4939: sub parse_block_record {
 4940:     my ($record) = @_;
 4941:     my ($setuname,$setudom,$title,$blocks);
 4942:     if (ref($record) eq 'HASH') {
 4943:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 4944:         $title = &unescape($record->{'event'});
 4945:         $blocks = $record->{'blocks'};
 4946:     } else {
 4947:         my @data = split(/:/,$record,3);
 4948:         if (scalar(@data) eq 2) {
 4949:             $title = $data[1];
 4950:             ($setuname,$setudom) = split(/@/,$data[0]);
 4951:         } else {
 4952:             ($setuname,$setudom,$title) = @data;
 4953:         }
 4954:         $blocks = { 'com' => 'on' };
 4955:     }
 4956:     return ($setuname,$setudom,$title,$blocks);
 4957: }
 4958: 
 4959: sub blocking_status {
 4960:     my ($activity,$uname,$udom,$url,$is_course) = @_;
 4961:     my %setters;
 4962: 
 4963: # check for active blocking
 4964:     my ($startblock,$endblock,$triggerblock) = 
 4965:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
 4966:     my $blocked = 0;
 4967:     if ($startblock && $endblock) {
 4968:         $blocked = 1;
 4969:     }
 4970: 
 4971: # caller just wants to know whether a block is active
 4972:     if (!wantarray) { return $blocked; }
 4973: 
 4974: # build a link to a popup window containing the details
 4975:     my $querystring  = "?activity=$activity";
 4976: # $uname and $udom decide whose portfolio the user is trying to look at
 4977:     if (($activity eq 'port') || ($activity eq 'passwd')) {
 4978:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/);
 4979:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
 4980:     } elsif ($activity eq 'docs') {
 4981:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
 4982:     }
 4983: 
 4984:     my $output .= <<'END_MYBLOCK';
 4985: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 4986:     var options = "width=" + w + ",height=" + h + ",";
 4987:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 4988:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 4989:     var newWin = window.open(url, wdwName, options);
 4990:     newWin.focus();
 4991: }
 4992: END_MYBLOCK
 4993: 
 4994:     $output = Apache::lonhtmlcommon::scripttag($output);
 4995:   
 4996:     my $popupUrl = "/adm/blockingstatus/$querystring";
 4997:     my $text = &mt('Communication Blocked');
 4998:     my $class = 'LC_comblock';
 4999:     if ($activity eq 'docs') {
 5000:         $text = &mt('Content Access Blocked');
 5001:         $class = '';
 5002:     } elsif ($activity eq 'printout') {
 5003:         $text = &mt('Printing Blocked');
 5004:     } elsif ($activity eq 'passwd') {
 5005:         $text = &mt('Password Changing Blocked');
 5006:     }
 5007:     $output .= <<"END_BLOCK";
 5008: <div class='$class'>
 5009:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 5010:   title='$text'>
 5011:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 5012:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 5013:   title='$text'>$text</a>
 5014: </div>
 5015: 
 5016: END_BLOCK
 5017: 
 5018:     return ($blocked, $output);
 5019: }
 5020: 
 5021: ###############################################
 5022: 
 5023: sub check_ip_acc {
 5024:     my ($acc,$clientip)=@_;
 5025:     &Apache::lonxml::debug("acc is $acc");
 5026:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 5027:         return 1;
 5028:     }
 5029:     my $allowed=0;
 5030:     my $ip=$ENV{'REMOTE_ADDR'} || $clientip || $env{'request.host'};
 5031: 
 5032:     my $name;
 5033:     foreach my $pattern (split(',',$acc)) {
 5034:         $pattern =~ s/^\s*//;
 5035:         $pattern =~ s/\s*$//;
 5036:         if ($pattern =~ /\*$/) {
 5037:             #35.8.*
 5038:             $pattern=~s/\*//;
 5039:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 5040:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 5041:             #35.8.3.[34-56]
 5042:             my $low=$2;
 5043:             my $high=$3;
 5044:             $pattern=$1;
 5045:             if ($ip =~ /^\Q$pattern\E/) {
 5046:                 my $last=(split(/\./,$ip))[3];
 5047:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 5048:             }
 5049:         } elsif ($pattern =~ /^\*/) {
 5050:             #*.msu.edu
 5051:             $pattern=~s/\*//;
 5052:             if (!defined($name)) {
 5053:                 use Socket;
 5054:                 my $netaddr=inet_aton($ip);
 5055:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5056:             }
 5057:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 5058:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 5059:             #127.0.0.1
 5060:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 5061:         } else {
 5062:             #some.name.com
 5063:             if (!defined($name)) {
 5064:                 use Socket;
 5065:                 my $netaddr=inet_aton($ip);
 5066:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5067:             }
 5068:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 5069:         }
 5070:         if ($allowed) { last; }
 5071:     }
 5072:     return $allowed;
 5073: }
 5074: 
 5075: ###############################################
 5076: 
 5077: =pod
 5078: 
 5079: =head1 Domain Template Functions
 5080: 
 5081: =over 4
 5082: 
 5083: =item * &determinedomain()
 5084: 
 5085: Inputs: $domain (usually will be undef)
 5086: 
 5087: Returns: Determines which domain should be used for designs
 5088: 
 5089: =cut
 5090: 
 5091: ###############################################
 5092: sub determinedomain {
 5093:     my $domain=shift;
 5094:     if (! $domain) {
 5095:         # Determine domain if we have not been given one
 5096:         $domain = &Apache::lonnet::default_login_domain();
 5097:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 5098:         if ($env{'request.role.domain'}) { 
 5099:             $domain=$env{'request.role.domain'}; 
 5100:         }
 5101:     }
 5102:     return $domain;
 5103: }
 5104: ###############################################
 5105: 
 5106: sub devalidate_domconfig_cache {
 5107:     my ($udom)=@_;
 5108:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 5109: }
 5110: 
 5111: # ---------------------- Get domain configuration for a domain
 5112: sub get_domainconf {
 5113:     my ($udom) = @_;
 5114:     my $cachetime=1800;
 5115:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 5116:     if (defined($cached)) { return %{$result}; }
 5117: 
 5118:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 5119: 					     ['login','rolecolors','autoenroll'],$udom);
 5120:     my (%designhash,%legacy);
 5121:     if (keys(%domconfig) > 0) {
 5122:         if (ref($domconfig{'login'}) eq 'HASH') {
 5123:             if (keys(%{$domconfig{'login'}})) {
 5124:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 5125:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5126:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
 5127:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5128:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
 5129:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
 5130:                                         if ($key eq 'loginvia') {
 5131:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 5132:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 5133:                                                 $designhash{$udom.'.login.loginvia'} = $server;
 5134:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 5135:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 5136:                                                 } else {
 5137:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 5138:                                                 }
 5139:                                             }
 5140:                                         } elsif ($key eq 'headtag') {
 5141:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
 5142:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
 5143:                                             }
 5144:                                         }
 5145:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
 5146:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
 5147:                                         }
 5148:                                     }
 5149:                                 }
 5150:                             }
 5151:                         } else {
 5152:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 5153:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 5154:                                     $domconfig{'login'}{$key}{$img};
 5155:                             }
 5156:                         }
 5157:                     } else {
 5158:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 5159:                     }
 5160:                 }
 5161:             } else {
 5162:                 $legacy{'login'} = 1;
 5163:             }
 5164:         } else {
 5165:             $legacy{'login'} = 1;
 5166:         }
 5167:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 5168:             if (keys(%{$domconfig{'rolecolors'}})) {
 5169:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 5170:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 5171:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 5172:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 5173:                         }
 5174:                     }
 5175:                 }
 5176:             } else {
 5177:                 $legacy{'rolecolors'} = 1;
 5178:             }
 5179:         } else {
 5180:             $legacy{'rolecolors'} = 1;
 5181:         }
 5182:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5183:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 5184:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 5185:             }
 5186:         }
 5187:         if (keys(%legacy) > 0) {
 5188:             my %legacyhash = &get_legacy_domconf($udom);
 5189:             foreach my $item (keys(%legacyhash)) {
 5190:                 if ($item =~ /^\Q$udom\E\.login/) {
 5191:                     if ($legacy{'login'}) { 
 5192:                         $designhash{$item} = $legacyhash{$item};
 5193:                     }
 5194:                 } else {
 5195:                     if ($legacy{'rolecolors'}) {
 5196:                         $designhash{$item} = $legacyhash{$item};
 5197:                     }
 5198:                 }
 5199:             }
 5200:         }
 5201:     } else {
 5202:         %designhash = &get_legacy_domconf($udom); 
 5203:     }
 5204:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 5205: 				  $cachetime);
 5206:     return %designhash;
 5207: }
 5208: 
 5209: sub get_legacy_domconf {
 5210:     my ($udom) = @_;
 5211:     my %legacyhash;
 5212:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 5213:     my $designfile =  $designdir.'/'.$udom.'.tab';
 5214:     if (-e $designfile) {
 5215:         if ( open (my $fh,'<',$designfile) ) {
 5216:             while (my $line = <$fh>) {
 5217:                 next if ($line =~ /^\#/);
 5218:                 chomp($line);
 5219:                 my ($key,$val)=(split(/\=/,$line));
 5220:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 5221:             }
 5222:             close($fh);
 5223:         }
 5224:     }
 5225:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 5226:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 5227:     }
 5228:     return %legacyhash;
 5229: }
 5230: 
 5231: =pod
 5232: 
 5233: =item * &domainlogo()
 5234: 
 5235: Inputs: $domain (usually will be undef)
 5236: 
 5237: Returns: A link to a domain logo, if the domain logo exists.
 5238: If the domain logo does not exist, a description of the domain.
 5239: 
 5240: =cut
 5241: 
 5242: ###############################################
 5243: sub domainlogo {
 5244:     my $domain = &determinedomain(shift);
 5245:     my %designhash = &get_domainconf($domain);    
 5246:     # See if there is a logo
 5247:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 5248:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 5249:         if ($imgsrc =~ m{^/(adm|res)/}) {
 5250: 	    if ($imgsrc =~ m{^/res/}) {
 5251: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 5252: 		&Apache::lonnet::repcopy($local_name);
 5253: 	    }
 5254: 	   $imgsrc = &lonhttpdurl($imgsrc);
 5255:         } 
 5256:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 5257:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 5258:         return &Apache::lonnet::domain($domain,'description');
 5259:     } else {
 5260:         return '';
 5261:     }
 5262: }
 5263: ##############################################
 5264: 
 5265: =pod
 5266: 
 5267: =item * &designparm()
 5268: 
 5269: Inputs: $which parameter; $domain (usually will be undef)
 5270: 
 5271: Returns: value of designparamter $which
 5272: 
 5273: =cut
 5274: 
 5275: 
 5276: ##############################################
 5277: sub designparm {
 5278:     my ($which,$domain)=@_;
 5279:     if (exists($env{'environment.color.'.$which})) {
 5280:         return $env{'environment.color.'.$which};
 5281:     }
 5282:     $domain=&determinedomain($domain);
 5283:     my %domdesign;
 5284:     unless ($domain eq 'public') {
 5285:         %domdesign = &get_domainconf($domain);
 5286:     }
 5287:     my $output;
 5288:     if ($domdesign{$domain.'.'.$which} ne '') {
 5289:         $output = $domdesign{$domain.'.'.$which};
 5290:     } else {
 5291:         $output = $defaultdesign{$which};
 5292:     }
 5293:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 5294:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 5295:         if ($output =~ m{^/(adm|res)/}) {
 5296:             if ($output =~ m{^/res/}) {
 5297:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 5298:                 &Apache::lonnet::repcopy($local_name);
 5299:             }
 5300:             $output = &lonhttpdurl($output);
 5301:         }
 5302:     }
 5303:     return $output;
 5304: }
 5305: 
 5306: ##############################################
 5307: =pod
 5308: 
 5309: =item * &authorspace()
 5310: 
 5311: Inputs: $url (usually will be undef).
 5312: 
 5313: Returns: Path to Authoring Space containing the resource or 
 5314:          directory being viewed (or for which action is being taken). 
 5315:          If $url is provided, and begins /priv/<domain>/<uname>
 5316:          the path will be that portion of the $context argument.
 5317:          Otherwise the path will be for the author space of the current
 5318:          user when the current role is author, or for that of the 
 5319:          co-author/assistant co-author space when the current role 
 5320:          is co-author or assistant co-author.
 5321: 
 5322: =cut
 5323: 
 5324: sub authorspace {
 5325:     my ($url) = @_;
 5326:     if ($url ne '') {
 5327:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 5328:            return $1;
 5329:         }
 5330:     }
 5331:     my $caname = '';
 5332:     my $cadom = '';
 5333:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 5334:         ($cadom,$caname) =
 5335:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 5336:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 5337:         $caname = $env{'user.name'};
 5338:         $cadom = $env{'user.domain'};
 5339:     }
 5340:     if (($caname ne '') && ($cadom ne '')) {
 5341:         return "/priv/$cadom/$caname/";
 5342:     }
 5343:     return;
 5344: }
 5345: 
 5346: ##############################################
 5347: =pod
 5348: 
 5349: =item * &head_subbox()
 5350: 
 5351: Inputs: $content (contains HTML code with page functions, etc.)
 5352: 
 5353: Returns: HTML div with $content
 5354:          To be included in page header
 5355: 
 5356: =cut
 5357: 
 5358: sub head_subbox {
 5359:     my ($content)=@_;
 5360:     my $output =
 5361:         '<div class="LC_head_subbox">'
 5362:        .$content
 5363:        .'</div>'
 5364: }
 5365: 
 5366: ##############################################
 5367: =pod
 5368: 
 5369: =item * &CSTR_pageheader()
 5370: 
 5371: Input: (optional) filename from which breadcrumb trail is built.
 5372:        In most cases no input as needed, as $env{'request.filename'}
 5373:        is appropriate for use in building the breadcrumb trail.
 5374: 
 5375: Returns: HTML div with CSTR path and recent box
 5376:          To be included on Authoring Space pages
 5377: 
 5378: =cut
 5379: 
 5380: sub CSTR_pageheader {
 5381:     my ($trailfile) = @_;
 5382:     if ($trailfile eq '') {
 5383:         $trailfile = $env{'request.filename'};
 5384:     }
 5385: 
 5386: # this is for resources; directories have customtitle, and crumbs
 5387: # and select recent are created in lonpubdir.pm
 5388: 
 5389:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 5390:     my ($udom,$uname,$thisdisfn)=
 5391:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 5392:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 5393:     $formaction =~ s{/+}{/}g;
 5394: 
 5395:     my $parentpath = '';
 5396:     my $lastitem = '';
 5397:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 5398:         $parentpath = $1;
 5399:         $lastitem = $2;
 5400:     } else {
 5401:         $lastitem = $thisdisfn;
 5402:     }
 5403: 
 5404:     my $output =
 5405:          '<div>'
 5406:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 5407:         .'<b>'.&mt('Authoring Space:').'</b> '
 5408:         .'<form name="dirs" method="post" action="'.$formaction
 5409:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
 5410:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
 5411: 
 5412:     if ($lastitem) {
 5413:         $output .=
 5414:              '<span class="LC_filename">'
 5415:             .$lastitem
 5416:             .'</span>';
 5417:     }
 5418:     $output .=
 5419:          '<br />'
 5420:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 5421:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 5422:         .'</form>'
 5423:         .&Apache::lonmenu::constspaceform()
 5424:         .'</div>';
 5425: 
 5426:     return $output;
 5427: }
 5428: 
 5429: ###############################################
 5430: ###############################################
 5431: 
 5432: =pod
 5433: 
 5434: =back
 5435: 
 5436: =head1 HTML Helpers
 5437: 
 5438: =over 4
 5439: 
 5440: =item * &bodytag()
 5441: 
 5442: Returns a uniform header for LON-CAPA web pages.
 5443: 
 5444: Inputs: 
 5445: 
 5446: =over 4
 5447: 
 5448: =item * $title, A title to be displayed on the page.
 5449: 
 5450: =item * $function, the current role (can be undef).
 5451: 
 5452: =item * $addentries, extra parameters for the <body> tag.
 5453: 
 5454: =item * $bodyonly, if defined, only return the <body> tag.
 5455: 
 5456: =item * $domain, if defined, force a given domain.
 5457: 
 5458: =item * $forcereg, if page should register as content page (relevant for 
 5459:             text interface only)
 5460: 
 5461: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 5462:                      navigational links
 5463: 
 5464: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 5465: 
 5466: =item * $no_inline_link, if true and in remote mode, don't show the
 5467:          'Switch To Inline Menu' link
 5468: 
 5469: =item * $args, optional argument valid values are
 5470:             no_auto_mt_title -> prevents &mt()ing the title arg
 5471:             use_absolute     -> for external resource or syllabus, this will
 5472:                                 contain https://<hostname> if server uses
 5473:                                 https (as per hosts.tab), but request is for http
 5474:             hostname         -> hostname, from $r->hostname().
 5475: 
 5476: =item * $advtoolsref, optional argument, ref to an array containing
 5477:             inlineremote items to be added in "Functions" menu below
 5478:             breadcrumbs.
 5479: 
 5480: =back
 5481: 
 5482: Returns: A uniform header for LON-CAPA web pages.  
 5483: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 5484: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 5485: other decorations will be returned.
 5486: 
 5487: =cut
 5488: 
 5489: sub bodytag {
 5490:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 5491:         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_;
 5492: 
 5493:     my $public;
 5494:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 5495:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 5496:         $public = 1;
 5497:     }
 5498:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5499:     my $httphost = $args->{'use_absolute'};
 5500:     my $hostname = $args->{'hostname'};
 5501: 
 5502:     $function = &get_users_function() if (!$function);
 5503:     my $img =    &designparm($function.'.img',$domain);
 5504:     my $font =   &designparm($function.'.font',$domain);
 5505:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 5506: 
 5507:     my %design = ( 'style'   => 'margin-top: 0',
 5508: 		   'bgcolor' => $pgbg,
 5509: 		   'text'    => $font,
 5510:                    'alink'   => &designparm($function.'.alink',$domain),
 5511: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 5512: 		   'link'    => &designparm($function.'.link',$domain),);
 5513:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 5514: 
 5515:  # role and realm
 5516:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
 5517:     if ($realm) {
 5518:         $realm = '/'.$realm;
 5519:     }
 5520:     if ($role  eq 'ca') {
 5521:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 5522:         $realm = &plainname($rname,$rdom);
 5523:     } 
 5524: # realm
 5525:     if ($env{'request.course.id'}) {
 5526:         if ($env{'request.role'} !~ /^cr/) {
 5527:             $role = &Apache::lonnet::plaintext($role,&course_type());
 5528:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
 5529:             if ($env{'request.role.desc'}) {
 5530:                 $role = $env{'request.role.desc'};
 5531:             } else {
 5532:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
 5533:             }
 5534:         } else {
 5535:             $role = (split(/\//,$role,4))[-1];
 5536:         }
 5537:         if ($env{'request.course.sec'}) {
 5538:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
 5539:         }   
 5540: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 5541:     } else {
 5542:         $role = &Apache::lonnet::plaintext($role);
 5543:     }
 5544: 
 5545:     if (!$realm) { $realm='&nbsp;'; }
 5546: 
 5547:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 5548: 
 5549: # construct main body tag
 5550:     my $bodytag = "<body $extra_body_attr>".
 5551: 	&Apache::lontexconvert::init_math_support();
 5552: 
 5553:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 5554: 
 5555:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 5556:         return $bodytag;
 5557:     }
 5558: 
 5559:     if ($public) {
 5560: 	undef($role);
 5561:     }
 5562:     
 5563:     my $titleinfo = '<h1>'.$title.'</h1>';
 5564:     #
 5565:     # Extra info if you are the DC
 5566:     my $dc_info = '';
 5567:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 5568:                         $env{'course.'.$env{'request.course.id'}.
 5569:                                  '.domain'}.'/'})) {
 5570:         my $cid = $env{'request.course.id'};
 5571:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 5572:         $dc_info =~ s/\s+$//;
 5573:     }
 5574: 
 5575:     $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
 5576: 
 5577:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 5578: 
 5579: 
 5580: 
 5581:     my $funclist;
 5582:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
 5583:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
 5584:                     Apache::lonmenu::serverform();
 5585:         my $forbodytag;
 5586:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5587:                                             $forcereg,$args->{'group'},
 5588:                                             $args->{'bread_crumbs'},
 5589:                                             $advtoolsref,'','',\$forbodytag);
 5590:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 5591:             $funclist = $forbodytag;
 5592:         }
 5593:     } else {
 5594: 
 5595:         #    if ($env{'request.state'} eq 'construct') {
 5596:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 5597:         #    }
 5598: 
 5599:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 5600:             Apache::lonmenu::utilityfunctions($httphost), 'start');
 5601: 
 5602:         my ($left,$right) = Apache::lonmenu::primary_menu();
 5603: 
 5604:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 5605:             if ($dc_info) {
 5606:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 5607:             }
 5608:             $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 5609:                            <em>$realm</em> $dc_info</div>|;
 5610:             return $bodytag;
 5611:         }
 5612: 
 5613:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 5614:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 5615:         }
 5616: 
 5617:         $bodytag .= $right;
 5618: 
 5619:         if ($dc_info) {
 5620:             $dc_info = &dc_courseid_toggle($dc_info);
 5621:         }
 5622:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 5623: 
 5624:         #if directed to not display the secondary menu, don't.
 5625:         if ($args->{'no_secondary_menu'}) {
 5626:             return $bodytag;
 5627:         }
 5628:         #don't show menus for public users
 5629:         if (!$public){
 5630:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
 5631:             $bodytag .= Apache::lonmenu::serverform();
 5632:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 5633:             if ($env{'request.state'} eq 'construct') {
 5634:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 5635:                                 $args->{'bread_crumbs'},'','',$hostname);
 5636:             } elsif ($forcereg) {
 5637:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 5638:                                                             $args->{'group'},
 5639:                                                             $args->{'hide_buttons',
 5640:                                                             $hostname});
 5641:             } else {
 5642:                 my $forbodytag;
 5643:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5644:                                                     $forcereg,$args->{'group'},
 5645:                                                     $args->{'bread_crumbs'},
 5646:                                                     $advtoolsref,'',$hostname,
 5647:                                                     \$forbodytag);
 5648:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 5649:                     $bodytag .= $forbodytag;
 5650:                 }
 5651:             }
 5652:         }else{
 5653:             # this is to seperate menu from content when there's no secondary
 5654:             # menu. Especially needed for public accessible ressources.
 5655:             $bodytag .= '<hr style="clear:both" />';
 5656:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 5657:         }
 5658: 
 5659:         return $bodytag;
 5660:     }
 5661: 
 5662: #
 5663: # Top frame rendering, Remote is up
 5664: #
 5665: 
 5666:     my $imgsrc = $img;
 5667:     if ($img =~ /^\/adm/) {
 5668:         $imgsrc = &lonhttpdurl($img);
 5669:     }
 5670:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 5671: 
 5672:     my $help=($no_inline_link?''
 5673:               :&Apache::loncommon::top_nav_help('Help'));
 5674: 
 5675:     # Explicit link to get inline menu
 5676:     my $menu= ($no_inline_link?''
 5677:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
 5678: 
 5679:     if ($dc_info) {
 5680:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
 5681:     }
 5682: 
 5683:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 5684:     unless ($public) {
 5685:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
 5686:                                 undef,'LC_menubuttons_link');
 5687:     }
 5688: 
 5689:     unless ($env{'form.inhibitmenu'}) {
 5690:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
 5691:                        <ol class="LC_primary_menu LC_floatright LC_right">
 5692:                        <li>$help</li>
 5693:                        <li>$menu</li>
 5694:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
 5695:     }
 5696:     if ($env{'request.state'} eq 'construct') {
 5697:         if (!$public){
 5698:             if ($env{'request.state'} eq 'construct') {
 5699:                 $funclist = &Apache::lonhtmlcommon::scripttag(
 5700:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
 5701:                             &Apache::lonhtmlcommon::scripttag('','end').
 5702:                             &Apache::lonmenu::innerregister($forcereg,
 5703:                                                             $args->{'bread_crumbs'});
 5704:             }
 5705:         }
 5706:     }
 5707:     return $bodytag."\n".$funclist;
 5708: }
 5709: 
 5710: sub dc_courseid_toggle {
 5711:     my ($dc_info) = @_;
 5712:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 5713:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 5714:            &mt('(More ...)').'</a></span>'.
 5715:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 5716: }
 5717: 
 5718: sub make_attr_string {
 5719:     my ($register,$attr_ref) = @_;
 5720: 
 5721:     if ($attr_ref && !ref($attr_ref)) {
 5722: 	die("addentries Must be a hash ref ".
 5723: 	    join(':',caller(1))." ".
 5724: 	    join(':',caller(0))." ");
 5725:     }
 5726: 
 5727:     if ($register) {
 5728: 	my ($on_load,$on_unload);
 5729: 	foreach my $key (keys(%{$attr_ref})) {
 5730: 	    if      (lc($key) eq 'onload') {
 5731: 		$on_load.=$attr_ref->{$key}.';';
 5732: 		delete($attr_ref->{$key});
 5733: 
 5734: 	    } elsif (lc($key) eq 'onunload') {
 5735: 		$on_unload.=$attr_ref->{$key}.';';
 5736: 		delete($attr_ref->{$key});
 5737: 	    }
 5738: 	}
 5739:         if ($env{'environment.remote'} eq 'on') {
 5740:             $attr_ref->{'onload'}  =
 5741:                 &Apache::lonmenu::loadevents().  $on_load;
 5742:             $attr_ref->{'onunload'}=
 5743:                 &Apache::lonmenu::unloadevents().$on_unload;
 5744:         } else {  
 5745: 	    $attr_ref->{'onload'}  = $on_load;
 5746: 	    $attr_ref->{'onunload'}= $on_unload;
 5747:         }
 5748:     }
 5749: 
 5750:     my $attr_string;
 5751:     foreach my $attr (sort(keys(%$attr_ref))) {
 5752: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 5753:     }
 5754:     return $attr_string;
 5755: }
 5756: 
 5757: 
 5758: ###############################################
 5759: ###############################################
 5760: 
 5761: =pod
 5762: 
 5763: =item * &endbodytag()
 5764: 
 5765: Returns a uniform footer for LON-CAPA web pages.
 5766: 
 5767: Inputs: 1 - optional reference to an args hash
 5768: If in the hash, key for noredirectlink has a value which evaluates to true,
 5769: a 'Continue' link is not displayed if the page contains an
 5770: internal redirect in the <head></head> section,
 5771: i.e., $env{'internal.head.redirect'} exists   
 5772: 
 5773: =cut
 5774: 
 5775: sub endbodytag {
 5776:     my ($args) = @_;
 5777:     my $endbodytag;
 5778:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 5779:         $endbodytag='</body>';
 5780:     }
 5781:     if ( exists( $env{'internal.head.redirect'} ) ) {
 5782:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 5783: 	    $endbodytag=
 5784: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 5785: 	        &mt('Continue').'</a>'.
 5786: 	        $endbodytag;
 5787:         }
 5788:     }
 5789:     return $endbodytag;
 5790: }
 5791: 
 5792: =pod
 5793: 
 5794: =item * &standard_css()
 5795: 
 5796: Returns a style sheet
 5797: 
 5798: Inputs: (all optional)
 5799:             domain         -> force to color decorate a page for a specific
 5800:                                domain
 5801:             function       -> force usage of a specific rolish color scheme
 5802:             bgcolor        -> override the default page bgcolor
 5803: 
 5804: =cut
 5805: 
 5806: sub standard_css {
 5807:     my ($function,$domain,$bgcolor) = @_;
 5808:     $function  = &get_users_function() if (!$function);
 5809:     my $img    = &designparm($function.'.img',   $domain);
 5810:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 5811:     my $font   = &designparm($function.'.font',  $domain);
 5812:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 5813: #second colour for later usage
 5814:     my $sidebg = &designparm($function.'.sidebg',$domain);
 5815:     my $pgbg_or_bgcolor =
 5816: 	         $bgcolor ||
 5817: 	         &designparm($function.'.pgbg',  $domain);
 5818:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 5819:     my $alink  = &designparm($function.'.alink', $domain);
 5820:     my $vlink  = &designparm($function.'.vlink', $domain);
 5821:     my $link   = &designparm($function.'.link',  $domain);
 5822: 
 5823:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 5824:     my $mono                 = 'monospace';
 5825:     my $data_table_head      = $sidebg;
 5826:     my $data_table_light     = '#FAFAFA';
 5827:     my $data_table_dark      = '#E0E0E0';
 5828:     my $data_table_darker    = '#CCCCCC';
 5829:     my $data_table_highlight = '#FFFF00';
 5830:     my $mail_new             = '#FFBB77';
 5831:     my $mail_new_hover       = '#DD9955';
 5832:     my $mail_read            = '#BBBB77';
 5833:     my $mail_read_hover      = '#999944';
 5834:     my $mail_replied         = '#AAAA88';
 5835:     my $mail_replied_hover   = '#888855';
 5836:     my $mail_other           = '#99BBBB';
 5837:     my $mail_other_hover     = '#669999';
 5838:     my $table_header         = '#DDDDDD';
 5839:     my $feedback_link_bg     = '#BBBBBB';
 5840:     my $lg_border_color      = '#C8C8C8';
 5841:     my $button_hover         = '#BF2317';
 5842: 
 5843:     my $border = ($env{'browser.type'} eq 'explorer' ||
 5844:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 5845:                                              : '0 3px 0 4px';
 5846: 
 5847: 
 5848:     return <<END;
 5849: 
 5850: /* needed for iframe to allow 100% height in FF */
 5851: body, html { 
 5852:     margin: 0;
 5853:     padding: 0 0.5%;
 5854:     height: 99%; /* to avoid scrollbars */
 5855: }
 5856: 
 5857: body {
 5858:   font-family: $sans;
 5859:   line-height:130%;
 5860:   font-size:0.83em;
 5861:   color:$font;
 5862: }
 5863: 
 5864: a:focus,
 5865: a:focus img {
 5866:   color: red;
 5867: }
 5868: 
 5869: form, .inline {
 5870:   display: inline;
 5871: }
 5872: 
 5873: .LC_right {
 5874:   text-align:right;
 5875: }
 5876: 
 5877: .LC_middle {
 5878:   vertical-align:middle;
 5879: }
 5880: 
 5881: .LC_floatleft {
 5882:   float: left;
 5883: }
 5884: 
 5885: .LC_floatright {
 5886:   float: right;
 5887: }
 5888: 
 5889: .LC_400Box {
 5890:   width:400px;
 5891: }
 5892: 
 5893: .LC_iframecontainer {
 5894:     width: 98%;
 5895:     margin: 0;
 5896:     position: fixed;
 5897:     top: 8.5em;
 5898:     bottom: 0;
 5899: }
 5900: 
 5901: .LC_iframecontainer iframe{
 5902:     border: none;
 5903:     width: 100%;
 5904:     height: 100%;
 5905: }
 5906: 
 5907: .LC_filename {
 5908:   font-family: $mono;
 5909:   white-space:pre;
 5910:   font-size: 120%;
 5911: }
 5912: 
 5913: .LC_fileicon {
 5914:   border: none;
 5915:   height: 1.3em;
 5916:   vertical-align: text-bottom;
 5917:   margin-right: 0.3em;
 5918:   text-decoration:none;
 5919: }
 5920: 
 5921: .LC_setting {
 5922:   text-decoration:underline;
 5923: }
 5924: 
 5925: .LC_error {
 5926:   color: red;
 5927: }
 5928: 
 5929: .LC_warning {
 5930:   color: darkorange;
 5931: }
 5932: 
 5933: .LC_diff_removed {
 5934:   color: red;
 5935: }
 5936: 
 5937: .LC_info,
 5938: .LC_success,
 5939: .LC_diff_added {
 5940:   color: green;
 5941: }
 5942: 
 5943: div.LC_confirm_box {
 5944:   background-color: #FAFAFA;
 5945:   border: 1px solid $lg_border_color;
 5946:   margin-right: 0;
 5947:   padding: 5px;
 5948: }
 5949: 
 5950: div.LC_confirm_box .LC_error img,
 5951: div.LC_confirm_box .LC_success img {
 5952:   vertical-align: middle;
 5953: }
 5954: 
 5955: .LC_maxwidth {
 5956:   max-width: 100%;
 5957:   height: auto;
 5958: }
 5959: 
 5960: .LC_textsize_mobile {
 5961:   \@media only screen and (max-device-width: 480px) {
 5962:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
 5963:   }
 5964: }
 5965: 
 5966: .LC_icon {
 5967:   border: none;
 5968:   vertical-align: middle;
 5969: }
 5970: 
 5971: .LC_docs_spacer {
 5972:   width: 25px;
 5973:   height: 1px;
 5974:   border: none;
 5975: }
 5976: 
 5977: .LC_internal_info {
 5978:   color: #999999;
 5979: }
 5980: 
 5981: .LC_discussion {
 5982:   background: $data_table_dark;
 5983:   border: 1px solid black;
 5984:   margin: 2px;
 5985: }
 5986: 
 5987: .LC_disc_action_left {
 5988:   background: $sidebg;
 5989:   text-align: left;
 5990:   padding: 4px;
 5991:   margin: 2px;
 5992: }
 5993: 
 5994: .LC_disc_action_right {
 5995:   background: $sidebg;
 5996:   text-align: right;
 5997:   padding: 4px;
 5998:   margin: 2px;
 5999: }
 6000: 
 6001: .LC_disc_new_item {
 6002:   background: white;
 6003:   border: 2px solid red;
 6004:   margin: 4px;
 6005:   padding: 4px;
 6006: }
 6007: 
 6008: .LC_disc_old_item {
 6009:   background: white;
 6010:   margin: 4px;
 6011:   padding: 4px;
 6012: }
 6013: 
 6014: table.LC_pastsubmission {
 6015:   border: 1px solid black;
 6016:   margin: 2px;
 6017: }
 6018: 
 6019: table#LC_menubuttons {
 6020:   width: 100%;
 6021:   background: $pgbg;
 6022:   border: 2px;
 6023:   border-collapse: separate;
 6024:   padding: 0;
 6025: }
 6026: 
 6027: table#LC_title_bar a {
 6028:   color: $fontmenu;
 6029: }
 6030: 
 6031: table#LC_title_bar {
 6032:   clear: both;
 6033:   display: none;
 6034: }
 6035: 
 6036: table#LC_title_bar,
 6037: table.LC_breadcrumbs, /* obsolete? */
 6038: table#LC_title_bar.LC_with_remote {
 6039:   width: 100%;
 6040:   border-color: $pgbg;
 6041:   border-style: solid;
 6042:   border-width: $border;
 6043:   background: $pgbg;
 6044:   color: $fontmenu;
 6045:   border-collapse: collapse;
 6046:   padding: 0;
 6047:   margin: 0;
 6048: }
 6049: 
 6050: ul.LC_breadcrumb_tools_outerlist {
 6051:     margin: 0;
 6052:     padding: 0;
 6053:     position: relative;
 6054:     list-style: none;
 6055: }
 6056: ul.LC_breadcrumb_tools_outerlist li {
 6057:     display: inline;
 6058: }
 6059: 
 6060: .LC_breadcrumb_tools_navigation {
 6061:     padding: 0;
 6062:     margin: 0;
 6063:     float: left;
 6064: }
 6065: .LC_breadcrumb_tools_tools {
 6066:     padding: 0;
 6067:     margin: 0;
 6068:     float: right;
 6069: }
 6070: 
 6071: table#LC_title_bar td {
 6072:   background: $tabbg;
 6073: }
 6074: 
 6075: table#LC_menubuttons img {
 6076:   border: none;
 6077: }
 6078: 
 6079: .LC_breadcrumbs_component {
 6080:   float: right;
 6081:   margin: 0 1em;
 6082: }
 6083: .LC_breadcrumbs_component img {
 6084:   vertical-align: middle;
 6085: }
 6086: 
 6087: .LC_breadcrumbs_hoverable {
 6088:   background: $sidebg;
 6089: }
 6090: 
 6091: td.LC_table_cell_checkbox {
 6092:   text-align: center;
 6093: }
 6094: 
 6095: .LC_fontsize_small {
 6096:   font-size: 70%;
 6097: }
 6098: 
 6099: #LC_breadcrumbs {
 6100:   clear:both;
 6101:   background: $sidebg;
 6102:   border-bottom: 1px solid $lg_border_color;
 6103:   line-height: 2.5em;
 6104:   overflow: hidden;
 6105:   margin: 0;
 6106:   padding: 0;
 6107:   text-align: left;
 6108: }
 6109: 
 6110: .LC_head_subbox, .LC_actionbox {
 6111:   clear:both;
 6112:   background: #F8F8F8; /* $sidebg; */
 6113:   border: 1px solid $sidebg;
 6114:   margin: 0 0 10px 0;
 6115:   padding: 3px;
 6116:   text-align: left;
 6117: }
 6118: 
 6119: .LC_fontsize_medium {
 6120:   font-size: 85%;
 6121: }
 6122: 
 6123: .LC_fontsize_large {
 6124:   font-size: 120%;
 6125: }
 6126: 
 6127: .LC_menubuttons_inline_text {
 6128:   color: $font;
 6129:   font-size: 90%;
 6130:   padding-left:3px;
 6131: }
 6132: 
 6133: .LC_menubuttons_inline_text img{
 6134:   vertical-align: middle;
 6135: }
 6136: 
 6137: li.LC_menubuttons_inline_text img {
 6138:   cursor:pointer;
 6139:   text-decoration: none;
 6140: }
 6141: 
 6142: .LC_menubuttons_link {
 6143:   text-decoration: none;
 6144: }
 6145: 
 6146: .LC_menubuttons_category {
 6147:   color: $font;
 6148:   background: $pgbg;
 6149:   font-size: larger;
 6150:   font-weight: bold;
 6151: }
 6152: 
 6153: td.LC_menubuttons_text {
 6154:   color: $font;
 6155: }
 6156: 
 6157: .LC_current_location {
 6158:   background: $tabbg;
 6159: }
 6160: 
 6161: td.LC_zero_height {
 6162:   line-height: 0;
 6163:   cellpadding: 0;
 6164: }
 6165: 
 6166: table.LC_data_table {
 6167:   border: 1px solid #000000;
 6168:   border-collapse: separate;
 6169:   border-spacing: 1px;
 6170:   background: $pgbg;
 6171: }
 6172: 
 6173: .LC_data_table_dense {
 6174:   font-size: small;
 6175: }
 6176: 
 6177: table.LC_nested_outer {
 6178:   border: 1px solid #000000;
 6179:   border-collapse: collapse;
 6180:   border-spacing: 0;
 6181:   width: 100%;
 6182: }
 6183: 
 6184: table.LC_innerpickbox,
 6185: table.LC_nested {
 6186:   border: none;
 6187:   border-collapse: collapse;
 6188:   border-spacing: 0;
 6189:   width: 100%;
 6190: }
 6191: 
 6192: table.LC_data_table tr th,
 6193: table.LC_calendar tr th,
 6194: table.LC_prior_tries tr th,
 6195: table.LC_innerpickbox tr th {
 6196:   font-weight: bold;
 6197:   background-color: $data_table_head;
 6198:   color:$fontmenu;
 6199:   font-size:90%;
 6200: }
 6201: 
 6202: table.LC_innerpickbox tr th,
 6203: table.LC_innerpickbox tr td {
 6204:   vertical-align: top;
 6205: }
 6206: 
 6207: table.LC_data_table tr.LC_info_row > td {
 6208:   background-color: #CCCCCC;
 6209:   font-weight: bold;
 6210:   text-align: left;
 6211: }
 6212: 
 6213: table.LC_data_table tr.LC_odd_row > td {
 6214:   background-color: $data_table_light;
 6215:   padding: 2px;
 6216:   vertical-align: top;
 6217: }
 6218: 
 6219: table.LC_pick_box tr > td.LC_odd_row {
 6220:   background-color: $data_table_light;
 6221:   vertical-align: top;
 6222: }
 6223: 
 6224: table.LC_data_table tr.LC_even_row > td {
 6225:   background-color: $data_table_dark;
 6226:   padding: 2px;
 6227:   vertical-align: top;
 6228: }
 6229: 
 6230: table.LC_pick_box tr > td.LC_even_row {
 6231:   background-color: $data_table_dark;
 6232:   vertical-align: top;
 6233: }
 6234: 
 6235: table.LC_data_table tr.LC_data_table_highlight td {
 6236:   background-color: $data_table_darker;
 6237: }
 6238: 
 6239: table.LC_data_table tr td.LC_leftcol_header {
 6240:   background-color: $data_table_head;
 6241:   font-weight: bold;
 6242: }
 6243: 
 6244: table.LC_data_table tr.LC_empty_row td,
 6245: table.LC_nested tr.LC_empty_row td {
 6246:   font-weight: bold;
 6247:   font-style: italic;
 6248:   text-align: center;
 6249:   padding: 8px;
 6250: }
 6251: 
 6252: table.LC_data_table tr.LC_empty_row td,
 6253: table.LC_data_table tr.LC_footer_row td {
 6254:   background-color: $sidebg;
 6255: }
 6256: 
 6257: table.LC_nested tr.LC_empty_row td {
 6258:   background-color: #FFFFFF;
 6259: }
 6260: 
 6261: table.LC_caption {
 6262: }
 6263: 
 6264: table.LC_nested tr.LC_empty_row td {
 6265:   padding: 4ex
 6266: }
 6267: 
 6268: table.LC_nested_outer tr th {
 6269:   font-weight: bold;
 6270:   color:$fontmenu;
 6271:   background-color: $data_table_head;
 6272:   font-size: small;
 6273:   border-bottom: 1px solid #000000;
 6274: }
 6275: 
 6276: table.LC_nested_outer tr td.LC_subheader {
 6277:   background-color: $data_table_head;
 6278:   font-weight: bold;
 6279:   font-size: small;
 6280:   border-bottom: 1px solid #000000;
 6281:   text-align: right;
 6282: }
 6283: 
 6284: table.LC_nested tr.LC_info_row td {
 6285:   background-color: #CCCCCC;
 6286:   font-weight: bold;
 6287:   font-size: small;
 6288:   text-align: center;
 6289: }
 6290: 
 6291: table.LC_nested tr.LC_info_row td.LC_left_item,
 6292: table.LC_nested_outer tr th.LC_left_item {
 6293:   text-align: left;
 6294: }
 6295: 
 6296: table.LC_nested td {
 6297:   background-color: #FFFFFF;
 6298:   font-size: small;
 6299: }
 6300: 
 6301: table.LC_nested_outer tr th.LC_right_item,
 6302: table.LC_nested tr.LC_info_row td.LC_right_item,
 6303: table.LC_nested tr.LC_odd_row td.LC_right_item,
 6304: table.LC_nested tr td.LC_right_item {
 6305:   text-align: right;
 6306: }
 6307: 
 6308: table.LC_nested tr.LC_odd_row td {
 6309:   background-color: #EEEEEE;
 6310: }
 6311: 
 6312: table.LC_createuser {
 6313: }
 6314: 
 6315: table.LC_createuser tr.LC_section_row td {
 6316:   font-size: small;
 6317: }
 6318: 
 6319: table.LC_createuser tr.LC_info_row td  {
 6320:   background-color: #CCCCCC;
 6321:   font-weight: bold;
 6322:   text-align: center;
 6323: }
 6324: 
 6325: table.LC_calendar {
 6326:   border: 1px solid #000000;
 6327:   border-collapse: collapse;
 6328:   width: 98%;
 6329: }
 6330: 
 6331: table.LC_calendar_pickdate {
 6332:   font-size: xx-small;
 6333: }
 6334: 
 6335: table.LC_calendar tr td {
 6336:   border: 1px solid #000000;
 6337:   vertical-align: top;
 6338:   width: 14%;
 6339: }
 6340: 
 6341: table.LC_calendar tr td.LC_calendar_day_empty {
 6342:   background-color: $data_table_dark;
 6343: }
 6344: 
 6345: table.LC_calendar tr td.LC_calendar_day_current {
 6346:   background-color: $data_table_highlight;
 6347: }
 6348: 
 6349: table.LC_data_table tr td.LC_mail_new {
 6350:   background-color: $mail_new;
 6351: }
 6352: 
 6353: table.LC_data_table tr.LC_mail_new:hover {
 6354:   background-color: $mail_new_hover;
 6355: }
 6356: 
 6357: table.LC_data_table tr td.LC_mail_read {
 6358:   background-color: $mail_read;
 6359: }
 6360: 
 6361: /*
 6362: table.LC_data_table tr.LC_mail_read:hover {
 6363:   background-color: $mail_read_hover;
 6364: }
 6365: */
 6366: 
 6367: table.LC_data_table tr td.LC_mail_replied {
 6368:   background-color: $mail_replied;
 6369: }
 6370: 
 6371: /*
 6372: table.LC_data_table tr.LC_mail_replied:hover {
 6373:   background-color: $mail_replied_hover;
 6374: }
 6375: */
 6376: 
 6377: table.LC_data_table tr td.LC_mail_other {
 6378:   background-color: $mail_other;
 6379: }
 6380: 
 6381: /*
 6382: table.LC_data_table tr.LC_mail_other:hover {
 6383:   background-color: $mail_other_hover;
 6384: }
 6385: */
 6386: 
 6387: table.LC_data_table tr > td.LC_browser_file,
 6388: table.LC_data_table tr > td.LC_browser_file_published {
 6389:   background: #AAEE77;
 6390: }
 6391: 
 6392: table.LC_data_table tr > td.LC_browser_file_locked,
 6393: table.LC_data_table tr > td.LC_browser_file_unpublished {
 6394:   background: #FFAA99;
 6395: }
 6396: 
 6397: table.LC_data_table tr > td.LC_browser_file_obsolete {
 6398:   background: #888888;
 6399: }
 6400: 
 6401: table.LC_data_table tr > td.LC_browser_file_modified,
 6402: table.LC_data_table tr > td.LC_browser_file_metamodified {
 6403:   background: #F8F866;
 6404: }
 6405: 
 6406: table.LC_data_table tr.LC_browser_folder > td {
 6407:   background: #E0E8FF;
 6408: }
 6409: 
 6410: table.LC_data_table tr > td.LC_roles_is {
 6411:   /* background: #77FF77; */
 6412: }
 6413: 
 6414: table.LC_data_table tr > td.LC_roles_future {
 6415:   border-right: 8px solid #FFFF77;
 6416: }
 6417: 
 6418: table.LC_data_table tr > td.LC_roles_will {
 6419:   border-right: 8px solid #FFAA77;
 6420: }
 6421: 
 6422: table.LC_data_table tr > td.LC_roles_expired {
 6423:   border-right: 8px solid #FF7777;
 6424: }
 6425: 
 6426: table.LC_data_table tr > td.LC_roles_will_not {
 6427:   border-right: 8px solid #AAFF77;
 6428: }
 6429: 
 6430: table.LC_data_table tr > td.LC_roles_selected {
 6431:   border-right: 8px solid #11CC55;
 6432: }
 6433: 
 6434: span.LC_current_location {
 6435:   font-size:larger;
 6436:   background: $pgbg;
 6437: }
 6438: 
 6439: span.LC_current_nav_location {
 6440:   font-weight:bold;
 6441:   background: $sidebg;
 6442: }
 6443: 
 6444: span.LC_parm_menu_item {
 6445:   font-size: larger;
 6446: }
 6447: 
 6448: span.LC_parm_scope_all {
 6449:   color: red;
 6450: }
 6451: 
 6452: span.LC_parm_scope_folder {
 6453:   color: green;
 6454: }
 6455: 
 6456: span.LC_parm_scope_resource {
 6457:   color: orange;
 6458: }
 6459: 
 6460: span.LC_parm_part {
 6461:   color: blue;
 6462: }
 6463: 
 6464: span.LC_parm_folder,
 6465: span.LC_parm_symb {
 6466:   font-size: x-small;
 6467:   font-family: $mono;
 6468:   color: #AAAAAA;
 6469: }
 6470: 
 6471: ul.LC_parm_parmlist li {
 6472:   display: inline-block;
 6473:   padding: 0.3em 0.8em;
 6474:   vertical-align: top;
 6475:   width: 150px;
 6476:   border-top:1px solid $lg_border_color;
 6477: }
 6478: 
 6479: td.LC_parm_overview_level_menu,
 6480: td.LC_parm_overview_map_menu,
 6481: td.LC_parm_overview_parm_selectors,
 6482: td.LC_parm_overview_restrictions  {
 6483:   border: 1px solid black;
 6484:   border-collapse: collapse;
 6485: }
 6486: 
 6487: table.LC_parm_overview_restrictions td {
 6488:   border-width: 1px 4px 1px 4px;
 6489:   border-style: solid;
 6490:   border-color: $pgbg;
 6491:   text-align: center;
 6492: }
 6493: 
 6494: table.LC_parm_overview_restrictions th {
 6495:   background: $tabbg;
 6496:   border-width: 1px 4px 1px 4px;
 6497:   border-style: solid;
 6498:   border-color: $pgbg;
 6499: }
 6500: 
 6501: table#LC_helpmenu {
 6502:   border: none;
 6503:   height: 55px;
 6504:   border-spacing: 0;
 6505: }
 6506: 
 6507: table#LC_helpmenu fieldset legend {
 6508:   font-size: larger;
 6509: }
 6510: 
 6511: table#LC_helpmenu_links {
 6512:   width: 100%;
 6513:   border: 1px solid black;
 6514:   background: $pgbg;
 6515:   padding: 0;
 6516:   border-spacing: 1px;
 6517: }
 6518: 
 6519: table#LC_helpmenu_links tr td {
 6520:   padding: 1px;
 6521:   background: $tabbg;
 6522:   text-align: center;
 6523:   font-weight: bold;
 6524: }
 6525: 
 6526: table#LC_helpmenu_links a:link,
 6527: table#LC_helpmenu_links a:visited,
 6528: table#LC_helpmenu_links a:active {
 6529:   text-decoration: none;
 6530:   color: $font;
 6531: }
 6532: 
 6533: table#LC_helpmenu_links a:hover {
 6534:   text-decoration: underline;
 6535:   color: $vlink;
 6536: }
 6537: 
 6538: .LC_chrt_popup_exists {
 6539:   border: 1px solid #339933;
 6540:   margin: -1px;
 6541: }
 6542: 
 6543: .LC_chrt_popup_up {
 6544:   border: 1px solid yellow;
 6545:   margin: -1px;
 6546: }
 6547: 
 6548: .LC_chrt_popup {
 6549:   border: 1px solid #8888FF;
 6550:   background: #CCCCFF;
 6551: }
 6552: 
 6553: table.LC_pick_box {
 6554:   border-collapse: separate;
 6555:   background: white;
 6556:   border: 1px solid black;
 6557:   border-spacing: 1px;
 6558: }
 6559: 
 6560: table.LC_pick_box td.LC_pick_box_title {
 6561:   background: $sidebg;
 6562:   font-weight: bold;
 6563:   text-align: left;
 6564:   vertical-align: top;
 6565:   width: 184px;
 6566:   padding: 8px;
 6567: }
 6568: 
 6569: table.LC_pick_box td.LC_pick_box_value {
 6570:   text-align: left;
 6571:   padding: 8px;
 6572: }
 6573: 
 6574: table.LC_pick_box td.LC_pick_box_select {
 6575:   text-align: left;
 6576:   padding: 8px;
 6577: }
 6578: 
 6579: table.LC_pick_box td.LC_pick_box_separator {
 6580:   padding: 0;
 6581:   height: 1px;
 6582:   background: black;
 6583: }
 6584: 
 6585: table.LC_pick_box td.LC_pick_box_submit {
 6586:   text-align: right;
 6587: }
 6588: 
 6589: table.LC_pick_box td.LC_evenrow_value {
 6590:   text-align: left;
 6591:   padding: 8px;
 6592:   background-color: $data_table_light;
 6593: }
 6594: 
 6595: table.LC_pick_box td.LC_oddrow_value {
 6596:   text-align: left;
 6597:   padding: 8px;
 6598:   background-color: $data_table_light;
 6599: }
 6600: 
 6601: span.LC_helpform_receipt_cat {
 6602:   font-weight: bold;
 6603: }
 6604: 
 6605: table.LC_group_priv_box {
 6606:   background: white;
 6607:   border: 1px solid black;
 6608:   border-spacing: 1px;
 6609: }
 6610: 
 6611: table.LC_group_priv_box td.LC_pick_box_title {
 6612:   background: $tabbg;
 6613:   font-weight: bold;
 6614:   text-align: right;
 6615:   width: 184px;
 6616: }
 6617: 
 6618: table.LC_group_priv_box td.LC_groups_fixed {
 6619:   background: $data_table_light;
 6620:   text-align: center;
 6621: }
 6622: 
 6623: table.LC_group_priv_box td.LC_groups_optional {
 6624:   background: $data_table_dark;
 6625:   text-align: center;
 6626: }
 6627: 
 6628: table.LC_group_priv_box td.LC_groups_functionality {
 6629:   background: $data_table_darker;
 6630:   text-align: center;
 6631:   font-weight: bold;
 6632: }
 6633: 
 6634: table.LC_group_priv td {
 6635:   text-align: left;
 6636:   padding: 0;
 6637: }
 6638: 
 6639: .LC_navbuttons {
 6640:   margin: 2ex 0ex 2ex 0ex;
 6641: }
 6642: 
 6643: .LC_topic_bar {
 6644:   font-weight: bold;
 6645:   background: $tabbg;
 6646:   margin: 1em 0em 1em 2em;
 6647:   padding: 3px;
 6648:   font-size: 1.2em;
 6649: }
 6650: 
 6651: .LC_topic_bar span {
 6652:   left: 0.5em;
 6653:   position: absolute;
 6654:   vertical-align: middle;
 6655:   font-size: 1.2em;
 6656: }
 6657: 
 6658: table.LC_course_group_status {
 6659:   margin: 20px;
 6660: }
 6661: 
 6662: table.LC_status_selector td {
 6663:   vertical-align: top;
 6664:   text-align: center;
 6665:   padding: 4px;
 6666: }
 6667: 
 6668: div.LC_feedback_link {
 6669:   clear: both;
 6670:   background: $sidebg;
 6671:   width: 100%;
 6672:   padding-bottom: 10px;
 6673:   border: 1px $tabbg solid;
 6674:   height: 22px;
 6675:   line-height: 22px;
 6676:   padding-top: 5px;
 6677: }
 6678: 
 6679: div.LC_feedback_link img {
 6680:   height: 22px;
 6681:   vertical-align:middle;
 6682: }
 6683: 
 6684: div.LC_feedback_link a {
 6685:   text-decoration: none;
 6686: }
 6687: 
 6688: div.LC_comblock {
 6689:   display:inline;
 6690:   color:$font;
 6691:   font-size:90%;
 6692: }
 6693: 
 6694: div.LC_feedback_link div.LC_comblock {
 6695:   padding-left:5px;
 6696: }
 6697: 
 6698: div.LC_feedback_link div.LC_comblock a {
 6699:   color:$font;
 6700: }
 6701: 
 6702: span.LC_feedback_link {
 6703:   /* background: $feedback_link_bg; */
 6704:   font-size: larger;
 6705: }
 6706: 
 6707: span.LC_message_link {
 6708:   /* background: $feedback_link_bg; */
 6709:   font-size: larger;
 6710:   position: absolute;
 6711:   right: 1em;
 6712: }
 6713: 
 6714: table.LC_prior_tries {
 6715:   border: 1px solid #000000;
 6716:   border-collapse: separate;
 6717:   border-spacing: 1px;
 6718: }
 6719: 
 6720: table.LC_prior_tries td {
 6721:   padding: 2px;
 6722: }
 6723: 
 6724: .LC_answer_correct {
 6725:   background: lightgreen;
 6726:   color: darkgreen;
 6727:   padding: 6px;
 6728: }
 6729: 
 6730: .LC_answer_charged_try {
 6731:   background: #FFAAAA;
 6732:   color: darkred;
 6733:   padding: 6px;
 6734: }
 6735: 
 6736: .LC_answer_not_charged_try,
 6737: .LC_answer_no_grade,
 6738: .LC_answer_late {
 6739:   background: lightyellow;
 6740:   color: black;
 6741:   padding: 6px;
 6742: }
 6743: 
 6744: .LC_answer_previous {
 6745:   background: lightblue;
 6746:   color: darkblue;
 6747:   padding: 6px;
 6748: }
 6749: 
 6750: .LC_answer_no_message {
 6751:   background: #FFFFFF;
 6752:   color: black;
 6753:   padding: 6px;
 6754: }
 6755: 
 6756: .LC_answer_unknown,
 6757: .LC_answer_warning {
 6758:   background: orange;
 6759:   color: black;
 6760:   padding: 6px;
 6761: }
 6762: 
 6763: span.LC_prior_numerical,
 6764: span.LC_prior_string,
 6765: span.LC_prior_custom,
 6766: span.LC_prior_reaction,
 6767: span.LC_prior_math {
 6768:   font-family: $mono;
 6769:   white-space: pre;
 6770: }
 6771: 
 6772: span.LC_prior_string {
 6773:   font-family: $mono;
 6774:   white-space: pre;
 6775: }
 6776: 
 6777: table.LC_prior_option {
 6778:   width: 100%;
 6779:   border-collapse: collapse;
 6780: }
 6781: 
 6782: table.LC_prior_rank,
 6783: table.LC_prior_match {
 6784:   border-collapse: collapse;
 6785: }
 6786: 
 6787: table.LC_prior_option tr td,
 6788: table.LC_prior_rank tr td,
 6789: table.LC_prior_match tr td {
 6790:   border: 1px solid #000000;
 6791: }
 6792: 
 6793: .LC_nobreak {
 6794:   white-space: nowrap;
 6795: }
 6796: 
 6797: span.LC_cusr_emph {
 6798:   font-style: italic;
 6799: }
 6800: 
 6801: span.LC_cusr_subheading {
 6802:   font-weight: normal;
 6803:   font-size: 85%;
 6804: }
 6805: 
 6806: div.LC_docs_entry_move {
 6807:   border: 1px solid #BBBBBB;
 6808:   background: #DDDDDD;
 6809:   width: 22px;
 6810:   padding: 1px;
 6811:   margin: 0;
 6812: }
 6813: 
 6814: table.LC_data_table tr > td.LC_docs_entry_commands,
 6815: table.LC_data_table tr > td.LC_docs_entry_parameter {
 6816:   font-size: x-small;
 6817: }
 6818: 
 6819: .LC_docs_entry_parameter {
 6820:   white-space: nowrap;
 6821: }
 6822: 
 6823: .LC_docs_copy {
 6824:   color: #000099;
 6825: }
 6826: 
 6827: .LC_docs_cut {
 6828:   color: #550044;
 6829: }
 6830: 
 6831: .LC_docs_rename {
 6832:   color: #009900;
 6833: }
 6834: 
 6835: .LC_docs_remove {
 6836:   color: #990000;
 6837: }
 6838: 
 6839: .LC_domprefs_email,
 6840: .LC_docs_reinit_warn,
 6841: .LC_docs_ext_edit {
 6842:   font-size: x-small;
 6843: }
 6844: 
 6845: table.LC_docs_adddocs td,
 6846: table.LC_docs_adddocs th {
 6847:   border: 1px solid #BBBBBB;
 6848:   padding: 4px;
 6849:   background: #DDDDDD;
 6850: }
 6851: 
 6852: table.LC_sty_begin {
 6853:   background: #BBFFBB;
 6854: }
 6855: 
 6856: table.LC_sty_end {
 6857:   background: #FFBBBB;
 6858: }
 6859: 
 6860: table.LC_double_column {
 6861:   border-width: 0;
 6862:   border-collapse: collapse;
 6863:   width: 100%;
 6864:   padding: 2px;
 6865: }
 6866: 
 6867: table.LC_double_column tr td.LC_left_col {
 6868:   top: 2px;
 6869:   left: 2px;
 6870:   width: 47%;
 6871:   vertical-align: top;
 6872: }
 6873: 
 6874: table.LC_double_column tr td.LC_right_col {
 6875:   top: 2px;
 6876:   right: 2px;
 6877:   width: 47%;
 6878:   vertical-align: top;
 6879: }
 6880: 
 6881: div.LC_left_float {
 6882:   float: left;
 6883:   padding-right: 5%;
 6884:   padding-bottom: 4px;
 6885: }
 6886: 
 6887: div.LC_clear_float_header {
 6888:   padding-bottom: 2px;
 6889: }
 6890: 
 6891: div.LC_clear_float_footer {
 6892:   padding-top: 10px;
 6893:   clear: both;
 6894: }
 6895: 
 6896: div.LC_grade_show_user {
 6897: /*  border-left: 5px solid $sidebg; */
 6898:   border-top: 5px solid #000000;
 6899:   margin: 50px 0 0 0;
 6900:   padding: 15px 0 5px 10px;
 6901: }
 6902: 
 6903: div.LC_grade_show_user_odd_row {
 6904: /*  border-left: 5px solid #000000; */
 6905: }
 6906: 
 6907: div.LC_grade_show_user div.LC_Box {
 6908:   margin-right: 50px;
 6909: }
 6910: 
 6911: div.LC_grade_submissions,
 6912: div.LC_grade_message_center,
 6913: div.LC_grade_info_links {
 6914:   margin: 5px;
 6915:   width: 99%;
 6916:   background: #FFFFFF;
 6917: }
 6918: 
 6919: div.LC_grade_submissions_header,
 6920: div.LC_grade_message_center_header {
 6921:   font-weight: bold;
 6922:   font-size: large;
 6923: }
 6924: 
 6925: div.LC_grade_submissions_body,
 6926: div.LC_grade_message_center_body {
 6927:   border: 1px solid black;
 6928:   width: 99%;
 6929:   background: #FFFFFF;
 6930: }
 6931: 
 6932: table.LC_scantron_action {
 6933:   width: 100%;
 6934: }
 6935: 
 6936: table.LC_scantron_action tr th {
 6937:   font-weight:bold;
 6938:   font-style:normal;
 6939: }
 6940: 
 6941: .LC_edit_problem_header,
 6942: div.LC_edit_problem_footer {
 6943:   font-weight: normal;
 6944:   font-size:  medium;
 6945:   margin: 2px;
 6946:   background-color: $sidebg;
 6947: }
 6948: 
 6949: div.LC_edit_problem_header,
 6950: div.LC_edit_problem_header div,
 6951: div.LC_edit_problem_footer,
 6952: div.LC_edit_problem_footer div,
 6953: div.LC_edit_problem_editxml_header,
 6954: div.LC_edit_problem_editxml_header div {
 6955:   z-index: 100;
 6956: }
 6957: 
 6958: div.LC_edit_problem_header_title {
 6959:   font-weight: bold;
 6960:   font-size: larger;
 6961:   background: $tabbg;
 6962:   padding: 3px;
 6963:   margin: 0 0 5px 0;
 6964: }
 6965: 
 6966: table.LC_edit_problem_header_title {
 6967:   width: 100%;
 6968:   background: $tabbg;
 6969: }
 6970: 
 6971: div.LC_edit_actionbar {
 6972:     background-color: $sidebg;
 6973:     margin: 0;
 6974:     padding: 0;
 6975:     line-height: 200%;
 6976: }
 6977: 
 6978: div.LC_edit_actionbar div{
 6979:     padding: 0;
 6980:     margin: 0;
 6981:     display: inline-block;
 6982: }
 6983: 
 6984: .LC_edit_opt {
 6985:   padding-left: 1em;
 6986:   white-space: nowrap;
 6987: }
 6988: 
 6989: .LC_edit_problem_latexhelper{
 6990:     text-align: right;
 6991: }
 6992: 
 6993: #LC_edit_problem_colorful div{
 6994:     margin-left: 40px;
 6995: }
 6996: 
 6997: #LC_edit_problem_codemirror div{
 6998:     margin-left: 0px;
 6999: }
 7000: 
 7001: img.stift {
 7002:   border-width: 0;
 7003:   vertical-align: middle;
 7004: }
 7005: 
 7006: table td.LC_mainmenu_col_fieldset {
 7007:   vertical-align: top;
 7008: }
 7009: 
 7010: div.LC_createcourse {
 7011:   margin: 10px 10px 10px 10px;
 7012: }
 7013: 
 7014: .LC_dccid {
 7015:   float: right;
 7016:   margin: 0.2em 0 0 0;
 7017:   padding: 0;
 7018:   font-size: 90%;
 7019:   display:none;
 7020: }
 7021: 
 7022: ol.LC_primary_menu a:hover,
 7023: ol#LC_MenuBreadcrumbs a:hover,
 7024: ol#LC_PathBreadcrumbs a:hover,
 7025: ul#LC_secondary_menu a:hover,
 7026: .LC_FormSectionClearButton input:hover
 7027: ul.LC_TabContent   li:hover a {
 7028:   color:$button_hover;
 7029:   text-decoration:none;
 7030: }
 7031: 
 7032: h1 {
 7033:   padding: 0;
 7034:   line-height:130%;
 7035: }
 7036: 
 7037: h2,
 7038: h3,
 7039: h4,
 7040: h5,
 7041: h6 {
 7042:   margin: 5px 0 5px 0;
 7043:   padding: 0;
 7044:   line-height:130%;
 7045: }
 7046: 
 7047: .LC_hcell {
 7048:   padding:3px 15px 3px 15px;
 7049:   margin: 0;
 7050:   background-color:$tabbg;
 7051:   color:$fontmenu;
 7052:   border-bottom:solid 1px $lg_border_color;
 7053: }
 7054: 
 7055: .LC_Box > .LC_hcell {
 7056:   margin: 0 -10px 10px -10px;
 7057: }
 7058: 
 7059: .LC_noBorder {
 7060:   border: 0;
 7061: }
 7062: 
 7063: .LC_FormSectionClearButton input {
 7064:   background-color:transparent;
 7065:   border: none;
 7066:   cursor:pointer;
 7067:   text-decoration:underline;
 7068: }
 7069: 
 7070: .LC_help_open_topic {
 7071:   color: #FFFFFF;
 7072:   background-color: #EEEEFF;
 7073:   margin: 1px;
 7074:   padding: 4px;
 7075:   border: 1px solid #000033;
 7076:   white-space: nowrap;
 7077:   /* vertical-align: middle; */
 7078: }
 7079: 
 7080: dl,
 7081: ul,
 7082: div,
 7083: fieldset {
 7084:   margin: 10px 10px 10px 0;
 7085:   /* overflow: hidden; */
 7086: }
 7087: 
 7088: article.geogebraweb div {
 7089:     margin: 0;
 7090: }
 7091: 
 7092: fieldset > legend {
 7093:   font-weight: bold;
 7094:   padding: 0 5px 0 5px;
 7095: }
 7096: 
 7097: #LC_nav_bar {
 7098:   float: left;
 7099:   background-color: $pgbg_or_bgcolor;
 7100:   margin: 0 0 2px 0;
 7101: }
 7102: 
 7103: #LC_realm {
 7104:   margin: 0.2em 0 0 0;
 7105:   padding: 0;
 7106:   font-weight: bold;
 7107:   text-align: center;
 7108:   background-color: $pgbg_or_bgcolor;
 7109: }
 7110: 
 7111: #LC_nav_bar em {
 7112:   font-weight: bold;
 7113:   font-style: normal;
 7114: }
 7115: 
 7116: ol.LC_primary_menu {
 7117:   margin: 0;
 7118:   padding: 0;
 7119: }
 7120: 
 7121: ol#LC_PathBreadcrumbs {
 7122:   margin: 0;
 7123: }
 7124: 
 7125: ol.LC_primary_menu li {
 7126:   color: RGB(80, 80, 80);
 7127:   vertical-align: middle;
 7128:   text-align: left;
 7129:   list-style: none;
 7130:   position: relative;
 7131:   float: left;
 7132:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
 7133:   line-height: 1.5em;
 7134: }
 7135: 
 7136: ol.LC_primary_menu li a, 
 7137: ol.LC_primary_menu li p {
 7138:   display: block;
 7139:   margin: 0;
 7140:   padding: 0 5px 0 10px;
 7141:   text-decoration: none;
 7142: }
 7143: 
 7144: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
 7145:   display: inline-block;
 7146:   width: 95%;
 7147:   text-align: left;
 7148: }
 7149: 
 7150: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
 7151:   display: inline-block;
 7152:   width: 5%;
 7153:   float: right;
 7154:   text-align: right;
 7155:   font-size: 70%;
 7156: }
 7157: 
 7158: ol.LC_primary_menu ul {
 7159:   display: none;
 7160:   width: 15em;
 7161:   background-color: $data_table_light;
 7162:   position: absolute;
 7163:   top: 100%;
 7164: }
 7165: 
 7166: ol.LC_primary_menu ul ul {
 7167:   left: 100%;
 7168:   top: 0;
 7169: }
 7170: 
 7171: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
 7172:   display: block;
 7173:   position: absolute;
 7174:   margin: 0;
 7175:   padding: 0;
 7176:   z-index: 2;
 7177: }
 7178: 
 7179: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 7180: /* First Submenu -> size should be smaller than the menu title of the whole menu */
 7181:   font-size: 90%;
 7182:   vertical-align: top;
 7183:   float: none;
 7184:   border-left: 1px solid black;
 7185:   border-right: 1px solid black;
 7186: /* A dark bottom border to visualize different menu options;
 7187: overwritten in the create_submenu routine for the last border-bottom of the menu */
 7188:   border-bottom: 1px solid $data_table_dark;
 7189: }
 7190: 
 7191: ol.LC_primary_menu li li p:hover {
 7192:   color:$button_hover;
 7193:   text-decoration:none;
 7194:   background-color:$data_table_dark;
 7195: }
 7196: 
 7197: ol.LC_primary_menu li li a:hover {
 7198:    color:$button_hover;
 7199:    background-color:$data_table_dark;
 7200: }
 7201: 
 7202: /* Font-size equal to the size of the predecessors*/
 7203: ol.LC_primary_menu li:hover li li {
 7204:   font-size: 100%;
 7205: }
 7206: 
 7207: ol.LC_primary_menu li img {
 7208:   vertical-align: bottom;
 7209:   height: 1.1em;
 7210:   margin: 0.2em 0 0 0;
 7211: }
 7212: 
 7213: ol.LC_primary_menu a {
 7214:   color: RGB(80, 80, 80);
 7215:   text-decoration: none;
 7216: }
 7217: 
 7218: ol.LC_primary_menu a.LC_new_message {
 7219:   font-weight:bold;
 7220:   color: darkred;
 7221: }
 7222: 
 7223: ol.LC_docs_parameters {
 7224:   margin-left: 0;
 7225:   padding: 0;
 7226:   list-style: none;
 7227: }
 7228: 
 7229: ol.LC_docs_parameters li {
 7230:   margin: 0;
 7231:   padding-right: 20px;
 7232:   display: inline;
 7233: }
 7234: 
 7235: ol.LC_docs_parameters li:before {
 7236:   content: "\\002022 \\0020";
 7237: }
 7238: 
 7239: li.LC_docs_parameters_title {
 7240:   font-weight: bold;
 7241: }
 7242: 
 7243: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 7244:   content: "";
 7245: }
 7246: 
 7247: ul#LC_secondary_menu {
 7248:   clear: right;
 7249:   color: $fontmenu;
 7250:   background: $tabbg;
 7251:   list-style: none;
 7252:   padding: 0;
 7253:   margin: 0;
 7254:   width: 100%;
 7255:   text-align: left;
 7256:   float: left;
 7257: }
 7258: 
 7259: ul#LC_secondary_menu li {
 7260:   font-weight: bold;
 7261:   line-height: 1.8em;
 7262:   border-right: 1px solid black;
 7263:   float: left;
 7264: }
 7265: 
 7266: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 7267:   background-color: $data_table_light;
 7268: }
 7269: 
 7270: ul#LC_secondary_menu li a {
 7271:   padding: 0 0.8em;
 7272: }
 7273: 
 7274: ul#LC_secondary_menu li ul {
 7275:   display: none;
 7276: }
 7277: 
 7278: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 7279:   display: block;
 7280:   position: absolute;
 7281:   margin: 0;
 7282:   padding: 0;
 7283:   list-style:none;
 7284:   float: none;
 7285:   background-color: $data_table_light;
 7286:   z-index: 2;
 7287:   margin-left: -1px;
 7288: }
 7289: 
 7290: ul#LC_secondary_menu li ul li {
 7291:   font-size: 90%;
 7292:   vertical-align: top;
 7293:   border-left: 1px solid black;
 7294:   border-right: 1px solid black;
 7295:   background-color: $data_table_light;
 7296:   list-style:none;
 7297:   float: none;
 7298: }
 7299: 
 7300: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 7301:   background-color: $data_table_dark;
 7302: }
 7303: 
 7304: ul.LC_TabContent {
 7305:   display:block;
 7306:   background: $sidebg;
 7307:   border-bottom: solid 1px $lg_border_color;
 7308:   list-style:none;
 7309:   margin: -1px -10px 0 -10px;
 7310:   padding: 0;
 7311: }
 7312: 
 7313: ul.LC_TabContent li,
 7314: ul.LC_TabContentBigger li {
 7315:   float:left;
 7316: }
 7317: 
 7318: ul#LC_secondary_menu li a {
 7319:   color: $fontmenu;
 7320:   text-decoration: none;
 7321: }
 7322: 
 7323: ul.LC_TabContent {
 7324:   min-height:20px;
 7325: }
 7326: 
 7327: ul.LC_TabContent li {
 7328:   vertical-align:middle;
 7329:   padding: 0 16px 0 10px;
 7330:   background-color:$tabbg;
 7331:   border-bottom:solid 1px $lg_border_color;
 7332:   border-left: solid 1px $font;
 7333: }
 7334: 
 7335: ul.LC_TabContent .right {
 7336:   float:right;
 7337: }
 7338: 
 7339: ul.LC_TabContent li a,
 7340: ul.LC_TabContent li {
 7341:   color:rgb(47,47,47);
 7342:   text-decoration:none;
 7343:   font-size:95%;
 7344:   font-weight:bold;
 7345:   min-height:20px;
 7346: }
 7347: 
 7348: ul.LC_TabContent li a:hover,
 7349: ul.LC_TabContent li a:focus {
 7350:   color: $button_hover;
 7351:   background:none;
 7352:   outline:none;
 7353: }
 7354: 
 7355: ul.LC_TabContent li:hover {
 7356:   color: $button_hover;
 7357:   cursor:pointer;
 7358: }
 7359: 
 7360: ul.LC_TabContent li.active {
 7361:   color: $font;
 7362:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 7363:   border-bottom:solid 1px #FFFFFF;
 7364:   cursor: default;
 7365: }
 7366: 
 7367: ul.LC_TabContent li.active a {
 7368:   color:$font;
 7369:   background:#FFFFFF;
 7370:   outline: none;
 7371: }
 7372: 
 7373: ul.LC_TabContent li.goback {
 7374:   float: left;
 7375:   border-left: none;
 7376: }
 7377: 
 7378: #maincoursedoc {
 7379:   clear:both;
 7380: }
 7381: 
 7382: ul.LC_TabContentBigger {
 7383:   display:block;
 7384:   list-style:none;
 7385:   padding: 0;
 7386: }
 7387: 
 7388: ul.LC_TabContentBigger li {
 7389:   vertical-align:bottom;
 7390:   height: 30px;
 7391:   font-size:110%;
 7392:   font-weight:bold;
 7393:   color: #737373;
 7394: }
 7395: 
 7396: ul.LC_TabContentBigger li.active {
 7397:   position: relative;
 7398:   top: 1px;
 7399: }
 7400: 
 7401: ul.LC_TabContentBigger li a {
 7402:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 7403:   height: 30px;
 7404:   line-height: 30px;
 7405:   text-align: center;
 7406:   display: block;
 7407:   text-decoration: none;
 7408:   outline: none;  
 7409: }
 7410: 
 7411: ul.LC_TabContentBigger li.active a {
 7412:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 7413:   color:$font;
 7414: }
 7415: 
 7416: ul.LC_TabContentBigger li b {
 7417:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 7418:   display: block;
 7419:   float: left;
 7420:   padding: 0 30px;
 7421:   border-bottom: 1px solid $lg_border_color;
 7422: }
 7423: 
 7424: ul.LC_TabContentBigger li:hover b {
 7425:   color:$button_hover;
 7426: }
 7427: 
 7428: ul.LC_TabContentBigger li.active b {
 7429:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 7430:   color:$font;
 7431:   border: 0;
 7432: }
 7433: 
 7434: 
 7435: ul.LC_CourseBreadcrumbs {
 7436:   background: $sidebg;
 7437:   height: 2em;
 7438:   padding-left: 10px;
 7439:   margin: 0;
 7440:   list-style-position: inside;
 7441: }
 7442: 
 7443: ol#LC_MenuBreadcrumbs,
 7444: ol#LC_PathBreadcrumbs {
 7445:   padding-left: 10px;
 7446:   margin: 0;
 7447:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 7448: }
 7449: 
 7450: ol#LC_MenuBreadcrumbs li,
 7451: ol#LC_PathBreadcrumbs li,
 7452: ul.LC_CourseBreadcrumbs li {
 7453:   display: inline;
 7454:   white-space: normal;  
 7455: }
 7456: 
 7457: ol#LC_MenuBreadcrumbs li a,
 7458: ul.LC_CourseBreadcrumbs li a {
 7459:   text-decoration: none;
 7460:   font-size:90%;
 7461: }
 7462: 
 7463: ol#LC_MenuBreadcrumbs h1 {
 7464:   display: inline;
 7465:   font-size: 90%;
 7466:   line-height: 2.5em;
 7467:   margin: 0;
 7468:   padding: 0;
 7469: }
 7470: 
 7471: ol#LC_PathBreadcrumbs li a {
 7472:   text-decoration:none;
 7473:   font-size:100%;
 7474:   font-weight:bold;
 7475: }
 7476: 
 7477: .LC_Box {
 7478:   border: solid 1px $lg_border_color;
 7479:   padding: 0 10px 10px 10px;
 7480: }
 7481: 
 7482: .LC_DocsBox {
 7483:   border: solid 1px $lg_border_color;
 7484:   padding: 0 0 10px 10px;
 7485: }
 7486: 
 7487: .LC_AboutMe_Image {
 7488:   float:left;
 7489:   margin-right:10px;
 7490: }
 7491: 
 7492: .LC_Clear_AboutMe_Image {
 7493:   clear:left;
 7494: }
 7495: 
 7496: dl.LC_ListStyleClean dt {
 7497:   padding-right: 5px;
 7498:   display: table-header-group;
 7499: }
 7500: 
 7501: dl.LC_ListStyleClean dd {
 7502:   display: table-row;
 7503: }
 7504: 
 7505: .LC_ListStyleClean,
 7506: .LC_ListStyleSimple,
 7507: .LC_ListStyleNormal,
 7508: .LC_ListStyleSpecial {
 7509:   /* display:block; */
 7510:   list-style-position: inside;
 7511:   list-style-type: none;
 7512:   overflow: hidden;
 7513:   padding: 0;
 7514: }
 7515: 
 7516: .LC_ListStyleSimple li,
 7517: .LC_ListStyleSimple dd,
 7518: .LC_ListStyleNormal li,
 7519: .LC_ListStyleNormal dd,
 7520: .LC_ListStyleSpecial li,
 7521: .LC_ListStyleSpecial dd {
 7522:   margin: 0;
 7523:   padding: 5px 5px 5px 10px;
 7524:   clear: both;
 7525: }
 7526: 
 7527: .LC_ListStyleClean li,
 7528: .LC_ListStyleClean dd {
 7529:   padding-top: 0;
 7530:   padding-bottom: 0;
 7531: }
 7532: 
 7533: .LC_ListStyleSimple dd,
 7534: .LC_ListStyleSimple li {
 7535:   border-bottom: solid 1px $lg_border_color;
 7536: }
 7537: 
 7538: .LC_ListStyleSpecial li,
 7539: .LC_ListStyleSpecial dd {
 7540:   list-style-type: none;
 7541:   background-color: RGB(220, 220, 220);
 7542:   margin-bottom: 4px;
 7543: }
 7544: 
 7545: table.LC_SimpleTable {
 7546:   margin:5px;
 7547:   border:solid 1px $lg_border_color;
 7548: }
 7549: 
 7550: table.LC_SimpleTable tr {
 7551:   padding: 0;
 7552:   border:solid 1px $lg_border_color;
 7553: }
 7554: 
 7555: table.LC_SimpleTable thead {
 7556:   background:rgb(220,220,220);
 7557: }
 7558: 
 7559: div.LC_columnSection {
 7560:   display: block;
 7561:   clear: both;
 7562:   overflow: hidden;
 7563:   margin: 0;
 7564: }
 7565: 
 7566: div.LC_columnSection>* {
 7567:   float: left;
 7568:   margin: 10px 20px 10px 0;
 7569:   overflow:hidden;
 7570: }
 7571: 
 7572: table em {
 7573:   font-weight: bold;
 7574:   font-style: normal;
 7575: }
 7576: 
 7577: table.LC_tableBrowseRes,
 7578: table.LC_tableOfContent {
 7579:   border:none;
 7580:   border-spacing: 1px;
 7581:   padding: 3px;
 7582:   background-color: #FFFFFF;
 7583:   font-size: 90%;
 7584: }
 7585: 
 7586: table.LC_tableOfContent {
 7587:   border-collapse: collapse;
 7588: }
 7589: 
 7590: table.LC_tableBrowseRes a,
 7591: table.LC_tableOfContent a {
 7592:   background-color: transparent;
 7593:   text-decoration: none;
 7594: }
 7595: 
 7596: table.LC_tableOfContent img {
 7597:   border: none;
 7598:   height: 1.3em;
 7599:   vertical-align: text-bottom;
 7600:   margin-right: 0.3em;
 7601: }
 7602: 
 7603: a#LC_content_toolbar_firsthomework {
 7604:   background-image:url(/res/adm/pages/open-first-problem.gif);
 7605: }
 7606: 
 7607: a#LC_content_toolbar_everything {
 7608:   background-image:url(/res/adm/pages/show-all.gif);
 7609: }
 7610: 
 7611: a#LC_content_toolbar_uncompleted {
 7612:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 7613: }
 7614: 
 7615: #LC_content_toolbar_clearbubbles {
 7616:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 7617: }
 7618: 
 7619: a#LC_content_toolbar_changefolder {
 7620:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 7621: }
 7622: 
 7623: a#LC_content_toolbar_changefolder_toggled {
 7624:   background-image:url(/res/adm/pages/open-all-folders.gif);
 7625: }
 7626: 
 7627: a#LC_content_toolbar_edittoplevel {
 7628:   background-image:url(/res/adm/pages/edittoplevel.gif);
 7629: }
 7630: 
 7631: ul#LC_toolbar li a:hover {
 7632:   background-position: bottom center;
 7633: }
 7634: 
 7635: ul#LC_toolbar {
 7636:   padding: 0;
 7637:   margin: 2px;
 7638:   list-style:none;
 7639:   position:relative;
 7640:   background-color:white;
 7641:   overflow: auto;
 7642: }
 7643: 
 7644: ul#LC_toolbar li {
 7645:   border:1px solid white;
 7646:   padding: 0;
 7647:   margin: 0;
 7648:   float: left;
 7649:   display:inline;
 7650:   vertical-align:middle;
 7651:   white-space: nowrap;
 7652: }
 7653: 
 7654: 
 7655: a.LC_toolbarItem {
 7656:   display:block;
 7657:   padding: 0;
 7658:   margin: 0;
 7659:   height: 32px;
 7660:   width: 32px;
 7661:   color:white;
 7662:   border: none;
 7663:   background-repeat:no-repeat;
 7664:   background-color:transparent;
 7665: }
 7666: 
 7667: ul.LC_funclist {
 7668:     margin: 0;
 7669:     padding: 0.5em 1em 0.5em 0;
 7670: }
 7671: 
 7672: ul.LC_funclist > li:first-child {
 7673:     font-weight:bold; 
 7674:     margin-left:0.8em;
 7675: }
 7676: 
 7677: ul.LC_funclist + ul.LC_funclist {
 7678:     /* 
 7679:        left border as a seperator if we have more than
 7680:        one list 
 7681:     */
 7682:     border-left: 1px solid $sidebg;
 7683:     /* 
 7684:        this hides the left border behind the border of the 
 7685:        outer box if element is wrapped to the next 'line' 
 7686:     */
 7687:     margin-left: -1px;
 7688: }
 7689: 
 7690: ul.LC_funclist li {
 7691:   display: inline;
 7692:   white-space: nowrap;
 7693:   margin: 0 0 0 25px;
 7694:   line-height: 150%;
 7695: }
 7696: 
 7697: .LC_hidden {
 7698:   display: none;
 7699: }
 7700: 
 7701: .LCmodal-overlay {
 7702: 		position:fixed;
 7703: 		top:0;
 7704: 		right:0;
 7705: 		bottom:0;
 7706: 		left:0;
 7707: 		height:100%;
 7708: 		width:100%;
 7709: 		margin:0;
 7710: 		padding:0;
 7711: 		background:#999;
 7712: 		opacity:.75;
 7713: 		filter: alpha(opacity=75);
 7714: 		-moz-opacity: 0.75;
 7715: 		z-index:101;
 7716: }
 7717: 
 7718: * html .LCmodal-overlay {   
 7719: 		position: absolute;
 7720: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 7721: }
 7722: 
 7723: .LCmodal-window {
 7724: 		position:fixed;
 7725: 		top:50%;
 7726: 		left:50%;
 7727: 		margin:0;
 7728: 		padding:0;
 7729: 		z-index:102;
 7730: 	}
 7731: 
 7732: * html .LCmodal-window {
 7733: 		position:absolute;
 7734: }
 7735: 
 7736: .LCclose-window {
 7737: 		position:absolute;
 7738: 		width:32px;
 7739: 		height:32px;
 7740: 		right:8px;
 7741: 		top:8px;
 7742: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 7743: 		text-indent:-99999px;
 7744: 		overflow:hidden;
 7745: 		cursor:pointer;
 7746: }
 7747: 
 7748: pre.LC_wordwrap {
 7749:   white-space: pre-wrap;
 7750:   white-space: -moz-pre-wrap;
 7751:   white-space: -pre-wrap;
 7752:   white-space: -o-pre-wrap;
 7753:   word-wrap: break-word;
 7754: }
 7755: 
 7756: /*
 7757:   styles used by TTH when "Default set of options to pass to tth/m
 7758:   when converting TeX" in course settings has been set
 7759: 
 7760:   option passed: -t
 7761: 
 7762: */
 7763: 
 7764: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 7765: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 7766: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 7767: td div.norm {line-height:normal;}
 7768: 
 7769: /*
 7770:   option passed -y3
 7771: */
 7772: 
 7773: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 7774: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 7775: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 7776: 
 7777: #LC_minitab_header {
 7778:   float:left;
 7779:   width:100%;
 7780:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
 7781:   font-size:93%;
 7782:   line-height:normal;
 7783:   margin: 0.5em 0 0.5em 0;
 7784: }
 7785: #LC_minitab_header ul {
 7786:   margin:0;
 7787:   padding:10px 10px 0;
 7788:   list-style:none;
 7789: }
 7790: #LC_minitab_header li {
 7791:   float:left;
 7792:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
 7793:   margin:0;
 7794:   padding:0 0 0 9px;
 7795: }
 7796: #LC_minitab_header a {
 7797:   display:block;
 7798:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
 7799:   padding:5px 15px 4px 6px;
 7800: }
 7801: #LC_minitab_header #LC_current_minitab {
 7802:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
 7803: }
 7804: #LC_minitab_header #LC_current_minitab a {
 7805:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
 7806:   padding-bottom:5px;
 7807: }
 7808: 
 7809: 
 7810: END
 7811: }
 7812: 
 7813: =pod
 7814: 
 7815: =item * &headtag()
 7816: 
 7817: Returns a uniform footer for LON-CAPA web pages.
 7818: 
 7819: Inputs: $title - optional title for the head
 7820:         $head_extra - optional extra HTML to put inside the <head>
 7821:         $args - optional arguments
 7822:             force_register - if is true call registerurl so the remote is 
 7823:                              informed
 7824:             redirect       -> array ref of
 7825:                                    1- seconds before redirect occurs
 7826:                                    2- url to redirect to
 7827:                                    3- whether the side effect should occur
 7828:                            (side effect of setting 
 7829:                                $env{'internal.head.redirect'} to the url 
 7830:                                redirected too)
 7831:             domain         -> force to color decorate a page for a specific
 7832:                                domain
 7833:             function       -> force usage of a specific rolish color scheme
 7834:             bgcolor        -> override the default page bgcolor
 7835:             no_auto_mt_title
 7836:                            -> prevent &mt()ing the title arg
 7837: 
 7838: =cut
 7839: 
 7840: sub headtag {
 7841:     my ($title,$head_extra,$args) = @_;
 7842:     
 7843:     my $function = $args->{'function'} || &get_users_function();
 7844:     my $domain   = $args->{'domain'}   || &determinedomain();
 7845:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 7846:     my $httphost = $args->{'use_absolute'};
 7847:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 7848: 		   $Apache::lonnet::perlvar{'lonVersion'},
 7849: 		   #time(),
 7850: 		   $env{'environment.color.timestamp'},
 7851: 		   $function,$domain,$bgcolor);
 7852: 
 7853:     $url = '/adm/css/'.&escape($url).'.css';
 7854: 
 7855:     my $result =
 7856: 	'<head>'.
 7857: 	&font_settings($args);
 7858: 
 7859:     my $inhibitprint;
 7860:     if ($args->{'print_suppress'}) {
 7861:         $inhibitprint = &print_suppression();
 7862:     }
 7863: 
 7864:     if (!$args->{'frameset'}) {
 7865: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 7866:     }
 7867:     if ($args->{'force_register'}) {
 7868:         $result .= &Apache::lonmenu::registerurl(1);
 7869:     }
 7870:     if (!$args->{'no_nav_bar'} 
 7871: 	&& !$args->{'only_body'}
 7872: 	&& !$args->{'frameset'}) {
 7873: 	$result .= &help_menu_js($httphost);
 7874:         $result.=&modal_window();
 7875:         $result.=&togglebox_script();
 7876:         $result.=&wishlist_window();
 7877:         $result.=&LCprogressbarUpdate_script();
 7878:     } else {
 7879:         if ($args->{'add_modal'}) {
 7880:            $result.=&modal_window();
 7881:         }
 7882:         if ($args->{'add_wishlist'}) {
 7883:            $result.=&wishlist_window();
 7884:         }
 7885:         if ($args->{'add_togglebox'}) {
 7886:            $result.=&togglebox_script();
 7887:         }
 7888:         if ($args->{'add_progressbar'}) {
 7889:            $result.=&LCprogressbarUpdate_script();
 7890:         }
 7891:     }
 7892:     if (ref($args->{'redirect'})) {
 7893: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 7894: 	$url = &Apache::lonenc::check_encrypt($url);
 7895: 	if (!$inhibit_continue) {
 7896: 	    $env{'internal.head.redirect'} = $url;
 7897: 	}
 7898: 	$result.=<<ADDMETA
 7899: <meta http-equiv="pragma" content="no-cache" />
 7900: <meta http-equiv="Refresh" content="$time; url=$url" />
 7901: ADDMETA
 7902:     } else {
 7903:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
 7904:             my $requrl = $env{'request.uri'};
 7905:             if ($requrl eq '') {
 7906:                 $requrl = $ENV{'REQUEST_URI'};
 7907:                 $requrl =~ s/\?.+$//;
 7908:             }
 7909:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
 7910:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
 7911:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
 7912:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
 7913:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
 7914:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
 7915:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
 7916:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 7917:                         if ($domdefs{'offloadnow'}{$lonhost}) {
 7918:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
 7919:                             if (($newserver) && ($newserver ne $lonhost)) {
 7920:                                 my $numsec = 5;
 7921:                                 my $timeout = $numsec * 1000;
 7922:                                 my ($newurl,$locknum,%locks,$msg);
 7923:                                 if ($env{'request.role.adv'}) {
 7924:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
 7925:                                 }
 7926:                                 my $disable_submit = 0;
 7927:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
 7928:                                     $disable_submit = 1;
 7929:                                 }
 7930:                                 if ($locknum) {
 7931:                                     my @lockinfo = sort(values(%locks));
 7932:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
 7933:                                            join(", ",sort(values(%locks)))."\\n".
 7934:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
 7935:                                 } else {
 7936:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
 7937:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
 7938:                                     }
 7939:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
 7940:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
 7941:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
 7942:                                         $newurl .= '&role='.$env{'request.role'};
 7943:                                     }
 7944:                                     if ($env{'request.symb'}) {
 7945:                                         $newurl .= '&symb='.$env{'request.symb'};
 7946:                                     } else {
 7947:                                         $newurl .= '&origurl='.$requrl;
 7948:                                     }
 7949:                                 }
 7950:                                 &js_escape(\$msg);
 7951:                                 $result.=<<OFFLOAD
 7952: <meta http-equiv="pragma" content="no-cache" />
 7953: <script type="text/javascript">
 7954: // <![CDATA[
 7955: function LC_Offload_Now() {
 7956:     var dest = "$newurl";
 7957:     if (dest != '') {
 7958:         window.location.href="$newurl";
 7959:     }
 7960: }
 7961: \$(document).ready(function () {
 7962:     window.alert('$msg');
 7963:     if ($disable_submit) {
 7964:         \$(".LC_hwk_submit").prop("disabled", true);
 7965:         \$( ".LC_textline" ).prop( "readonly", "readonly");
 7966:     }
 7967:     setTimeout('LC_Offload_Now()', $timeout);
 7968: });
 7969: // ]]>
 7970: </script>
 7971: OFFLOAD
 7972:                             }
 7973:                         }
 7974:                     }
 7975:                 }
 7976:             }
 7977:         }
 7978:     }
 7979:     if (!defined($title)) {
 7980: 	$title = 'The LearningOnline Network with CAPA';
 7981:     }
 7982:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 7983:     $result .= '<title> LON-CAPA '.$title.'</title>'
 7984: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
 7985:     if (!$args->{'frameset'}) {
 7986:         $result .= ' /';
 7987:     }
 7988:     $result .= '>'
 7989:         .$inhibitprint
 7990: 	.$head_extra;
 7991:     my $clientmobile;
 7992:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 7993:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
 7994:     } else {
 7995:         $clientmobile = $env{'browser.mobile'};
 7996:     }
 7997:     if ($clientmobile) {
 7998:         $result .= '
 7999: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 8000: <meta name="apple-mobile-web-app-capable" content="yes" />';
 8001:     }
 8002:     $result .= '<meta name="google" content="notranslate" />'."\n";
 8003:     return $result.'</head>';
 8004: }
 8005: 
 8006: =pod
 8007: 
 8008: =item * &font_settings()
 8009: 
 8010: Returns neccessary <meta> to set the proper encoding
 8011: 
 8012: Inputs: optional reference to HASH -- $args passed to &headtag()
 8013: 
 8014: =cut
 8015: 
 8016: sub font_settings {
 8017:     my ($args) = @_;
 8018:     my $headerstring='';
 8019:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
 8020:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
 8021: 	$headerstring.=
 8022: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
 8023:         if (!$args->{'frameset'}) {
 8024:             $headerstring.= ' /';
 8025:         }
 8026:         $headerstring .= '>'."\n";
 8027:     }
 8028:     return $headerstring;
 8029: }
 8030: 
 8031: =pod
 8032: 
 8033: =item * &print_suppression()
 8034: 
 8035: In course context returns css which causes the body to be blank when media="print",
 8036: if printout generation is unavailable for the current resource.
 8037: 
 8038: This could be because:
 8039: 
 8040: (a) printstartdate is in the future
 8041: 
 8042: (b) printenddate is in the past
 8043: 
 8044: (c) there is an active exam block with "printout"
 8045: functionality blocked
 8046: 
 8047: Users with pav, pfo or evb privileges are exempt.
 8048: 
 8049: Inputs: none
 8050: 
 8051: =cut
 8052: 
 8053: 
 8054: sub print_suppression {
 8055:     my $noprint;
 8056:     if ($env{'request.course.id'}) {
 8057:         my $scope = $env{'request.course.id'};
 8058:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8059:             (&Apache::lonnet::allowed('pfo',$scope))) {
 8060:             return;
 8061:         }
 8062:         if ($env{'request.course.sec'} ne '') {
 8063:             $scope .= "/$env{'request.course.sec'}";
 8064:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8065:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 8066:                 return;
 8067:             }
 8068:         }
 8069:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8070:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8071:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
 8072:         if ($blocked) {
 8073:             my $checkrole = "cm./$cdom/$cnum";
 8074:             if ($env{'request.course.sec'} ne '') {
 8075:                 $checkrole .= "/$env{'request.course.sec'}";
 8076:             }
 8077:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 8078:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 8079:                 $noprint = 1;
 8080:             }
 8081:         }
 8082:         unless ($noprint) {
 8083:             my $symb = &Apache::lonnet::symbread();
 8084:             if ($symb ne '') {
 8085:                 my $navmap = Apache::lonnavmaps::navmap->new();
 8086:                 if (ref($navmap)) {
 8087:                     my $res = $navmap->getBySymb($symb);
 8088:                     if (ref($res)) {
 8089:                         if (!$res->resprintable()) {
 8090:                             $noprint = 1;
 8091:                         }
 8092:                     }
 8093:                 }
 8094:             }
 8095:         }
 8096:         if ($noprint) {
 8097:             return <<"ENDSTYLE";
 8098: <style type="text/css" media="print">
 8099:     body { display:none }
 8100: </style>
 8101: ENDSTYLE
 8102:         }
 8103:     }
 8104:     return;
 8105: }
 8106: 
 8107: =pod
 8108: 
 8109: =item * &xml_begin()
 8110: 
 8111: Returns the needed doctype and <html>
 8112: 
 8113: Inputs: none
 8114: 
 8115: =cut
 8116: 
 8117: sub xml_begin {
 8118:     my ($is_frameset) = @_;
 8119:     my $output='';
 8120: 
 8121:     if ($env{'browser.mathml'}) {
 8122: 	$output='<?xml version="1.0"?>'
 8123:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 8124: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 8125:             
 8126: #	    .'<!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">] >'
 8127: 	    .'<!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">'
 8128:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 8129: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 8130:     } elsif ($is_frameset) {
 8131:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
 8132:                 '<html>'."\n";
 8133:     } else {
 8134: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
 8135:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
 8136:     }
 8137:     return $output;
 8138: }
 8139: 
 8140: =pod
 8141: 
 8142: =item * &start_page()
 8143: 
 8144: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 8145: 
 8146: Inputs:
 8147: 
 8148: =over 4
 8149: 
 8150: $title - optional title for the page
 8151: 
 8152: $head_extra - optional extra HTML to incude inside the <head>
 8153: 
 8154: $args - additional optional args supported are:
 8155: 
 8156: =over 8
 8157: 
 8158:              only_body      -> is true will set &bodytag() onlybodytag
 8159:                                     arg on
 8160:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 8161:              add_entries    -> additional attributes to add to the  <body>
 8162:              domain         -> force to color decorate a page for a 
 8163:                                     specific domain
 8164:              function       -> force usage of a specific rolish color
 8165:                                     scheme
 8166:              redirect       -> see &headtag()
 8167:              bgcolor        -> override the default page bg color
 8168:              js_ready       -> return a string ready for being used in 
 8169:                                     a javascript writeln
 8170:              html_encode    -> return a string ready for being used in 
 8171:                                     a html attribute
 8172:              force_register -> if is true will turn on the &bodytag()
 8173:                                     $forcereg arg
 8174:              frameset       -> if true will start with a <frameset>
 8175:                                     rather than <body>
 8176:              skip_phases    -> hash ref of 
 8177:                                     head -> skip the <html><head> generation
 8178:                                     body -> skip all <body> generation
 8179:              no_inline_link -> if true and in remote mode, don't show the
 8180:                                     'Switch To Inline Menu' link
 8181:              no_auto_mt_title -> prevent &mt()ing the title arg
 8182:              bread_crumbs ->             Array containing breadcrumbs
 8183:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 8184:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
 8185:                                     to lonhtmlcommon::breadcrumbs
 8186:              group          -> includes the current group, if page is for a
 8187:                                specific group
 8188:              use_absolute   -> for request for external resource or syllabus, this
 8189:                                will contain https://<hostname> if server uses
 8190:                                https (as per hosts.tab), but request is for http
 8191:              hostname       -> hostname, originally from $r->hostname(), (optional).
 8192: 
 8193: =back
 8194: 
 8195: =back
 8196: 
 8197: =cut
 8198: 
 8199: sub start_page {
 8200:     my ($title,$head_extra,$args) = @_;
 8201:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 8202: 
 8203:     $env{'internal.start_page'}++;
 8204:     my ($result,@advtools);
 8205: 
 8206:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 8207:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
 8208:     }
 8209:     
 8210:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 8211: 	if ($args->{'frameset'}) {
 8212: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 8213: 						$args->{'add_entries'});
 8214: 	    $result .= "\n<frameset $attr_string>\n";
 8215:         } else {
 8216:             $result .=
 8217:                 &bodytag($title, 
 8218:                          $args->{'function'},       $args->{'add_entries'},
 8219:                          $args->{'only_body'},      $args->{'domain'},
 8220:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 8221:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
 8222:                          $args,                     \@advtools);
 8223:         }
 8224:     }
 8225: 
 8226:     if ($args->{'js_ready'}) {
 8227: 		$result = &js_ready($result);
 8228:     }
 8229:     if ($args->{'html_encode'}) {
 8230: 		$result = &html_encode($result);
 8231:     }
 8232: 
 8233:     # Preparation for new and consistent functionlist at top of screen
 8234:     # if ($args->{'functionlist'}) {
 8235:     #            $result .= &build_functionlist();
 8236:     #}
 8237: 
 8238:     # Don't add anything more if only_body wanted or in const space
 8239:     return $result if    $args->{'only_body'} 
 8240:                       || $env{'request.state'} eq 'construct';
 8241: 
 8242:     #Breadcrumbs
 8243:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 8244: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 8245: 		#if any br links exists, add them to the breadcrumbs
 8246: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 8247: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 8248: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 8249: 			}
 8250: 		}
 8251:                 # if @advtools array contains items add then to the breadcrumbs
 8252:                 if (@advtools > 0) {
 8253:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 8254:                 }
 8255:                 my $menulink;
 8256:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
 8257:                 if (exists($args->{'bread_crumbs_nomenu'})) {
 8258:                     $menulink = 0;
 8259:                 } else {
 8260:                     undef($menulink);
 8261:                 }
 8262: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 8263: 		if(exists($args->{'bread_crumbs_component'})){
 8264: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
 8265: 		}else{
 8266: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
 8267: 		}
 8268:     } elsif (($env{'environment.remote'} eq 'on') &&
 8269:              ($env{'form.inhibitmenu'} ne 'yes') &&
 8270:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
 8271:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
 8272:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
 8273:     }
 8274:     return $result;
 8275: }
 8276: 
 8277: sub end_page {
 8278:     my ($args) = @_;
 8279:     $env{'internal.end_page'}++;
 8280:     my $result;
 8281:     if ($args->{'discussion'}) {
 8282: 	my ($target,$parser);
 8283: 	if (ref($args->{'discussion'})) {
 8284: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 8285: 				$args->{'discussion'}{'parser'});
 8286: 	}
 8287: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 8288:     }
 8289:     if ($args->{'frameset'}) {
 8290: 	$result .= '</frameset>';
 8291:     } else {
 8292: 	$result .= &endbodytag($args);
 8293:     }
 8294:     unless ($args->{'notbody'}) {
 8295:         $result .= "\n</html>";
 8296:     }
 8297: 
 8298:     if ($args->{'js_ready'}) {
 8299: 	$result = &js_ready($result);
 8300:     }
 8301: 
 8302:     if ($args->{'html_encode'}) {
 8303: 	$result = &html_encode($result);
 8304:     }
 8305: 
 8306:     return $result;
 8307: }
 8308: 
 8309: sub wishlist_window {
 8310:     return(<<'ENDWISHLIST');
 8311: <script type="text/javascript">
 8312: // <![CDATA[
 8313: // <!-- BEGIN LON-CAPA Internal
 8314: function set_wishlistlink(title, path) {
 8315:     if (!title) {
 8316:         title = document.title;
 8317:         title = title.replace(/^LON-CAPA /,'');
 8318:     }
 8319:     title = encodeURIComponent(title);
 8320:     title = title.replace("'","\\\'");
 8321:     if (!path) {
 8322:         path = location.pathname;
 8323:     }
 8324:     path = encodeURIComponent(path);
 8325:     path = path.replace("'","\\\'");
 8326:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 8327:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 8328: }
 8329: // END LON-CAPA Internal -->
 8330: // ]]>
 8331: </script>
 8332: ENDWISHLIST
 8333: }
 8334: 
 8335: sub modal_window {
 8336:     return(<<'ENDMODAL');
 8337: <script type="text/javascript">
 8338: // <![CDATA[
 8339: // <!-- BEGIN LON-CAPA Internal
 8340: var modalWindow = {
 8341: 	parent:"body",
 8342: 	windowId:null,
 8343: 	content:null,
 8344: 	width:null,
 8345: 	height:null,
 8346: 	close:function()
 8347: 	{
 8348: 	        $(".LCmodal-window").remove();
 8349: 	        $(".LCmodal-overlay").remove();
 8350: 	},
 8351: 	open:function()
 8352: 	{
 8353: 		var modal = "";
 8354: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 8355: 		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;\">";
 8356: 		modal += this.content;
 8357: 		modal += "</div>";	
 8358: 
 8359: 		$(this.parent).append(modal);
 8360: 
 8361: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 8362: 		$(".LCclose-window").click(function(){modalWindow.close();});
 8363: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 8364: 	}
 8365: };
 8366: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
 8367: 	{
 8368:                 source = source.replace(/'/g,"&#39;");
 8369: 		modalWindow.windowId = "myModal";
 8370: 		modalWindow.width = width;
 8371: 		modalWindow.height = height;
 8372: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
 8373: 		modalWindow.open();
 8374: 	};
 8375: // END LON-CAPA Internal -->
 8376: // ]]>
 8377: </script>
 8378: ENDMODAL
 8379: }
 8380: 
 8381: sub modal_link {
 8382:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
 8383:     unless ($width) { $width=480; }
 8384:     unless ($height) { $height=400; }
 8385:     unless ($scrolling) { $scrolling='yes'; }
 8386:     unless ($transparency) { $transparency='true'; }
 8387: 
 8388:     my $target_attr;
 8389:     if (defined($target)) {
 8390:         $target_attr = 'target="'.$target.'"';
 8391:     }
 8392:     return <<"ENDLINK";
 8393: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
 8394:            $linktext</a>
 8395: ENDLINK
 8396: }
 8397: 
 8398: sub modal_adhoc_script {
 8399:     my ($funcname,$width,$height,$content)=@_;
 8400:     return (<<ENDADHOC);
 8401: <script type="text/javascript">
 8402: // <![CDATA[
 8403:         var $funcname = function()
 8404:         {
 8405:                 modalWindow.windowId = "myModal";
 8406:                 modalWindow.width = $width;
 8407:                 modalWindow.height = $height;
 8408:                 modalWindow.content = '$content';
 8409:                 modalWindow.open();
 8410:         };  
 8411: // ]]>
 8412: </script>
 8413: ENDADHOC
 8414: }
 8415: 
 8416: sub modal_adhoc_inner {
 8417:     my ($funcname,$width,$height,$content)=@_;
 8418:     my $innerwidth=$width-20;
 8419:     $content=&js_ready(
 8420:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 8421:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
 8422:                  $content.
 8423:                  &end_scrollbox().
 8424:                  &end_page()
 8425:              );
 8426:     return &modal_adhoc_script($funcname,$width,$height,$content);
 8427: }
 8428: 
 8429: sub modal_adhoc_window {
 8430:     my ($funcname,$width,$height,$content,$linktext)=@_;
 8431:     return &modal_adhoc_inner($funcname,$width,$height,$content).
 8432:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 8433: }
 8434: 
 8435: sub modal_adhoc_launch {
 8436:     my ($funcname,$width,$height,$content)=@_;
 8437:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 8438: <script type="text/javascript">
 8439: // <![CDATA[
 8440: $funcname();
 8441: // ]]>
 8442: </script>
 8443: ENDLAUNCH
 8444: }
 8445: 
 8446: sub modal_adhoc_close {
 8447:     return (<<ENDCLOSE);
 8448: <script type="text/javascript">
 8449: // <![CDATA[
 8450: modalWindow.close();
 8451: // ]]>
 8452: </script>
 8453: ENDCLOSE
 8454: }
 8455: 
 8456: sub togglebox_script {
 8457:    return(<<ENDTOGGLE);
 8458: <script type="text/javascript"> 
 8459: // <![CDATA[
 8460: function LCtoggleDisplay(id,hidetext,showtext) {
 8461:    link = document.getElementById(id + "link").childNodes[0];
 8462:    with (document.getElementById(id).style) {
 8463:       if (display == "none" ) {
 8464:           display = "inline";
 8465:           link.nodeValue = hidetext;
 8466:         } else {
 8467:           display = "none";
 8468:           link.nodeValue = showtext;
 8469:        }
 8470:    }
 8471: }
 8472: // ]]>
 8473: </script>
 8474: ENDTOGGLE
 8475: }
 8476: 
 8477: sub start_togglebox {
 8478:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 8479:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 8480:     unless ($showtext) { $showtext=&mt('show'); }
 8481:     unless ($hidetext) { $hidetext=&mt('hide'); }
 8482:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 8483:     return &start_data_table().
 8484:            &start_data_table_header_row().
 8485:            '<td bgcolor="'.$headerbg.'">'.$heading.
 8486:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 8487:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 8488:            &end_data_table_header_row().
 8489:            '<tr id="'.$id.'" style="display:none""><td>';
 8490: }
 8491: 
 8492: sub end_togglebox {
 8493:     return '</td></tr>'.&end_data_table();
 8494: }
 8495: 
 8496: sub LCprogressbar_script {
 8497:    my ($id,$number_to_do)=@_;
 8498:    if ($number_to_do) {
 8499:        return(<<ENDPROGRESS);
 8500: <script type="text/javascript">
 8501: // <![CDATA[
 8502: \$('#progressbar$id').progressbar({
 8503:   value: 0,
 8504:   change: function(event, ui) {
 8505:     var newVal = \$(this).progressbar('option', 'value');
 8506:     \$('.pblabel', this).text(LCprogressTxt);
 8507:   }
 8508: });
 8509: // ]]>
 8510: </script>
 8511: ENDPROGRESS
 8512:    } else {
 8513:        return(<<ENDPROGRESS);
 8514: <script type="text/javascript">
 8515: // <![CDATA[
 8516: \$('#progressbar$id').progressbar({
 8517:   value: false,
 8518:   create: function(event, ui) {
 8519:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
 8520:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
 8521:   }
 8522: });
 8523: // ]]>
 8524: </script>
 8525: ENDPROGRESS
 8526:    }
 8527: }
 8528: 
 8529: sub LCprogressbarUpdate_script {
 8530:    return(<<ENDPROGRESSUPDATE);
 8531: <style type="text/css">
 8532: .ui-progressbar { position:relative; }
 8533: .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%; }
 8534: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 8535: </style>
 8536: <script type="text/javascript">
 8537: // <![CDATA[
 8538: var LCprogressTxt='---';
 8539: 
 8540: function LCupdateProgress(percent,progresstext,id,maxnum) {
 8541:    LCprogressTxt=progresstext;
 8542:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
 8543:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
 8544:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
 8545:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
 8546:    } else {
 8547:        \$('#progressbar'+id).progressbar('value',percent);
 8548:    }
 8549: }
 8550: // ]]>
 8551: </script>
 8552: ENDPROGRESSUPDATE
 8553: }
 8554: 
 8555: my $LClastpercent;
 8556: my $LCidcnt;
 8557: my $LCcurrentid;
 8558: 
 8559: sub LCprogressbar {
 8560:     my ($r,$number_to_do,$preamble)=@_;
 8561:     $LClastpercent=0;
 8562:     $LCidcnt++;
 8563:     $LCcurrentid=$$.'_'.$LCidcnt;
 8564:     my ($starting,$content);
 8565:     if ($number_to_do) {
 8566:         $starting=&mt('Starting');
 8567:         $content=(<<ENDPROGBAR);
 8568: $preamble
 8569:   <div id="progressbar$LCcurrentid">
 8570:     <span class="pblabel">$starting</span>
 8571:   </div>
 8572: ENDPROGBAR
 8573:     } else {
 8574:         $starting=&mt('Loading...');
 8575:         $LClastpercent='false';
 8576:         $content=(<<ENDPROGBAR);
 8577: $preamble
 8578:   <div id="progressbar$LCcurrentid">
 8579:       <div class="progress-label">$starting</div>
 8580:   </div>
 8581: ENDPROGBAR
 8582:     }
 8583:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
 8584: }
 8585: 
 8586: sub LCprogressbarUpdate {
 8587:     my ($r,$val,$text,$number_to_do)=@_;
 8588:     if ($number_to_do) {
 8589:         unless ($val) { 
 8590:             if ($LClastpercent) {
 8591:                 $val=$LClastpercent;
 8592:             } else {
 8593:                 $val=0;
 8594:             }
 8595:         }
 8596:         if ($val<0) { $val=0; }
 8597:         if ($val>100) { $val=0; }
 8598:         $LClastpercent=$val;
 8599:         unless ($text) { $text=$val.'%'; }
 8600:     } else {
 8601:         $val = 'false';
 8602:     }
 8603:     $text=&js_ready($text);
 8604:     &r_print($r,<<ENDUPDATE);
 8605: <script type="text/javascript">
 8606: // <![CDATA[
 8607: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
 8608: // ]]>
 8609: </script>
 8610: ENDUPDATE
 8611: }
 8612: 
 8613: sub LCprogressbarClose {
 8614:     my ($r)=@_;
 8615:     $LClastpercent=0;
 8616:     &r_print($r,<<ENDCLOSE);
 8617: <script type="text/javascript">
 8618: // <![CDATA[
 8619: \$("#progressbar$LCcurrentid").hide('slow'); 
 8620: // ]]>
 8621: </script>
 8622: ENDCLOSE
 8623: }
 8624: 
 8625: sub r_print {
 8626:     my ($r,$to_print)=@_;
 8627:     if ($r) {
 8628:       $r->print($to_print);
 8629:       $r->rflush();
 8630:     } else {
 8631:       print($to_print);
 8632:     }
 8633: }
 8634: 
 8635: sub html_encode {
 8636:     my ($result) = @_;
 8637: 
 8638:     $result = &HTML::Entities::encode($result,'<>&"');
 8639:     
 8640:     return $result;
 8641: }
 8642: 
 8643: sub js_ready {
 8644:     my ($result) = @_;
 8645: 
 8646:     $result =~ s/[\n\r]/ /xmsg;
 8647:     $result =~ s/\\/\\\\/xmsg;
 8648:     $result =~ s/'/\\'/xmsg;
 8649:     $result =~ s{</}{<\\/}xmsg;
 8650:     
 8651:     return $result;
 8652: }
 8653: 
 8654: sub validate_page {
 8655:     if (  exists($env{'internal.start_page'})
 8656: 	  &&     $env{'internal.start_page'} > 1) {
 8657: 	&Apache::lonnet::logthis('start_page called multiple times '.
 8658: 				 $env{'internal.start_page'}.' '.
 8659: 				 $ENV{'request.filename'});
 8660:     }
 8661:     if (  exists($env{'internal.end_page'})
 8662: 	  &&     $env{'internal.end_page'} > 1) {
 8663: 	&Apache::lonnet::logthis('end_page called multiple times '.
 8664: 				 $env{'internal.end_page'}.' '.
 8665: 				 $env{'request.filename'});
 8666:     }
 8667:     if (     exists($env{'internal.start_page'})
 8668: 	&& ! exists($env{'internal.end_page'})) {
 8669: 	&Apache::lonnet::logthis('start_page called without end_page '.
 8670: 				 $env{'request.filename'});
 8671:     }
 8672:     if (   ! exists($env{'internal.start_page'})
 8673: 	&&   exists($env{'internal.end_page'})) {
 8674: 	&Apache::lonnet::logthis('end_page called without start_page'.
 8675: 				 $env{'request.filename'});
 8676:     }
 8677: }
 8678: 
 8679: 
 8680: sub start_scrollbox {
 8681:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
 8682:     unless ($outerwidth) { $outerwidth='520px'; }
 8683:     unless ($width) { $width='500px'; }
 8684:     unless ($height) { $height='200px'; }
 8685:     my ($table_id,$div_id,$tdcol);
 8686:     if ($id ne '') {
 8687:         $table_id = ' id="table_'.$id.'"';
 8688:         $div_id = ' id="div_'.$id.'"';
 8689:     }
 8690:     if ($bgcolor ne '') {
 8691:         $tdcol = "background-color: $bgcolor;";
 8692:     }
 8693:     my $nicescroll_js;
 8694:     if ($env{'browser.mobile'}) {
 8695:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
 8696:     }
 8697:     return <<"END";
 8698: $nicescroll_js
 8699: 
 8700: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
 8701: <div style="overflow:auto; width:$width; height:$height;"$div_id>
 8702: END
 8703: }
 8704: 
 8705: sub end_scrollbox {
 8706:     return '</div></td></tr></table>';
 8707: }
 8708: 
 8709: sub nicescroll_javascript {
 8710:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
 8711:     my %options;
 8712:     if (ref($cursor) eq 'HASH') {
 8713:         %options = %{$cursor};
 8714:     }
 8715:     unless ($options{'railalign'} =~ /^left|right$/) {
 8716:         $options{'railalign'} = 'left';
 8717:     }
 8718:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 8719:         my $function  = &get_users_function();
 8720:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
 8721:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 8722:             $options{'cursorcolor'} = '#00F';
 8723:         }
 8724:     }
 8725:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
 8726:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
 8727:             $options{'cursoropacity'}='1.0';
 8728:         }
 8729:     } else {
 8730:         $options{'cursoropacity'}='1.0';
 8731:     }
 8732:     if ($options{'cursorfixedheight'} eq 'none') {
 8733:         delete($options{'cursorfixedheight'});
 8734:     } else {
 8735:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
 8736:     }
 8737:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
 8738:         delete($options{'railoffset'});
 8739:     }
 8740:     my @niceoptions;
 8741:     while (my($key,$value) = each(%options)) {
 8742:         if ($value =~ /^\{.+\}$/) {
 8743:             push(@niceoptions,$key.':'.$value);
 8744:         } else {
 8745:             push(@niceoptions,$key.':"'.$value.'"');
 8746:         }
 8747:     }
 8748:     my $nicescroll_js = '
 8749: $(document).ready(
 8750:       function() {
 8751:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
 8752:       }
 8753: );
 8754: ';
 8755:     if ($framecheck) {
 8756:         $nicescroll_js .= '
 8757: function expand_div(caller) {
 8758:     if (top === self) {
 8759:         document.getElementById("'.$id.'").style.width = "auto";
 8760:         document.getElementById("'.$id.'").style.height = "auto";
 8761:     } else {
 8762:         try {
 8763:             if (parent.frames) {
 8764:                 if (parent.frames.length > 1) {
 8765:                     var framesrc = parent.frames[1].location.href;
 8766:                     var currsrc = framesrc.replace(/\#.*$/,"");
 8767:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
 8768:                         document.getElementById("'.$id.'").style.width = "auto";
 8769:                         document.getElementById("'.$id.'").style.height = "auto";
 8770:                     }
 8771:                 }
 8772:             }
 8773:         } catch (e) {
 8774:             return;
 8775:         }
 8776:     }
 8777:     return;
 8778: }
 8779: ';
 8780:     }
 8781:     if ($needjsready) {
 8782:         $nicescroll_js = '
 8783: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
 8784:     } else {
 8785:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
 8786:     }
 8787:     return $nicescroll_js;
 8788: }
 8789: 
 8790: sub simple_error_page {
 8791:     my ($r,$title,$msg,$args) = @_;
 8792:     if (ref($args) eq 'HASH') {
 8793:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
 8794:     } else {
 8795:         $msg = &mt($msg);
 8796:     }
 8797: 
 8798:     my $page =
 8799: 	&Apache::loncommon::start_page($title).
 8800: 	'<p class="LC_error">'.$msg.'</p>'.
 8801: 	&Apache::loncommon::end_page();
 8802:     if (ref($r)) {
 8803: 	$r->print($page);
 8804: 	return;
 8805:     }
 8806:     return $page;
 8807: }
 8808: 
 8809: {
 8810:     my @row_count;
 8811: 
 8812:     sub start_data_table_count {
 8813:         unshift(@row_count, 0);
 8814:         return;
 8815:     }
 8816: 
 8817:     sub end_data_table_count {
 8818:         shift(@row_count);
 8819:         return;
 8820:     }
 8821: 
 8822:     sub start_data_table {
 8823: 	my ($add_class,$id) = @_;
 8824: 	my $css_class = (join(' ','LC_data_table',$add_class));
 8825:         my $table_id;
 8826:         if (defined($id)) {
 8827:             $table_id = ' id="'.$id.'"';
 8828:         }
 8829: 	&start_data_table_count();
 8830: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 8831:     }
 8832: 
 8833:     sub end_data_table {
 8834: 	&end_data_table_count();
 8835: 	return '</table>'."\n";;
 8836:     }
 8837: 
 8838:     sub start_data_table_row {
 8839: 	my ($add_class, $id) = @_;
 8840: 	$row_count[0]++;
 8841: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 8842: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 8843:         $id = (' id="'.$id.'"') unless ($id eq '');
 8844:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 8845:     }
 8846:     
 8847:     sub continue_data_table_row {
 8848: 	my ($add_class, $id) = @_;
 8849: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 8850: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 8851:         $id = (' id="'.$id.'"') unless ($id eq '');
 8852:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 8853:     }
 8854: 
 8855:     sub end_data_table_row {
 8856: 	return '</tr>'."\n";;
 8857:     }
 8858: 
 8859:     sub start_data_table_empty_row {
 8860: #	$row_count[0]++;
 8861: 	return  '<tr class="LC_empty_row" >'."\n";;
 8862:     }
 8863: 
 8864:     sub end_data_table_empty_row {
 8865: 	return '</tr>'."\n";;
 8866:     }
 8867: 
 8868:     sub start_data_table_header_row {
 8869: 	return  '<tr class="LC_header_row">'."\n";;
 8870:     }
 8871: 
 8872:     sub end_data_table_header_row {
 8873: 	return '</tr>'."\n";;
 8874:     }
 8875: 
 8876:     sub data_table_caption {
 8877:         my $caption = shift;
 8878:         return "<caption class=\"LC_caption\">$caption</caption>";
 8879:     }
 8880: }
 8881: 
 8882: =pod
 8883: 
 8884: =item * &inhibit_menu_check($arg)
 8885: 
 8886: Checks for a inhibitmenu state and generates output to preserve it
 8887: 
 8888: Inputs:         $arg - can be any of
 8889:                      - undef - in which case the return value is a string 
 8890:                                to add  into arguments list of a uri
 8891:                      - 'input' - in which case the return value is a HTML
 8892:                                  <form> <input> field of type hidden to
 8893:                                  preserve the value
 8894:                      - a url - in which case the return value is the url with
 8895:                                the neccesary cgi args added to preserve the
 8896:                                inhibitmenu state
 8897:                      - a ref to a url - no return value, but the string is
 8898:                                         updated to include the neccessary cgi
 8899:                                         args to preserve the inhibitmenu state
 8900: 
 8901: =cut
 8902: 
 8903: sub inhibit_menu_check {
 8904:     my ($arg) = @_;
 8905:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 8906:     if ($arg eq 'input') {
 8907: 	if ($env{'form.inhibitmenu'}) {
 8908: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 8909: 	} else {
 8910: 	    return
 8911: 	}
 8912:     }
 8913:     if ($env{'form.inhibitmenu'}) {
 8914: 	if (ref($arg)) {
 8915: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8916: 	} elsif ($arg eq '') {
 8917: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 8918: 	} else {
 8919: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8920: 	}
 8921:     }
 8922:     if (!ref($arg)) {
 8923: 	return $arg;
 8924:     }
 8925: }
 8926: 
 8927: ###############################################
 8928: 
 8929: =pod
 8930: 
 8931: =back
 8932: 
 8933: =head1 User Information Routines
 8934: 
 8935: =over 4
 8936: 
 8937: =item * &get_users_function()
 8938: 
 8939: Used by &bodytag to determine the current users primary role.
 8940: Returns either 'student','coordinator','admin', or 'author'.
 8941: 
 8942: =cut
 8943: 
 8944: ###############################################
 8945: sub get_users_function {
 8946:     my $function = 'norole';
 8947:     if ($env{'request.role'}=~/^(st)/) {
 8948:         $function='student';
 8949:     }
 8950:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 8951:         $function='coordinator';
 8952:     }
 8953:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 8954:         $function='admin';
 8955:     }
 8956:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 8957:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 8958:         $function='author';
 8959:     }
 8960:     return $function;
 8961: }
 8962: 
 8963: ###############################################
 8964: 
 8965: =pod
 8966: 
 8967: =item * &show_course()
 8968: 
 8969: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 8970: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 8971: 
 8972: Inputs:
 8973: None
 8974: 
 8975: Outputs:
 8976: Scalar: 1 if 'Course' to be used, 0 otherwise.
 8977: 
 8978: =cut
 8979: 
 8980: ###############################################
 8981: sub show_course {
 8982:     my $course = !$env{'user.adv'};
 8983:     if (!$env{'user.adv'}) {
 8984:         foreach my $env (keys(%env)) {
 8985:             next if ($env !~ m/^user\.priv\./);
 8986:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 8987:                 $course = 0;
 8988:                 last;
 8989:             }
 8990:         }
 8991:     }
 8992:     return $course;
 8993: }
 8994: 
 8995: ###############################################
 8996: 
 8997: =pod
 8998: 
 8999: =item * &check_user_status()
 9000: 
 9001: Determines current status of supplied role for a
 9002: specific user. Roles can be active, previous or future.
 9003: 
 9004: Inputs: 
 9005: user's domain, user's username, course's domain,
 9006: course's number, optional section ID.
 9007: 
 9008: Outputs:
 9009: role status: active, previous or future. 
 9010: 
 9011: =cut
 9012: 
 9013: sub check_user_status {
 9014:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 9015:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 9016:     my @uroles = keys(%userinfo);
 9017:     my $srchstr;
 9018:     my $active_chk = 'none';
 9019:     my $now = time;
 9020:     if (@uroles > 0) {
 9021:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 9022:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 9023:         } else {
 9024:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 9025:         }
 9026:         if (grep/^\Q$srchstr\E$/,@uroles) {
 9027:             my $role_end = 0;
 9028:             my $role_start = 0;
 9029:             $active_chk = 'active';
 9030:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 9031:                 $role_end = $1;
 9032:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 9033:                     $role_start = $1;
 9034:                 }
 9035:             }
 9036:             if ($role_start > 0) {
 9037:                 if ($now < $role_start) {
 9038:                     $active_chk = 'future';
 9039:                 }
 9040:             }
 9041:             if ($role_end > 0) {
 9042:                 if ($now > $role_end) {
 9043:                     $active_chk = 'previous';
 9044:                 }
 9045:             }
 9046:         }
 9047:     }
 9048:     return $active_chk;
 9049: }
 9050: 
 9051: ###############################################
 9052: 
 9053: =pod
 9054: 
 9055: =item * &get_sections()
 9056: 
 9057: Determines all the sections for a course including
 9058: sections with students and sections containing other roles.
 9059: Incoming parameters: 
 9060: 
 9061: 1. domain
 9062: 2. course number 
 9063: 3. reference to array containing roles for which sections should 
 9064: be gathered (optional).
 9065: 4. reference to array containing status types for which sections 
 9066: should be gathered (optional).
 9067: 
 9068: If the third argument is undefined, sections are gathered for any role. 
 9069: If the fourth argument is undefined, sections are gathered for any status.
 9070: Permissible values are 'active' or 'future' or 'previous'.
 9071:  
 9072: Returns section hash (keys are section IDs, values are
 9073: number of users in each section), subject to the
 9074: optional roles filter, optional status filter 
 9075: 
 9076: =cut
 9077: 
 9078: ###############################################
 9079: sub get_sections {
 9080:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 9081:     if (!defined($cdom) || !defined($cnum)) {
 9082:         my $cid =  $env{'request.course.id'};
 9083: 
 9084: 	return if (!defined($cid));
 9085: 
 9086:         $cdom = $env{'course.'.$cid.'.domain'};
 9087:         $cnum = $env{'course.'.$cid.'.num'};
 9088:     }
 9089: 
 9090:     my %sectioncount;
 9091:     my $now = time;
 9092: 
 9093:     my $check_students = 1;
 9094:     my $only_students = 0;
 9095:     if (ref($possible_roles) eq 'ARRAY') {
 9096:         if (grep(/^st$/,@{$possible_roles})) {
 9097:             if (@{$possible_roles} == 1) {
 9098:                 $only_students = 1;
 9099:             }
 9100:         } else {
 9101:             $check_students = 0;
 9102:         }
 9103:     }
 9104: 
 9105:     if ($check_students) {
 9106: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 9107: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 9108: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 9109:         my $start_index = &Apache::loncoursedata::CL_START();
 9110:         my $end_index = &Apache::loncoursedata::CL_END();
 9111:         my $status;
 9112: 	while (my ($student,$data) = each(%$classlist)) {
 9113: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 9114: 				                     $data->[$status_index],
 9115:                                                      $data->[$start_index],
 9116:                                                      $data->[$end_index]);
 9117:             if ($stu_status eq 'Active') {
 9118:                 $status = 'active';
 9119:             } elsif ($end < $now) {
 9120:                 $status = 'previous';
 9121:             } elsif ($start > $now) {
 9122:                 $status = 'future';
 9123:             } 
 9124: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 9125:                 if ((!defined($possible_status)) || (($status ne '') && 
 9126:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 9127: 		    $sectioncount{$section}++;
 9128:                 }
 9129: 	    }
 9130: 	}
 9131:     }
 9132:     if ($only_students) {
 9133:         return %sectioncount;
 9134:     }
 9135:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9136:     foreach my $user (sort(keys(%courseroles))) {
 9137: 	if ($user !~ /^(\w{2})/) { next; }
 9138: 	my ($role) = ($user =~ /^(\w{2})/);
 9139: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 9140: 	my ($section,$status);
 9141: 	if ($role eq 'cr' &&
 9142: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 9143: 	    $section=$1;
 9144: 	}
 9145: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 9146: 	if (!defined($section) || $section eq '-1') { next; }
 9147:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 9148:         if ($end == -1 && $start == -1) {
 9149:             next; #deleted role
 9150:         }
 9151:         if (!defined($possible_status)) { 
 9152:             $sectioncount{$section}++;
 9153:         } else {
 9154:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 9155:                 $status = 'active';
 9156:             } elsif ($end < $now) {
 9157:                 $status = 'future';
 9158:             } elsif ($start > $now) {
 9159:                 $status = 'previous';
 9160:             }
 9161:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 9162:                 $sectioncount{$section}++;
 9163:             }
 9164:         }
 9165:     }
 9166:     return %sectioncount;
 9167: }
 9168: 
 9169: ###############################################
 9170: 
 9171: =pod
 9172: 
 9173: =item * &get_course_users()
 9174: 
 9175: Retrieves usernames:domains for users in the specified course
 9176: with specific role(s), and access status. 
 9177: 
 9178: Incoming parameters:
 9179: 1. course domain
 9180: 2. course number
 9181: 3. access status: users must have - either active, 
 9182: previous, future, or all.
 9183: 4. reference to array of permissible roles
 9184: 5. reference to array of section restrictions (optional)
 9185: 6. reference to results object (hash of hashes).
 9186: 7. reference to optional userdata hash
 9187: 8. reference to optional statushash
 9188: 9. flag if privileged users (except those set to unhide in
 9189:    course settings) should be excluded    
 9190: Keys of top level results hash are roles.
 9191: Keys of inner hashes are username:domain, with 
 9192: values set to access type.
 9193: Optional userdata hash returns an array with arguments in the 
 9194: same order as loncoursedata::get_classlist() for student data.
 9195: 
 9196: Optional statushash returns
 9197: 
 9198: Entries for end, start, section and status are blank because
 9199: of the possibility of multiple values for non-student roles.
 9200: 
 9201: =cut
 9202: 
 9203: ###############################################
 9204: 
 9205: sub get_course_users {
 9206:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 9207:     my %idx = ();
 9208:     my %seclists;
 9209: 
 9210:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 9211:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 9212:     $idx{end} = &Apache::loncoursedata::CL_END();
 9213:     $idx{start} = &Apache::loncoursedata::CL_START();
 9214:     $idx{id} = &Apache::loncoursedata::CL_ID();
 9215:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 9216:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 9217:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 9218: 
 9219:     if (grep(/^st$/,@{$roles})) {
 9220:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 9221:         my $now = time;
 9222:         foreach my $student (keys(%{$classlist})) {
 9223:             my $match = 0;
 9224:             my $secmatch = 0;
 9225:             my $section = $$classlist{$student}[$idx{section}];
 9226:             my $status = $$classlist{$student}[$idx{status}];
 9227:             if ($section eq '') {
 9228:                 $section = 'none';
 9229:             }
 9230:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 9231:                 if (grep(/^all$/,@{$sections})) {
 9232:                     $secmatch = 1;
 9233:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 9234:                     if (grep(/^none$/,@{$sections})) {
 9235:                         $secmatch = 1;
 9236:                     }
 9237:                 } else {  
 9238: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 9239: 		        $secmatch = 1;
 9240:                     }
 9241: 		}
 9242:                 if (!$secmatch) {
 9243:                     next;
 9244:                 }
 9245:             }
 9246:             if (defined($$types{'active'})) {
 9247:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 9248:                     push(@{$$users{st}{$student}},'active');
 9249:                     $match = 1;
 9250:                 }
 9251:             }
 9252:             if (defined($$types{'previous'})) {
 9253:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 9254:                     push(@{$$users{st}{$student}},'previous');
 9255:                     $match = 1;
 9256:                 }
 9257:             }
 9258:             if (defined($$types{'future'})) {
 9259:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 9260:                     push(@{$$users{st}{$student}},'future');
 9261:                     $match = 1;
 9262:                 }
 9263:             }
 9264:             if ($match) {
 9265:                 push(@{$seclists{$student}},$section);
 9266:                 if (ref($userdata) eq 'HASH') {
 9267:                     $$userdata{$student} = $$classlist{$student};
 9268:                 }
 9269:                 if (ref($statushash) eq 'HASH') {
 9270:                     $statushash->{$student}{'st'}{$section} = $status;
 9271:                 }
 9272:             }
 9273:         }
 9274:     }
 9275:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 9276:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9277:         my $now = time;
 9278:         my %displaystatus = ( previous => 'Expired',
 9279:                               active   => 'Active',
 9280:                               future   => 'Future',
 9281:                             );
 9282:         my (%nothide,@possdoms);
 9283:         if ($hidepriv) {
 9284:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 9285:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 9286:                 if ($user !~ /:/) {
 9287:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 9288:                 } else {
 9289:                     $nothide{$user} = 1;
 9290:                 }
 9291:             }
 9292:             my @possdoms = ($cdom);
 9293:             if ($coursehash{'checkforpriv'}) {
 9294:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 9295:             }
 9296:         }
 9297:         foreach my $person (sort(keys(%coursepersonnel))) {
 9298:             my $match = 0;
 9299:             my $secmatch = 0;
 9300:             my $status;
 9301:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 9302:             $user =~ s/:$//;
 9303:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 9304:             if ($end == -1 || $start == -1) {
 9305:                 next;
 9306:             }
 9307:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 9308:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 9309:                 my ($uname,$udom) = split(/:/,$user);
 9310:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 9311:                     if (grep(/^all$/,@{$sections})) {
 9312:                         $secmatch = 1;
 9313:                     } elsif ($usec eq '') {
 9314:                         if (grep(/^none$/,@{$sections})) {
 9315:                             $secmatch = 1;
 9316:                         }
 9317:                     } else {
 9318:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 9319:                             $secmatch = 1;
 9320:                         }
 9321:                     }
 9322:                     if (!$secmatch) {
 9323:                         next;
 9324:                     }
 9325:                 }
 9326:                 if ($usec eq '') {
 9327:                     $usec = 'none';
 9328:                 }
 9329:                 if ($uname ne '' && $udom ne '') {
 9330:                     if ($hidepriv) {
 9331:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
 9332:                             (!$nothide{$uname.':'.$udom})) {
 9333:                             next;
 9334:                         }
 9335:                     }
 9336:                     if ($end > 0 && $end < $now) {
 9337:                         $status = 'previous';
 9338:                     } elsif ($start > $now) {
 9339:                         $status = 'future';
 9340:                     } else {
 9341:                         $status = 'active';
 9342:                     }
 9343:                     foreach my $type (keys(%{$types})) { 
 9344:                         if ($status eq $type) {
 9345:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 9346:                                 push(@{$$users{$role}{$user}},$type);
 9347:                             }
 9348:                             $match = 1;
 9349:                         }
 9350:                     }
 9351:                     if (($match) && (ref($userdata) eq 'HASH')) {
 9352:                         if (!exists($$userdata{$uname.':'.$udom})) {
 9353: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 9354:                         }
 9355:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 9356:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 9357:                         }
 9358:                         if (ref($statushash) eq 'HASH') {
 9359:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 9360:                         }
 9361:                     }
 9362:                 }
 9363:             }
 9364:         }
 9365:         if (grep(/^ow$/,@{$roles})) {
 9366:             if ((defined($cdom)) && (defined($cnum))) {
 9367:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 9368:                 if ( defined($csettings{'internal.courseowner'}) ) {
 9369:                     my $owner = $csettings{'internal.courseowner'};
 9370:                     next if ($owner eq '');
 9371:                     my ($ownername,$ownerdom);
 9372:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 9373:                         $ownername = $1;
 9374:                         $ownerdom = $2;
 9375:                     } else {
 9376:                         $ownername = $owner;
 9377:                         $ownerdom = $cdom;
 9378:                         $owner = $ownername.':'.$ownerdom;
 9379:                     }
 9380:                     @{$$users{'ow'}{$owner}} = 'any';
 9381:                     if (defined($userdata) && 
 9382: 			!exists($$userdata{$owner})) {
 9383: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 9384:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 9385:                             push(@{$seclists{$owner}},'none');
 9386:                         }
 9387:                         if (ref($statushash) eq 'HASH') {
 9388:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 9389:                         }
 9390: 		    }
 9391:                 }
 9392:             }
 9393:         }
 9394:         foreach my $user (keys(%seclists)) {
 9395:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 9396:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 9397:         }
 9398:     }
 9399:     return;
 9400: }
 9401: 
 9402: sub get_user_info {
 9403:     my ($udom,$uname,$idx,$userdata) = @_;
 9404:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 9405: 	&plainname($uname,$udom,'lastname');
 9406:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 9407:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 9408:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 9409:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 9410:     return;
 9411: }
 9412: 
 9413: ###############################################
 9414: 
 9415: =pod
 9416: 
 9417: =item * &get_user_quota()
 9418: 
 9419: Retrieves quota assigned for storage of user files.
 9420: Default is to report quota for portfolio files.
 9421: 
 9422: Incoming parameters:
 9423: 1. user's username
 9424: 2. user's domain
 9425: 3. quota name - portfolio, author, or course
 9426:    (if no quota name provided, defaults to portfolio).
 9427: 4. crstype - official, unofficial, textbook or community, if quota name is
 9428:    course
 9429: 
 9430: Returns:
 9431: 1. Disk quota (in MB) assigned to student.
 9432: 2. (Optional) Type of setting: custom or default
 9433:    (individually assigned or default for user's 
 9434:    institutional status).
 9435: 3. (Optional) - User's institutional status (e.g., faculty, staff
 9436:    or student - types as defined in localenroll::inst_usertypes 
 9437:    for user's domain, which determines default quota for user.
 9438: 4. (Optional) - Default quota which would apply to the user.
 9439: 
 9440: If a value has been stored in the user's environment, 
 9441: it will return that, otherwise it returns the maximal default
 9442: defined for the user's institutional status(es) in the domain.
 9443: 
 9444: =cut
 9445: 
 9446: ###############################################
 9447: 
 9448: 
 9449: sub get_user_quota {
 9450:     my ($uname,$udom,$quotaname,$crstype) = @_;
 9451:     my ($quota,$quotatype,$settingstatus,$defquota);
 9452:     if (!defined($udom)) {
 9453:         $udom = $env{'user.domain'};
 9454:     }
 9455:     if (!defined($uname)) {
 9456:         $uname = $env{'user.name'};
 9457:     }
 9458:     if (($udom eq '' || $uname eq '') ||
 9459:         ($udom eq 'public') && ($uname eq 'public')) {
 9460:         $quota = 0;
 9461:         $quotatype = 'default';
 9462:         $defquota = 0; 
 9463:     } else {
 9464:         my $inststatus;
 9465:         if ($quotaname eq 'course') {
 9466:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
 9467:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
 9468:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
 9469:             } else {
 9470:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
 9471:                 $quota = $cenv{'internal.uploadquota'};
 9472:             }
 9473:         } else {
 9474:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 9475:                 if ($quotaname eq 'author') {
 9476:                     $quota = $env{'environment.authorquota'};
 9477:                 } else {
 9478:                     $quota = $env{'environment.portfolioquota'};
 9479:                 }
 9480:                 $inststatus = $env{'environment.inststatus'};
 9481:             } else {
 9482:                 my %userenv = 
 9483:                     &Apache::lonnet::get('environment',['portfolioquota',
 9484:                                          'authorquota','inststatus'],$udom,$uname);
 9485:                 my ($tmp) = keys(%userenv);
 9486:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9487:                     if ($quotaname eq 'author') {
 9488:                         $quota = $userenv{'authorquota'};
 9489:                     } else {
 9490:                         $quota = $userenv{'portfolioquota'};
 9491:                     }
 9492:                     $inststatus = $userenv{'inststatus'};
 9493:                 } else {
 9494:                     undef(%userenv);
 9495:                 }
 9496:             }
 9497:         }
 9498:         if ($quota eq '' || wantarray) {
 9499:             if ($quotaname eq 'course') {
 9500:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 9501:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
 9502:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
 9503:                     $defquota = $domdefs{$crstype.'quota'};
 9504:                 }
 9505:                 if ($defquota eq '') {
 9506:                     $defquota = 500;
 9507:                 }
 9508:             } else {
 9509:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
 9510:             }
 9511:             if ($quota eq '') {
 9512:                 $quota = $defquota;
 9513:                 $quotatype = 'default';
 9514:             } else {
 9515:                 $quotatype = 'custom';
 9516:             }
 9517:         }
 9518:     }
 9519:     if (wantarray) {
 9520:         return ($quota,$quotatype,$settingstatus,$defquota);
 9521:     } else {
 9522:         return $quota;
 9523:     }
 9524: }
 9525: 
 9526: ###############################################
 9527: 
 9528: =pod
 9529: 
 9530: =item * &default_quota()
 9531: 
 9532: Retrieves default quota assigned for storage of user portfolio files,
 9533: given an (optional) user's institutional status.
 9534: 
 9535: Incoming parameters:
 9536: 
 9537: 1. domain
 9538: 2. (Optional) institutional status(es).  This is a : separated list of 
 9539:    status types (e.g., faculty, staff, student etc.)
 9540:    which apply to the user for whom the default is being retrieved.
 9541:    If the institutional status string in undefined, the domain
 9542:    default quota will be returned.
 9543: 3.  quota name - portfolio, author, or course
 9544:    (if no quota name provided, defaults to portfolio).
 9545: 
 9546: Returns:
 9547: 
 9548: 1. Default disk quota (in MB) for user portfolios in the domain.
 9549: 2. (Optional) institutional type which determined the value of the
 9550:    default quota.
 9551: 
 9552: If a value has been stored in the domain's configuration db,
 9553: it will return that, otherwise it returns 20 (for backwards 
 9554: compatibility with domains which have not set up a configuration
 9555: db file; the original statically defined portfolio quota was 20 MB). 
 9556: 
 9557: If the user's status includes multiple types (e.g., staff and student),
 9558: the largest default quota which applies to the user determines the
 9559: default quota returned.
 9560: 
 9561: =cut
 9562: 
 9563: ###############################################
 9564: 
 9565: 
 9566: sub default_quota {
 9567:     my ($udom,$inststatus,$quotaname) = @_;
 9568:     my ($defquota,$settingstatus);
 9569:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 9570:                                             ['quotas'],$udom);
 9571:     my $key = 'defaultquota';
 9572:     if ($quotaname eq 'author') {
 9573:         $key = 'authorquota';
 9574:     }
 9575:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 9576:         if ($inststatus ne '') {
 9577:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 9578:             foreach my $item (@statuses) {
 9579:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 9580:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
 9581:                         if ($defquota eq '') {
 9582:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 9583:                             $settingstatus = $item;
 9584:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
 9585:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 9586:                             $settingstatus = $item;
 9587:                         }
 9588:                     }
 9589:                 } elsif ($key eq 'defaultquota') {
 9590:                     if ($quotahash{'quotas'}{$item} ne '') {
 9591:                         if ($defquota eq '') {
 9592:                             $defquota = $quotahash{'quotas'}{$item};
 9593:                             $settingstatus = $item;
 9594:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 9595:                             $defquota = $quotahash{'quotas'}{$item};
 9596:                             $settingstatus = $item;
 9597:                         }
 9598:                     }
 9599:                 }
 9600:             }
 9601:         }
 9602:         if ($defquota eq '') {
 9603:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 9604:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
 9605:             } elsif ($key eq 'defaultquota') {
 9606:                 $defquota = $quotahash{'quotas'}{'default'};
 9607:             }
 9608:             $settingstatus = 'default';
 9609:             if ($defquota eq '') {
 9610:                 if ($quotaname eq 'author') {
 9611:                     $defquota = 500;
 9612:                 }
 9613:             }
 9614:         }
 9615:     } else {
 9616:         $settingstatus = 'default';
 9617:         if ($quotaname eq 'author') {
 9618:             $defquota = 500;
 9619:         } else {
 9620:             $defquota = 20;
 9621:         }
 9622:     }
 9623:     if (wantarray) {
 9624:         return ($defquota,$settingstatus);
 9625:     } else {
 9626:         return $defquota;
 9627:     }
 9628: }
 9629: 
 9630: ###############################################
 9631: 
 9632: =pod
 9633: 
 9634: =item * &excess_filesize_warning()
 9635: 
 9636: Returns warning message if upload of file to authoring space, or copying
 9637: of existing file within authoring space will cause quota for the authoring
 9638: space to be exceeded.
 9639: 
 9640: Same, if upload of a file directly to a course/community via Course Editor
 9641: will cause quota for uploaded content for the course to be exceeded.
 9642: 
 9643: Inputs: 7 
 9644: 1. username or coursenum
 9645: 2. domain
 9646: 3. context ('author' or 'course')
 9647: 4. filename of file for which action is being requested
 9648: 5. filesize (kB) of file
 9649: 6. action being taken: copy or upload.
 9650: 7. quotatype (in course context -- official, unofficial, community or textbook).
 9651: 
 9652: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
 9653:          otherwise return null.
 9654: 
 9655: =back
 9656: 
 9657: =cut
 9658: 
 9659: sub excess_filesize_warning {
 9660:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
 9661:     my $current_disk_usage = 0;
 9662:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
 9663:     if ($context eq 'author') {
 9664:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
 9665:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
 9666:     } else {
 9667:         foreach my $subdir ('docs','supplemental') {
 9668:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
 9669:         }
 9670:     }
 9671:     $disk_quota = int($disk_quota * 1000);
 9672:     if (($current_disk_usage + $filesize) > $disk_quota) {
 9673:         return '<p class="LC_warning">'.
 9674:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
 9675:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
 9676:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
 9677:                             $disk_quota,$current_disk_usage).
 9678:                '</p>';
 9679:     }
 9680:     return;
 9681: }
 9682: 
 9683: ###############################################
 9684: 
 9685: 
 9686: sub get_secgrprole_info {
 9687:     my ($cdom,$cnum,$needroles,$type)  = @_;
 9688:     my %sections_count = &get_sections($cdom,$cnum);
 9689:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 9690:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 9691:     my @groups = sort(keys(%curr_groups));
 9692:     my $allroles = [];
 9693:     my $rolehash;
 9694:     my $accesshash = {
 9695:                      active => 'Currently has access',
 9696:                      future => 'Will have future access',
 9697:                      previous => 'Previously had access',
 9698:                   };
 9699:     if ($needroles) {
 9700:         $rolehash = {'all' => 'all'};
 9701:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9702: 	if (&Apache::lonnet::error(%user_roles)) {
 9703: 	    undef(%user_roles);
 9704: 	}
 9705:         foreach my $item (keys(%user_roles)) {
 9706:             my ($role)=split(/\:/,$item,2);
 9707:             if ($role eq 'cr') { next; }
 9708:             if ($role =~ /^cr/) {
 9709:                 $$rolehash{$role} = (split('/',$role))[3];
 9710:             } else {
 9711:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 9712:             }
 9713:         }
 9714:         foreach my $key (sort(keys(%{$rolehash}))) {
 9715:             push(@{$allroles},$key);
 9716:         }
 9717:         push (@{$allroles},'st');
 9718:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 9719:     }
 9720:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 9721: }
 9722: 
 9723: sub user_picker {
 9724:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
 9725:     my $currdom = $dom;
 9726:     my @alldoms = &Apache::lonnet::all_domains();
 9727:     if (@alldoms == 1) {
 9728:         my %domsrch = &Apache::lonnet::get_dom('configuration',
 9729:                                                ['directorysrch'],$alldoms[0]);
 9730:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
 9731:         my $showdom = $domdesc;
 9732:         if ($showdom eq '') {
 9733:             $showdom = $dom;
 9734:         }
 9735:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
 9736:             if ((!$domsrch{'directorysrch'}{'available'}) &&
 9737:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
 9738:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
 9739:             }
 9740:         }
 9741:     }
 9742:     my %curr_selected = (
 9743:                         srchin => 'dom',
 9744:                         srchby => 'lastname',
 9745:                       );
 9746:     my $srchterm;
 9747:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 9748:         if ($srch->{'srchby'} ne '') {
 9749:             $curr_selected{'srchby'} = $srch->{'srchby'};
 9750:         }
 9751:         if ($srch->{'srchin'} ne '') {
 9752:             $curr_selected{'srchin'} = $srch->{'srchin'};
 9753:         }
 9754:         if ($srch->{'srchtype'} ne '') {
 9755:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 9756:         }
 9757:         if ($srch->{'srchdomain'} ne '') {
 9758:             $currdom = $srch->{'srchdomain'};
 9759:         }
 9760:         $srchterm = $srch->{'srchterm'};
 9761:     }
 9762:     my %html_lt=&Apache::lonlocal::texthash(
 9763:                     'usr'       => 'Search criteria',
 9764:                     'doma'      => 'Domain/institution to search',
 9765:                     'uname'     => 'username',
 9766:                     'lastname'  => 'last name',
 9767:                     'lastfirst' => 'last name, first name',
 9768:                     'crs'       => 'in this course',
 9769:                     'dom'       => 'in selected LON-CAPA domain', 
 9770:                     'alc'       => 'all LON-CAPA',
 9771:                     'instd'     => 'in institutional directory for selected domain',
 9772:                     'exact'     => 'is',
 9773:                     'contains'  => 'contains',
 9774:                     'begins'    => 'begins with',
 9775:                                        );
 9776:     my %js_lt=&Apache::lonlocal::texthash(
 9777:                     'youm'      => "You must include some text to search for.",
 9778:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 9779:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 9780:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 9781:                     'ymcd'      => "You must choose a domain when using a domain search.",
 9782:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 9783:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 9784:                      'thfo'     => "The following need to be corrected before the search can be run:",
 9785:                                        );
 9786:     &html_escape(\%html_lt);
 9787:     &js_escape(\%js_lt);
 9788:     my $domform;
 9789:     my $allow_blank = 1;
 9790:     if ($fixeddom) {
 9791:         $allow_blank = 0;
 9792:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
 9793:     } else {
 9794:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1);
 9795:     }
 9796:     my $srchinsel = ' <select name="srchin">';
 9797: 
 9798:     my @srchins = ('crs','dom','alc','instd');
 9799: 
 9800:     foreach my $option (@srchins) {
 9801:         # FIXME 'alc' option unavailable until 
 9802:         #       loncreateuser::print_user_query_page()
 9803:         #       has been completed.
 9804:         next if ($option eq 'alc');
 9805:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
 9806:         next if ($option eq 'crs' && !$env{'request.course.id'});
 9807:         next if (($option eq 'instd') && ($noinstd));
 9808:         if ($curr_selected{'srchin'} eq $option) {
 9809:             $srchinsel .= ' 
 9810:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
 9811:         } else {
 9812:             $srchinsel .= '
 9813:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
 9814:         }
 9815:     }
 9816:     $srchinsel .= "\n  </select>\n";
 9817: 
 9818:     my $srchbysel =  ' <select name="srchby">';
 9819:     foreach my $option ('lastname','lastfirst','uname') {
 9820:         if ($curr_selected{'srchby'} eq $option) {
 9821:             $srchbysel .= '
 9822:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
 9823:         } else {
 9824:             $srchbysel .= '
 9825:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
 9826:          }
 9827:     }
 9828:     $srchbysel .= "\n  </select>\n";
 9829: 
 9830:     my $srchtypesel = ' <select name="srchtype">';
 9831:     foreach my $option ('begins','contains','exact') {
 9832:         if ($curr_selected{'srchtype'} eq $option) {
 9833:             $srchtypesel .= '
 9834:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
 9835:         } else {
 9836:             $srchtypesel .= '
 9837:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
 9838:         }
 9839:     }
 9840:     $srchtypesel .= "\n  </select>\n";
 9841: 
 9842:     my ($newuserscript,$new_user_create);
 9843:     my $context_dom = $env{'request.role.domain'};
 9844:     if ($context eq 'requestcrs') {
 9845:         if ($env{'form.coursedom'} ne '') { 
 9846:             $context_dom = $env{'form.coursedom'};
 9847:         }
 9848:     }
 9849:     if ($forcenewuser) {
 9850:         if (ref($srch) eq 'HASH') {
 9851:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
 9852:                 if ($cancreate) {
 9853:                     $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>';
 9854:                 } else {
 9855:                     my $helplink = 'javascript:helpMenu('."'display'".')';
 9856:                     my %usertypetext = (
 9857:                         official   => 'institutional',
 9858:                         unofficial => 'non-institutional',
 9859:                     );
 9860:                     $new_user_create = '<p class="LC_warning">'
 9861:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 9862:                                       .' '
 9863:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 9864:                                           ,'<a href="'.$helplink.'">','</a>')
 9865:                                       .'</p><br />';
 9866:                 }
 9867:             }
 9868:         }
 9869: 
 9870:         $newuserscript = <<"ENDSCRIPT";
 9871: 
 9872: function setSearch(createnew,callingForm) {
 9873:     if (createnew == 1) {
 9874:         for (var i=0; i<callingForm.srchby.length; i++) {
 9875:             if (callingForm.srchby.options[i].value == 'uname') {
 9876:                 callingForm.srchby.selectedIndex = i;
 9877:             }
 9878:         }
 9879:         for (var i=0; i<callingForm.srchin.length; i++) {
 9880:             if ( callingForm.srchin.options[i].value == 'dom') {
 9881: 		callingForm.srchin.selectedIndex = i;
 9882:             }
 9883:         }
 9884:         for (var i=0; i<callingForm.srchtype.length; i++) {
 9885:             if (callingForm.srchtype.options[i].value == 'exact') {
 9886:                 callingForm.srchtype.selectedIndex = i;
 9887:             }
 9888:         }
 9889:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 9890:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
 9891:                 callingForm.srchdomain.selectedIndex = i;
 9892:             }
 9893:         }
 9894:     }
 9895: }
 9896: ENDSCRIPT
 9897: 
 9898:     }
 9899: 
 9900:     my $output = <<"END_BLOCK";
 9901: <script type="text/javascript">
 9902: // <![CDATA[
 9903: function validateEntry(callingForm) {
 9904: 
 9905:     var checkok = 1;
 9906:     var srchin;
 9907:     for (var i=0; i<callingForm.srchin.length; i++) {
 9908: 	if ( callingForm.srchin[i].checked ) {
 9909: 	    srchin = callingForm.srchin[i].value;
 9910: 	}
 9911:     }
 9912: 
 9913:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 9914:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 9915:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 9916:     var srchterm =  callingForm.srchterm.value;
 9917:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 9918:     var msg = "";
 9919: 
 9920:     if (srchterm == "") {
 9921:         checkok = 0;
 9922:         msg += "$js_lt{'youm'}\\n";
 9923:     }
 9924: 
 9925:     if (srchtype== 'begins') {
 9926:         if (srchterm.length < 2) {
 9927:             checkok = 0;
 9928:             msg += "$js_lt{'thte'}\\n";
 9929:         }
 9930:     }
 9931: 
 9932:     if (srchtype== 'contains') {
 9933:         if (srchterm.length < 3) {
 9934:             checkok = 0;
 9935:             msg += "$js_lt{'thet'}\\n";
 9936:         }
 9937:     }
 9938:     if (srchin == 'instd') {
 9939:         if (srchdomain == '') {
 9940:             checkok = 0;
 9941:             msg += "$js_lt{'yomc'}\\n";
 9942:         }
 9943:     }
 9944:     if (srchin == 'dom') {
 9945:         if (srchdomain == '') {
 9946:             checkok = 0;
 9947:             msg += "$js_lt{'ymcd'}\\n";
 9948:         }
 9949:     }
 9950:     if (srchby == 'lastfirst') {
 9951:         if (srchterm.indexOf(",") == -1) {
 9952:             checkok = 0;
 9953:             msg += "$js_lt{'whus'}\\n";
 9954:         }
 9955:         if (srchterm.indexOf(",") == srchterm.length -1) {
 9956:             checkok = 0;
 9957:             msg += "$js_lt{'whse'}\\n";
 9958:         }
 9959:     }
 9960:     if (checkok == 0) {
 9961:         alert("$js_lt{'thfo'}\\n"+msg);
 9962:         return;
 9963:     }
 9964:     if (checkok == 1) {
 9965:         callingForm.submit();
 9966:     }
 9967: }
 9968: 
 9969: $newuserscript
 9970: 
 9971: // ]]>
 9972: </script>
 9973: 
 9974: $new_user_create
 9975: 
 9976: END_BLOCK
 9977: 
 9978:     $output .= &Apache::lonhtmlcommon::start_pick_box().
 9979:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
 9980:                $domform.
 9981:                &Apache::lonhtmlcommon::row_closure().
 9982:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
 9983:                $srchbysel.
 9984:                $srchtypesel. 
 9985:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
 9986:                $srchinsel.
 9987:                &Apache::lonhtmlcommon::row_closure(1). 
 9988:                &Apache::lonhtmlcommon::end_pick_box().
 9989:                '<br />';
 9990:     return ($output,1);
 9991: }
 9992: 
 9993: sub user_rule_check {
 9994:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 9995:     my ($response,%inst_response);
 9996:     if (ref($usershash) eq 'HASH') {
 9997:         if (keys(%{$usershash}) > 1) {
 9998:             my (%by_username,%by_id,%userdoms);
 9999:             my $checkid;
10000:             if (ref($checks) eq 'HASH') {
10001:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
10002:                     $checkid = 1;
10003:                 }
10004:             }
10005:             foreach my $user (keys(%{$usershash})) {
10006:                 my ($uname,$udom) = split(/:/,$user);
10007:                 if ($checkid) {
10008:                     if (ref($usershash->{$user}) eq 'HASH') {
10009:                         if ($usershash->{$user}->{'id'} ne '') {
10010:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
10011:                             $userdoms{$udom} = 1;
10012:                             if (ref($inst_results) eq 'HASH') {
10013:                                 $inst_results->{$uname.':'.$udom} = {};
10014:                             }
10015:                         }
10016:                     }
10017:                 } else {
10018:                     $by_username{$udom}{$uname} = 1;
10019:                     $userdoms{$udom} = 1;
10020:                     if (ref($inst_results) eq 'HASH') {
10021:                         $inst_results->{$uname.':'.$udom} = {};
10022:                     }
10023:                 }
10024:             }
10025:             foreach my $udom (keys(%userdoms)) {
10026:                 if (!$got_rules->{$udom}) {
10027:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
10028:                                                              ['usercreation'],$udom);
10029:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
10030:                         foreach my $item ('username','id') {
10031:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10032:                                 $$curr_rules{$udom}{$item} =
10033:                                     $domconfig{'usercreation'}{$item.'_rule'};
10034:                             }
10035:                         }
10036:                     }
10037:                     $got_rules->{$udom} = 1;
10038:                 }
10039:             }
10040:             if ($checkid) {
10041:                 foreach my $udom (keys(%by_id)) {
10042:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
10043:                     if ($outcome eq 'ok') {
10044:                         foreach my $id (keys(%{$by_id{$udom}})) {
10045:                             my $uname = $by_id{$udom}{$id};
10046:                             $inst_response{$uname.':'.$udom} = $outcome;
10047:                         }
10048:                         if (ref($results) eq 'HASH') {
10049:                             foreach my $uname (keys(%{$results})) {
10050:                                 if (exists($inst_response{$uname.':'.$udom})) {
10051:                                     $inst_response{$uname.':'.$udom} = $outcome;
10052:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
10053:                                 }
10054:                             }
10055:                         }
10056:                     }
10057:                 }
10058:             } else {
10059:                 foreach my $udom (keys(%by_username)) {
10060:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
10061:                     if ($outcome eq 'ok') {
10062:                         foreach my $uname (keys(%{$by_username{$udom}})) {
10063:                             $inst_response{$uname.':'.$udom} = $outcome;
10064:                         }
10065:                         if (ref($results) eq 'HASH') {
10066:                             foreach my $uname (keys(%{$results})) {
10067:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
10068:                             }
10069:                         }
10070:                     }
10071:                 }
10072:             }
10073:         } elsif (keys(%{$usershash}) == 1) {
10074:             my $user = (keys(%{$usershash}))[0];
10075:             my ($uname,$udom) = split(/:/,$user);
10076:             if (($udom ne '') && ($uname ne '')) {
10077:                 if (ref($usershash->{$user}) eq 'HASH') {
10078:                     if (ref($checks) eq 'HASH') {
10079:                         if (defined($checks->{'username'})) {
10080:                             ($inst_response{$user},%{$inst_results->{$user}}) =
10081:                                 &Apache::lonnet::get_instuser($udom,$uname);
10082:                         } elsif (defined($checks->{'id'})) {
10083:                             if ($usershash->{$user}->{'id'} ne '') {
10084:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
10085:                                     &Apache::lonnet::get_instuser($udom,undef,
10086:                                                                   $usershash->{$user}->{'id'});
10087:                             } else {
10088:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
10089:                                     &Apache::lonnet::get_instuser($udom,$uname);
10090:                             }
10091:                         }
10092:                     } else {
10093:                        ($inst_response{$user},%{$inst_results->{$user}}) =
10094:                             &Apache::lonnet::get_instuser($udom,$uname);
10095:                        return;
10096:                     }
10097:                     if (!$got_rules->{$udom}) {
10098:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
10099:                                                                  ['usercreation'],$udom);
10100:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
10101:                             foreach my $item ('username','id') {
10102:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10103:                                    $$curr_rules{$udom}{$item} =
10104:                                        $domconfig{'usercreation'}{$item.'_rule'};
10105:                                 }
10106:                             }
10107:                         }
10108:                         $got_rules->{$udom} = 1;
10109:                     }
10110:                 }
10111:             } else {
10112:                 return;
10113:             }
10114:         } else {
10115:             return;
10116:         }
10117:         foreach my $user (keys(%{$usershash})) {
10118:             my ($uname,$udom) = split(/:/,$user);
10119:             next if (($udom eq '') || ($uname eq ''));
10120:             my $id;
10121:             if (ref($inst_results) eq 'HASH') {
10122:                 if (ref($inst_results->{$user}) eq 'HASH') {
10123:                     $id = $inst_results->{$user}->{'id'};
10124:                 }
10125:             }
10126:             if ($id eq '') {
10127:                 if (ref($usershash->{$user})) {
10128:                     $id = $usershash->{$user}->{'id'};
10129:                 }
10130:             }
10131:             foreach my $item (keys(%{$checks})) {
10132:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
10133:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
10134:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
10135:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
10136:                                                                              $$curr_rules{$udom}{$item});
10137:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
10138:                                 if ($rule_check{$rule}) {
10139:                                     $$rulematch{$user}{$item} = $rule;
10140:                                     if ($inst_response{$user} eq 'ok') {
10141:                                         if (ref($inst_results) eq 'HASH') {
10142:                                             if (ref($inst_results->{$user}) eq 'HASH') {
10143:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
10144:                                                     $$alerts{$item}{$udom}{$uname} = 1;
10145:                                                 } elsif ($item eq 'id') {
10146:                                                     if ($inst_results->{$user}->{'id'} eq '') {
10147:                                                         $$alerts{$item}{$udom}{$uname} = 1;
10148:                                                     }
10149:                                                 }
10150:                                             }
10151:                                         }
10152:                                     }
10153:                                     last;
10154:                                 }
10155:                             }
10156:                         }
10157:                     }
10158:                 }
10159:             }
10160:         }
10161:     }
10162:     return;
10163: }
10164: 
10165: sub user_rule_formats {
10166:     my ($domain,$domdesc,$curr_rules,$check) = @_;
10167:     my %text = ( 
10168:                  'username' => 'Usernames',
10169:                  'id'       => 'IDs',
10170:                );
10171:     my $output;
10172:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
10173:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
10174:         if (@{$ruleorder} > 0) {
10175:             $output = '<br />'.
10176:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
10177:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
10178:                       ' <ul>';
10179:             foreach my $rule (@{$ruleorder}) {
10180:                 if (ref($curr_rules) eq 'ARRAY') {
10181:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
10182:                         if (ref($rules->{$rule}) eq 'HASH') {
10183:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
10184:                                         $rules->{$rule}{'desc'}.'</li>';
10185:                         }
10186:                     }
10187:                 }
10188:             }
10189:             $output .= '</ul>';
10190:         }
10191:     }
10192:     return $output;
10193: }
10194: 
10195: sub instrule_disallow_msg {
10196:     my ($checkitem,$domdesc,$count,$mode) = @_;
10197:     my $response;
10198:     my %text = (
10199:                   item   => 'username',
10200:                   items  => 'usernames',
10201:                   match  => 'matches',
10202:                   do     => 'does',
10203:                   action => 'a username',
10204:                   one    => 'one',
10205:                );
10206:     if ($count > 1) {
10207:         $text{'item'} = 'usernames';
10208:         $text{'match'} ='match';
10209:         $text{'do'} = 'do';
10210:         $text{'action'} = 'usernames',
10211:         $text{'one'} = 'ones';
10212:     }
10213:     if ($checkitem eq 'id') {
10214:         $text{'items'} = 'IDs';
10215:         $text{'item'} = 'ID';
10216:         $text{'action'} = 'an ID';
10217:         if ($count > 1) {
10218:             $text{'item'} = 'IDs';
10219:             $text{'action'} = 'IDs';
10220:         }
10221:     }
10222:     $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 />';
10223:     if ($mode eq 'upload') {
10224:         if ($checkitem eq 'username') {
10225:             $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'}.");
10226:         } elsif ($checkitem eq 'id') {
10227:             $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.");
10228:         }
10229:     } elsif ($mode eq 'selfcreate') {
10230:         if ($checkitem eq 'id') {
10231:             $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.");
10232:         }
10233:     } else {
10234:         if ($checkitem eq 'username') {
10235:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
10236:         } elsif ($checkitem eq 'id') {
10237:             $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.");
10238:         }
10239:     }
10240:     return $response;
10241: }
10242: 
10243: sub personal_data_fieldtitles {
10244:     my %fieldtitles = &Apache::lonlocal::texthash (
10245:                         id => 'Student/Employee ID',
10246:                         permanentemail => 'E-mail address',
10247:                         lastname => 'Last Name',
10248:                         firstname => 'First Name',
10249:                         middlename => 'Middle Name',
10250:                         generation => 'Generation',
10251:                         gen => 'Generation',
10252:                         inststatus => 'Affiliation',
10253:                    );
10254:     return %fieldtitles;
10255: }
10256: 
10257: sub sorted_inst_types {
10258:     my ($dom) = @_;
10259:     my ($usertypes,$order);
10260:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
10261:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
10262:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
10263:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
10264:     } else {
10265:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
10266:     }
10267:     my $othertitle = &mt('All users');
10268:     if ($env{'request.course.id'}) {
10269:         $othertitle  = &mt('Any users');
10270:     }
10271:     my @types;
10272:     if (ref($order) eq 'ARRAY') {
10273:         @types = @{$order};
10274:     }
10275:     if (@types == 0) {
10276:         if (ref($usertypes) eq 'HASH') {
10277:             @types = sort(keys(%{$usertypes}));
10278:         }
10279:     }
10280:     if (keys(%{$usertypes}) > 0) {
10281:         $othertitle = &mt('Other users');
10282:     }
10283:     return ($othertitle,$usertypes,\@types);
10284: }
10285: 
10286: sub get_institutional_codes {
10287:     my ($settings,$allcourses,$LC_code) = @_;
10288: # Get complete list of course sections to update
10289:     my @currsections = ();
10290:     my @currxlists = ();
10291:     my $coursecode = $$settings{'internal.coursecode'};
10292: 
10293:     if ($$settings{'internal.sectionnums'} ne '') {
10294:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
10295:     }
10296: 
10297:     if ($$settings{'internal.crosslistings'} ne '') {
10298:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
10299:     }
10300: 
10301:     if (@currxlists > 0) {
10302:         foreach (@currxlists) {
10303:             if (m/^([^:]+):(\w*)$/) {
10304:                 unless (grep/^$1$/,@{$allcourses}) {
10305:                     push(@{$allcourses},$1);
10306:                     $$LC_code{$1} = $2;
10307:                 }
10308:             }
10309:         }
10310:     }
10311:  
10312:     if (@currsections > 0) {
10313:         foreach (@currsections) {
10314:             if (m/^(\w+):(\w*)$/) {
10315:                 my $sec = $coursecode.$1;
10316:                 my $lc_sec = $2;
10317:                 unless (grep/^$sec$/,@{$allcourses}) {
10318:                     push(@{$allcourses},$sec);
10319:                     $$LC_code{$sec} = $lc_sec;
10320:                 }
10321:             }
10322:         }
10323:     }
10324:     return;
10325: }
10326: 
10327: sub get_standard_codeitems {
10328:     return ('Year','Semester','Department','Number','Section');
10329: }
10330: 
10331: =pod
10332: 
10333: =head1 Slot Helpers
10334: 
10335: =over 4
10336: 
10337: =item * sorted_slots()
10338: 
10339: Sorts an array of slot names in order of an optional sort key,
10340: default sort is by slot start time (earliest first). 
10341: 
10342: Inputs:
10343: 
10344: =over 4
10345: 
10346: slotsarr  - Reference to array of unsorted slot names.
10347: 
10348: slots     - Reference to hash of hash, where outer hash keys are slot names.
10349: 
10350: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
10351: 
10352: =back
10353: 
10354: Returns:
10355: 
10356: =over 4
10357: 
10358: sorted   - An array of slot names sorted by a specified sort key 
10359:            (default sort key is start time of the slot).
10360: 
10361: =back
10362: 
10363: =cut
10364: 
10365: 
10366: sub sorted_slots {
10367:     my ($slotsarr,$slots,$sortkey) = @_;
10368:     if ($sortkey eq '') {
10369:         $sortkey = 'starttime';
10370:     }
10371:     my @sorted;
10372:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
10373:         @sorted =
10374:             sort {
10375:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
10376:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
10377:                      }
10378:                      if (ref($slots->{$a})) { return -1;}
10379:                      if (ref($slots->{$b})) { return 1;}
10380:                      return 0;
10381:                  } @{$slotsarr};
10382:     }
10383:     return @sorted;
10384: }
10385: 
10386: =pod
10387: 
10388: =item * get_future_slots()
10389: 
10390: Inputs:
10391: 
10392: =over 4
10393: 
10394: cnum - course number
10395: 
10396: cdom - course domain
10397: 
10398: now - current UNIX time
10399: 
10400: symb - optional symb
10401: 
10402: =back
10403: 
10404: Returns:
10405: 
10406: =over 4
10407: 
10408: sorted_reservable - ref to array of student_schedulable slots currently 
10409:                     reservable, ordered by end date of reservation period.
10410: 
10411: reservable_now - ref to hash of student_schedulable slots currently
10412:                  reservable.
10413: 
10414:     Keys in inner hash are:
10415:     (a) symb: either blank or symb to which slot use is restricted.
10416:     (b) endreserve: end date of reservation period.
10417:     (c) uniqueperiod: start,end dates when slot is to be uniquely
10418:         selected.
10419: 
10420: sorted_future - ref to array of student_schedulable slots reservable in
10421:                 the future, ordered by start date of reservation period.
10422: 
10423: future_reservable - ref to hash of student_schedulable slots reservable
10424:                     in the future.
10425: 
10426:     Keys in inner hash are:
10427:     (a) symb: either blank or symb to which slot use is restricted.
10428:     (b) startreserve:  start date of reservation period.
10429:     (c) uniqueperiod: start,end dates when slot is to be uniquely
10430:         selected.
10431: 
10432: =back
10433: 
10434: =cut
10435: 
10436: sub get_future_slots {
10437:     my ($cnum,$cdom,$now,$symb) = @_;
10438:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
10439:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
10440:     foreach my $slot (keys(%slots)) {
10441:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
10442:         if ($symb) {
10443:             next if (($slots{$slot}->{'symb'} ne '') && 
10444:                      ($slots{$slot}->{'symb'} ne $symb));
10445:         }
10446:         if (($slots{$slot}->{'starttime'} > $now) &&
10447:             ($slots{$slot}->{'endtime'} > $now)) {
10448:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
10449:                 my $userallowed = 0;
10450:                 if ($slots{$slot}->{'allowedsections'}) {
10451:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
10452:                     if (!defined($env{'request.role.sec'})
10453:                         && grep(/^No section assigned$/,@allowed_sec)) {
10454:                         $userallowed=1;
10455:                     } else {
10456:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
10457:                             $userallowed=1;
10458:                         }
10459:                     }
10460:                     unless ($userallowed) {
10461:                         if (defined($env{'request.course.groups'})) {
10462:                             my @groups = split(/:/,$env{'request.course.groups'});
10463:                             foreach my $group (@groups) {
10464:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
10465:                                     $userallowed=1;
10466:                                     last;
10467:                                 }
10468:                             }
10469:                         }
10470:                     }
10471:                 }
10472:                 if ($slots{$slot}->{'allowedusers'}) {
10473:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
10474:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
10475:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
10476:                         $userallowed = 1;
10477:                     }
10478:                 }
10479:                 next unless($userallowed);
10480:             }
10481:             my $startreserve = $slots{$slot}->{'startreserve'};
10482:             my $endreserve = $slots{$slot}->{'endreserve'};
10483:             my $symb = $slots{$slot}->{'symb'};
10484:             my $uniqueperiod;
10485:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
10486:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
10487:             }
10488:             if (($startreserve < $now) &&
10489:                 (!$endreserve || $endreserve > $now)) {
10490:                 my $lastres = $endreserve;
10491:                 if (!$lastres) {
10492:                     $lastres = $slots{$slot}->{'starttime'};
10493:                 }
10494:                 $reservable_now{$slot} = {
10495:                                            symb       => $symb,
10496:                                            endreserve => $lastres,
10497:                                            uniqueperiod => $uniqueperiod,   
10498:                                          };
10499:             } elsif (($startreserve > $now) &&
10500:                      (!$endreserve || $endreserve > $startreserve)) {
10501:                 $future_reservable{$slot} = {
10502:                                               symb         => $symb,
10503:                                               startreserve => $startreserve,
10504:                                               uniqueperiod => $uniqueperiod,
10505:                                             };
10506:             }
10507:         }
10508:     }
10509:     my @unsorted_reservable = keys(%reservable_now);
10510:     if (@unsorted_reservable > 0) {
10511:         @sorted_reservable = 
10512:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
10513:     }
10514:     my @unsorted_future = keys(%future_reservable);
10515:     if (@unsorted_future > 0) {
10516:         @sorted_future =
10517:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
10518:     }
10519:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
10520: }
10521: 
10522: =pod
10523: 
10524: =back
10525: 
10526: =head1 HTTP Helpers
10527: 
10528: =over 4
10529: 
10530: =item * &get_unprocessed_cgi($query,$possible_names)
10531: 
10532: Modify the %env hash to contain unprocessed CGI form parameters held in
10533: $query.  The parameters listed in $possible_names (an array reference),
10534: will be set in $env{'form.name'} if they do not already exist.
10535: 
10536: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
10537: $possible_names is an ref to an array of form element names.  As an example:
10538: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
10539: will result in $env{'form.uname'} and $env{'form.udom'} being set.
10540: 
10541: =cut
10542: 
10543: sub get_unprocessed_cgi {
10544:   my ($query,$possible_names)= @_;
10545:   # $Apache::lonxml::debug=1;
10546:   foreach my $pair (split(/&/,$query)) {
10547:     my ($name, $value) = split(/=/,$pair);
10548:     $name = &unescape($name);
10549:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
10550:       $value =~ tr/+/ /;
10551:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
10552:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
10553:     }
10554:   }
10555: }
10556: 
10557: =pod
10558: 
10559: =item * &cacheheader() 
10560: 
10561: returns cache-controlling header code
10562: 
10563: =cut
10564: 
10565: sub cacheheader {
10566:     unless ($env{'request.method'} eq 'GET') { return ''; }
10567:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
10568:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
10569:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
10570:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
10571:     return $output;
10572: }
10573: 
10574: =pod
10575: 
10576: =item * &no_cache($r) 
10577: 
10578: specifies header code to not have cache
10579: 
10580: =cut
10581: 
10582: sub no_cache {
10583:     my ($r) = @_;
10584:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
10585: 	$env{'request.method'} ne 'GET') { return ''; }
10586:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
10587:     $r->no_cache(1);
10588:     $r->header_out("Expires" => $date);
10589:     $r->header_out("Pragma" => "no-cache");
10590: }
10591: 
10592: sub content_type {
10593:     my ($r,$type,$charset) = @_;
10594:     if ($r) {
10595: 	#  Note that printout.pl calls this with undef for $r.
10596: 	&no_cache($r);
10597:     }
10598:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
10599:     unless ($charset) {
10600: 	$charset=&Apache::lonlocal::current_encoding;
10601:     }
10602:     if ($charset) { $type.='; charset='.$charset; }
10603:     if ($r) {
10604: 	$r->content_type($type);
10605:     } else {
10606: 	print("Content-type: $type\n\n");
10607:     }
10608: }
10609: 
10610: =pod
10611: 
10612: =item * &add_to_env($name,$value) 
10613: 
10614: adds $name to the %env hash with value
10615: $value, if $name already exists, the entry is converted to an array
10616: reference and $value is added to the array.
10617: 
10618: =cut
10619: 
10620: sub add_to_env {
10621:   my ($name,$value)=@_;
10622:   if (defined($env{$name})) {
10623:     if (ref($env{$name})) {
10624:       #already have multiple values
10625:       push(@{ $env{$name} },$value);
10626:     } else {
10627:       #first time seeing multiple values, convert hash entry to an arrayref
10628:       my $first=$env{$name};
10629:       undef($env{$name});
10630:       push(@{ $env{$name} },$first,$value);
10631:     }
10632:   } else {
10633:     $env{$name}=$value;
10634:   }
10635: }
10636: 
10637: =pod
10638: 
10639: =item * &get_env_multiple($name) 
10640: 
10641: gets $name from the %env hash, it seemlessly handles the cases where multiple
10642: values may be defined and end up as an array ref.
10643: 
10644: returns an array of values
10645: 
10646: =cut
10647: 
10648: sub get_env_multiple {
10649:     my ($name) = @_;
10650:     my @values;
10651:     if (defined($env{$name})) {
10652:         # exists is it an array
10653:         if (ref($env{$name})) {
10654:             @values=@{ $env{$name} };
10655:         } else {
10656:             $values[0]=$env{$name};
10657:         }
10658:     }
10659:     return(@values);
10660: }
10661: 
10662: sub ask_for_embedded_content {
10663:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
10664:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
10665:         %currsubfile,%unused,$rem);
10666:     my $counter = 0;
10667:     my $numnew = 0;
10668:     my $numremref = 0;
10669:     my $numinvalid = 0;
10670:     my $numpathchg = 0;
10671:     my $numexisting = 0;
10672:     my $numunused = 0;
10673:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
10674:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
10675:     my $heading = &mt('Upload embedded files');
10676:     my $buttontext = &mt('Upload');
10677: 
10678:     if ($env{'request.course.id'}) {
10679:         if ($actionurl eq '/adm/dependencies') {
10680:             $navmap = Apache::lonnavmaps::navmap->new();
10681:         }
10682:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10683:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10684:     }
10685:     if (($actionurl eq '/adm/portfolio') ||
10686:         ($actionurl eq '/adm/coursegrp_portfolio')) {
10687:         my $current_path='/';
10688:         if ($env{'form.currentpath'}) {
10689:             $current_path = $env{'form.currentpath'};
10690:         }
10691:         if ($actionurl eq '/adm/coursegrp_portfolio') {
10692:             $udom = $cdom;
10693:             $uname = $cnum;
10694:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
10695:         } else {
10696:             $udom = $env{'user.domain'};
10697:             $uname = $env{'user.name'};
10698:             $url = '/userfiles/portfolio';
10699:         }
10700:         $toplevel = $url.'/';
10701:         $url .= $current_path;
10702:         $getpropath = 1;
10703:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
10704:              ($actionurl eq '/adm/imsimport')) { 
10705:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
10706:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
10707:         $toplevel = $url;
10708:         if ($rest ne '') {
10709:             $url .= $rest;
10710:         }
10711:     } elsif ($actionurl eq '/adm/coursedocs') {
10712:         if (ref($args) eq 'HASH') {
10713:             $url = $args->{'docs_url'};
10714:             $toplevel = $url;
10715:             if ($args->{'context'} eq 'paste') {
10716:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
10717:                 ($path) =
10718:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
10719:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
10720:                 $fileloc =~ s{^/}{};
10721:             }
10722:         }
10723:     } elsif ($actionurl eq '/adm/dependencies') {
10724:         if ($env{'request.course.id'} ne '') {
10725:             if (ref($args) eq 'HASH') {
10726:                 $url = $args->{'docs_url'};
10727:                 $title = $args->{'docs_title'};
10728:                 $toplevel = $url;
10729:                 unless ($toplevel =~ m{^/}) {
10730:                     $toplevel = "/$url";
10731:                 }
10732:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
10733:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
10734:                     $path = $1;
10735:                 } else {
10736:                     ($path) =
10737:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
10738:                 }
10739:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
10740:                     $fileloc = $toplevel;
10741:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
10742:                     my ($udom,$uname,$fname) =
10743:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
10744:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
10745:                 } else {
10746:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
10747:                 }
10748:                 $fileloc =~ s{^/}{};
10749:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
10750:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
10751:             }
10752:         }
10753:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
10754:         $udom = $cdom;
10755:         $uname = $cnum;
10756:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
10757:         $toplevel = $url;
10758:         $path = $url;
10759:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
10760:         $fileloc =~ s{^/}{};
10761:     }
10762:     foreach my $file (keys(%{$allfiles})) {
10763:         my $embed_file;
10764:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
10765:             $embed_file = $1;
10766:         } else {
10767:             $embed_file = $file;
10768:         }
10769:         my ($absolutepath,$cleaned_file);
10770:         if ($embed_file =~ m{^\w+://}) {
10771:             $cleaned_file = $embed_file;
10772:             $newfiles{$cleaned_file} = 1;
10773:             $mapping{$cleaned_file} = $embed_file;
10774:         } else {
10775:             $cleaned_file = &clean_path($embed_file);
10776:             if ($embed_file =~ m{^/}) {
10777:                 $absolutepath = $embed_file;
10778:             }
10779:             if ($cleaned_file =~ m{/}) {
10780:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
10781:                 $path = &check_for_traversal($path,$url,$toplevel);
10782:                 my $item = $fname;
10783:                 if ($path ne '') {
10784:                     $item = $path.'/'.$fname;
10785:                     $subdependencies{$path}{$fname} = 1;
10786:                 } else {
10787:                     $dependencies{$item} = 1;
10788:                 }
10789:                 if ($absolutepath) {
10790:                     $mapping{$item} = $absolutepath;
10791:                 } else {
10792:                     $mapping{$item} = $embed_file;
10793:                 }
10794:             } else {
10795:                 $dependencies{$embed_file} = 1;
10796:                 if ($absolutepath) {
10797:                     $mapping{$cleaned_file} = $absolutepath;
10798:                 } else {
10799:                     $mapping{$cleaned_file} = $embed_file;
10800:                 }
10801:             }
10802:         }
10803:     }
10804:     my $dirptr = 16384;
10805:     foreach my $path (keys(%subdependencies)) {
10806:         $currsubfile{$path} = {};
10807:         if (($actionurl eq '/adm/portfolio') ||
10808:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
10809:             my ($sublistref,$listerror) =
10810:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
10811:             if (ref($sublistref) eq 'ARRAY') {
10812:                 foreach my $line (@{$sublistref}) {
10813:                     my ($file_name,$rest) = split(/\&/,$line,2);
10814:                     $currsubfile{$path}{$file_name} = 1;
10815:                 }
10816:             }
10817:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10818:             if (opendir(my $dir,$url.'/'.$path)) {
10819:                 my @subdir_list = grep(!/^\./,readdir($dir));
10820:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
10821:             }
10822:         } elsif (($actionurl eq '/adm/dependencies') ||
10823:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10824:                   ($args->{'context'} eq 'paste')) ||
10825:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
10826:             if ($env{'request.course.id'} ne '') {
10827:                 my $dir;
10828:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
10829:                     $dir = $fileloc;
10830:                 } else {
10831:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
10832:                 }
10833:                 if ($dir ne '') {
10834:                     my ($sublistref,$listerror) =
10835:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
10836:                     if (ref($sublistref) eq 'ARRAY') {
10837:                         foreach my $line (@{$sublistref}) {
10838:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
10839:                                 undef,$mtime)=split(/\&/,$line,12);
10840:                             unless (($testdir&$dirptr) ||
10841:                                     ($file_name =~ /^\.\.?$/)) {
10842:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
10843:                             }
10844:                         }
10845:                     }
10846:                 }
10847:             }
10848:         }
10849:         foreach my $file (keys(%{$subdependencies{$path}})) {
10850:             if (exists($currsubfile{$path}{$file})) {
10851:                 my $item = $path.'/'.$file;
10852:                 unless ($mapping{$item} eq $item) {
10853:                     $pathchanges{$item} = 1;
10854:                 }
10855:                 $existing{$item} = 1;
10856:                 $numexisting ++;
10857:             } else {
10858:                 $newfiles{$path.'/'.$file} = 1;
10859:             }
10860:         }
10861:         if ($actionurl eq '/adm/dependencies') {
10862:             foreach my $path (keys(%currsubfile)) {
10863:                 if (ref($currsubfile{$path}) eq 'HASH') {
10864:                     foreach my $file (keys(%{$currsubfile{$path}})) {
10865:                          unless ($subdependencies{$path}{$file}) {
10866:                              next if (($rem ne '') &&
10867:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
10868:                                        (ref($navmap) &&
10869:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
10870:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10871:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
10872:                              $unused{$path.'/'.$file} = 1; 
10873:                          }
10874:                     }
10875:                 }
10876:             }
10877:         }
10878:     }
10879:     my %currfile;
10880:     if (($actionurl eq '/adm/portfolio') ||
10881:         ($actionurl eq '/adm/coursegrp_portfolio')) {
10882:         my ($dirlistref,$listerror) =
10883:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
10884:         if (ref($dirlistref) eq 'ARRAY') {
10885:             foreach my $line (@{$dirlistref}) {
10886:                 my ($file_name,$rest) = split(/\&/,$line,2);
10887:                 $currfile{$file_name} = 1;
10888:             }
10889:         }
10890:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10891:         if (opendir(my $dir,$url)) {
10892:             my @dir_list = grep(!/^\./,readdir($dir));
10893:             map {$currfile{$_} = 1;} @dir_list;
10894:         }
10895:     } elsif (($actionurl eq '/adm/dependencies') ||
10896:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10897:               ($args->{'context'} eq 'paste')) ||
10898:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
10899:         if ($env{'request.course.id'} ne '') {
10900:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
10901:             if ($dir ne '') {
10902:                 my ($dirlistref,$listerror) =
10903:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
10904:                 if (ref($dirlistref) eq 'ARRAY') {
10905:                     foreach my $line (@{$dirlistref}) {
10906:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
10907:                             $size,undef,$mtime)=split(/\&/,$line,12);
10908:                         unless (($testdir&$dirptr) ||
10909:                                 ($file_name =~ /^\.\.?$/)) {
10910:                             $currfile{$file_name} = [$size,$mtime];
10911:                         }
10912:                     }
10913:                 }
10914:             }
10915:         }
10916:     }
10917:     foreach my $file (keys(%dependencies)) {
10918:         if (exists($currfile{$file})) {
10919:             unless ($mapping{$file} eq $file) {
10920:                 $pathchanges{$file} = 1;
10921:             }
10922:             $existing{$file} = 1;
10923:             $numexisting ++;
10924:         } else {
10925:             $newfiles{$file} = 1;
10926:         }
10927:     }
10928:     foreach my $file (keys(%currfile)) {
10929:         unless (($file eq $filename) ||
10930:                 ($file eq $filename.'.bak') ||
10931:                 ($dependencies{$file})) {
10932:             if ($actionurl eq '/adm/dependencies') {
10933:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
10934:                     next if (($rem ne '') &&
10935:                              (($env{"httpref.$rem".$file} ne '') ||
10936:                               (ref($navmap) &&
10937:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
10938:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10939:                                 ($navmap->getResourceByUrl($rem.$1)))))));
10940:                 }
10941:             }
10942:             $unused{$file} = 1;
10943:         }
10944:     }
10945:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10946:         ($args->{'context'} eq 'paste')) {
10947:         $counter = scalar(keys(%existing));
10948:         $numpathchg = scalar(keys(%pathchanges));
10949:         return ($output,$counter,$numpathchg,\%existing);
10950:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
10951:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
10952:         $counter = scalar(keys(%existing));
10953:         $numpathchg = scalar(keys(%pathchanges));
10954:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
10955:     }
10956:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
10957:         if ($actionurl eq '/adm/dependencies') {
10958:             next if ($embed_file =~ m{^\w+://});
10959:         }
10960:         $upload_output .= &start_data_table_row().
10961:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
10962:                           '<span class="LC_filename">'.$embed_file.'</span>';
10963:         unless ($mapping{$embed_file} eq $embed_file) {
10964:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
10965:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
10966:         }
10967:         $upload_output .= '</td>';
10968:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
10969:             $upload_output.='<td align="right">'.
10970:                             '<span class="LC_info LC_fontsize_medium">'.
10971:                             &mt("URL points to web address").'</span>';
10972:             $numremref++;
10973:         } elsif ($args->{'error_on_invalid_names'}
10974:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
10975:             $upload_output.='<td align="right"><span class="LC_warning">'.
10976:                             &mt('Invalid characters').'</span>';
10977:             $numinvalid++;
10978:         } else {
10979:             $upload_output .= '<td>'.
10980:                               &embedded_file_element('upload_embedded',$counter,
10981:                                                      $embed_file,\%mapping,
10982:                                                      $allfiles,$codebase,'upload');
10983:             $counter ++;
10984:             $numnew ++;
10985:         }
10986:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
10987:     }
10988:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
10989:         if ($actionurl eq '/adm/dependencies') {
10990:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
10991:             $modify_output .= &start_data_table_row().
10992:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
10993:                               '<img src="'.&icon($embed_file).'" border="0" />'.
10994:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
10995:                               '<td>'.$size.'</td>'.
10996:                               '<td>'.$mtime.'</td>'.
10997:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
10998:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
10999:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
11000:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
11001:                               &embedded_file_element('upload_embedded',$counter,
11002:                                                      $embed_file,\%mapping,
11003:                                                      $allfiles,$codebase,'modify').
11004:                               '</div></td>'.
11005:                               &end_data_table_row()."\n";
11006:             $counter ++;
11007:         } else {
11008:             $upload_output .= &start_data_table_row().
11009:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
11010:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
11011:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
11012:                               &Apache::loncommon::end_data_table_row()."\n";
11013:         }
11014:     }
11015:     my $delidx = $counter;
11016:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
11017:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
11018:         $delete_output .= &start_data_table_row().
11019:                           '<td><img src="'.&icon($oldfile).'" />'.
11020:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
11021:                           '<td>'.$size.'</td>'.
11022:                           '<td>'.$mtime.'</td>'.
11023:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
11024:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
11025:                           &embedded_file_element('upload_embedded',$delidx,
11026:                                                  $oldfile,\%mapping,$allfiles,
11027:                                                  $codebase,'delete').'</td>'.
11028:                           &end_data_table_row()."\n"; 
11029:         $numunused ++;
11030:         $delidx ++;
11031:     }
11032:     if ($upload_output) {
11033:         $upload_output = &start_data_table().
11034:                          $upload_output.
11035:                          &end_data_table()."\n";
11036:     }
11037:     if ($modify_output) {
11038:         $modify_output = &start_data_table().
11039:                          &start_data_table_header_row().
11040:                          '<th>'.&mt('File').'</th>'.
11041:                          '<th>'.&mt('Size (KB)').'</th>'.
11042:                          '<th>'.&mt('Modified').'</th>'.
11043:                          '<th>'.&mt('Upload replacement?').'</th>'.
11044:                          &end_data_table_header_row().
11045:                          $modify_output.
11046:                          &end_data_table()."\n";
11047:     }
11048:     if ($delete_output) {
11049:         $delete_output = &start_data_table().
11050:                          &start_data_table_header_row().
11051:                          '<th>'.&mt('File').'</th>'.
11052:                          '<th>'.&mt('Size (KB)').'</th>'.
11053:                          '<th>'.&mt('Modified').'</th>'.
11054:                          '<th>'.&mt('Delete?').'</th>'.
11055:                          &end_data_table_header_row().
11056:                          $delete_output.
11057:                          &end_data_table()."\n";
11058:     }
11059:     my $applies = 0;
11060:     if ($numremref) {
11061:         $applies ++;
11062:     }
11063:     if ($numinvalid) {
11064:         $applies ++;
11065:     }
11066:     if ($numexisting) {
11067:         $applies ++;
11068:     }
11069:     if ($counter || $numunused) {
11070:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
11071:                   ' method="post" enctype="multipart/form-data">'."\n".
11072:                   $state.'<h3>'.$heading.'</h3>'; 
11073:         if ($actionurl eq '/adm/dependencies') {
11074:             if ($numnew) {
11075:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
11076:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
11077:                            $upload_output.'<br />'."\n";
11078:             }
11079:             if ($numexisting) {
11080:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
11081:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
11082:                            $modify_output.'<br />'."\n";
11083:                            $buttontext = &mt('Save changes');
11084:             }
11085:             if ($numunused) {
11086:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
11087:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
11088:                            $delete_output.'<br />'."\n";
11089:                            $buttontext = &mt('Save changes');
11090:             }
11091:         } else {
11092:             $output .= $upload_output.'<br />'."\n";
11093:         }
11094:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
11095:                    $counter.'" />'."\n";
11096:         if ($actionurl eq '/adm/dependencies') { 
11097:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
11098:                        $numnew.'" />'."\n";
11099:         } elsif ($actionurl eq '') {
11100:             $output .=  '<input type="hidden" name="phase" value="three" />';
11101:         }
11102:     } elsif ($applies) {
11103:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
11104:         if ($applies > 1) {
11105:             $output .=  
11106:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
11107:             if ($numremref) {
11108:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
11109:             }
11110:             if ($numinvalid) {
11111:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
11112:             }
11113:             if ($numexisting) {
11114:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
11115:             }
11116:             $output .= '</ul><br />';
11117:         } elsif ($numremref) {
11118:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
11119:         } elsif ($numinvalid) {
11120:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
11121:         } elsif ($numexisting) {
11122:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
11123:         }
11124:         $output .= $upload_output.'<br />';
11125:     }
11126:     my ($pathchange_output,$chgcount);
11127:     $chgcount = $counter;
11128:     if (keys(%pathchanges) > 0) {
11129:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
11130:             if ($counter) {
11131:                 $output .= &embedded_file_element('pathchange',$chgcount,
11132:                                                   $embed_file,\%mapping,
11133:                                                   $allfiles,$codebase,'change');
11134:             } else {
11135:                 $pathchange_output .= 
11136:                     &start_data_table_row().
11137:                     '<td><input type ="checkbox" name="namechange" value="'.
11138:                     $chgcount.'" checked="checked" /></td>'.
11139:                     '<td>'.$mapping{$embed_file}.'</td>'.
11140:                     '<td>'.$embed_file.
11141:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
11142:                                            \%mapping,$allfiles,$codebase,'change').
11143:                     '</td>'.&end_data_table_row();
11144:             }
11145:             $numpathchg ++;
11146:             $chgcount ++;
11147:         }
11148:     }
11149:     if (($counter) || ($numunused)) {
11150:         if ($numpathchg) {
11151:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
11152:                        $numpathchg.'" />'."\n";
11153:         }
11154:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
11155:             ($actionurl eq '/adm/imsimport')) {
11156:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
11157:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
11158:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
11159:         } elsif ($actionurl eq '/adm/dependencies') {
11160:             $output .= '<input type="hidden" name="action" value="process_changes" />';
11161:         }
11162:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
11163:     } elsif ($numpathchg) {
11164:         my %pathchange = ();
11165:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
11166:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11167:             $output .= '<p>'.&mt('or').'</p>'; 
11168:         }
11169:     }
11170:     return ($output,$counter,$numpathchg);
11171: }
11172: 
11173: =pod
11174: 
11175: =item * clean_path($name)
11176: 
11177: Performs clean-up of directories, subdirectories and filename in an
11178: embedded object, referenced in an HTML file which is being uploaded
11179: to a course or portfolio, where
11180: "Upload embedded images/multimedia files if HTML file" checkbox was
11181: checked.
11182: 
11183: Clean-up is similar to replacements in lonnet::clean_filename()
11184: except each / between sub-directory and next level is preserved.
11185: 
11186: =cut
11187: 
11188: sub clean_path {
11189:     my ($embed_file) = @_;
11190:     $embed_file =~s{^/+}{};
11191:     my @contents;
11192:     if ($embed_file =~ m{/}) {
11193:         @contents = split(/\//,$embed_file);
11194:     } else {
11195:         @contents = ($embed_file);
11196:     }
11197:     my $lastidx = scalar(@contents)-1;
11198:     for (my $i=0; $i<=$lastidx; $i++) {
11199:         $contents[$i]=~s{\\}{/}g;
11200:         $contents[$i]=~s/\s+/\_/g;
11201:         $contents[$i]=~s{[^/\w\.\-]}{}g;
11202:         if ($i == $lastidx) {
11203:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
11204:         }
11205:     }
11206:     if ($lastidx > 0) {
11207:         return join('/',@contents);
11208:     } else {
11209:         return $contents[0];
11210:     }
11211: }
11212: 
11213: sub embedded_file_element {
11214:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
11215:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
11216:                    (ref($codebase) eq 'HASH'));
11217:     my $output;
11218:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
11219:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
11220:     }
11221:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
11222:                &escape($embed_file).'" />';
11223:     unless (($context eq 'upload_embedded') && 
11224:             ($mapping->{$embed_file} eq $embed_file)) {
11225:         $output .='
11226:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
11227:     }
11228:     my $attrib;
11229:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
11230:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
11231:     }
11232:     $output .=
11233:         "\n\t\t".
11234:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
11235:         $attrib.'" />';
11236:     if (exists($codebase->{$mapping->{$embed_file}})) {
11237:         $output .=
11238:             "\n\t\t".
11239:             '<input name="codebase_'.$num.'" type="hidden" value="'.
11240:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
11241:     }
11242:     return $output;
11243: }
11244: 
11245: sub get_dependency_details {
11246:     my ($currfile,$currsubfile,$embed_file) = @_;
11247:     my ($size,$mtime,$showsize,$showmtime);
11248:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
11249:         if ($embed_file =~ m{/}) {
11250:             my ($path,$fname) = split(/\//,$embed_file);
11251:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
11252:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
11253:             }
11254:         } else {
11255:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
11256:                 ($size,$mtime) = @{$currfile->{$embed_file}};
11257:             }
11258:         }
11259:         $showsize = $size/1024.0;
11260:         $showsize = sprintf("%.1f",$showsize);
11261:         if ($mtime > 0) {
11262:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
11263:         }
11264:     }
11265:     return ($showsize,$showmtime);
11266: }
11267: 
11268: sub ask_embedded_js {
11269:     return <<"END";
11270: <script type="text/javascript"">
11271: // <![CDATA[
11272: function toggleBrowse(counter) {
11273:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
11274:     var fileid = document.getElementById('embedded_item_'+counter);
11275:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
11276:     if (chkboxid.checked == true) {
11277:         uploaddivid.style.display='block';
11278:     } else {
11279:         uploaddivid.style.display='none';
11280:         fileid.value = '';
11281:     }
11282: }
11283: // ]]>
11284: </script>
11285: 
11286: END
11287: }
11288: 
11289: sub upload_embedded {
11290:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
11291:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
11292:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
11293:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
11294:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
11295:         my $orig_uploaded_filename =
11296:             $env{'form.embedded_item_'.$i.'.filename'};
11297:         foreach my $type ('orig','ref','attrib','codebase') {
11298:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
11299:                 $env{'form.embedded_'.$type.'_'.$i} =
11300:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
11301:             }
11302:         }
11303:         my ($path,$fname) =
11304:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
11305:         # no path, whole string is fname
11306:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
11307:         $fname = &Apache::lonnet::clean_filename($fname);
11308:         # See if there is anything left
11309:         next if ($fname eq '');
11310: 
11311:         # Check if file already exists as a file or directory.
11312:         my ($state,$msg);
11313:         if ($context eq 'portfolio') {
11314:             my $port_path = $dirpath;
11315:             if ($group ne '') {
11316:                 $port_path = "groups/$group/$port_path";
11317:             }
11318:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
11319:                                               $fname,$group,'embedded_item_'.$i,
11320:                                               $dir_root,$port_path,$disk_quota,
11321:                                               $current_disk_usage,$uname,$udom);
11322:             if ($state eq 'will_exceed_quota'
11323:                 || $state eq 'file_locked') {
11324:                 $output .= $msg;
11325:                 next;
11326:             }
11327:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
11328:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
11329:             if ($state eq 'exists') {
11330:                 $output .= $msg;
11331:                 next;
11332:             }
11333:         }
11334:         # Check if extension is valid
11335:         if (($fname =~ /\.(\w+)$/) &&
11336:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
11337:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
11338:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
11339:             next;
11340:         } elsif (($fname =~ /\.(\w+)$/) &&
11341:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
11342:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
11343:             next;
11344:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
11345:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
11346:             next;
11347:         }
11348:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
11349:         my $subdir = $path;
11350:         $subdir =~ s{/+$}{};
11351:         if ($context eq 'portfolio') {
11352:             my $result;
11353:             if ($state eq 'existingfile') {
11354:                 $result=
11355:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
11356:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
11357:             } else {
11358:                 $result=
11359:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
11360:                                                     $dirpath.
11361:                                                     $env{'form.currentpath'}.$subdir);
11362:                 if ($result !~ m|^/uploaded/|) {
11363:                     $output .= '<span class="LC_error">'
11364:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11365:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11366:                                .'</span><br />';
11367:                     next;
11368:                 } else {
11369:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11370:                                $path.$fname.'</span>').'<br />';     
11371:                 }
11372:             }
11373:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
11374:             my $extendedsubdir = $dirpath.'/'.$subdir;
11375:             $extendedsubdir =~ s{/+$}{};
11376:             my $result =
11377:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
11378:             if ($result !~ m|^/uploaded/|) {
11379:                 $output .= '<span class="LC_error">'
11380:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11381:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11382:                            .'</span><br />';
11383:                     next;
11384:             } else {
11385:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11386:                            $path.$fname.'</span>').'<br />';
11387:                 if ($context eq 'syllabus') {
11388:                     &Apache::lonnet::make_public_indefinitely($result);
11389:                 }
11390:             }
11391:         } else {
11392: # Save the file
11393:             my $target = $env{'form.embedded_item_'.$i};
11394:             my $fullpath = $dir_root.$dirpath.'/'.$path;
11395:             my $dest = $fullpath.$fname;
11396:             my $url = $url_root.$dirpath.'/'.$path.$fname;
11397:             my @parts=split(/\//,"$dirpath/$path");
11398:             my $count;
11399:             my $filepath = $dir_root;
11400:             foreach my $subdir (@parts) {
11401:                 $filepath .= "/$subdir";
11402:                 if (!-e $filepath) {
11403:                     mkdir($filepath,0770);
11404:                 }
11405:             }
11406:             my $fh;
11407:             if (!open($fh,'>'.$dest)) {
11408:                 &Apache::lonnet::logthis('Failed to create '.$dest);
11409:                 $output .= '<span class="LC_error">'.
11410:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
11411:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11412:                            '</span><br />';
11413:             } else {
11414:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
11415:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
11416:                     $output .= '<span class="LC_error">'.
11417:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
11418:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11419:                               '</span><br />';
11420:                 } else {
11421:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11422:                                $url.'</span>').'<br />';
11423:                     unless ($context eq 'testbank') {
11424:                         $footer .= &mt('View embedded file: [_1]',
11425:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
11426:                     }
11427:                 }
11428:                 close($fh);
11429:             }
11430:         }
11431:         if ($env{'form.embedded_ref_'.$i}) {
11432:             $pathchange{$i} = 1;
11433:         }
11434:     }
11435:     if ($output) {
11436:         $output = '<p>'.$output.'</p>';
11437:     }
11438:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
11439:     $returnflag = 'ok';
11440:     my $numpathchgs = scalar(keys(%pathchange));
11441:     if ($numpathchgs > 0) {
11442:         if ($context eq 'portfolio') {
11443:             $output .= '<p>'.&mt('or').'</p>';
11444:         } elsif ($context eq 'testbank') {
11445:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
11446:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
11447:             $returnflag = 'modify_orightml';
11448:         }
11449:     }
11450:     return ($output.$footer,$returnflag,$numpathchgs);
11451: }
11452: 
11453: sub modify_html_form {
11454:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
11455:     my $end = 0;
11456:     my $modifyform;
11457:     if ($context eq 'upload_embedded') {
11458:         return unless (ref($pathchange) eq 'HASH');
11459:         if ($env{'form.number_embedded_items'}) {
11460:             $end += $env{'form.number_embedded_items'};
11461:         }
11462:         if ($env{'form.number_pathchange_items'}) {
11463:             $end += $env{'form.number_pathchange_items'};
11464:         }
11465:         if ($end) {
11466:             for (my $i=0; $i<$end; $i++) {
11467:                 if ($i < $env{'form.number_embedded_items'}) {
11468:                     next unless($pathchange->{$i});
11469:                 }
11470:                 $modifyform .=
11471:                     &start_data_table_row().
11472:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
11473:                     'checked="checked" /></td>'.
11474:                     '<td>'.$env{'form.embedded_ref_'.$i}.
11475:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
11476:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
11477:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
11478:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
11479:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
11480:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
11481:                     '<td>'.$env{'form.embedded_orig_'.$i}.
11482:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
11483:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
11484:                     &end_data_table_row();
11485:             }
11486:         }
11487:     } else {
11488:         $modifyform = $pathchgtable;
11489:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11490:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
11491:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11492:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
11493:         }
11494:     }
11495:     if ($modifyform) {
11496:         if ($actionurl eq '/adm/dependencies') {
11497:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
11498:         }
11499:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
11500:                '<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".
11501:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
11502:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
11503:                '</ol></p>'."\n".'<p>'.
11504:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
11505:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
11506:                &start_data_table()."\n".
11507:                &start_data_table_header_row().
11508:                '<th>'.&mt('Change?').'</th>'.
11509:                '<th>'.&mt('Current reference').'</th>'.
11510:                '<th>'.&mt('Required reference').'</th>'.
11511:                &end_data_table_header_row()."\n".
11512:                $modifyform.
11513:                &end_data_table().'<br />'."\n".$hiddenstate.
11514:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
11515:                '</form>'."\n";
11516:     }
11517:     return;
11518: }
11519: 
11520: sub modify_html_refs {
11521:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
11522:     my $container;
11523:     if ($context eq 'portfolio') {
11524:         $container = $env{'form.container'};
11525:     } elsif ($context eq 'coursedoc') {
11526:         $container = $env{'form.primaryurl'};
11527:     } elsif ($context eq 'manage_dependencies') {
11528:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
11529:         $container = "/$container";
11530:     } elsif ($context eq 'syllabus') {
11531:         $container = $url;
11532:     } else {
11533:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
11534:     }
11535:     my (%allfiles,%codebase,$output,$content);
11536:     my @changes = &get_env_multiple('form.namechange');
11537:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
11538:         if (wantarray) {
11539:             return ('',0,0); 
11540:         } else {
11541:             return;
11542:         }
11543:     }
11544:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
11545:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
11546:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
11547:             if (wantarray) {
11548:                 return ('',0,0);
11549:             } else {
11550:                 return;
11551:             }
11552:         } 
11553:         $content = &Apache::lonnet::getfile($container);
11554:         if ($content eq '-1') {
11555:             if (wantarray) {
11556:                 return ('',0,0);
11557:             } else {
11558:                 return;
11559:             }
11560:         }
11561:     } else {
11562:         unless ($container =~ /^\Q$dir_root\E/) {
11563:             if (wantarray) {
11564:                 return ('',0,0);
11565:             } else {
11566:                 return;
11567:             }
11568:         } 
11569:         if (open(my $fh,'<',$container)) {
11570:             $content = join('', <$fh>);
11571:             close($fh);
11572:         } else {
11573:             if (wantarray) {
11574:                 return ('',0,0);
11575:             } else {
11576:                 return;
11577:             }
11578:         }
11579:     }
11580:     my ($count,$codebasecount) = (0,0);
11581:     my $mm = new File::MMagic;
11582:     my $mime_type = $mm->checktype_contents($content);
11583:     if ($mime_type eq 'text/html') {
11584:         my $parse_result = 
11585:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
11586:                                                     \%codebase,\$content);
11587:         if ($parse_result eq 'ok') {
11588:             foreach my $i (@changes) {
11589:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
11590:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
11591:                 if ($allfiles{$ref}) {
11592:                     my $newname =  $orig;
11593:                     my ($attrib_regexp,$codebase);
11594:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
11595:                     if ($attrib_regexp =~ /:/) {
11596:                         $attrib_regexp =~ s/\:/|/g;
11597:                     }
11598:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
11599:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
11600:                         $count += $numchg;
11601:                         $allfiles{$newname} = $allfiles{$ref};
11602:                         delete($allfiles{$ref});
11603:                     }
11604:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
11605:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
11606:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
11607:                         $codebasecount ++;
11608:                     }
11609:                 }
11610:             }
11611:             my $skiprewrites;
11612:             if ($count || $codebasecount) {
11613:                 my $saveresult;
11614:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
11615:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
11616:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
11617:                     if ($url eq $container) {
11618:                         my ($fname) = ($container =~ m{/([^/]+)$});
11619:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
11620:                                             $count,'<span class="LC_filename">'.
11621:                                             $fname.'</span>').'</p>';
11622:                     } else {
11623:                          $output = '<p class="LC_error">'.
11624:                                    &mt('Error: update failed for: [_1].',
11625:                                    '<span class="LC_filename">'.
11626:                                    $container.'</span>').'</p>';
11627:                     }
11628:                     if ($context eq 'syllabus') {
11629:                         unless ($saveresult eq 'ok') {
11630:                             $skiprewrites = 1;
11631:                         }
11632:                     }
11633:                 } else {
11634:                     if (open(my $fh,'>',$container)) {
11635:                         print $fh $content;
11636:                         close($fh);
11637:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
11638:                                   $count,'<span class="LC_filename">'.
11639:                                   $container.'</span>').'</p>';
11640:                     } else {
11641:                          $output = '<p class="LC_error">'.
11642:                                    &mt('Error: could not update [_1].',
11643:                                    '<span class="LC_filename">'.
11644:                                    $container.'</span>').'</p>';
11645:                     }
11646:                 }
11647:             }
11648:             if (($context eq 'syllabus') && (!$skiprewrites)) {
11649:                 my ($actionurl,$state);
11650:                 $actionurl = "/public/$udom/$uname/syllabus";
11651:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
11652:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
11653:                                               \%codebase,
11654:                                               {'context' => 'rewrites',
11655:                                                'ignore_remote_references' => 1,});
11656:                 if (ref($mapping) eq 'HASH') {
11657:                     my $rewrites = 0;
11658:                     foreach my $key (keys(%{$mapping})) {
11659:                         next if ($key =~ m{^https?://});
11660:                         my $ref = $mapping->{$key};
11661:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
11662:                         my $attrib;
11663:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
11664:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
11665:                         }
11666:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
11667:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
11668:                             $rewrites += $numchg;
11669:                         }
11670:                     }
11671:                     if ($rewrites) {
11672:                         my $saveresult;
11673:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
11674:                         if ($url eq $container) {
11675:                             my ($fname) = ($container =~ m{/([^/]+)$});
11676:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
11677:                                             $count,'<span class="LC_filename">'.
11678:                                             $fname.'</span>').'</p>';
11679:                         } else {
11680:                             $output .= '<p class="LC_error">'.
11681:                                        &mt('Error: could not update links in [_1].',
11682:                                        '<span class="LC_filename">'.
11683:                                        $container.'</span>').'</p>';
11684: 
11685:                         }
11686:                     }
11687:                 }
11688:             }
11689:         } else {
11690:             &logthis('Failed to parse '.$container.
11691:                      ' to modify references: '.$parse_result);
11692:         }
11693:     }
11694:     if (wantarray) {
11695:         return ($output,$count,$codebasecount);
11696:     } else {
11697:         return $output;
11698:     }
11699: }
11700: 
11701: sub check_for_existing {
11702:     my ($path,$fname,$element) = @_;
11703:     my ($state,$msg);
11704:     if (-d $path.'/'.$fname) {
11705:         $state = 'exists';
11706:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
11707:     } elsif (-e $path.'/'.$fname) {
11708:         $state = 'exists';
11709:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
11710:     }
11711:     if ($state eq 'exists') {
11712:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
11713:     }
11714:     return ($state,$msg);
11715: }
11716: 
11717: sub check_for_upload {
11718:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
11719:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
11720:     my $filesize = length($env{'form.'.$element});
11721:     if (!$filesize) {
11722:         my $msg = '<span class="LC_error">'.
11723:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
11724:                       '<span class="LC_filename">'.$fname.'</span>',
11725:                       $filesize).'<br />'.
11726:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
11727:                   '</span>';
11728:         return ('zero_bytes',$msg);
11729:     }
11730:     $filesize =  $filesize/1000; #express in k (1024?)
11731:     my $getpropath = 1;
11732:     my ($dirlistref,$listerror) =
11733:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
11734:     my $found_file = 0;
11735:     my $locked_file = 0;
11736:     my @lockers;
11737:     my $navmap;
11738:     if ($env{'request.course.id'}) {
11739:         $navmap = Apache::lonnavmaps::navmap->new();
11740:     }
11741:     if (ref($dirlistref) eq 'ARRAY') {
11742:         foreach my $line (@{$dirlistref}) {
11743:             my ($file_name,$rest)=split(/\&/,$line,2);
11744:             if ($file_name eq $fname){
11745:                 $file_name = $path.$file_name;
11746:                 if ($group ne '') {
11747:                     $file_name = $group.$file_name;
11748:                 }
11749:                 $found_file = 1;
11750:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
11751:                     foreach my $lock (@lockers) {
11752:                         if (ref($lock) eq 'ARRAY') {
11753:                             my ($symb,$crsid) = @{$lock};
11754:                             if ($crsid eq $env{'request.course.id'}) {
11755:                                 if (ref($navmap)) {
11756:                                     my $res = $navmap->getBySymb($symb);
11757:                                     foreach my $part (@{$res->parts()}) { 
11758:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
11759:                                         unless (($slot_status == $res->RESERVED) ||
11760:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
11761:                                             $locked_file = 1;
11762:                                         }
11763:                                     }
11764:                                 } else {
11765:                                     $locked_file = 1;
11766:                                 }
11767:                             } else {
11768:                                 $locked_file = 1;
11769:                             }
11770:                         }
11771:                    }
11772:                 } else {
11773:                     my @info = split(/\&/,$rest);
11774:                     my $currsize = $info[6]/1000;
11775:                     if ($currsize < $filesize) {
11776:                         my $extra = $filesize - $currsize;
11777:                         if (($current_disk_usage + $extra) > $disk_quota) {
11778:                             my $msg = '<p class="LC_warning">'.
11779:                                       &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.',
11780:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
11781:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
11782:                                                    $disk_quota,$current_disk_usage).'</p>';
11783:                             return ('will_exceed_quota',$msg);
11784:                         }
11785:                     }
11786:                 }
11787:             }
11788:         }
11789:     }
11790:     if (($current_disk_usage + $filesize) > $disk_quota){
11791:         my $msg = '<p class="LC_warning">'.
11792:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
11793:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
11794:         return ('will_exceed_quota',$msg);
11795:     } elsif ($found_file) {
11796:         if ($locked_file) {
11797:             my $msg = '<p class="LC_warning">';
11798:             $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>');
11799:             $msg .= '</p>';
11800:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
11801:             return ('file_locked',$msg);
11802:         } else {
11803:             my $msg = '<p class="LC_error">';
11804:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
11805:             $msg .= '</p>';
11806:             return ('existingfile',$msg);
11807:         }
11808:     }
11809: }
11810: 
11811: sub check_for_traversal {
11812:     my ($path,$url,$toplevel) = @_;
11813:     my @parts=split(/\//,$path);
11814:     my $cleanpath;
11815:     my $fullpath = $url;
11816:     for (my $i=0;$i<@parts;$i++) {
11817:         next if ($parts[$i] eq '.');
11818:         if ($parts[$i] eq '..') {
11819:             $fullpath =~ s{([^/]+/)$}{};
11820:         } else {
11821:             $fullpath .= $parts[$i].'/';
11822:         }
11823:     }
11824:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
11825:         $cleanpath = $1;
11826:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
11827:         my $curr_toprel = $1;
11828:         my @parts = split(/\//,$curr_toprel);
11829:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
11830:         my @urlparts = split(/\//,$url_toprel);
11831:         my $doubledots;
11832:         my $startdiff = -1;
11833:         for (my $i=0; $i<@urlparts; $i++) {
11834:             if ($startdiff == -1) {
11835:                 unless ($urlparts[$i] eq $parts[$i]) {
11836:                     $startdiff = $i;
11837:                     $doubledots .= '../';
11838:                 }
11839:             } else {
11840:                 $doubledots .= '../';
11841:             }
11842:         }
11843:         if ($startdiff > -1) {
11844:             $cleanpath = $doubledots;
11845:             for (my $i=$startdiff; $i<@parts; $i++) {
11846:                 $cleanpath .= $parts[$i].'/';
11847:             }
11848:         }
11849:     }
11850:     $cleanpath =~ s{(/)$}{};
11851:     return $cleanpath;
11852: }
11853: 
11854: sub is_archive_file {
11855:     my ($mimetype) = @_;
11856:     if (($mimetype eq 'application/octet-stream') ||
11857:         ($mimetype eq 'application/x-stuffit') ||
11858:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
11859:         return 1;
11860:     }
11861:     return;
11862: }
11863: 
11864: sub decompress_form {
11865:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
11866:     my %lt = &Apache::lonlocal::texthash (
11867:         this => 'This file is an archive file.',
11868:         camt => 'This file is a Camtasia archive file.',
11869:         itsc => 'Its contents are as follows:',
11870:         youm => 'You may wish to extract its contents.',
11871:         extr => 'Extract contents',
11872:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
11873:         proa => 'Process automatically?',
11874:         yes  => 'Yes',
11875:         no   => 'No',
11876:         fold => 'Title for folder containing movie',
11877:         movi => 'Title for page containing embedded movie', 
11878:     );
11879:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
11880:     my ($is_camtasia,$topdir,%toplevel,@paths);
11881:     my $info = &list_archive_contents($fileloc,\@paths);
11882:     if (@paths) {
11883:         foreach my $path (@paths) {
11884:             $path =~ s{^/}{};
11885:             if ($path =~ m{^([^/]+)/$}) {
11886:                 $topdir = $1;
11887:             }
11888:             if ($path =~ m{^([^/]+)/}) {
11889:                 $toplevel{$1} = $path;
11890:             } else {
11891:                 $toplevel{$path} = $path;
11892:             }
11893:         }
11894:     }
11895:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
11896:         my @camtasia6 = ("$topdir/","$topdir/index.html",
11897:                         "$topdir/media/",
11898:                         "$topdir/media/$topdir.mp4",
11899:                         "$topdir/media/FirstFrame.png",
11900:                         "$topdir/media/player.swf",
11901:                         "$topdir/media/swfobject.js",
11902:                         "$topdir/media/expressInstall.swf");
11903:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
11904:                          "$topdir/$topdir.mp4",
11905:                          "$topdir/$topdir\_config.xml",
11906:                          "$topdir/$topdir\_controller.swf",
11907:                          "$topdir/$topdir\_embed.css",
11908:                          "$topdir/$topdir\_First_Frame.png",
11909:                          "$topdir/$topdir\_player.html",
11910:                          "$topdir/$topdir\_Thumbnails.png",
11911:                          "$topdir/playerProductInstall.swf",
11912:                          "$topdir/scripts/",
11913:                          "$topdir/scripts/config_xml.js",
11914:                          "$topdir/scripts/handlebars.js",
11915:                          "$topdir/scripts/jquery-1.7.1.min.js",
11916:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
11917:                          "$topdir/scripts/modernizr.js",
11918:                          "$topdir/scripts/player-min.js",
11919:                          "$topdir/scripts/swfobject.js",
11920:                          "$topdir/skins/",
11921:                          "$topdir/skins/configuration_express.xml",
11922:                          "$topdir/skins/express_show/",
11923:                          "$topdir/skins/express_show/player-min.css",
11924:                          "$topdir/skins/express_show/spritesheet.png");
11925:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
11926:                          "$topdir/$topdir.mp4",
11927:                          "$topdir/$topdir\_config.xml",
11928:                          "$topdir/$topdir\_controller.swf",
11929:                          "$topdir/$topdir\_embed.css",
11930:                          "$topdir/$topdir\_First_Frame.png",
11931:                          "$topdir/$topdir\_player.html",
11932:                          "$topdir/$topdir\_Thumbnails.png",
11933:                          "$topdir/playerProductInstall.swf",
11934:                          "$topdir/scripts/",
11935:                          "$topdir/scripts/config_xml.js",
11936:                          "$topdir/scripts/techsmith-smart-player.min.js",
11937:                          "$topdir/skins/",
11938:                          "$topdir/skins/configuration_express.xml",
11939:                          "$topdir/skins/express_show/",
11940:                          "$topdir/skins/express_show/spritesheet.min.css",
11941:                          "$topdir/skins/express_show/spritesheet.png",
11942:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
11943:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
11944:         if (@diffs == 0) {
11945:             $is_camtasia = 6;
11946:         } else {
11947:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
11948:             if (@diffs == 0) {
11949:                 $is_camtasia = 8;
11950:             } else {
11951:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
11952:                 if (@diffs == 0) {
11953:                     $is_camtasia = 8;
11954:                 }
11955:             }
11956:         }
11957:     }
11958:     my $output;
11959:     if ($is_camtasia) {
11960:         $output = <<"ENDCAM";
11961: <script type="text/javascript" language="Javascript">
11962: // <![CDATA[
11963: 
11964: function camtasiaToggle() {
11965:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
11966:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
11967:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
11968:                 document.getElementById('camtasia_titles').style.display='block';
11969:             } else {
11970:                 document.getElementById('camtasia_titles').style.display='none';
11971:             }
11972:         }
11973:     }
11974:     return;
11975: }
11976: 
11977: // ]]>
11978: </script>
11979: <p>$lt{'camt'}</p>
11980: ENDCAM
11981:     } else {
11982:         $output = '<p>'.$lt{'this'};
11983:         if ($info eq '') {
11984:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
11985:         } else {
11986:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
11987:                        '<div><pre>'.$info.'</pre></div>';
11988:         }
11989:     }
11990:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
11991:     my $duplicates;
11992:     my $num = 0;
11993:     if (ref($dirlist) eq 'ARRAY') {
11994:         foreach my $item (@{$dirlist}) {
11995:             if (ref($item) eq 'ARRAY') {
11996:                 if (exists($toplevel{$item->[0]})) {
11997:                     $duplicates .= 
11998:                         &start_data_table_row().
11999:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
12000:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
12001:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
12002:                         'value="1" />'.&mt('Yes').'</label>'.
12003:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
12004:                         '<td>'.$item->[0].'</td>';
12005:                     if ($item->[2]) {
12006:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
12007:                     } else {
12008:                         $duplicates .= '<td>'.&mt('File').'</td>';
12009:                     }
12010:                     $duplicates .= '<td>'.$item->[3].'</td>'.
12011:                                    '<td>'.
12012:                                    &Apache::lonlocal::locallocaltime($item->[4]).
12013:                                    '</td>'.
12014:                                    &end_data_table_row();
12015:                     $num ++;
12016:                 }
12017:             }
12018:         }
12019:     }
12020:     my $itemcount;
12021:     if (@paths > 0) {
12022:         $itemcount = scalar(@paths);
12023:     } else {
12024:         $itemcount = 1;
12025:     }
12026:     if ($is_camtasia) {
12027:         $output .= $lt{'auto'}.'<br />'.
12028:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
12029:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
12030:                    $lt{'yes'}.'</label>&nbsp;<label>'.
12031:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
12032:                    $lt{'no'}.'</label></span><br />'.
12033:                    '<div id="camtasia_titles" style="display:block">'.
12034:                    &Apache::lonhtmlcommon::start_pick_box().
12035:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
12036:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
12037:                    &Apache::lonhtmlcommon::row_closure().
12038:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
12039:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
12040:                    &Apache::lonhtmlcommon::row_closure(1).
12041:                    &Apache::lonhtmlcommon::end_pick_box().
12042:                    '</div>';
12043:     }
12044:     $output .= 
12045:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
12046:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
12047:         "\n";
12048:     if ($duplicates ne '') {
12049:         $output .= '<p><span class="LC_warning">'.
12050:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
12051:                    &start_data_table().
12052:                    &start_data_table_header_row().
12053:                    '<th>'.&mt('Overwrite?').'</th>'.
12054:                    '<th>'.&mt('Name').'</th>'.
12055:                    '<th>'.&mt('Type').'</th>'.
12056:                    '<th>'.&mt('Size').'</th>'.
12057:                    '<th>'.&mt('Last modified').'</th>'.
12058:                    &end_data_table_header_row().
12059:                    $duplicates.
12060:                    &end_data_table().
12061:                    '</p>';
12062:     }
12063:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
12064:     if (ref($hiddenelements) eq 'HASH') {
12065:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
12066:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
12067:         }
12068:     }
12069:     $output .= <<"END";
12070: <br />
12071: <input type="submit" name="decompress" value="$lt{'extr'}" />
12072: </form>
12073: $noextract
12074: END
12075:     return $output;
12076: }
12077: 
12078: sub decompression_utility {
12079:     my ($program) = @_;
12080:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
12081:     my $location;
12082:     if (grep(/^\Q$program\E$/,@utilities)) { 
12083:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
12084:                          '/usr/sbin/') {
12085:             if (-x $dir.$program) {
12086:                 $location = $dir.$program;
12087:                 last;
12088:             }
12089:         }
12090:     }
12091:     return $location;
12092: }
12093: 
12094: sub list_archive_contents {
12095:     my ($file,$pathsref) = @_;
12096:     my (@cmd,$output);
12097:     my $needsregexp;
12098:     if ($file =~ /\.zip$/) {
12099:         @cmd = (&decompression_utility('unzip'),"-l");
12100:         $needsregexp = 1;
12101:     } elsif (($file =~ m/\.tar\.gz$/) ||
12102:              ($file =~ /\.tgz$/)) {
12103:         @cmd = (&decompression_utility('tar'),"-ztf");
12104:     } elsif ($file =~ /\.tar\.bz2$/) {
12105:         @cmd = (&decompression_utility('tar'),"-jtf");
12106:     } elsif ($file =~ m|\.tar$|) {
12107:         @cmd = (&decompression_utility('tar'),"-tf");
12108:     }
12109:     if (@cmd) {
12110:         undef($!);
12111:         undef($@);
12112:         if (open(my $fh,"-|", @cmd, $file)) {
12113:             while (my $line = <$fh>) {
12114:                 $output .= $line;
12115:                 chomp($line);
12116:                 my $item;
12117:                 if ($needsregexp) {
12118:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
12119:                 } else {
12120:                     $item = $line;
12121:                 }
12122:                 if ($item ne '') {
12123:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
12124:                         push(@{$pathsref},$item);
12125:                     } 
12126:                 }
12127:             }
12128:             close($fh);
12129:         }
12130:     }
12131:     return $output;
12132: }
12133: 
12134: sub decompress_uploaded_file {
12135:     my ($file,$dir) = @_;
12136:     &Apache::lonnet::appenv({'cgi.file' => $file});
12137:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
12138:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
12139:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
12140:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
12141:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
12142:     my $decompressed = $env{'cgi.decompressed'};
12143:     &Apache::lonnet::delenv('cgi.file');
12144:     &Apache::lonnet::delenv('cgi.dir');
12145:     &Apache::lonnet::delenv('cgi.decompressed');
12146:     return ($decompressed,$result);
12147: }
12148: 
12149: sub process_decompression {
12150:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
12151:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
12152:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12153:                &mt('Unexpected file path.').'</p>'."\n";
12154:     }
12155:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
12156:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12157:                &mt('Unexpected course context.').'</p>'."\n";
12158:     }
12159:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
12160:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12161:                &mt('Filename contained unexpected characters.').'</p>'."\n";
12162:     }
12163:     my ($dir,$error,$warning,$output);
12164:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
12165:         $error = &mt('Filename not a supported archive file type.').
12166:                  '<br />'.&mt('Filename should end with one of: [_1].',
12167:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
12168:     } else {
12169:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
12170:         if ($docuhome eq 'no_host') {
12171:             $error = &mt('Could not determine home server for course.');
12172:         } else {
12173:             my @ids=&Apache::lonnet::current_machine_ids();
12174:             my $currdir = "$dir_root/$destination";
12175:             if (grep(/^\Q$docuhome\E$/,@ids)) {
12176:                 $dir = &LONCAPA::propath($docudom,$docuname).
12177:                        "$dir_root/$destination";
12178:             } else {
12179:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
12180:                        "$dir_root/$docudom/$docuname/$destination";
12181:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
12182:                     $error = &mt('Archive file not found.');
12183:                 }
12184:             }
12185:             my (@to_overwrite,@to_skip);
12186:             if ($env{'form.archive_overwrite_total'} > 0) {
12187:                 my $total = $env{'form.archive_overwrite_total'};
12188:                 for (my $i=0; $i<$total; $i++) {
12189:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
12190:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
12191:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
12192:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
12193:                     }
12194:                 }
12195:             }
12196:             my $numskip = scalar(@to_skip);
12197:             my $numoverwrite = scalar(@to_overwrite);
12198:             if (($numskip) && (!$numoverwrite)) {
12199:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
12200:             } elsif ($dir eq '') {
12201:                 $error = &mt('Directory containing archive file unavailable.');
12202:             } elsif (!$error) {
12203:                 my ($decompressed,$display);
12204:                 if (($numskip) || ($numoverwrite)) {
12205:                     my $tempdir = time.'_'.$$.int(rand(10000));
12206:                     mkdir("$dir/$tempdir",0755);
12207:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
12208:                         ($decompressed,$display) =
12209:                             &decompress_uploaded_file($file,"$dir/$tempdir");
12210:                         foreach my $item (@to_skip) {
12211:                             if (($item ne '') && ($item !~ /\.\./)) {
12212:                                 if (-f "$dir/$tempdir/$item") {
12213:                                     unlink("$dir/$tempdir/$item");
12214:                                 } elsif (-d "$dir/$tempdir/$item") {
12215:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
12216:                                 }
12217:                             }
12218:                         }
12219:                         foreach my $item (@to_overwrite) {
12220:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
12221:                                 if (($item ne '') && ($item !~ /\.\./)) {
12222:                                     if (-f "$dir/$item") {
12223:                                         unlink("$dir/$item");
12224:                                     } elsif (-d "$dir/$item") {
12225:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
12226:                                     }
12227:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
12228:                                 }
12229:                             }
12230:                         }
12231:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
12232:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
12233:                         }
12234:                     }
12235:                 } else {
12236:                     ($decompressed,$display) = 
12237:                         &decompress_uploaded_file($file,$dir);
12238:                 }
12239:                 if ($decompressed eq 'ok') {
12240:                     $output = '<p class="LC_info">'.
12241:                               &mt('Files extracted successfully from archive.').
12242:                               '</p>'."\n";
12243:                     my ($warning,$result,@contents);
12244:                     my ($newdirlistref,$newlisterror) =
12245:                         &Apache::lonnet::dirlist($currdir,$docudom,
12246:                                                  $docuname,1);
12247:                     my (%is_dir,%changes,@newitems);
12248:                     my $dirptr = 16384;
12249:                     if (ref($newdirlistref) eq 'ARRAY') {
12250:                         foreach my $dir_line (@{$newdirlistref}) {
12251:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12252:                             unless (($item =~ /^\.+$/) || ($item eq $file)) { 
12253:                                 push(@newitems,$item);
12254:                                 if ($dirptr&$testdir) {
12255:                                     $is_dir{$item} = 1;
12256:                                 }
12257:                                 $changes{$item} = 1;
12258:                             }
12259:                         }
12260:                     }
12261:                     if (keys(%changes) > 0) {
12262:                         foreach my $item (sort(@newitems)) {
12263:                             if ($changes{$item}) {
12264:                                 push(@contents,$item);
12265:                             }
12266:                         }
12267:                     }
12268:                     if (@contents > 0) {
12269:                         my $wantform;
12270:                         unless ($env{'form.autoextract_camtasia'}) {
12271:                             $wantform = 1;
12272:                         }
12273:                         my (%children,%parent,%dirorder,%titles);
12274:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
12275:                                                                 $currdir,\%is_dir,
12276:                                                                 \%children,\%parent,
12277:                                                                 \@contents,\%dirorder,
12278:                                                                 \%titles,$wantform);
12279:                         if ($datatable ne '') {
12280:                             $output .= &archive_options_form('decompressed',$datatable,
12281:                                                              $count,$hiddenelem);
12282:                             my $startcount = 6;
12283:                             $output .= &archive_javascript($startcount,$count,
12284:                                                            \%titles,\%children);
12285:                         }
12286:                         if ($env{'form.autoextract_camtasia'}) {
12287:                             my $version = $env{'form.autoextract_camtasia'};
12288:                             my %displayed;
12289:                             my $total = 1;
12290:                             $env{'form.archive_directory'} = [];
12291:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
12292:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
12293:                                 $path =~ s{/$}{};
12294:                                 my $item;
12295:                                 if ($path ne '') {
12296:                                     $item = "$path/$titles{$i}";
12297:                                 } else {
12298:                                     $item = $titles{$i};
12299:                                 }
12300:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
12301:                                 if ($item eq $contents[0]) {
12302:                                     push(@{$env{'form.archive_directory'}},$i);
12303:                                     $env{'form.archive_'.$i} = 'display';
12304:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
12305:                                     $displayed{'folder'} = $i;
12306:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
12307:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
12308:                                     $env{'form.archive_'.$i} = 'display';
12309:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
12310:                                     $displayed{'web'} = $i;
12311:                                 } else {
12312:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
12313:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
12314:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
12315:                                         push(@{$env{'form.archive_directory'}},$i);
12316:                                     }
12317:                                     $env{'form.archive_'.$i} = 'dependency';
12318:                                 }
12319:                                 $total ++;
12320:                             }
12321:                             for (my $i=1; $i<$total; $i++) {
12322:                                 next if ($i == $displayed{'web'});
12323:                                 next if ($i == $displayed{'folder'});
12324:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
12325:                             }
12326:                             $env{'form.phase'} = 'decompress_cleanup';
12327:                             $env{'form.archivedelete'} = 1;
12328:                             $env{'form.archive_count'} = $total-1;
12329:                             $output .=
12330:                                 &process_extracted_files('coursedocs',$docudom,
12331:                                                          $docuname,$destination,
12332:                                                          $dir_root,$hiddenelem);
12333:                         }
12334:                     } else {
12335:                         $warning = &mt('No new items extracted from archive file.');
12336:                     }
12337:                 } else {
12338:                     $output = $display;
12339:                     $error = &mt('An error occurred during extraction from the archive file.');
12340:                 }
12341:             }
12342:         }
12343:     }
12344:     if ($error) {
12345:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12346:                    $error.'</p>'."\n";
12347:     }
12348:     if ($warning) {
12349:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12350:     }
12351:     return $output;
12352: }
12353: 
12354: sub get_extracted {
12355:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
12356:         $titles,$wantform) = @_;
12357:     my $count = 0;
12358:     my $depth = 0;
12359:     my $datatable;
12360:     my @hierarchy;
12361:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
12362:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
12363:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
12364:     foreach my $item (@{$contents}) {
12365:         $count ++;
12366:         @{$dirorder->{$count}} = @hierarchy;
12367:         $titles->{$count} = $item;
12368:         &archive_hierarchy($depth,$count,$parent,$children);
12369:         if ($wantform) {
12370:             $datatable .= &archive_row($is_dir->{$item},$item,
12371:                                        $currdir,$depth,$count);
12372:         }
12373:         if ($is_dir->{$item}) {
12374:             $depth ++;
12375:             push(@hierarchy,$count);
12376:             $parent->{$depth} = $count;
12377:             $datatable .=
12378:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
12379:                                            \$depth,\$count,\@hierarchy,$dirorder,
12380:                                            $children,$parent,$titles,$wantform);
12381:             $depth --;
12382:             pop(@hierarchy);
12383:         }
12384:     }
12385:     return ($count,$datatable);
12386: }
12387: 
12388: sub recurse_extracted_archive {
12389:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
12390:         $children,$parent,$titles,$wantform) = @_;
12391:     my $result='';
12392:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
12393:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
12394:             (ref($dirorder) eq 'HASH')) {
12395:         return $result;
12396:     }
12397:     my $dirptr = 16384;
12398:     my ($newdirlistref,$newlisterror) =
12399:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
12400:     if (ref($newdirlistref) eq 'ARRAY') {
12401:         foreach my $dir_line (@{$newdirlistref}) {
12402:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12403:             unless ($item =~ /^\.+$/) {
12404:                 $$count ++;
12405:                 @{$dirorder->{$$count}} = @{$hierarchy};
12406:                 $titles->{$$count} = $item;
12407:                 &archive_hierarchy($$depth,$$count,$parent,$children);
12408: 
12409:                 my $is_dir;
12410:                 if ($dirptr&$testdir) {
12411:                     $is_dir = 1;
12412:                 }
12413:                 if ($wantform) {
12414:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
12415:                 }
12416:                 if ($is_dir) {
12417:                     $$depth ++;
12418:                     push(@{$hierarchy},$$count);
12419:                     $parent->{$$depth} = $$count;
12420:                     $result .=
12421:                         &recurse_extracted_archive("$currdir/$item",$docudom,
12422:                                                    $docuname,$depth,$count,
12423:                                                    $hierarchy,$dirorder,$children,
12424:                                                    $parent,$titles,$wantform);
12425:                     $$depth --;
12426:                     pop(@{$hierarchy});
12427:                 }
12428:             }
12429:         }
12430:     }
12431:     return $result;
12432: }
12433: 
12434: sub archive_hierarchy {
12435:     my ($depth,$count,$parent,$children) =@_;
12436:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
12437:         if (exists($parent->{$depth})) {
12438:              $children->{$parent->{$depth}} .= $count.':';
12439:         }
12440:     }
12441:     return;
12442: }
12443: 
12444: sub archive_row {
12445:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
12446:     my ($name) = ($item =~ m{([^/]+)$});
12447:     my %choices = &Apache::lonlocal::texthash (
12448:                                        'display'    => 'Add as file',
12449:                                        'dependency' => 'Include as dependency',
12450:                                        'discard'    => 'Discard',
12451:                                       );
12452:     if ($is_dir) {
12453:         $choices{'display'} = &mt('Add as folder'); 
12454:     }
12455:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
12456:     my $offset = 0;
12457:     foreach my $action ('display','dependency','discard') {
12458:         $offset ++;
12459:         if ($action ne 'display') {
12460:             $offset ++;
12461:         }  
12462:         $output .= '<td><span class="LC_nobreak">'.
12463:                    '<label><input type="radio" name="archive_'.$count.
12464:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
12465:         my $text = $choices{$action};
12466:         if ($is_dir) {
12467:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
12468:             if ($action eq 'display') {
12469:                 $text = &mt('Add as folder');
12470:             }
12471:         } else {
12472:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
12473: 
12474:         }
12475:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
12476:         if ($action eq 'dependency') {
12477:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
12478:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
12479:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
12480:                        '<option value=""></option>'."\n".
12481:                        '</select>'."\n".
12482:                        '</div>';
12483:         } elsif ($action eq 'display') {
12484:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
12485:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
12486:                        '</div>';
12487:         }
12488:         $output .= '</td>';
12489:     }
12490:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
12491:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
12492:     for (my $i=0; $i<$depth; $i++) {
12493:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
12494:     }
12495:     if ($is_dir) {
12496:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
12497:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
12498:     } else {
12499:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
12500:     }
12501:     $output .= '&nbsp;'.$name.'</td>'."\n".
12502:                &end_data_table_row();
12503:     return $output;
12504: }
12505: 
12506: sub archive_options_form {
12507:     my ($form,$display,$count,$hiddenelem) = @_;
12508:     my %lt = &Apache::lonlocal::texthash(
12509:                perm => 'Permanently remove archive file?',
12510:                hows => 'How should each extracted item be incorporated in the course?',
12511:                cont => 'Content actions for all',
12512:                addf => 'Add as folder/file',
12513:                incd => 'Include as dependency for a displayed file',
12514:                disc => 'Discard',
12515:                no   => 'No',
12516:                yes  => 'Yes',
12517:                save => 'Save',
12518:     );
12519:     my $output = <<"END";
12520: <form name="$form" method="post" action="">
12521: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
12522: <label>
12523:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
12524: </label>
12525: &nbsp;
12526: <label>
12527:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
12528: </span>
12529: </p>
12530: <input type="hidden" name="phase" value="decompress_cleanup" />
12531: <br />$lt{'hows'}
12532: <div class="LC_columnSection">
12533:   <fieldset>
12534:     <legend>$lt{'cont'}</legend>
12535:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
12536:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
12537:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
12538:   </fieldset>
12539: </div>
12540: END
12541:     return $output.
12542:            &start_data_table()."\n".
12543:            $display."\n".
12544:            &end_data_table()."\n".
12545:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
12546:            $hiddenelem.
12547:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
12548:            '</form>';
12549: }
12550: 
12551: sub archive_javascript {
12552:     my ($startcount,$numitems,$titles,$children) = @_;
12553:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
12554:     my $maintitle = $env{'form.comment'};
12555:     my $scripttag = <<START;
12556: <script type="text/javascript">
12557: // <![CDATA[
12558: 
12559: function checkAll(form,prefix) {
12560:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
12561:     for (var i=0; i < form.elements.length; i++) {
12562:         var id = form.elements[i].id;
12563:         if ((id != '') && (id != undefined)) {
12564:             if (idstr.test(id)) {
12565:                 if (form.elements[i].type == 'radio') {
12566:                     form.elements[i].checked = true;
12567:                     var nostart = i-$startcount;
12568:                     var offset = nostart%7;
12569:                     var count = (nostart-offset)/7;    
12570:                     dependencyCheck(form,count,offset);
12571:                 }
12572:             }
12573:         }
12574:     }
12575: }
12576: 
12577: function propagateCheck(form,count) {
12578:     if (count > 0) {
12579:         var startelement = $startcount + ((count-1) * 7);
12580:         for (var j=1; j<6; j++) {
12581:             if ((j != 2) && (j != 4)) {
12582:                 var item = startelement + j; 
12583:                 if (form.elements[item].type == 'radio') {
12584:                     if (form.elements[item].checked) {
12585:                         containerCheck(form,count,j);
12586:                         break;
12587:                     }
12588:                 }
12589:             }
12590:         }
12591:     }
12592: }
12593: 
12594: numitems = $numitems
12595: var titles = new Array(numitems);
12596: var parents = new Array(numitems);
12597: for (var i=0; i<numitems; i++) {
12598:     parents[i] = new Array;
12599: }
12600: var maintitle = '$maintitle';
12601: 
12602: START
12603: 
12604:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
12605:         my @contents = split(/:/,$children->{$container});
12606:         for (my $i=0; $i<@contents; $i ++) {
12607:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
12608:         }
12609:     }
12610: 
12611:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
12612:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
12613:     }
12614: 
12615:     $scripttag .= <<END;
12616: 
12617: function containerCheck(form,count,offset) {
12618:     if (count > 0) {
12619:         dependencyCheck(form,count,offset);
12620:         var item = (offset+$startcount)+7*(count-1);
12621:         form.elements[item].checked = true;
12622:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
12623:             if (parents[count].length > 0) {
12624:                 for (var j=0; j<parents[count].length; j++) {
12625:                     containerCheck(form,parents[count][j],offset);
12626:                 }
12627:             }
12628:         }
12629:     }
12630: }
12631: 
12632: function dependencyCheck(form,count,offset) {
12633:     if (count > 0) {
12634:         var chosen = (offset+$startcount)+7*(count-1);
12635:         var depitem = $startcount + ((count-1) * 7) + 4;
12636:         var currtype = form.elements[depitem].type;
12637:         if (form.elements[chosen].value == 'dependency') {
12638:             document.getElementById('arc_depon_'+count).style.display='block'; 
12639:             form.elements[depitem].options.length = 0;
12640:             form.elements[depitem].options[0] = new Option('Select','',true,true);
12641:             for (var i=1; i<=numitems; i++) {
12642:                 if (i == count) {
12643:                     continue;
12644:                 }
12645:                 var startelement = $startcount + (i-1) * 7;
12646:                 for (var j=1; j<6; j++) {
12647:                     if ((j != 2) && (j!= 4)) {
12648:                         var item = startelement + j;
12649:                         if (form.elements[item].type == 'radio') {
12650:                             if (form.elements[item].checked) {
12651:                                 if (form.elements[item].value == 'display') {
12652:                                     var n = form.elements[depitem].options.length;
12653:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
12654:                                 }
12655:                             }
12656:                         }
12657:                     }
12658:                 }
12659:             }
12660:         } else {
12661:             document.getElementById('arc_depon_'+count).style.display='none';
12662:             form.elements[depitem].options.length = 0;
12663:             form.elements[depitem].options[0] = new Option('Select','',true,true);
12664:         }
12665:         titleCheck(form,count,offset);
12666:     }
12667: }
12668: 
12669: function propagateSelect(form,count,offset) {
12670:     if (count > 0) {
12671:         var item = (1+offset+$startcount)+7*(count-1);
12672:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
12673:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
12674:             if (parents[count].length > 0) {
12675:                 for (var j=0; j<parents[count].length; j++) {
12676:                     containerSelect(form,parents[count][j],offset,picked);
12677:                 }
12678:             }
12679:         }
12680:     }
12681: }
12682: 
12683: function containerSelect(form,count,offset,picked) {
12684:     if (count > 0) {
12685:         var item = (offset+$startcount)+7*(count-1);
12686:         if (form.elements[item].type == 'radio') {
12687:             if (form.elements[item].value == 'dependency') {
12688:                 if (form.elements[item+1].type == 'select-one') {
12689:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
12690:                         if (form.elements[item+1].options[i].value == picked) {
12691:                             form.elements[item+1].selectedIndex = i;
12692:                             break;
12693:                         }
12694:                     }
12695:                 }
12696:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
12697:                     if (parents[count].length > 0) {
12698:                         for (var j=0; j<parents[count].length; j++) {
12699:                             containerSelect(form,parents[count][j],offset,picked);
12700:                         }
12701:                     }
12702:                 }
12703:             }
12704:         }
12705:     }
12706: }
12707: 
12708: function titleCheck(form,count,offset) {
12709:     if (count > 0) {
12710:         var chosen = (offset+$startcount)+7*(count-1);
12711:         var depitem = $startcount + ((count-1) * 7) + 2;
12712:         var currtype = form.elements[depitem].type;
12713:         if (form.elements[chosen].value == 'display') {
12714:             document.getElementById('arc_title_'+count).style.display='block';
12715:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
12716:                 document.getElementById('archive_title_'+count).value=maintitle;
12717:             }
12718:         } else {
12719:             document.getElementById('arc_title_'+count).style.display='none';
12720:             if (currtype == 'text') { 
12721:                 document.getElementById('archive_title_'+count).value='';
12722:             }
12723:         }
12724:     }
12725:     return;
12726: }
12727: 
12728: // ]]>
12729: </script>
12730: END
12731:     return $scripttag;
12732: }
12733: 
12734: sub process_extracted_files {
12735:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
12736:     my $numitems = $env{'form.archive_count'};
12737:     return if ((!$numitems) || ($numitems =~ /\D/));
12738:     my @ids=&Apache::lonnet::current_machine_ids();
12739:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
12740:         %folders,%containers,%mapinner,%prompttofetch);
12741:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
12742:     if (grep(/^\Q$docuhome\E$/,@ids)) {
12743:         $prefix = &LONCAPA::propath($docudom,$docuname);
12744:         $pathtocheck = "$dir_root/$destination";
12745:         $dir = $dir_root;
12746:         $ishome = 1;
12747:     } else {
12748:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
12749:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
12750:         $dir = "$dir_root/$docudom/$docuname";
12751:     }
12752:     my $currdir = "$dir_root/$destination";
12753:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
12754:     if ($env{'form.folderpath'}) {
12755:         my @items = split('&',$env{'form.folderpath'});
12756:         $folders{'0'} = $items[-2];
12757:         if ($env{'form.folderpath'} =~ /\:1$/) {
12758:             $containers{'0'}='page';
12759:         } else {
12760:             $containers{'0'}='sequence';
12761:         }
12762:     }
12763:     my @archdirs = &get_env_multiple('form.archive_directory');
12764:     if ($numitems) {
12765:         for (my $i=1; $i<=$numitems; $i++) {
12766:             my $path = $env{'form.archive_content_'.$i};
12767:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
12768:                 my $item = $1;
12769:                 $toplevelitems{$item} = $i;
12770:                 if (grep(/^\Q$i\E$/,@archdirs)) {
12771:                     $is_dir{$item} = 1;
12772:                 }
12773:             }
12774:         }
12775:     }
12776:     my ($output,%children,%parent,%titles,%dirorder,$result);
12777:     if (keys(%toplevelitems) > 0) {
12778:         my @contents = sort(keys(%toplevelitems));
12779:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
12780:                                            \%parent,\@contents,\%dirorder,\%titles);
12781:     }
12782:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
12783:     if ($numitems) {
12784:         for (my $i=1; $i<=$numitems; $i++) {
12785:             next if ($env{'form.archive_'.$i} eq 'dependency');
12786:             my $path = $env{'form.archive_content_'.$i};
12787:             if ($path =~ /^\Q$pathtocheck\E/) {
12788:                 if ($env{'form.archive_'.$i} eq 'discard') {
12789:                     if ($prefix ne '' && $path ne '') {
12790:                         if (-e $prefix.$path) {
12791:                             if ((@archdirs > 0) && 
12792:                                 (grep(/^\Q$i\E$/,@archdirs))) {
12793:                                 $todeletedir{$prefix.$path} = 1;
12794:                             } else {
12795:                                 $todelete{$prefix.$path} = 1;
12796:                             }
12797:                         }
12798:                     }
12799:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
12800:                     my ($docstitle,$title,$url,$outer);
12801:                     ($title) = ($path =~ m{/([^/]+)$});
12802:                     $docstitle = $env{'form.archive_title_'.$i};
12803:                     if ($docstitle eq '') {
12804:                         $docstitle = $title;
12805:                     }
12806:                     $outer = 0;
12807:                     if (ref($dirorder{$i}) eq 'ARRAY') {
12808:                         if (@{$dirorder{$i}} > 0) {
12809:                             foreach my $item (reverse(@{$dirorder{$i}})) {
12810:                                 if ($env{'form.archive_'.$item} eq 'display') {
12811:                                     $outer = $item;
12812:                                     last;
12813:                                 }
12814:                             }
12815:                         }
12816:                     }
12817:                     my ($errtext,$fatal) = 
12818:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
12819:                                                '/'.$folders{$outer}.'.'.
12820:                                                $containers{$outer});
12821:                     next if ($fatal);
12822:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
12823:                         if ($context eq 'coursedocs') {
12824:                             $mapinner{$i} = time;
12825:                             $folders{$i} = 'default_'.$mapinner{$i};
12826:                             $containers{$i} = 'sequence';
12827:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
12828:                                       $folders{$i}.'.'.$containers{$i};
12829:                             my $newidx = &LONCAPA::map::getresidx();
12830:                             $LONCAPA::map::resources[$newidx]=
12831:                                 $docstitle.':'.$url.':false:normal:res';
12832:                             push(@LONCAPA::map::order,$newidx);
12833:                             my ($outtext,$errtext) =
12834:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
12835:                                                         $docuname.'/'.$folders{$outer}.
12836:                                                         '.'.$containers{$outer},1,1);
12837:                             $newseqid{$i} = $newidx;
12838:                             unless ($errtext) {
12839:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
12840:                                                        &HTML::Entities::encode($docstitle,'<>&"'))..
12841:                                             '</li>'."\n";
12842:                             }
12843:                         }
12844:                     } else {
12845:                         if ($context eq 'coursedocs') {
12846:                             my $newidx=&LONCAPA::map::getresidx();
12847:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
12848:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
12849:                                       $title;
12850:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
12851:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
12852:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
12853:                                 }
12854:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
12855:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
12856:                                 }
12857:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
12858:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
12859:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
12860:                                         unless ($ishome) {
12861:                                             my $fetch = "$newdest{$i}/$title";
12862:                                             $fetch =~ s/^\Q$prefix$dir\E//;
12863:                                             $prompttofetch{$fetch} = 1;
12864:                                         }
12865:                                    }
12866:                                 }
12867:                                 $LONCAPA::map::resources[$newidx]=
12868:                                     $docstitle.':'.$url.':false:normal:res';
12869:                                 push(@LONCAPA::map::order, $newidx);
12870:                                 my ($outtext,$errtext)=
12871:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
12872:                                                             $docuname.'/'.$folders{$outer}.
12873:                                                             '.'.$containers{$outer},1,1);
12874:                                 unless ($errtext) {
12875:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
12876:                                         $result .= '<li>'.&mt('File: [_1] added to course',
12877:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
12878:                                                    '</li>'."\n";
12879:                                     }
12880:                                 }
12881:                             } else {
12882:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
12883:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
12884:                             }
12885:                         }
12886:                     }
12887:                 }
12888:             } else {
12889:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
12890:                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
12891:             }
12892:         }
12893:         for (my $i=1; $i<=$numitems; $i++) {
12894:             next unless ($env{'form.archive_'.$i} eq 'dependency');
12895:             my $path = $env{'form.archive_content_'.$i};
12896:             if ($path =~ /^\Q$pathtocheck\E/) {
12897:                 my ($title) = ($path =~ m{/([^/]+)$});
12898:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
12899:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
12900:                     if (ref($dirorder{$i}) eq 'ARRAY') {
12901:                         my ($itemidx,$fullpath,$relpath);
12902:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
12903:                             my $container = $dirorder{$referrer{$i}}->[-1];
12904:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
12905:                                 if ($dirorder{$i}->[$j] eq $container) {
12906:                                     $itemidx = $j;
12907:                                 }
12908:                             }
12909:                         }
12910:                         if ($itemidx eq '') {
12911:                             $itemidx =  0;
12912:                         }
12913:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
12914:                             if ($mapinner{$referrer{$i}}) {
12915:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
12916:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
12917:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
12918:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
12919:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
12920:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
12921:                                             if (!-e $fullpath) {
12922:                                                 mkdir($fullpath,0755);
12923:                                             }
12924:                                         }
12925:                                     } else {
12926:                                         last;
12927:                                     }
12928:                                 }
12929:                             }
12930:                         } elsif ($newdest{$referrer{$i}}) {
12931:                             $fullpath = $newdest{$referrer{$i}};
12932:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
12933:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
12934:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
12935:                                     last;
12936:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
12937:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
12938:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
12939:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
12940:                                         if (!-e $fullpath) {
12941:                                             mkdir($fullpath,0755);
12942:                                         }
12943:                                     }
12944:                                 } else {
12945:                                     last;
12946:                                 }
12947:                             }
12948:                         }
12949:                         if ($fullpath ne '') {
12950:                             if (-e "$prefix$path") {
12951:                                 unless (rename("$prefix$path","$fullpath/$title")) {
12952:                                      $warning .= &mt('Failed to rename dependency').'<br />';
12953:                                 }
12954:                             }
12955:                             if (-e "$fullpath/$title") {
12956:                                 my $showpath;
12957:                                 if ($relpath ne '') {
12958:                                     $showpath = "$relpath/$title";
12959:                                 } else {
12960:                                     $showpath = "/$title";
12961:                                 }
12962:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
12963:                                                       &HTML::Entities::encode($showpath,'<>&"')).
12964:                                            '</li>'."\n";
12965:                                 unless ($ishome) {
12966:                                     my $fetch = "$fullpath/$title";
12967:                                     $fetch =~ s/^\Q$prefix$dir\E//;
12968:                                     $prompttofetch{$fetch} = 1;
12969:                                 }
12970:                             }
12971:                         }
12972:                     }
12973:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
12974:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
12975:                                     &HTML::Entities::encode($path,'<>&"'),
12976:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
12977:                                 '<br />';
12978:                 }
12979:             } else {
12980:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
12981:                                 &HTML::Entities::encode($path)).'<br />';
12982:             }
12983:         }
12984:         if (keys(%todelete)) {
12985:             foreach my $key (keys(%todelete)) {
12986:                 unlink($key);
12987:             }
12988:         }
12989:         if (keys(%todeletedir)) {
12990:             foreach my $key (keys(%todeletedir)) {
12991:                 rmdir($key);
12992:             }
12993:         }
12994:         foreach my $dir (sort(keys(%is_dir))) {
12995:             if (($pathtocheck ne '') && ($dir ne ''))  {
12996:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
12997:             }
12998:         }
12999:         if ($result ne '') {
13000:             $output .= '<ul>'."\n".
13001:                        $result."\n".
13002:                        '</ul>';
13003:         }
13004:         unless ($ishome) {
13005:             my $replicationfail;
13006:             foreach my $item (keys(%prompttofetch)) {
13007:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
13008:                 unless ($fetchresult eq 'ok') {
13009:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
13010:                 }
13011:             }
13012:             if ($replicationfail) {
13013:                 $output .= '<p class="LC_error">'.
13014:                            &mt('Course home server failed to retrieve:').'<ul>'.
13015:                            $replicationfail.
13016:                            '</ul></p>';
13017:             }
13018:         }
13019:     } else {
13020:         $warning = &mt('No items found in archive.');
13021:     }
13022:     if ($error) {
13023:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13024:                    $error.'</p>'."\n";
13025:     }
13026:     if ($warning) {
13027:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
13028:     }
13029:     return $output;
13030: }
13031: 
13032: sub cleanup_empty_dirs {
13033:     my ($path) = @_;
13034:     if (($path ne '') && (-d $path)) {
13035:         if (opendir(my $dirh,$path)) {
13036:             my @dircontents = grep(!/^\./,readdir($dirh));
13037:             my $numitems = 0;
13038:             foreach my $item (@dircontents) {
13039:                 if (-d "$path/$item") {
13040:                     &cleanup_empty_dirs("$path/$item");
13041:                     if (-e "$path/$item") {
13042:                         $numitems ++;
13043:                     }
13044:                 } else {
13045:                     $numitems ++;
13046:                 }
13047:             }
13048:             if ($numitems == 0) {
13049:                 rmdir($path);
13050:             }
13051:             closedir($dirh);
13052:         }
13053:     }
13054:     return;
13055: }
13056: 
13057: =pod
13058: 
13059: =item * &get_folder_hierarchy()
13060: 
13061: Provides hierarchy of names of folders/sub-folders containing the current
13062: item,
13063: 
13064: Inputs: 3
13065:      - $navmap - navmaps object
13066: 
13067:      - $map - url for map (either the trigger itself, or map containing
13068:                            the resource, which is the trigger).
13069: 
13070:      - $showitem - 1 => show title for map itself; 0 => do not show.
13071: 
13072: Outputs: 1 @pathitems - array of folder/subfolder names.
13073: 
13074: =cut
13075: 
13076: sub get_folder_hierarchy {
13077:     my ($navmap,$map,$showitem) = @_;
13078:     my @pathitems;
13079:     if (ref($navmap)) {
13080:         my $mapres = $navmap->getResourceByUrl($map);
13081:         if (ref($mapres)) {
13082:             my $pcslist = $mapres->map_hierarchy();
13083:             if ($pcslist ne '') {
13084:                 my @pcs = split(/,/,$pcslist);
13085:                 foreach my $pc (@pcs) {
13086:                     if ($pc == 1) {
13087:                         push(@pathitems,&mt('Main Content'));
13088:                     } else {
13089:                         my $res = $navmap->getByMapPc($pc);
13090:                         if (ref($res)) {
13091:                             my $title = $res->compTitle();
13092:                             $title =~ s/\W+/_/g;
13093:                             if ($title ne '') {
13094:                                 push(@pathitems,$title);
13095:                             }
13096:                         }
13097:                     }
13098:                 }
13099:             }
13100:             if ($showitem) {
13101:                 if ($mapres->{ID} eq '0.0') {
13102:                     push(@pathitems,&mt('Main Content'));
13103:                 } else {
13104:                     my $maptitle = $mapres->compTitle();
13105:                     $maptitle =~ s/\W+/_/g;
13106:                     if ($maptitle ne '') {
13107:                         push(@pathitems,$maptitle);
13108:                     }
13109:                 }
13110:             }
13111:         }
13112:     }
13113:     return @pathitems;
13114: }
13115: 
13116: =pod
13117: 
13118: =item * &get_turnedin_filepath()
13119: 
13120: Determines path in a user's portfolio file for storage of files uploaded
13121: to a specific essayresponse or dropbox item.
13122: 
13123: Inputs: 3 required + 1 optional.
13124: $symb is symb for resource, $uname and $udom are for current user (required).
13125: $caller is optional (can be "submission", if routine is called when storing
13126: an upoaded file when "Submit Answer" button was pressed).
13127: 
13128: Returns array containing $path and $multiresp. 
13129: $path is path in portfolio.  $multiresp is 1 if this resource contains more
13130: than one file upload item.  Callers of routine should append partid as a 
13131: subdirectory to $path in cases where $multiresp is 1.
13132: 
13133: Called by: homework/essayresponse.pm and homework/structuretags.pm
13134: 
13135: =cut
13136: 
13137: sub get_turnedin_filepath {
13138:     my ($symb,$uname,$udom,$caller) = @_;
13139:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
13140:     my $turnindir;
13141:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
13142:     $turnindir = $userhash{'turnindir'};
13143:     my ($path,$multiresp);
13144:     if ($turnindir eq '') {
13145:         if ($caller eq 'submission') {
13146:             $turnindir = &mt('turned in');
13147:             $turnindir =~ s/\W+/_/g;
13148:             my %newhash = (
13149:                             'turnindir' => $turnindir,
13150:                           );
13151:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
13152:         }
13153:     }
13154:     if ($turnindir ne '') {
13155:         $path = '/'.$turnindir.'/';
13156:         my ($multipart,$turnin,@pathitems);
13157:         my $navmap = Apache::lonnavmaps::navmap->new();
13158:         if (defined($navmap)) {
13159:             my $mapres = $navmap->getResourceByUrl($map);
13160:             if (ref($mapres)) {
13161:                 my $pcslist = $mapres->map_hierarchy();
13162:                 if ($pcslist ne '') {
13163:                     foreach my $pc (split(/,/,$pcslist)) {
13164:                         my $res = $navmap->getByMapPc($pc);
13165:                         if (ref($res)) {
13166:                             my $title = $res->compTitle();
13167:                             $title =~ s/\W+/_/g;
13168:                             if ($title ne '') {
13169:                                 if (($pc > 1) && (length($title) > 12)) {
13170:                                     $title = substr($title,0,12);
13171:                                 }
13172:                                 push(@pathitems,$title);
13173:                             }
13174:                         }
13175:                     }
13176:                 }
13177:                 my $maptitle = $mapres->compTitle();
13178:                 $maptitle =~ s/\W+/_/g;
13179:                 if ($maptitle ne '') {
13180:                     if (length($maptitle) > 12) {
13181:                         $maptitle = substr($maptitle,0,12);
13182:                     }
13183:                     push(@pathitems,$maptitle);
13184:                 }
13185:                 unless ($env{'request.state'} eq 'construct') {
13186:                     my $res = $navmap->getBySymb($symb);
13187:                     if (ref($res)) {
13188:                         my $partlist = $res->parts();
13189:                         my $totaluploads = 0;
13190:                         if (ref($partlist) eq 'ARRAY') {
13191:                             foreach my $part (@{$partlist}) {
13192:                                 my @types = $res->responseType($part);
13193:                                 my @ids = $res->responseIds($part);
13194:                                 for (my $i=0; $i < scalar(@ids); $i++) {
13195:                                     if ($types[$i] eq 'essay') {
13196:                                         my $partid = $part.'_'.$ids[$i];
13197:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
13198:                                             $totaluploads ++;
13199:                                         }
13200:                                     }
13201:                                 }
13202:                             }
13203:                             if ($totaluploads > 1) {
13204:                                 $multiresp = 1;
13205:                             }
13206:                         }
13207:                     }
13208:                 }
13209:             } else {
13210:                 return;
13211:             }
13212:         } else {
13213:             return;
13214:         }
13215:         my $restitle=&Apache::lonnet::gettitle($symb);
13216:         $restitle =~ s/\W+/_/g;
13217:         if ($restitle eq '') {
13218:             $restitle = ($resurl =~ m{/[^/]+$});
13219:             if ($restitle eq '') {
13220:                 $restitle = time;
13221:             }
13222:         }
13223:         if (length($restitle) > 12) {
13224:             $restitle = substr($restitle,0,12);
13225:         }
13226:         push(@pathitems,$restitle);
13227:         $path .= join('/',@pathitems);
13228:     }
13229:     return ($path,$multiresp);
13230: }
13231: 
13232: =pod
13233: 
13234: =back
13235: 
13236: =head1 CSV Upload/Handling functions
13237: 
13238: =over 4
13239: 
13240: =item * &upfile_store($r)
13241: 
13242: Store uploaded file, $r should be the HTTP Request object,
13243: needs $env{'form.upfile'}
13244: returns $datatoken to be put into hidden field
13245: 
13246: =cut
13247: 
13248: sub upfile_store {
13249:     my $r=shift;
13250:     $env{'form.upfile'}=~s/\r/\n/gs;
13251:     $env{'form.upfile'}=~s/\f/\n/gs;
13252:     $env{'form.upfile'}=~s/\n+/\n/gs;
13253:     $env{'form.upfile'}=~s/\n+$//gs;
13254: 
13255:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
13256:                                      '_enroll_'.$env{'request.course.id'}.'_'.
13257:                                      time.'_'.$$);
13258:     return if ($datatoken eq '');
13259: 
13260:     {
13261:         my $datafile = $r->dir_config('lonDaemons').
13262:                            '/tmp/'.$datatoken.'.tmp';
13263:         if ( open(my $fh,'>',$datafile) ) {
13264:             print $fh $env{'form.upfile'};
13265:             close($fh);
13266:         }
13267:     }
13268:     return $datatoken;
13269: }
13270: 
13271: =pod
13272: 
13273: =item * &load_tmp_file($r,$datatoken)
13274: 
13275: Load uploaded file from tmp, $r should be the HTTP Request object,
13276: $datatoken is the name to assign to the temporary file.
13277: sets $env{'form.upfile'} to the contents of the file
13278: 
13279: =cut
13280: 
13281: sub load_tmp_file {
13282:     my ($r,$datatoken) = @_;
13283:     return if ($datatoken eq '');
13284:     my @studentdata=();
13285:     {
13286:         my $studentfile = $r->dir_config('lonDaemons').
13287:                               '/tmp/'.$datatoken.'.tmp';
13288:         if ( open(my $fh,'<',$studentfile) ) {
13289:             @studentdata=<$fh>;
13290:             close($fh);
13291:         }
13292:     }
13293:     $env{'form.upfile'}=join('',@studentdata);
13294: }
13295: 
13296: sub valid_datatoken {
13297:     my ($datatoken) = @_;
13298:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
13299:         return $datatoken;
13300:     }
13301:     return;
13302: }
13303: 
13304: =pod
13305: 
13306: =item * &upfile_record_sep()
13307: 
13308: Separate uploaded file into records
13309: returns array of records,
13310: needs $env{'form.upfile'} and $env{'form.upfiletype'}
13311: 
13312: =cut
13313: 
13314: sub upfile_record_sep {
13315:     if ($env{'form.upfiletype'} eq 'xml') {
13316:     } else {
13317: 	my @records;
13318: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
13319: 	    if ($line=~/^\s*$/) { next; }
13320: 	    push(@records,$line);
13321: 	}
13322: 	return @records;
13323:     }
13324: }
13325: 
13326: =pod
13327: 
13328: =item * &record_sep($record)
13329: 
13330: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
13331: 
13332: =cut
13333: 
13334: sub takeleft {
13335:     my $index=shift;
13336:     return substr('0000'.$index,-4,4);
13337: }
13338: 
13339: sub record_sep {
13340:     my $record=shift;
13341:     my %components=();
13342:     if ($env{'form.upfiletype'} eq 'xml') {
13343:     } elsif ($env{'form.upfiletype'} eq 'space') {
13344:         my $i=0;
13345:         foreach my $field (split(/\s+/,$record)) {
13346:             $field=~s/^(\"|\')//;
13347:             $field=~s/(\"|\')$//;
13348:             $components{&takeleft($i)}=$field;
13349:             $i++;
13350:         }
13351:     } elsif ($env{'form.upfiletype'} eq 'tab') {
13352:         my $i=0;
13353:         foreach my $field (split(/\t/,$record)) {
13354:             $field=~s/^(\"|\')//;
13355:             $field=~s/(\"|\')$//;
13356:             $components{&takeleft($i)}=$field;
13357:             $i++;
13358:         }
13359:     } else {
13360:         my $separator=',';
13361:         if ($env{'form.upfiletype'} eq 'semisv') {
13362:             $separator=';';
13363:         }
13364:         my $i=0;
13365: # the character we are looking for to indicate the end of a quote or a record 
13366:         my $looking_for=$separator;
13367: # do not add the characters to the fields
13368:         my $ignore=0;
13369: # we just encountered a separator (or the beginning of the record)
13370:         my $just_found_separator=1;
13371: # store the field we are working on here
13372:         my $field='';
13373: # work our way through all characters in record
13374:         foreach my $character ($record=~/(.)/g) {
13375:             if ($character eq $looking_for) {
13376:                if ($character ne $separator) {
13377: # Found the end of a quote, again looking for separator
13378:                   $looking_for=$separator;
13379:                   $ignore=1;
13380:                } else {
13381: # Found a separator, store away what we got
13382:                   $components{&takeleft($i)}=$field;
13383: 	          $i++;
13384:                   $just_found_separator=1;
13385:                   $ignore=0;
13386:                   $field='';
13387:                }
13388:                next;
13389:             }
13390: # single or double quotation marks after a separator indicate beginning of a quote
13391: # we are now looking for the end of the quote and need to ignore separators
13392:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
13393:                $looking_for=$character;
13394:                next;
13395:             }
13396: # ignore would be true after we reached the end of a quote
13397:             if ($ignore) { next; }
13398:             if (($just_found_separator) && ($character=~/\s/)) { next; }
13399:             $field.=$character;
13400:             $just_found_separator=0; 
13401:         }
13402: # catch the very last entry, since we never encountered the separator
13403:         $components{&takeleft($i)}=$field;
13404:     }
13405:     return %components;
13406: }
13407: 
13408: ######################################################
13409: ######################################################
13410: 
13411: =pod
13412: 
13413: =item * &upfile_select_html()
13414: 
13415: Return HTML code to select a file from the users machine and specify 
13416: the file type.
13417: 
13418: =cut
13419: 
13420: ######################################################
13421: ######################################################
13422: sub upfile_select_html {
13423:     my %Types = (
13424:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
13425:                  semisv => &mt('Semicolon separated values'),
13426:                  space => &mt('Space separated'),
13427:                  tab   => &mt('Tabulator separated'),
13428: #                 xml   => &mt('HTML/XML'),
13429:                  );
13430:     my $Str = '<input type="file" name="upfile" size="50" />'.
13431:         '<br />'.&mt('Type').': <select name="upfiletype">';
13432:     foreach my $type (sort(keys(%Types))) {
13433:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
13434:     }
13435:     $Str .= "</select>\n";
13436:     return $Str;
13437: }
13438: 
13439: sub get_samples {
13440:     my ($records,$toget) = @_;
13441:     my @samples=({});
13442:     my $got=0;
13443:     foreach my $rec (@$records) {
13444: 	my %temp = &record_sep($rec);
13445: 	if (! grep(/\S/, values(%temp))) { next; }
13446: 	if (%temp) {
13447: 	    $samples[$got]=\%temp;
13448: 	    $got++;
13449: 	    if ($got == $toget) { last; }
13450: 	}
13451:     }
13452:     return \@samples;
13453: }
13454: 
13455: ######################################################
13456: ######################################################
13457: 
13458: =pod
13459: 
13460: =item * &csv_print_samples($r,$records)
13461: 
13462: Prints a table of sample values from each column uploaded $r is an
13463: Apache Request ref, $records is an arrayref from
13464: &Apache::loncommon::upfile_record_sep
13465: 
13466: =cut
13467: 
13468: ######################################################
13469: ######################################################
13470: sub csv_print_samples {
13471:     my ($r,$records) = @_;
13472:     my $samples = &get_samples($records,5);
13473: 
13474:     $r->print(&mt('Samples').'<br />'.&start_data_table().
13475:               &start_data_table_header_row());
13476:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
13477:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
13478:     $r->print(&end_data_table_header_row());
13479:     foreach my $hash (@$samples) {
13480: 	$r->print(&start_data_table_row());
13481: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13482: 	    $r->print('<td>');
13483: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
13484: 	    $r->print('</td>');
13485: 	}
13486: 	$r->print(&end_data_table_row());
13487:     }
13488:     $r->print(&end_data_table().'<br />'."\n");
13489: }
13490: 
13491: ######################################################
13492: ######################################################
13493: 
13494: =pod
13495: 
13496: =item * &csv_print_select_table($r,$records,$d)
13497: 
13498: Prints a table to create associations between values and table columns.
13499: 
13500: $r is an Apache Request ref,
13501: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
13502: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
13503: 
13504: =cut
13505: 
13506: ######################################################
13507: ######################################################
13508: sub csv_print_select_table {
13509:     my ($r,$records,$d) = @_;
13510:     my $i=0;
13511:     my $samples = &get_samples($records,1);
13512:     $r->print(&mt('Associate columns with student attributes.')."\n".
13513: 	      &start_data_table().&start_data_table_header_row().
13514:               '<th>'.&mt('Attribute').'</th>'.
13515:               '<th>'.&mt('Column').'</th>'.
13516:               &end_data_table_header_row()."\n");
13517:     foreach my $array_ref (@$d) {
13518: 	my ($value,$display,$defaultcol)=@{ $array_ref };
13519: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
13520: 
13521: 	$r->print('<td><select name="f'.$i.'"'.
13522: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
13523: 	$r->print('<option value="none"></option>');
13524: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13525: 	    $r->print('<option value="'.$sample.'"'.
13526:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
13527:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
13528: 	}
13529: 	$r->print('</select></td>'.&end_data_table_row()."\n");
13530: 	$i++;
13531:     }
13532:     $r->print(&end_data_table());
13533:     $i--;
13534:     return $i;
13535: }
13536: 
13537: ######################################################
13538: ######################################################
13539: 
13540: =pod
13541: 
13542: =item * &csv_samples_select_table($r,$records,$d)
13543: 
13544: Prints a table of sample values from the upload and can make associate samples to internal names.
13545: 
13546: $r is an Apache Request ref,
13547: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
13548: $d is an array of 2 element arrays (internal name, displayed name)
13549: 
13550: =cut
13551: 
13552: ######################################################
13553: ######################################################
13554: sub csv_samples_select_table {
13555:     my ($r,$records,$d) = @_;
13556:     my $i=0;
13557:     #
13558:     my $max_samples = 5;
13559:     my $samples = &get_samples($records,$max_samples);
13560:     $r->print(&start_data_table().
13561:               &start_data_table_header_row().'<th>'.
13562:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
13563:               &end_data_table_header_row());
13564: 
13565:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
13566: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
13567: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
13568: 	foreach my $option (@$d) {
13569: 	    my ($value,$display,$defaultcol)=@{ $option };
13570: 	    $r->print('<option value="'.$value.'"'.
13571:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
13572:                       $display.'</option>');
13573: 	}
13574: 	$r->print('</select></td><td>');
13575: 	foreach my $line (0..($max_samples-1)) {
13576: 	    if (defined($samples->[$line]{$key})) { 
13577: 		$r->print($samples->[$line]{$key}."<br />\n"); 
13578: 	    }
13579: 	}
13580: 	$r->print('</td>'.&end_data_table_row());
13581: 	$i++;
13582:     }
13583:     $r->print(&end_data_table());
13584:     $i--;
13585:     return($i);
13586: }
13587: 
13588: ######################################################
13589: ######################################################
13590: 
13591: =pod
13592: 
13593: =item * &clean_excel_name($name)
13594: 
13595: Returns a replacement for $name which does not contain any illegal characters.
13596: 
13597: =cut
13598: 
13599: ######################################################
13600: ######################################################
13601: sub clean_excel_name {
13602:     my ($name) = @_;
13603:     $name =~ s/[:\*\?\/\\]//g;
13604:     if (length($name) > 31) {
13605:         $name = substr($name,0,31);
13606:     }
13607:     return $name;
13608: }
13609: 
13610: =pod
13611: 
13612: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
13613: 
13614: Returns either 1 or undef
13615: 
13616: 1 if the part is to be hidden, undef if it is to be shown
13617: 
13618: Arguments are:
13619: 
13620: $id the id of the part to be checked
13621: $symb, optional the symb of the resource to check
13622: $udom, optional the domain of the user to check for
13623: $uname, optional the username of the user to check for
13624: 
13625: =cut
13626: 
13627: sub check_if_partid_hidden {
13628:     my ($id,$symb,$udom,$uname) = @_;
13629:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
13630: 					 $symb,$udom,$uname);
13631:     my $truth=1;
13632:     #if the string starts with !, then the list is the list to show not hide
13633:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
13634:     my @hiddenlist=split(/,/,$hiddenparts);
13635:     foreach my $checkid (@hiddenlist) {
13636: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
13637:     }
13638:     return !$truth;
13639: }
13640: 
13641: 
13642: ############################################################
13643: ############################################################
13644: 
13645: =pod
13646: 
13647: =back 
13648: 
13649: =head1 cgi-bin script and graphing routines
13650: 
13651: =over 4
13652: 
13653: =item * &get_cgi_id()
13654: 
13655: Inputs: none
13656: 
13657: Returns an id which can be used to pass environment variables
13658: to various cgi-bin scripts.  These environment variables will
13659: be removed from the users environment after a given time by
13660: the routine &Apache::lonnet::transfer_profile_to_env.
13661: 
13662: =cut
13663: 
13664: ############################################################
13665: ############################################################
13666: my $uniq=0;
13667: sub get_cgi_id {
13668:     $uniq=($uniq+1)%100000;
13669:     return (time.'_'.$$.'_'.$uniq);
13670: }
13671: 
13672: ############################################################
13673: ############################################################
13674: 
13675: =pod
13676: 
13677: =item * &DrawBarGraph()
13678: 
13679: Facilitates the plotting of data in a (stacked) bar graph.
13680: Puts plot definition data into the users environment in order for 
13681: graph.png to plot it.  Returns an <img> tag for the plot.
13682: The bars on the plot are labeled '1','2',...,'n'.
13683: 
13684: Inputs:
13685: 
13686: =over 4
13687: 
13688: =item $Title: string, the title of the plot
13689: 
13690: =item $xlabel: string, text describing the X-axis of the plot
13691: 
13692: =item $ylabel: string, text describing the Y-axis of the plot
13693: 
13694: =item $Max: scalar, the maximum Y value to use in the plot
13695: If $Max is < any data point, the graph will not be rendered.
13696: 
13697: =item $colors: array ref holding the colors to be used for the data sets when
13698: they are plotted.  If undefined, default values will be used.
13699: 
13700: =item $labels: array ref holding the labels to use on the x-axis for the bars.
13701: 
13702: =item @Values: An array of array references.  Each array reference holds data
13703: to be plotted in a stacked bar chart.
13704: 
13705: =item If the final element of @Values is a hash reference the key/value
13706: pairs will be added to the graph definition.
13707: 
13708: =back
13709: 
13710: Returns:
13711: 
13712: An <img> tag which references graph.png and the appropriate identifying
13713: information for the plot.
13714: 
13715: =cut
13716: 
13717: ############################################################
13718: ############################################################
13719: sub DrawBarGraph {
13720:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
13721:     #
13722:     if (! defined($colors)) {
13723:         $colors = ['#33ff00', 
13724:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
13725:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
13726:                   ]; 
13727:     }
13728:     my $extra_settings = {};
13729:     if (ref($Values[-1]) eq 'HASH') {
13730:         $extra_settings = pop(@Values);
13731:     }
13732:     #
13733:     my $identifier = &get_cgi_id();
13734:     my $id = 'cgi.'.$identifier;        
13735:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
13736:         return '';
13737:     }
13738:     #
13739:     my @Labels;
13740:     if (defined($labels)) {
13741:         @Labels = @$labels;
13742:     } else {
13743:         for (my $i=0;$i<@{$Values[0]};$i++) {
13744:             push(@Labels,$i+1);
13745:         }
13746:     }
13747:     #
13748:     my $NumBars = scalar(@{$Values[0]});
13749:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
13750:     my %ValuesHash;
13751:     my $NumSets=1;
13752:     foreach my $array (@Values) {
13753:         next if (! ref($array));
13754:         $ValuesHash{$id.'.data.'.$NumSets++} = 
13755:             join(',',@$array);
13756:     }
13757:     #
13758:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
13759:     if ($NumBars < 3) {
13760:         $width = 120+$NumBars*32;
13761:         $xskip = 1;
13762:         $bar_width = 30;
13763:     } elsif ($NumBars < 5) {
13764:         $width = 120+$NumBars*20;
13765:         $xskip = 1;
13766:         $bar_width = 20;
13767:     } elsif ($NumBars < 10) {
13768:         $width = 120+$NumBars*15;
13769:         $xskip = 1;
13770:         $bar_width = 15;
13771:     } elsif ($NumBars <= 25) {
13772:         $width = 120+$NumBars*11;
13773:         $xskip = 5;
13774:         $bar_width = 8;
13775:     } elsif ($NumBars <= 50) {
13776:         $width = 120+$NumBars*8;
13777:         $xskip = 5;
13778:         $bar_width = 4;
13779:     } else {
13780:         $width = 120+$NumBars*8;
13781:         $xskip = 5;
13782:         $bar_width = 4;
13783:     }
13784:     #
13785:     $Max = 1 if ($Max < 1);
13786:     if ( int($Max) < $Max ) {
13787:         $Max++;
13788:         $Max = int($Max);
13789:     }
13790:     $Title  = '' if (! defined($Title));
13791:     $xlabel = '' if (! defined($xlabel));
13792:     $ylabel = '' if (! defined($ylabel));
13793:     $ValuesHash{$id.'.title'}    = &escape($Title);
13794:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
13795:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
13796:     $ValuesHash{$id.'.y_max_value'} = $Max;
13797:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
13798:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
13799:     $ValuesHash{$id.'.PlotType'} = 'bar';
13800:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
13801:     $ValuesHash{$id.'.height'}   = $height;
13802:     $ValuesHash{$id.'.width'}    = $width;
13803:     $ValuesHash{$id.'.xskip'}    = $xskip;
13804:     $ValuesHash{$id.'.bar_width'} = $bar_width;
13805:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
13806:     #
13807:     # Deal with other parameters
13808:     while (my ($key,$value) = each(%$extra_settings)) {
13809:         $ValuesHash{$id.'.'.$key} = $value;
13810:     }
13811:     #
13812:     &Apache::lonnet::appenv(\%ValuesHash);
13813:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13814: }
13815: 
13816: ############################################################
13817: ############################################################
13818: 
13819: =pod
13820: 
13821: =item * &DrawXYGraph()
13822: 
13823: Facilitates the plotting of data in an XY graph.
13824: Puts plot definition data into the users environment in order for 
13825: graph.png to plot it.  Returns an <img> tag for the plot.
13826: 
13827: Inputs:
13828: 
13829: =over 4
13830: 
13831: =item $Title: string, the title of the plot
13832: 
13833: =item $xlabel: string, text describing the X-axis of the plot
13834: 
13835: =item $ylabel: string, text describing the Y-axis of the plot
13836: 
13837: =item $Max: scalar, the maximum Y value to use in the plot
13838: If $Max is < any data point, the graph will not be rendered.
13839: 
13840: =item $colors: Array ref containing the hex color codes for the data to be 
13841: plotted in.  If undefined, default values will be used.
13842: 
13843: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
13844: 
13845: =item $Ydata: Array ref containing Array refs.  
13846: Each of the contained arrays will be plotted as a separate curve.
13847: 
13848: =item %Values: hash indicating or overriding any default values which are 
13849: passed to graph.png.  
13850: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
13851: 
13852: =back
13853: 
13854: Returns:
13855: 
13856: An <img> tag which references graph.png and the appropriate identifying
13857: information for the plot.
13858: 
13859: =cut
13860: 
13861: ############################################################
13862: ############################################################
13863: sub DrawXYGraph {
13864:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
13865:     #
13866:     # Create the identifier for the graph
13867:     my $identifier = &get_cgi_id();
13868:     my $id = 'cgi.'.$identifier;
13869:     #
13870:     $Title  = '' if (! defined($Title));
13871:     $xlabel = '' if (! defined($xlabel));
13872:     $ylabel = '' if (! defined($ylabel));
13873:     my %ValuesHash = 
13874:         (
13875:          $id.'.title'  => &escape($Title),
13876:          $id.'.xlabel' => &escape($xlabel),
13877:          $id.'.ylabel' => &escape($ylabel),
13878:          $id.'.y_max_value'=> $Max,
13879:          $id.'.labels'     => join(',',@$Xlabels),
13880:          $id.'.PlotType'   => 'XY',
13881:          );
13882:     #
13883:     if (defined($colors) && ref($colors) eq 'ARRAY') {
13884:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
13885:     }
13886:     #
13887:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
13888:         return '';
13889:     }
13890:     my $NumSets=1;
13891:     foreach my $array (@{$Ydata}){
13892:         next if (! ref($array));
13893:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
13894:     }
13895:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
13896:     #
13897:     # Deal with other parameters
13898:     while (my ($key,$value) = each(%Values)) {
13899:         $ValuesHash{$id.'.'.$key} = $value;
13900:     }
13901:     #
13902:     &Apache::lonnet::appenv(\%ValuesHash);
13903:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13904: }
13905: 
13906: ############################################################
13907: ############################################################
13908: 
13909: =pod
13910: 
13911: =item * &DrawXYYGraph()
13912: 
13913: Facilitates the plotting of data in an XY graph with two Y axes.
13914: Puts plot definition data into the users environment in order for 
13915: graph.png to plot it.  Returns an <img> tag for the plot.
13916: 
13917: Inputs:
13918: 
13919: =over 4
13920: 
13921: =item $Title: string, the title of the plot
13922: 
13923: =item $xlabel: string, text describing the X-axis of the plot
13924: 
13925: =item $ylabel: string, text describing the Y-axis of the plot
13926: 
13927: =item $colors: Array ref containing the hex color codes for the data to be 
13928: plotted in.  If undefined, default values will be used.
13929: 
13930: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
13931: 
13932: =item $Ydata1: The first data set
13933: 
13934: =item $Min1: The minimum value of the left Y-axis
13935: 
13936: =item $Max1: The maximum value of the left Y-axis
13937: 
13938: =item $Ydata2: The second data set
13939: 
13940: =item $Min2: The minimum value of the right Y-axis
13941: 
13942: =item $Max2: The maximum value of the left Y-axis
13943: 
13944: =item %Values: hash indicating or overriding any default values which are 
13945: passed to graph.png.  
13946: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
13947: 
13948: =back
13949: 
13950: Returns:
13951: 
13952: An <img> tag which references graph.png and the appropriate identifying
13953: information for the plot.
13954: 
13955: =cut
13956: 
13957: ############################################################
13958: ############################################################
13959: sub DrawXYYGraph {
13960:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
13961:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
13962:     #
13963:     # Create the identifier for the graph
13964:     my $identifier = &get_cgi_id();
13965:     my $id = 'cgi.'.$identifier;
13966:     #
13967:     $Title  = '' if (! defined($Title));
13968:     $xlabel = '' if (! defined($xlabel));
13969:     $ylabel = '' if (! defined($ylabel));
13970:     my %ValuesHash = 
13971:         (
13972:          $id.'.title'  => &escape($Title),
13973:          $id.'.xlabel' => &escape($xlabel),
13974:          $id.'.ylabel' => &escape($ylabel),
13975:          $id.'.labels' => join(',',@$Xlabels),
13976:          $id.'.PlotType' => 'XY',
13977:          $id.'.NumSets' => 2,
13978:          $id.'.two_axes' => 1,
13979:          $id.'.y1_max_value' => $Max1,
13980:          $id.'.y1_min_value' => $Min1,
13981:          $id.'.y2_max_value' => $Max2,
13982:          $id.'.y2_min_value' => $Min2,
13983:          );
13984:     #
13985:     if (defined($colors) && ref($colors) eq 'ARRAY') {
13986:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
13987:     }
13988:     #
13989:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
13990:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
13991:         return '';
13992:     }
13993:     my $NumSets=1;
13994:     foreach my $array ($Ydata1,$Ydata2){
13995:         next if (! ref($array));
13996:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
13997:     }
13998:     #
13999:     # Deal with other parameters
14000:     while (my ($key,$value) = each(%Values)) {
14001:         $ValuesHash{$id.'.'.$key} = $value;
14002:     }
14003:     #
14004:     &Apache::lonnet::appenv(\%ValuesHash);
14005:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14006: }
14007: 
14008: ############################################################
14009: ############################################################
14010: 
14011: =pod
14012: 
14013: =back 
14014: 
14015: =head1 Statistics helper routines?  
14016: 
14017: Bad place for them but what the hell.
14018: 
14019: =over 4
14020: 
14021: =item * &chartlink()
14022: 
14023: Returns a link to the chart for a specific student.  
14024: 
14025: Inputs:
14026: 
14027: =over 4
14028: 
14029: =item $linktext: The text of the link
14030: 
14031: =item $sname: The students username
14032: 
14033: =item $sdomain: The students domain
14034: 
14035: =back
14036: 
14037: =back
14038: 
14039: =cut
14040: 
14041: ############################################################
14042: ############################################################
14043: sub chartlink {
14044:     my ($linktext, $sname, $sdomain) = @_;
14045:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
14046:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
14047:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
14048:        '">'.$linktext.'</a>';
14049: }
14050: 
14051: #######################################################
14052: #######################################################
14053: 
14054: =pod
14055: 
14056: =head1 Course Environment Routines
14057: 
14058: =over 4
14059: 
14060: =item * &restore_course_settings()
14061: 
14062: =item * &store_course_settings()
14063: 
14064: Restores/Store indicated form parameters from the course environment.
14065: Will not overwrite existing values of the form parameters.
14066: 
14067: Inputs: 
14068: a scalar describing the data (e.g. 'chart', 'problem_analysis')
14069: 
14070: a hash ref describing the data to be stored.  For example:
14071:    
14072: %Save_Parameters = ('Status' => 'scalar',
14073:     'chartoutputmode' => 'scalar',
14074:     'chartoutputdata' => 'scalar',
14075:     'Section' => 'array',
14076:     'Group' => 'array',
14077:     'StudentData' => 'array',
14078:     'Maps' => 'array');
14079: 
14080: Returns: both routines return nothing
14081: 
14082: =back
14083: 
14084: =cut
14085: 
14086: #######################################################
14087: #######################################################
14088: sub store_course_settings {
14089:     return &store_settings($env{'request.course.id'},@_);
14090: }
14091: 
14092: sub store_settings {
14093:     # save to the environment
14094:     # appenv the same items, just to be safe
14095:     my $udom  = $env{'user.domain'};
14096:     my $uname = $env{'user.name'};
14097:     my ($context,$prefix,$Settings) = @_;
14098:     my %SaveHash;
14099:     my %AppHash;
14100:     while (my ($setting,$type) = each(%$Settings)) {
14101:         my $basename = join('.','internal',$context,$prefix,$setting);
14102:         my $envname = 'environment.'.$basename;
14103:         if (exists($env{'form.'.$setting})) {
14104:             # Save this value away
14105:             if ($type eq 'scalar' &&
14106:                 (! exists($env{$envname}) || 
14107:                  $env{$envname} ne $env{'form.'.$setting})) {
14108:                 $SaveHash{$basename} = $env{'form.'.$setting};
14109:                 $AppHash{$envname}   = $env{'form.'.$setting};
14110:             } elsif ($type eq 'array') {
14111:                 my $stored_form;
14112:                 if (ref($env{'form.'.$setting})) {
14113:                     $stored_form = join(',',
14114:                                         map {
14115:                                             &escape($_);
14116:                                         } sort(@{$env{'form.'.$setting}}));
14117:                 } else {
14118:                     $stored_form = 
14119:                         &escape($env{'form.'.$setting});
14120:                 }
14121:                 # Determine if the array contents are the same.
14122:                 if ($stored_form ne $env{$envname}) {
14123:                     $SaveHash{$basename} = $stored_form;
14124:                     $AppHash{$envname}   = $stored_form;
14125:                 }
14126:             }
14127:         }
14128:     }
14129:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
14130:                                           $udom,$uname);
14131:     if ($put_result !~ /^(ok|delayed)/) {
14132:         &Apache::lonnet::logthis('unable to save form parameters, '.
14133:                                  'got error:'.$put_result);
14134:     }
14135:     # Make sure these settings stick around in this session, too
14136:     &Apache::lonnet::appenv(\%AppHash);
14137:     return;
14138: }
14139: 
14140: sub restore_course_settings {
14141:     return &restore_settings($env{'request.course.id'},@_);
14142: }
14143: 
14144: sub restore_settings {
14145:     my ($context,$prefix,$Settings) = @_;
14146:     while (my ($setting,$type) = each(%$Settings)) {
14147:         next if (exists($env{'form.'.$setting}));
14148:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
14149:             '.'.$setting;
14150:         if (exists($env{$envname})) {
14151:             if ($type eq 'scalar') {
14152:                 $env{'form.'.$setting} = $env{$envname};
14153:             } elsif ($type eq 'array') {
14154:                 $env{'form.'.$setting} = [ 
14155:                                            map { 
14156:                                                &unescape($_); 
14157:                                            } split(',',$env{$envname})
14158:                                            ];
14159:             }
14160:         }
14161:     }
14162: }
14163: 
14164: #######################################################
14165: #######################################################
14166: 
14167: =pod
14168: 
14169: =head1 Domain E-mail Routines  
14170: 
14171: =over 4
14172: 
14173: =item * &build_recipient_list()
14174: 
14175: Build recipient lists for following types of e-mail:
14176: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
14177: (d) Help requests, (e) Course requests needing approval, (f) loncapa
14178: module change checking, student/employee ID conflict checks, as
14179: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
14180: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
14181: 
14182: Inputs:
14183: defmail (scalar - email address of default recipient),
14184: mailing type (scalar: errormail, packagesmail, helpdeskmail,
14185: requestsmail, updatesmail, or idconflictsmail).
14186: 
14187: defdom (domain for which to retrieve configuration settings),
14188: 
14189: origmail (scalar - email address of recipient from loncapa.conf,
14190: i.e., predates configuration by DC via domainprefs.pm
14191: 
14192: $requname username of requester (if mailing type is helpdeskmail)
14193: 
14194: $requdom domain of requester (if mailing type is helpdeskmail)
14195: 
14196: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
14197: 
14198: Returns: comma separated list of addresses to which to send e-mail.
14199: 
14200: =back
14201: 
14202: =cut
14203: 
14204: ############################################################
14205: ############################################################
14206: sub build_recipient_list {
14207:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
14208:     my @recipients;
14209:     my ($otheremails,$lastresort,$allbcc,$addtext);
14210:     my %domconfig =
14211:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
14212:     if (ref($domconfig{'contacts'}) eq 'HASH') {
14213:         if (exists($domconfig{'contacts'}{$mailing})) {
14214:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
14215:                 my @contacts = ('adminemail','supportemail');
14216:                 foreach my $item (@contacts) {
14217:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
14218:                         my $addr = $domconfig{'contacts'}{$item}; 
14219:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
14220:                             push(@recipients,$addr);
14221:                         }
14222:                     }
14223:                 }
14224:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
14225:                 if ($mailing eq 'helpdeskmail') {
14226:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
14227:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
14228:                         my @ok_bccs;
14229:                         foreach my $bcc (@bccs) {
14230:                             $bcc =~ s/^\s+//g;
14231:                             $bcc =~ s/\s+$//g;
14232:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14233:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14234:                                     push(@ok_bccs,$bcc);
14235:                                 }
14236:                             }
14237:                         }
14238:                         if (@ok_bccs > 0) {
14239:                             $allbcc = join(', ',@ok_bccs);
14240:                         }
14241:                     }
14242:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
14243:                 }
14244:             }
14245:         } elsif ($origmail ne '') {
14246:             $lastresort = $origmail;
14247:         }
14248:         if ($mailing eq 'helpdeskmail') {
14249:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
14250:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
14251:                 my ($inststatus,$inststatus_checked);
14252:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
14253:                     ($env{'user.domain'} ne 'public')) {
14254:                     $inststatus_checked = 1;
14255:                     $inststatus = $env{'environment.inststatus'};
14256:                 }
14257:                 unless ($inststatus_checked) {
14258:                     if (($requname ne '') && ($requdom ne '')) {
14259:                         if (($requname =~ /^$match_username$/) &&
14260:                             ($requdom =~ /^$match_domain$/) &&
14261:                             (&Apache::lonnet::domain($requdom))) {
14262:                             my $requhome = &Apache::lonnet::homeserver($requname,
14263:                                                                       $requdom);
14264:                             unless ($requhome eq 'no_host') {
14265:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
14266:                                 $inststatus = $userenv{'inststatus'};
14267:                                 $inststatus_checked = 1;
14268:                             }
14269:                         }
14270:                     }
14271:                 }
14272:                 unless ($inststatus_checked) {
14273:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
14274:                         my %srch = (srchby     => 'email',
14275:                                     srchdomain => $defdom,
14276:                                     srchterm   => $reqemail,
14277:                                     srchtype   => 'exact');
14278:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
14279:                         foreach my $uname (keys(%srch_results)) {
14280:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
14281:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
14282:                                 $inststatus_checked = 1;
14283:                                 last;
14284:                             }
14285:                         }
14286:                         unless ($inststatus_checked) {
14287:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
14288:                             if ($dirsrchres eq 'ok') {
14289:                                 foreach my $uname (keys(%srch_results)) {
14290:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
14291:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
14292:                                         $inststatus_checked = 1;
14293:                                         last;
14294:                                     }
14295:                                 }
14296:                             }
14297:                         }
14298:                     }
14299:                 }
14300:                 if ($inststatus ne '') {
14301:                     foreach my $status (split(/\:/,$inststatus)) {
14302:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
14303:                             my @contacts = ('adminemail','supportemail');
14304:                             foreach my $item (@contacts) {
14305:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
14306:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
14307:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
14308:                                         push(@recipients,$addr);
14309:                                     }
14310:                                 }
14311:                             }
14312:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
14313:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
14314:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
14315:                                 my @ok_bccs;
14316:                                 foreach my $bcc (@bccs) {
14317:                                     $bcc =~ s/^\s+//g;
14318:                                     $bcc =~ s/\s+$//g;
14319:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14320:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14321:                                             push(@ok_bccs,$bcc);
14322:                                         }
14323:                                     }
14324:                                 }
14325:                                 if (@ok_bccs > 0) {
14326:                                     $allbcc = join(', ',@ok_bccs);
14327:                                 }
14328:                             }
14329:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
14330:                             last;
14331:                         }
14332:                     }
14333:                 }
14334:             }
14335:         }
14336:     } elsif ($origmail ne '') {
14337:         $lastresort = $origmail;
14338:     }
14339:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
14340:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
14341:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
14342:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
14343:             my %what = (
14344:                           perlvar => 1,
14345:                        );
14346:             my $primary = &Apache::lonnet::domain($defdom,'primary');
14347:             if ($primary) {
14348:                 my $gotaddr;
14349:                 my ($result,$returnhash) =
14350:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
14351:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
14352:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
14353:                         $lastresort = $returnhash->{'lonSupportEMail'};
14354:                         $gotaddr = 1;
14355:                     }
14356:                 }
14357:                 unless ($gotaddr) {
14358:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
14359:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
14360:                     unless ($uintdom eq $intdom) {
14361:                         my %domconfig =
14362:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
14363:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
14364:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
14365:                                 my @contacts = ('adminemail','supportemail');
14366:                                 foreach my $item (@contacts) {
14367:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
14368:                                         my $addr = $domconfig{'contacts'}{$item};
14369:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
14370:                                             push(@recipients,$addr);
14371:                                         }
14372:                                     }
14373:                                 }
14374:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
14375:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
14376:                                 }
14377:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
14378:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
14379:                                     my @ok_bccs;
14380:                                     foreach my $bcc (@bccs) {
14381:                                         $bcc =~ s/^\s+//g;
14382:                                         $bcc =~ s/\s+$//g;
14383:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14384:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14385:                                                 push(@ok_bccs,$bcc);
14386:                                             }
14387:                                         }
14388:                                     }
14389:                                     if (@ok_bccs > 0) {
14390:                                         $allbcc = join(', ',@ok_bccs);
14391:                                     }
14392:                                 }
14393:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
14394:                             }
14395:                         }
14396:                     }
14397:                 }
14398:             }
14399:         }
14400:     }
14401:     if (defined($defmail)) {
14402:         if ($defmail ne '') {
14403:             push(@recipients,$defmail);
14404:         }
14405:     }
14406:     if ($otheremails) {
14407:         my @others;
14408:         if ($otheremails =~ /,/) {
14409:             @others = split(/,/,$otheremails);
14410:         } else {
14411:             push(@others,$otheremails);
14412:         }
14413:         foreach my $addr (@others) {
14414:             if (!grep(/^\Q$addr\E$/,@recipients)) {
14415:                 push(@recipients,$addr);
14416:             }
14417:         }
14418:     }
14419:     if ($mailing eq 'helpdeskmail') {
14420:         if ((!@recipients) && ($lastresort ne '')) {
14421:             push(@recipients,$lastresort);
14422:         }
14423:     } elsif ($lastresort ne '') {
14424:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
14425:             push(@recipients,$lastresort);
14426:         }
14427:     }
14428:     my $recipientlist = join(',',@recipients);
14429:     if (wantarray) {
14430:         return ($recipientlist,$allbcc,$addtext);
14431:     } else {
14432:         return $recipientlist;
14433:     }
14434: }
14435: 
14436: ############################################################
14437: ############################################################
14438: 
14439: =pod
14440: 
14441: =head1 Course Catalog Routines
14442: 
14443: =over 4
14444: 
14445: =item * &gather_categories()
14446: 
14447: Converts category definitions - keys of categories hash stored in  
14448: coursecategories in configuration.db on the primary library server in a 
14449: domain - to an array.  Also generates javascript and idx hash used to 
14450: generate Domain Coordinator interface for editing Course Categories.
14451: 
14452: Inputs:
14453: 
14454: categories (reference to hash of category definitions).
14455: 
14456: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14457:       categories and subcategories).
14458: 
14459: idx (reference to hash of counters used in Domain Coordinator interface for 
14460:       editing Course Categories).
14461: 
14462: jsarray (reference to array of categories used to create Javascript arrays for
14463:          Domain Coordinator interface for editing Course Categories).
14464: 
14465: Returns: nothing
14466: 
14467: Side effects: populates cats, idx and jsarray. 
14468: 
14469: =cut
14470: 
14471: sub gather_categories {
14472:     my ($categories,$cats,$idx,$jsarray) = @_;
14473:     my %counters;
14474:     my $num = 0;
14475:     foreach my $item (keys(%{$categories})) {
14476:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
14477:         if ($container eq '' && $depth == 0) {
14478:             $cats->[$depth][$categories->{$item}] = $cat;
14479:         } else {
14480:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
14481:         }
14482:         my ($escitem,$tail) = split(/:/,$item,2);
14483:         if ($counters{$tail} eq '') {
14484:             $counters{$tail} = $num;
14485:             $num ++;
14486:         }
14487:         if (ref($idx) eq 'HASH') {
14488:             $idx->{$item} = $counters{$tail};
14489:         }
14490:         if (ref($jsarray) eq 'ARRAY') {
14491:             push(@{$jsarray->[$counters{$tail}]},$item);
14492:         }
14493:     }
14494:     return;
14495: }
14496: 
14497: =pod
14498: 
14499: =item * &extract_categories()
14500: 
14501: Used to generate breadcrumb trails for course categories.
14502: 
14503: Inputs:
14504: 
14505: categories (reference to hash of category definitions).
14506: 
14507: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14508:       categories and subcategories).
14509: 
14510: trails (reference to array of breacrumb trails for each category).
14511: 
14512: allitems (reference to hash - key is category key 
14513:          (format: escaped(name):escaped(parent category):depth in hierarchy).
14514: 
14515: idx (reference to hash of counters used in Domain Coordinator interface for
14516:       editing Course Categories).
14517: 
14518: jsarray (reference to array of categories used to create Javascript arrays for
14519:          Domain Coordinator interface for editing Course Categories).
14520: 
14521: subcats (reference to hash of arrays containing all subcategories within each 
14522:          category, -recursive)
14523: 
14524: maxd (reference to hash used to hold max depth for all top-level categories).
14525: 
14526: Returns: nothing
14527: 
14528: Side effects: populates trails and allitems hash references.
14529: 
14530: =cut
14531: 
14532: sub extract_categories {
14533:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
14534:     if (ref($categories) eq 'HASH') {
14535:         &gather_categories($categories,$cats,$idx,$jsarray);
14536:         if (ref($cats->[0]) eq 'ARRAY') {
14537:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
14538:                 my $name = $cats->[0][$i];
14539:                 my $item = &escape($name).'::0';
14540:                 my $trailstr;
14541:                 if ($name eq 'instcode') {
14542:                     $trailstr = &mt('Official courses (with institutional codes)');
14543:                 } elsif ($name eq 'communities') {
14544:                     $trailstr = &mt('Communities');
14545:                 } else {
14546:                     $trailstr = $name;
14547:                 }
14548:                 if ($allitems->{$item} eq '') {
14549:                     push(@{$trails},$trailstr);
14550:                     $allitems->{$item} = scalar(@{$trails})-1;
14551:                 }
14552:                 my @parents = ($name);
14553:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
14554:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
14555:                         my $category = $cats->[1]{$name}[$j];
14556:                         if (ref($subcats) eq 'HASH') {
14557:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
14558:                         }
14559:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
14560:                     }
14561:                 } else {
14562:                     if (ref($subcats) eq 'HASH') {
14563:                         $subcats->{$item} = [];
14564:                     }
14565:                     if (ref($maxd) eq 'HASH') {
14566:                         $maxd->{$name} = 1;
14567:                     }
14568:                 }
14569:             }
14570:         }
14571:     }
14572:     return;
14573: }
14574: 
14575: =pod
14576: 
14577: =item * &recurse_categories()
14578: 
14579: Recursively used to generate breadcrumb trails for course categories.
14580: 
14581: Inputs:
14582: 
14583: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14584:       categories and subcategories).
14585: 
14586: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
14587: 
14588: category (current course category, for which breadcrumb trail is being generated).
14589: 
14590: trails (reference to array of breadcrumb trails for each category).
14591: 
14592: allitems (reference to hash - key is category key
14593:          (format: escaped(name):escaped(parent category):depth in hierarchy).
14594: 
14595: parents (array containing containers directories for current category, 
14596:          back to top level). 
14597: 
14598: Returns: nothing
14599: 
14600: Side effects: populates trails and allitems hash references
14601: 
14602: =cut
14603: 
14604: sub recurse_categories {
14605:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
14606:     my $shallower = $depth - 1;
14607:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
14608:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
14609:             my $name = $cats->[$depth]{$category}[$k];
14610:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
14611:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
14612:             if ($allitems->{$item} eq '') {
14613:                 push(@{$trails},$trailstr);
14614:                 $allitems->{$item} = scalar(@{$trails})-1;
14615:             }
14616:             my $deeper = $depth+1;
14617:             push(@{$parents},$category);
14618:             if (ref($subcats) eq 'HASH') {
14619:                 my $subcat = &escape($name).':'.$category.':'.$depth;
14620:                 for (my $j=@{$parents}; $j>=0; $j--) {
14621:                     my $higher;
14622:                     if ($j > 0) {
14623:                         $higher = &escape($parents->[$j]).':'.
14624:                                   &escape($parents->[$j-1]).':'.$j;
14625:                     } else {
14626:                         $higher = &escape($parents->[$j]).'::'.$j;
14627:                     }
14628:                     push(@{$subcats->{$higher}},$subcat);
14629:                 }
14630:             }
14631:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
14632:                                 $subcats,$maxd);
14633:             pop(@{$parents});
14634:         }
14635:     } else {
14636:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
14637:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
14638:         if ($allitems->{$item} eq '') {
14639:             push(@{$trails},$trailstr);
14640:             $allitems->{$item} = scalar(@{$trails})-1;
14641:         }
14642:         if (ref($maxd) eq 'HASH') {
14643:             if ($depth > $maxd->{$parents->[0]}) {
14644:                 $maxd->{$parents->[0]} = $depth;
14645:             }
14646:         }
14647:     }
14648:     return;
14649: }
14650: 
14651: =pod
14652: 
14653: =item * &assign_categories_table()
14654: 
14655: Create a datatable for display of hierarchical categories in a domain,
14656: with checkboxes to allow a course to be categorized. 
14657: 
14658: Inputs:
14659: 
14660: cathash - reference to hash of categories defined for the domain (from
14661:           configuration.db)
14662: 
14663: currcat - scalar with an & separated list of categories assigned to a course. 
14664: 
14665: type    - scalar contains course type (Course or Community).
14666: 
14667: disabled - scalar (optional) contains disabled="disabled" if input elements are
14668:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
14669: 
14670: Returns: $output (markup to be displayed) 
14671: 
14672: =cut
14673: 
14674: sub assign_categories_table {
14675:     my ($cathash,$currcat,$type,$disabled) = @_;
14676:     my $output;
14677:     if (ref($cathash) eq 'HASH') {
14678:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
14679:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
14680:         $maxdepth = scalar(@cats);
14681:         if (@cats > 0) {
14682:             my $itemcount = 0;
14683:             if (ref($cats[0]) eq 'ARRAY') {
14684:                 my @currcategories;
14685:                 if ($currcat ne '') {
14686:                     @currcategories = split('&',$currcat);
14687:                 }
14688:                 my $table;
14689:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
14690:                     my $parent = $cats[0][$i];
14691:                     next if ($parent eq 'instcode');
14692:                     if ($type eq 'Community') {
14693:                         next unless ($parent eq 'communities');
14694:                     } else {
14695:                         next if ($parent eq 'communities');
14696:                     }
14697:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
14698:                     my $item = &escape($parent).'::0';
14699:                     my $checked = '';
14700:                     if (@currcategories > 0) {
14701:                         if (grep(/^\Q$item\E$/,@currcategories)) {
14702:                             $checked = ' checked="checked"';
14703:                         }
14704:                     }
14705:                     my $parent_title = $parent;
14706:                     if ($parent eq 'communities') {
14707:                         $parent_title = &mt('Communities');
14708:                     }
14709:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
14710:                               '<input type="checkbox" name="usecategory" value="'.
14711:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
14712:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
14713:                     my $depth = 1;
14714:                     push(@path,$parent);
14715:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
14716:                     pop(@path);
14717:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
14718:                     $itemcount ++;
14719:                 }
14720:                 if ($itemcount) {
14721:                     $output = &Apache::loncommon::start_data_table().
14722:                               $table.
14723:                               &Apache::loncommon::end_data_table();
14724:                 }
14725:             }
14726:         }
14727:     }
14728:     return $output;
14729: }
14730: 
14731: =pod
14732: 
14733: =item * &assign_category_rows()
14734: 
14735: Create a datatable row for display of nested categories in a domain,
14736: with checkboxes to allow a course to be categorized,called recursively.
14737: 
14738: Inputs:
14739: 
14740: itemcount - track row number for alternating colors
14741: 
14742: cats - reference to array of arrays/hashes which encapsulates hierarchy of
14743:       categories and subcategories.
14744: 
14745: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
14746: 
14747: parent - parent of current category item
14748: 
14749: path - Array containing all categories back up through the hierarchy from the
14750:        current category to the top level.
14751: 
14752: currcategories - reference to array of current categories assigned to the course
14753: 
14754: disabled - scalar (optional) contains disabled="disabled" if input elements are
14755:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
14756: 
14757: Returns: $output (markup to be displayed).
14758: 
14759: =cut
14760: 
14761: sub assign_category_rows {
14762:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
14763:     my ($text,$name,$item,$chgstr);
14764:     if (ref($cats) eq 'ARRAY') {
14765:         my $maxdepth = scalar(@{$cats});
14766:         if (ref($cats->[$depth]) eq 'HASH') {
14767:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
14768:                 my $numchildren = @{$cats->[$depth]{$parent}};
14769:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
14770:                 $text .= '<td><table class="LC_data_table">';
14771:                 for (my $j=0; $j<$numchildren; $j++) {
14772:                     $name = $cats->[$depth]{$parent}[$j];
14773:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
14774:                     my $deeper = $depth+1;
14775:                     my $checked = '';
14776:                     if (ref($currcategories) eq 'ARRAY') {
14777:                         if (@{$currcategories} > 0) {
14778:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
14779:                                 $checked = ' checked="checked"';
14780:                             }
14781:                         }
14782:                     }
14783:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
14784:                              '<input type="checkbox" name="usecategory" value="'.
14785:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
14786:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
14787:                              '</td><td>';
14788:                     if (ref($path) eq 'ARRAY') {
14789:                         push(@{$path},$name);
14790:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
14791:                         pop(@{$path});
14792:                     }
14793:                     $text .= '</td></tr>';
14794:                 }
14795:                 $text .= '</table></td>';
14796:             }
14797:         }
14798:     }
14799:     return $text;
14800: }
14801: 
14802: =pod
14803: 
14804: =back
14805: 
14806: =cut
14807: 
14808: ############################################################
14809: ############################################################
14810: 
14811: 
14812: sub commit_customrole {
14813:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
14814:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
14815:                          ($start?', '.&mt('starting').' '.localtime($start):'').
14816:                          ($end?', ending '.localtime($end):'').': <b>'.
14817:               &Apache::lonnet::assigncustomrole(
14818:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
14819:                  '</b><br />';
14820:     return $output;
14821: }
14822: 
14823: sub commit_standardrole {
14824:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
14825:     my ($output,$logmsg,$linefeed);
14826:     if ($context eq 'auto') {
14827:         $linefeed = "\n";
14828:     } else {
14829:         $linefeed = "<br />\n";
14830:     }  
14831:     if ($three eq 'st') {
14832:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
14833:                                          $one,$two,$sec,$context,$credits);
14834:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
14835:             ($result eq 'unknown_course') || ($result eq 'refused')) {
14836:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
14837:         } else {
14838:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
14839:                ($start?', '.&mt('starting').' '.localtime($start):'').
14840:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
14841:             if ($context eq 'auto') {
14842:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
14843:             } else {
14844:                $output .= '<b>'.$result.'</b>'.$linefeed.
14845:                &mt('Add to classlist').': <b>ok</b>';
14846:             }
14847:             $output .= $linefeed;
14848:         }
14849:     } else {
14850:         $output = &mt('Assigning').' '.$three.' in '.$url.
14851:                ($start?', '.&mt('starting').' '.localtime($start):'').
14852:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
14853:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
14854:         if ($context eq 'auto') {
14855:             $output .= $result.$linefeed;
14856:         } else {
14857:             $output .= '<b>'.$result.'</b>'.$linefeed;
14858:         }
14859:     }
14860:     return $output;
14861: }
14862: 
14863: sub commit_studentrole {
14864:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
14865:         $credits) = @_;
14866:     my ($result,$linefeed,$oldsecurl,$newsecurl);
14867:     if ($context eq 'auto') {
14868:         $linefeed = "\n";
14869:     } else {
14870:         $linefeed = '<br />'."\n";
14871:     }
14872:     if (defined($one) && defined($two)) {
14873:         my $cid=$one.'_'.$two;
14874:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
14875:         my $secchange = 0;
14876:         my $expire_role_result;
14877:         my $modify_section_result;
14878:         if ($oldsec ne '-1') { 
14879:             if ($oldsec ne $sec) {
14880:                 $secchange = 1;
14881:                 my $now = time;
14882:                 my $uurl='/'.$cid;
14883:                 $uurl=~s/\_/\//g;
14884:                 if ($oldsec) {
14885:                     $uurl.='/'.$oldsec;
14886:                 }
14887:                 $oldsecurl = $uurl;
14888:                 $expire_role_result = 
14889:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
14890:                 if ($env{'request.course.sec'} ne '') { 
14891:                     if ($expire_role_result eq 'refused') {
14892:                         my @roles = ('st');
14893:                         my @statuses = ('previous');
14894:                         my @roledoms = ($one);
14895:                         my $withsec = 1;
14896:                         my %roleshash = 
14897:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
14898:                                               \@statuses,\@roles,\@roledoms,$withsec);
14899:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
14900:                             my ($oldstart,$oldend) = 
14901:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
14902:                             if ($oldend > 0 && $oldend <= $now) {
14903:                                 $expire_role_result = 'ok';
14904:                             }
14905:                         }
14906:                     }
14907:                 }
14908:                 $result = $expire_role_result;
14909:             }
14910:         }
14911:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
14912:             $modify_section_result = 
14913:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
14914:                                                            undef,undef,undef,$sec,
14915:                                                            $end,$start,'','',$cid,
14916:                                                            '',$context,$credits);
14917:             if ($modify_section_result =~ /^ok/) {
14918:                 if ($secchange == 1) {
14919:                     if ($sec eq '') {
14920:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
14921:                     } else {
14922:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
14923:                     }
14924:                 } elsif ($oldsec eq '-1') {
14925:                     if ($sec eq '') {
14926:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
14927:                     } else {
14928:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
14929:                     }
14930:                 } else {
14931:                     if ($sec eq '') {
14932:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
14933:                     } else {
14934:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
14935:                     }
14936:                 }
14937:             } else {
14938:                 if ($secchange) {       
14939:                     $$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;
14940:                 } else {
14941:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
14942:                 }
14943:             }
14944:             $result = $modify_section_result;
14945:         } elsif ($secchange == 1) {
14946:             if ($oldsec eq '') {
14947:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
14948:             } else {
14949:                 $$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;
14950:             }
14951:             if ($expire_role_result eq 'refused') {
14952:                 my $newsecurl = '/'.$cid;
14953:                 $newsecurl =~ s/\_/\//g;
14954:                 if ($sec ne '') {
14955:                     $newsecurl.='/'.$sec;
14956:                 }
14957:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
14958:                     if ($sec eq '') {
14959:                         $$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;
14960:                     } else {
14961:                         $$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;
14962:                     }
14963:                 }
14964:             }
14965:         }
14966:     } else {
14967:         $$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;
14968:         $result = "error: incomplete course id\n";
14969:     }
14970:     return $result;
14971: }
14972: 
14973: sub show_role_extent {
14974:     my ($scope,$context,$role) = @_;
14975:     $scope =~ s{^/}{};
14976:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
14977:     push(@courseroles,'co');
14978:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
14979:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
14980:         $scope =~ s{/}{_};
14981:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
14982:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
14983:         my ($audom,$auname) = split(/\//,$scope);
14984:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
14985:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
14986:     } else {
14987:         $scope =~ s{/$}{};
14988:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
14989:                    &Apache::lonnet::domain($scope,'description').'</span>');
14990:     }
14991: }
14992: 
14993: ############################################################
14994: ############################################################
14995: 
14996: sub check_clone {
14997:     my ($args,$linefeed) = @_;
14998:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
14999:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
15000:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
15001:     my $clonemsg;
15002:     my $can_clone = 0;
15003:     my $lctype = lc($args->{'crstype'});
15004:     if ($lctype ne 'community') {
15005:         $lctype = 'course';
15006:     }
15007:     if ($clonehome eq 'no_host') {
15008:         if ($args->{'crstype'} eq 'Community') {
15009:             $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
15010:         } else {
15011:             $clonemsg = &mt('No new course created.').$linefeed.&mt('A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
15012:         }     
15013:     } else {
15014: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
15015:         if ($args->{'crstype'} eq 'Community') {
15016:             if ($clonedesc{'type'} ne 'Community') {
15017:                  $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
15018:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
15019:             }
15020:         }
15021: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
15022:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
15023: 	    $can_clone = 1;
15024: 	} else {
15025: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
15026: 						 $args->{'clonedomain'},$args->{'clonecourse'});
15027:             if ($clonehash{'cloners'} eq '') {
15028:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
15029:                 if ($domdefs{'canclone'}) {
15030:                     unless ($domdefs{'canclone'} eq 'none') {
15031:                         if ($domdefs{'canclone'} eq 'domain') {
15032:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
15033:                                 $can_clone = 1;
15034:                             }
15035:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
15036:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
15037:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
15038:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
15039:                                 $can_clone = 1;
15040:                             }
15041:                         }
15042:                     }
15043:                 }
15044:             } else {
15045: 	        my @cloners = split(/,/,$clonehash{'cloners'});
15046:                 if (grep(/^\*$/,@cloners)) {
15047:                     $can_clone = 1;
15048:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
15049:                     $can_clone = 1;
15050:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
15051:                     $can_clone = 1;
15052:                 }
15053:                 unless ($can_clone) {
15054:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
15055:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
15056:                         my (%gotdomdefaults,%gotcodedefaults);
15057:                         foreach my $cloner (@cloners) {
15058:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
15059:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
15060:                                 my (%codedefaults,@code_order);
15061:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
15062:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
15063:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
15064:                                     }
15065:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
15066:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
15067:                                     }
15068:                                 } else {
15069:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
15070:                                                                             \%codedefaults,
15071:                                                                             \@code_order);
15072:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
15073:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
15074:                                 }
15075:                                 if (@code_order > 0) {
15076:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
15077:                                                                                 $cloner,$clonehash{'internal.coursecode'},
15078:                                                                                 $args->{'crscode'})) {
15079:                                         $can_clone = 1;
15080:                                         last;
15081:                                     }
15082:                                 }
15083:                             }
15084:                         }
15085:                     }
15086:                 }
15087:             }
15088:             unless ($can_clone) {
15089:                 my $ccrole = 'cc';
15090:                 if ($args->{'crstype'} eq 'Community') {
15091:                     $ccrole = 'co';
15092:                 }
15093:                 my %roleshash =
15094:                     &Apache::lonnet::get_my_roles($args->{'ccuname'},
15095:                                                   $args->{'ccdomain'},
15096:                                                   'userroles',['active'],[$ccrole],
15097:                                                   [$args->{'clonedomain'}]);
15098:                 if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
15099:                     $can_clone = 1;
15100:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
15101:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
15102:                     $can_clone = 1;
15103:                 }
15104:             }
15105:             unless ($can_clone) {
15106:                 if ($args->{'crstype'} eq 'Community') {
15107:                     $clonemsg = &mt('No new community created.').$linefeed.&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]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
15108:                 } else {
15109:                     $clonemsg = &mt('No new course created.').$linefeed.&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]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
15110: 	        }
15111: 	    }
15112:         }
15113:     }
15114:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
15115: }
15116: 
15117: sub construct_course {
15118:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
15119:         $cnum,$category,$coderef) = @_;
15120:     my $outcome;
15121:     my $linefeed =  '<br />'."\n";
15122:     if ($context eq 'auto') {
15123:         $linefeed = "\n";
15124:     }
15125: 
15126: #
15127: # Are we cloning?
15128: #
15129:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
15130:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
15131: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
15132: 	if ($context ne 'auto') {
15133:             if ($clonemsg ne '') {
15134: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
15135:             }
15136: 	}
15137: 	$outcome .= $clonemsg.$linefeed;
15138: 
15139:         if (!$can_clone) {
15140: 	    return (0,$outcome);
15141: 	}
15142:     }
15143: 
15144: #
15145: # Open course
15146: #
15147:     my $crstype = lc($args->{'crstype'});
15148:     my %cenv=();
15149:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
15150:                                              $args->{'cdescr'},
15151:                                              $args->{'curl'},
15152:                                              $args->{'course_home'},
15153:                                              $args->{'nonstandard'},
15154:                                              $args->{'crscode'},
15155:                                              $args->{'ccuname'}.':'.
15156:                                              $args->{'ccdomain'},
15157:                                              $args->{'crstype'},
15158:                                              $cnum,$context,$category);
15159: 
15160:     # Note: The testing routines depend on this being output; see 
15161:     # Utils::Course. This needs to at least be output as a comment
15162:     # if anyone ever decides to not show this, and Utils::Course::new
15163:     # will need to be suitably modified.
15164:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
15165:     if ($$courseid =~ /^error:/) {
15166:         return (0,$outcome);
15167:     }
15168: 
15169: #
15170: # Check if created correctly
15171: #
15172:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
15173:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
15174:     if ($crsuhome eq 'no_host') {
15175:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
15176:         return (0,$outcome);
15177:     }
15178:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
15179: 
15180: #
15181: # Do the cloning
15182: #   
15183:     if ($can_clone && $cloneid) {
15184: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
15185: 	if ($context ne 'auto') {
15186: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
15187: 	}
15188: 	$outcome .= $clonemsg.$linefeed;
15189: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
15190: # Copy all files
15191: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
15192: # Restore URL
15193: 	$cenv{'url'}=$oldcenv{'url'};
15194: # Restore title
15195: 	$cenv{'description'}=$oldcenv{'description'};
15196: # Restore creation date, creator and creation context.
15197:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
15198:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
15199:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
15200: # Mark as cloned
15201: 	$cenv{'clonedfrom'}=$cloneid;
15202: # Need to clone grading mode
15203:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
15204:         $cenv{'grading'}=$newenv{'grading'};
15205: # Do not clone these environment entries
15206:         &Apache::lonnet::del('environment',
15207:                   ['default_enrollment_start_date',
15208:                    'default_enrollment_end_date',
15209:                    'question.email',
15210:                    'policy.email',
15211:                    'comment.email',
15212:                    'pch.users.denied',
15213:                    'plc.users.denied',
15214:                    'hidefromcat',
15215:                    'checkforpriv',
15216:                    'categories',
15217:                    'internal.uniquecode'],
15218:                    $$crsudom,$$crsunum);
15219:         if ($args->{'textbook'}) {
15220:             $cenv{'internal.textbook'} = $args->{'textbook'};
15221:         }
15222:     }
15223: 
15224: #
15225: # Set environment (will override cloned, if existing)
15226: #
15227:     my @sections = ();
15228:     my @xlists = ();
15229:     if ($args->{'crstype'}) {
15230:         $cenv{'type'}=$args->{'crstype'};
15231:     }
15232:     if ($args->{'crsid'}) {
15233:         $cenv{'courseid'}=$args->{'crsid'};
15234:     }
15235:     if ($args->{'crscode'}) {
15236:         $cenv{'internal.coursecode'}=$args->{'crscode'};
15237:     }
15238:     if ($args->{'crsquota'} ne '') {
15239:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
15240:     } else {
15241:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
15242:     }
15243:     if ($args->{'ccuname'}) {
15244:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
15245:                                         ':'.$args->{'ccdomain'};
15246:     } else {
15247:         $cenv{'internal.courseowner'} = $args->{'curruser'};
15248:     }
15249:     if ($args->{'defaultcredits'}) {
15250:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
15251:     }
15252:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
15253:     if ($args->{'crssections'}) {
15254:         $cenv{'internal.sectionnums'} = '';
15255:         if ($args->{'crssections'} =~ m/,/) {
15256:             @sections = split/,/,$args->{'crssections'};
15257:         } else {
15258:             $sections[0] = $args->{'crssections'};
15259:         }
15260:         if (@sections > 0) {
15261:             foreach my $item (@sections) {
15262:                 my ($sec,$gp) = split/:/,$item;
15263:                 my $class = $args->{'crscode'}.$sec;
15264:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
15265:                 $cenv{'internal.sectionnums'} .= $item.',';
15266:                 unless ($addcheck eq 'ok') {
15267:                     push(@badclasses,$class);
15268:                 }
15269:             }
15270:             $cenv{'internal.sectionnums'} =~ s/,$//;
15271:         }
15272:     }
15273: # do not hide course coordinator from staff listing, 
15274: # even if privileged
15275:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15276: # add course coordinator's domain to domains to check for privileged users
15277: # if different to course domain
15278:     if ($$crsudom ne $args->{'ccdomain'}) {
15279:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
15280:     }
15281: # add crosslistings
15282:     if ($args->{'crsxlist'}) {
15283:         $cenv{'internal.crosslistings'}='';
15284:         if ($args->{'crsxlist'} =~ m/,/) {
15285:             @xlists = split/,/,$args->{'crsxlist'};
15286:         } else {
15287:             $xlists[0] = $args->{'crsxlist'};
15288:         }
15289:         if (@xlists > 0) {
15290:             foreach my $item (@xlists) {
15291:                 my ($xl,$gp) = split/:/,$item;
15292:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
15293:                 $cenv{'internal.crosslistings'} .= $item.',';
15294:                 unless ($addcheck eq 'ok') {
15295:                     push(@badclasses,$xl);
15296:                 }
15297:             }
15298:             $cenv{'internal.crosslistings'} =~ s/,$//;
15299:         }
15300:     }
15301:     if ($args->{'autoadds'}) {
15302:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
15303:     }
15304:     if ($args->{'autodrops'}) {
15305:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
15306:     }
15307: # check for notification of enrollment changes
15308:     my @notified = ();
15309:     if ($args->{'notify_owner'}) {
15310:         if ($args->{'ccuname'} ne '') {
15311:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
15312:         }
15313:     }
15314:     if ($args->{'notify_dc'}) {
15315:         if ($uname ne '') { 
15316:             push(@notified,$uname.':'.$udom);
15317:         }
15318:     }
15319:     if (@notified > 0) {
15320:         my $notifylist;
15321:         if (@notified > 1) {
15322:             $notifylist = join(',',@notified);
15323:         } else {
15324:             $notifylist = $notified[0];
15325:         }
15326:         $cenv{'internal.notifylist'} = $notifylist;
15327:     }
15328:     if (@badclasses > 0) {
15329:         my %lt=&Apache::lonlocal::texthash(
15330:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
15331:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
15332:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
15333:         );
15334:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
15335:                            &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'};
15336:         if ($context eq 'auto') {
15337:             $outcome .= $badclass_msg.$linefeed;
15338:         } else {
15339:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
15340:         }
15341:         foreach my $item (@badclasses) {
15342:             if ($context eq 'auto') {
15343:                 $outcome .= " - $item\n";
15344:             } else {
15345:                 $outcome .= "<li>$item</li>\n";
15346:             }
15347:         }
15348:         if ($context eq 'auto') {
15349:             $outcome .= $linefeed;
15350:         } else {
15351:             $outcome .= "</ul><br /><br /></div>\n";
15352:         }
15353:     }
15354:     if ($args->{'no_end_date'}) {
15355:         $args->{'endaccess'} = 0;
15356:     }
15357:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
15358:     $cenv{'internal.autoend'}=$args->{'enrollend'};
15359:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
15360:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
15361:     if ($args->{'showphotos'}) {
15362:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
15363:     }
15364:     $cenv{'internal.authtype'} = $args->{'authtype'};
15365:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
15366:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
15367:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
15368:             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'); 
15369:             if ($context eq 'auto') {
15370:                 $outcome .= $krb_msg;
15371:             } else {
15372:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
15373:             }
15374:             $outcome .= $linefeed;
15375:         }
15376:     }
15377:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
15378:        if ($args->{'setpolicy'}) {
15379:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15380:        }
15381:        if ($args->{'setcontent'}) {
15382:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15383:        }
15384:        if ($args->{'setcomment'}) {
15385:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15386:        }
15387:     }
15388:     if ($args->{'reshome'}) {
15389: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
15390: 	$cenv{'reshome'}=~s/\/+$/\//;
15391:     }
15392: #
15393: # course has keyed access
15394: #
15395:     if ($args->{'setkeys'}) {
15396:        $cenv{'keyaccess'}='yes';
15397:     }
15398: # if specified, key authority is not course, but user
15399: # only active if keyaccess is yes
15400:     if ($args->{'keyauth'}) {
15401: 	my ($user,$domain) = split(':',$args->{'keyauth'});
15402: 	$user = &LONCAPA::clean_username($user);
15403: 	$domain = &LONCAPA::clean_username($domain);
15404: 	if ($user ne '' && $domain ne '') {
15405: 	    $cenv{'keyauth'}=$user.':'.$domain;
15406: 	}
15407:     }
15408: 
15409: #
15410: #  generate and store uniquecode (available to course requester), if course should have one.
15411: #
15412:     if ($args->{'uniquecode'}) {
15413:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
15414:         if ($code) {
15415:             $cenv{'internal.uniquecode'} = $code;
15416:             my %crsinfo =
15417:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
15418:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
15419:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
15420:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
15421:             }
15422:             if (ref($coderef)) {
15423:                 $$coderef = $code;
15424:             }
15425:         }
15426:     }
15427: 
15428:     if ($args->{'disresdis'}) {
15429:         $cenv{'pch.roles.denied'}='st';
15430:     }
15431:     if ($args->{'disablechat'}) {
15432:         $cenv{'plc.roles.denied'}='st';
15433:     }
15434: 
15435:     # Record we've not yet viewed the Course Initialization Helper for this 
15436:     # course
15437:     $cenv{'course.helper.not.run'} = 1;
15438:     #
15439:     # Use new Randomseed
15440:     #
15441:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
15442:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
15443:     #
15444:     # The encryption code and receipt prefix for this course
15445:     #
15446:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
15447:     $cenv{'internal.encpref'}=100+int(9*rand(99));
15448:     #
15449:     # By default, use standard grading
15450:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
15451: 
15452:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
15453:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
15454: #
15455: # Open all assignments
15456: #
15457:     if ($args->{'openall'}) {
15458:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
15459:        my %storecontent = ($storeunder         => time,
15460:                            $storeunder.'.type' => 'date_start');
15461:        
15462:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
15463:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
15464:    }
15465: #
15466: # Set first page
15467: #
15468:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
15469: 	    || ($cloneid)) {
15470: 	use LONCAPA::map;
15471: 	$outcome .= &mt('Setting first resource').': ';
15472: 
15473: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
15474:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
15475: 
15476:         $outcome .= ($fatal?$errtext:'read ok').' - ';
15477:         my $title; my $url;
15478:         if ($args->{'firstres'} eq 'syl') {
15479: 	    $title=&mt('Syllabus');
15480:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
15481:         } else {
15482:             $title=&mt('Table of Contents');
15483:             $url='/adm/navmaps';
15484:         }
15485: 
15486:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
15487: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
15488: 
15489: 	if ($errtext) { $fatal=2; }
15490:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
15491:     }
15492: 
15493:     return (1,$outcome);
15494: }
15495: 
15496: sub make_unique_code {
15497:     my ($cdom,$cnum) = @_;
15498:     # get lock on uniquecodes db
15499:     my $lockhash = {
15500:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
15501:                                                   ':'.$env{'user.domain'},
15502:                    };
15503:     my $tries = 0;
15504:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
15505:     my ($code,$error);
15506: 
15507:     while (($gotlock ne 'ok') && ($tries<3)) {
15508:         $tries ++;
15509:         sleep 1;
15510:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
15511:     }
15512:     if ($gotlock eq 'ok') {
15513:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
15514:         my $gotcode;
15515:         my $attempts = 0;
15516:         while ((!$gotcode) && ($attempts < 100)) {
15517:             $code = &generate_code();
15518:             if (!exists($currcodes{$code})) {
15519:                 $gotcode = 1;
15520:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
15521:                     $error = 'nostore';
15522:                 }
15523:             }
15524:             $attempts ++;
15525:         }
15526:         my @del_lock = ($cnum."\0".'uniquecodes');
15527:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
15528:     } else {
15529:         $error = 'nolock';
15530:     }
15531:     return ($code,$error);
15532: }
15533: 
15534: sub generate_code {
15535:     my $code;
15536:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
15537:     for (my $i=0; $i<6; $i++) {
15538:         my $lettnum = int (rand 2);
15539:         my $item = '';
15540:         if ($lettnum) {
15541:             $item = $letts[int( rand(18) )];
15542:         } else {
15543:             $item = 1+int( rand(8) );
15544:         }
15545:         $code .= $item;
15546:     }
15547:     return $code;
15548: }
15549: 
15550: ############################################################
15551: ############################################################
15552: 
15553: #SD
15554: # only Community and Course, or anything else?
15555: sub course_type {
15556:     my ($cid) = @_;
15557:     if (!defined($cid)) {
15558:         $cid = $env{'request.course.id'};
15559:     }
15560:     if (defined($env{'course.'.$cid.'.type'})) {
15561:         return $env{'course.'.$cid.'.type'};
15562:     } else {
15563:         return 'Course';
15564:     }
15565: }
15566: 
15567: sub group_term {
15568:     my $crstype = &course_type();
15569:     my %names = (
15570:                   'Course' => 'group',
15571:                   'Community' => 'group',
15572:                 );
15573:     return $names{$crstype};
15574: }
15575: 
15576: sub course_types {
15577:     my @types = ('official','unofficial','community','textbook');
15578:     my %typename = (
15579:                          official   => 'Official course',
15580:                          unofficial => 'Unofficial course',
15581:                          community  => 'Community',
15582:                          textbook   => 'Textbook course',
15583:                    );
15584:     return (\@types,\%typename);
15585: }
15586: 
15587: sub icon {
15588:     my ($file)=@_;
15589:     my $curfext = lc((split(/\./,$file))[-1]);
15590:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
15591:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
15592:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
15593: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
15594: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
15595: 	            $curfext.".gif") {
15596: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
15597: 		$curfext.".gif";
15598: 	}
15599:     }
15600:     return &lonhttpdurl($iconname);
15601: } 
15602: 
15603: sub lonhttpdurl {
15604: #
15605: # Had been used for "small fry" static images on separate port 8080.
15606: # Modify here if lightweight http functionality desired again.
15607: # Currently eliminated due to increasing firewall issues.
15608: #
15609:     my ($url)=@_;
15610:     return $url;
15611: }
15612: 
15613: sub connection_aborted {
15614:     my ($r)=@_;
15615:     $r->print(" ");$r->rflush();
15616:     my $c = $r->connection;
15617:     return $c->aborted();
15618: }
15619: 
15620: #    Escapes strings that may have embedded 's that will be put into
15621: #    strings as 'strings'.
15622: sub escape_single {
15623:     my ($input) = @_;
15624:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
15625:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
15626:     return $input;
15627: }
15628: 
15629: #  Same as escape_single, but escape's "'s  This 
15630: #  can be used for  "strings"
15631: sub escape_double {
15632:     my ($input) = @_;
15633:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
15634:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
15635:     return $input;
15636: }
15637:  
15638: #   Escapes the last element of a full URL.
15639: sub escape_url {
15640:     my ($url)   = @_;
15641:     my @urlslices = split(/\//, $url,-1);
15642:     my $lastitem = &escape(pop(@urlslices));
15643:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
15644: }
15645: 
15646: sub compare_arrays {
15647:     my ($arrayref1,$arrayref2) = @_;
15648:     my (@difference,%count);
15649:     @difference = ();
15650:     %count = ();
15651:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
15652:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
15653:         foreach my $element (keys(%count)) {
15654:             if ($count{$element} == 1) {
15655:                 push(@difference,$element);
15656:             }
15657:         }
15658:     }
15659:     return @difference;
15660: }
15661: 
15662: # -------------------------------------------------------- Initialize user login
15663: sub init_user_environment {
15664:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
15665:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
15666: 
15667:     my $public=($username eq 'public' && $domain eq 'public');
15668: 
15669: # See if old ID present, if so, remove
15670: 
15671:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
15672:     my $now=time;
15673: 
15674:     if ($public) {
15675: 	my $max_public=100;
15676: 	my $oldest;
15677: 	my $oldest_time=0;
15678: 	for(my $next=1;$next<=$max_public;$next++) {
15679: 	    if (-e $lonids."/publicuser_$next.id") {
15680: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
15681: 		if ($mtime<$oldest_time || !$oldest_time) {
15682: 		    $oldest_time=$mtime;
15683: 		    $oldest=$next;
15684: 		}
15685: 	    } else {
15686: 		$cookie="publicuser_$next";
15687: 		last;
15688: 	    }
15689: 	}
15690: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
15691:     } else {
15692: 	# if this isn't a robot, kill any existing non-robot sessions
15693: 	if (!$args->{'robot'}) {
15694: 	    opendir(DIR,$lonids);
15695: 	    while ($filename=readdir(DIR)) {
15696: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
15697:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
15698:                             &GDBM_READER(),0640)) {
15699:                         my $linkedfile;
15700:                         if (exists($oldenv{'user.linkedenv'})) {
15701:                             $linkedfile = $oldenv{'user.linkedenv'};
15702:                         }
15703:                         untie(%oldenv);
15704:                         if (unlink("$lonids/$filename")) {
15705:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
15706:                                 if (-l "$lonids/$linkedfile.id") {
15707:                                     unlink("$lonids/$linkedfile.id");
15708:                                 }
15709:                             }
15710:                         }
15711:                     } else {
15712:                         unlink($lonids.'/'.$filename);
15713:                     }
15714: 		}
15715: 	    }
15716: 	    closedir(DIR);
15717: # If there is a undeleted lockfile for the user's paste buffer remove it.
15718:             my $namespace = 'nohist_courseeditor';
15719:             my $lockingkey = 'paste'."\0".'locked_num';
15720:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
15721:                                                 $domain,$username);
15722:             if (exists($lockhash{$lockingkey})) {
15723:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
15724:                 unless ($delresult eq 'ok') {
15725:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
15726:                 }
15727:             }
15728: 	}
15729: # Give them a new cookie
15730: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
15731: 		                   : $now.$$.int(rand(10000)));
15732: 	$cookie="$username\_$id\_$domain\_$authhost";
15733:     
15734: # Initialize roles
15735: 
15736: 	($userroles,$firstaccenv,$timerintenv) = 
15737:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
15738:     }
15739: # ------------------------------------ Check browser type and MathML capability
15740: 
15741:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
15742:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
15743: 
15744: # ------------------------------------------------------------- Get environment
15745: 
15746:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
15747:     my ($tmp) = keys(%userenv);
15748:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
15749:     } else {
15750: 	undef(%userenv);
15751:     }
15752:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
15753: 	$form->{'interface'}=$userenv{'interface'};
15754:     }
15755:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
15756: 
15757: # --------------- Do not trust query string to be put directly into environment
15758:     foreach my $option ('interface','localpath','localres') {
15759:         $form->{$option}=~s/[\n\r\=]//gs;
15760:     }
15761: # --------------------------------------------------------- Write first profile
15762: 
15763:     {
15764: 	my %initial_env = 
15765: 	    ("user.name"          => $username,
15766: 	     "user.domain"        => $domain,
15767: 	     "user.home"          => $authhost,
15768: 	     "browser.type"       => $clientbrowser,
15769: 	     "browser.version"    => $clientversion,
15770: 	     "browser.mathml"     => $clientmathml,
15771: 	     "browser.unicode"    => $clientunicode,
15772: 	     "browser.os"         => $clientos,
15773:              "browser.mobile"     => $clientmobile,
15774:              "browser.info"       => $clientinfo,
15775:              "browser.osversion"  => $clientosversion,
15776: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
15777: 	     "request.course.fn"  => '',
15778: 	     "request.course.uri" => '',
15779: 	     "request.course.sec" => '',
15780: 	     "request.role"       => 'cm',
15781: 	     "request.role.adv"   => $env{'user.adv'},
15782: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
15783: 
15784:         if ($form->{'localpath'}) {
15785: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
15786: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
15787:         }
15788: 	
15789: 	if ($form->{'interface'}) {
15790: 	    $form->{'interface'}=~s/\W//gs;
15791: 	    $initial_env{"browser.interface"} = $form->{'interface'};
15792: 	    $env{'browser.interface'}=$form->{'interface'};
15793: 	}
15794: 
15795:         if ($form->{'iptoken'}) {
15796:             my $lonhost = $r->dir_config('lonHostID');
15797:             $initial_env{"user.noloadbalance"} = $lonhost;
15798:             $env{'user.noloadbalance'} = $lonhost;
15799:         }
15800: 
15801:         if ($form->{'noloadbalance'}) {
15802:             my @hosts = &Apache::lonnet::current_machine_ids();
15803:             my $hosthere = $form->{'noloadbalance'};
15804:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
15805:                 $initial_env{"user.noloadbalance"} = $hosthere;
15806:                 $env{'user.noloadbalance'} = $hosthere;
15807:             }
15808:         }
15809: 
15810:         unless ($domain eq 'public') {
15811:             my %is_adv = ( is_adv => $env{'user.adv'} );
15812:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
15813: 
15814:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
15815:                 $userenv{'availabletools.'.$tool} = 
15816:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
15817:                                                       undef,\%userenv,\%domdef,\%is_adv);
15818:             }
15819: 
15820:             foreach my $crstype ('official','unofficial','community','textbook') {
15821:                 $userenv{'canrequest.'.$crstype} =
15822:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
15823:                                                       'reload','requestcourses',
15824:                                                       \%userenv,\%domdef,\%is_adv);
15825:             }
15826: 
15827:             $userenv{'canrequest.author'} =
15828:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
15829:                                                   'reload','requestauthor',
15830:                                                   \%userenv,\%domdef,\%is_adv);
15831:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
15832:                                                  $domain,$username);
15833:             my $reqstatus = $reqauthor{'author_status'};
15834:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
15835:                 if (ref($reqauthor{'author'}) eq 'HASH') {
15836:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
15837:                                                       $reqauthor{'author'}{'timestamp'};
15838:                 }
15839:             }
15840:         }
15841: 
15842: 	$env{'user.environment'} = "$lonids/$cookie.id";
15843: 
15844: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
15845: 		 &GDBM_WRCREAT(),0640)) {
15846: 	    &_add_to_env(\%disk_env,\%initial_env);
15847: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
15848: 	    &_add_to_env(\%disk_env,$userroles);
15849:             if (ref($firstaccenv) eq 'HASH') {
15850:                 &_add_to_env(\%disk_env,$firstaccenv);
15851:             }
15852:             if (ref($timerintenv) eq 'HASH') {
15853:                 &_add_to_env(\%disk_env,$timerintenv);
15854:             }
15855: 	    if (ref($args->{'extra_env'})) {
15856: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
15857: 	    }
15858: 	    untie(%disk_env);
15859: 	} else {
15860: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
15861: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
15862: 	    return 'error: '.$!;
15863: 	}
15864:     }
15865:     $env{'request.role'}='cm';
15866:     $env{'request.role.adv'}=$env{'user.adv'};
15867:     $env{'browser.type'}=$clientbrowser;
15868: 
15869:     return $cookie;
15870: 
15871: }
15872: 
15873: sub _add_to_env {
15874:     my ($idf,$env_data,$prefix) = @_;
15875:     if (ref($env_data) eq 'HASH') {
15876:         while (my ($key,$value) = each(%$env_data)) {
15877: 	    $idf->{$prefix.$key} = $value;
15878: 	    $env{$prefix.$key}   = $value;
15879:         }
15880:     }
15881: }
15882: 
15883: # --- Get the symbolic name of a problem and the url
15884: sub get_symb {
15885:     my ($request,$silent) = @_;
15886:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
15887:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
15888:     if ($symb eq '') {
15889:         if (!$silent) {
15890:             if (ref($request)) { 
15891:                 $request->print("Unable to handle ambiguous references:$url:.");
15892:             }
15893:             return ();
15894:         }
15895:     }
15896:     &Apache::lonenc::check_decrypt(\$symb);
15897:     return ($symb);
15898: }
15899: 
15900: # --------------------------------------------------------------Get annotation
15901: 
15902: sub get_annotation {
15903:     my ($symb,$enc) = @_;
15904: 
15905:     my $key = $symb;
15906:     if (!$enc) {
15907:         $key =
15908:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
15909:     }
15910:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
15911:     return $annotation{$key};
15912: }
15913: 
15914: sub clean_symb {
15915:     my ($symb,$delete_enc) = @_;
15916: 
15917:     &Apache::lonenc::check_decrypt(\$symb);
15918:     my $enc = $env{'request.enc'};
15919:     if ($delete_enc) {
15920:         delete($env{'request.enc'});
15921:     }
15922: 
15923:     return ($symb,$enc);
15924: }
15925: 
15926: ############################################################
15927: ############################################################
15928: 
15929: =pod
15930: 
15931: =head1 Routines for building display used to search for courses
15932: 
15933: 
15934: =over 4
15935: 
15936: =item * &build_filters()
15937: 
15938: Create markup for a table used to set filters to use when selecting
15939: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
15940: and quotacheck.pl
15941: 
15942: 
15943: Inputs:
15944: 
15945: filterlist - anonymous array of fields to include as potential filters
15946: 
15947: crstype - course type
15948: 
15949: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
15950:               to pop-open a course selector (will contain "extra element").
15951: 
15952: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
15953: 
15954: filter - anonymous hash of criteria and their values
15955: 
15956: action - form action
15957: 
15958: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
15959: 
15960: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
15961: 
15962: cloneruname - username of owner of new course who wants to clone
15963: 
15964: clonerudom - domain of owner of new course who wants to clone
15965: 
15966: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
15967: 
15968: codetitlesref - reference to array of titles of components in institutional codes (official courses)
15969: 
15970: codedom - domain
15971: 
15972: formname - value of form element named "form".
15973: 
15974: fixeddom - domain, if fixed.
15975: 
15976: prevphase - value to assign to form element named "phase" when going back to the previous screen
15977: 
15978: cnameelement - name of form element in form on opener page which will receive title of selected course
15979: 
15980: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
15981: 
15982: cdomelement - name of form element in form on opener page which will receive domain of selected course
15983: 
15984: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
15985: 
15986: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
15987: 
15988: clonewarning - warning message about missing information for intended course owner when DC creates a course
15989: 
15990: 
15991: Returns: $output - HTML for display of search criteria, and hidden form elements.
15992: 
15993: 
15994: Side Effects: None
15995: 
15996: =cut
15997: 
15998: # ---------------------------------------------- search for courses based on last activity etc.
15999: 
16000: sub build_filters {
16001:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
16002:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
16003:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
16004:         $cnameelement,$cnumelement,$cdomelement,$setroles,
16005:         $clonetext,$clonewarning) = @_;
16006:     my ($list,$jscript);
16007:     my $onchange = 'javascript:updateFilters(this)';
16008:     my ($domainselectform,$sincefilterform,$createdfilterform,
16009:         $ownerdomselectform,$persondomselectform,$instcodeform,
16010:         $typeselectform,$instcodetitle);
16011:     if ($formname eq '') {
16012:         $formname = $caller;
16013:     }
16014:     foreach my $item (@{$filterlist}) {
16015:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
16016:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
16017:             if ($item eq 'domainfilter') {
16018:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
16019:             } elsif ($item eq 'coursefilter') {
16020:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
16021:             } elsif ($item eq 'ownerfilter') {
16022:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
16023:             } elsif ($item eq 'ownerdomfilter') {
16024:                 $filter->{'ownerdomfilter'} =
16025:                     &LONCAPA::clean_domain($filter->{$item});
16026:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
16027:                                                        'ownerdomfilter',1);
16028:             } elsif ($item eq 'personfilter') {
16029:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
16030:             } elsif ($item eq 'persondomfilter') {
16031:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
16032:                                                         'persondomfilter',1);
16033:             } else {
16034:                 $filter->{$item} =~ s/\W//g;
16035:             }
16036:             if (!$filter->{$item}) {
16037:                 $filter->{$item} = '';
16038:             }
16039:         }
16040:         if ($item eq 'domainfilter') {
16041:             my $allow_blank = 1;
16042:             if ($formname eq 'portform') {
16043:                 $allow_blank=0;
16044:             } elsif ($formname eq 'studentform') {
16045:                 $allow_blank=0;
16046:             }
16047:             if ($fixeddom) {
16048:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
16049:                                     ' value="'.$codedom.'" />'.
16050:                                     &Apache::lonnet::domain($codedom,'description');
16051:             } else {
16052:                 $domainselectform = &select_dom_form($filter->{$item},
16053:                                                      'domainfilter',
16054:                                                       $allow_blank,'',$onchange);
16055:             }
16056:         } else {
16057:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
16058:         }
16059:     }
16060: 
16061:     # last course activity filter and selection
16062:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
16063: 
16064:     # course created filter and selection
16065:     if (exists($filter->{'createdfilter'})) {
16066:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
16067:     }
16068: 
16069:     my %lt = &Apache::lonlocal::texthash(
16070:                 'cac' => "$crstype Activity",
16071:                 'ccr' => "$crstype Created",
16072:                 'cde' => "$crstype Title",
16073:                 'cdo' => "$crstype Domain",
16074:                 'ins' => 'Institutional Code',
16075:                 'inc' => 'Institutional Categorization',
16076:                 'cow' => "$crstype Owner/Co-owner",
16077:                 'cop' => "$crstype Personnel Includes",
16078:                 'cog' => 'Type',
16079:              );
16080: 
16081:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
16082:         my $typeval = 'Course';
16083:         if ($crstype eq 'Community') {
16084:             $typeval = 'Community';
16085:         }
16086:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
16087:     } else {
16088:         $typeselectform =  '<select name="type" size="1"';
16089:         if ($onchange) {
16090:             $typeselectform .= ' onchange="'.$onchange.'"';
16091:         }
16092:         $typeselectform .= '>'."\n";
16093:         foreach my $posstype ('Course','Community') {
16094:             $typeselectform.='<option value="'.$posstype.'"'.
16095:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
16096:         }
16097:         $typeselectform.="</select>";
16098:     }
16099: 
16100:     my ($cloneableonlyform,$cloneabletitle);
16101:     if (exists($filter->{'cloneableonly'})) {
16102:         my $cloneableon = '';
16103:         my $cloneableoff = ' checked="checked"';
16104:         if ($filter->{'cloneableonly'}) {
16105:             $cloneableon = $cloneableoff;
16106:             $cloneableoff = '';
16107:         }
16108:         $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>';
16109:         if ($formname eq 'ccrs') {
16110:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
16111:         } else {
16112:             $cloneabletitle = &mt('Cloneable by you');
16113:         }
16114:     }
16115:     my $officialjs;
16116:     if ($crstype eq 'Course') {
16117:         if (exists($filter->{'instcodefilter'})) {
16118: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
16119: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
16120:             if ($codedom) {
16121:                 $officialjs = 1;
16122:                 ($instcodeform,$jscript,$$numtitlesref) =
16123:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
16124:                                                                   $officialjs,$codetitlesref);
16125:                 if ($jscript) {
16126:                     $jscript = '<script type="text/javascript">'."\n".
16127:                                '// <![CDATA['."\n".
16128:                                $jscript."\n".
16129:                                '// ]]>'."\n".
16130:                                '</script>'."\n";
16131:                 }
16132:             }
16133:             if ($instcodeform eq '') {
16134:                 $instcodeform =
16135:                     '<input type="text" name="instcodefilter" size="10" value="'.
16136:                     $list->{'instcodefilter'}.'" />';
16137:                 $instcodetitle = $lt{'ins'};
16138:             } else {
16139:                 $instcodetitle = $lt{'inc'};
16140:             }
16141:             if ($fixeddom) {
16142:                 $instcodetitle .= '<br />('.$codedom.')';
16143:             }
16144:         }
16145:     }
16146:     my $output = qq|
16147: <form method="post" name="filterpicker" action="$action">
16148: <input type="hidden" name="form" value="$formname" />
16149: |;
16150:     if ($formname eq 'modifycourse') {
16151:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
16152:                    '<input type="hidden" name="prevphase" value="'.
16153:                    $prevphase.'" />'."\n";
16154:     } elsif ($formname eq 'quotacheck') {
16155:         $output .= qq|
16156: <input type="hidden" name="sortby" value="" />
16157: <input type="hidden" name="sortorder" value="" />
16158: |;
16159:     } else {
16160:         my $name_input;
16161:         if ($cnameelement ne '') {
16162:             $name_input = '<input type="hidden" name="cnameelement" value="'.
16163:                           $cnameelement.'" />';
16164:         }
16165:         $output .= qq|
16166: <input type="hidden" name="cnumelement" value="$cnumelement" />
16167: <input type="hidden" name="cdomelement" value="$cdomelement" />
16168: $name_input
16169: $roleelement
16170: $multelement
16171: $typeelement
16172: |;
16173:         if ($formname eq 'portform') {
16174:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
16175:         }
16176:     }
16177:     if ($fixeddom) {
16178:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
16179:     }
16180:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
16181:     if ($sincefilterform) {
16182:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
16183:                   .$sincefilterform
16184:                   .&Apache::lonhtmlcommon::row_closure();
16185:     }
16186:     if ($createdfilterform) {
16187:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
16188:                   .$createdfilterform
16189:                   .&Apache::lonhtmlcommon::row_closure();
16190:     }
16191:     if ($domainselectform) {
16192:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
16193:                   .$domainselectform
16194:                   .&Apache::lonhtmlcommon::row_closure();
16195:     }
16196:     if ($typeselectform) {
16197:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
16198:             $output .= $typeselectform;
16199:         } else {
16200:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
16201:                       .$typeselectform
16202:                       .&Apache::lonhtmlcommon::row_closure();
16203:         }
16204:     }
16205:     if ($instcodeform) {
16206:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
16207:                   .$instcodeform
16208:                   .&Apache::lonhtmlcommon::row_closure();
16209:     }
16210:     if (exists($filter->{'ownerfilter'})) {
16211:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
16212:                    '<table><tr><td>'.&mt('Username').'<br />'.
16213:                    '<input type="text" name="ownerfilter" size="20" value="'.
16214:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
16215:                    $ownerdomselectform.'</td></tr></table>'.
16216:                    &Apache::lonhtmlcommon::row_closure();
16217:     }
16218:     if (exists($filter->{'personfilter'})) {
16219:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
16220:                    '<table><tr><td>'.&mt('Username').'<br />'.
16221:                    '<input type="text" name="personfilter" size="20" value="'.
16222:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
16223:                    $persondomselectform.'</td></tr></table>'.
16224:                    &Apache::lonhtmlcommon::row_closure();
16225:     }
16226:     if (exists($filter->{'coursefilter'})) {
16227:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
16228:                   .'<input type="text" name="coursefilter" size="25" value="'
16229:                   .$list->{'coursefilter'}.'" />'
16230:                   .&Apache::lonhtmlcommon::row_closure();
16231:     }
16232:     if ($cloneableonlyform) {
16233:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
16234:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
16235:     }
16236:     if (exists($filter->{'descriptfilter'})) {
16237:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
16238:                   .'<input type="text" name="descriptfilter" size="40" value="'
16239:                   .$list->{'descriptfilter'}.'" />'
16240:                   .&Apache::lonhtmlcommon::row_closure(1);
16241:     }
16242:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
16243:                '<input type="hidden" name="updater" value="" />'."\n".
16244:                '<input type="submit" name="gosearch" value="'.
16245:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
16246:     return $jscript.$clonewarning.$output;
16247: }
16248: 
16249: =pod
16250: 
16251: =item * &timebased_select_form()
16252: 
16253: Create markup for a dropdown list used to select a time-based
16254: filter e.g., Course Activity, Course Created, when searching for courses
16255: or communities
16256: 
16257: Inputs:
16258: 
16259: item - name of form element (sincefilter or createdfilter)
16260: 
16261: filter - anonymous hash of criteria and their values
16262: 
16263: Returns: HTML for a select box contained a blank, then six time selections,
16264:          with value set in incoming form variables currently selected.
16265: 
16266: Side Effects: None
16267: 
16268: =cut
16269: 
16270: sub timebased_select_form {
16271:     my ($item,$filter) = @_;
16272:     if (ref($filter) eq 'HASH') {
16273:         $filter->{$item} =~ s/[^\d-]//g;
16274:         if (!$filter->{$item}) { $filter->{$item}=-1; }
16275:         return &select_form(
16276:                             $filter->{$item},
16277:                             $item,
16278:                             {      '-1' => '',
16279:                                 '86400' => &mt('today'),
16280:                                '604800' => &mt('last week'),
16281:                               '2592000' => &mt('last month'),
16282:                               '7776000' => &mt('last three months'),
16283:                              '15552000' => &mt('last six months'),
16284:                              '31104000' => &mt('last year'),
16285:                     'select_form_order' =>
16286:                            ['-1','86400','604800','2592000','7776000',
16287:                             '15552000','31104000']});
16288:     }
16289: }
16290: 
16291: =pod
16292: 
16293: =item * &js_changer()
16294: 
16295: Create script tag containing Javascript used to submit course search form
16296: when course type or domain is changed, and also to hide 'Searching ...' on
16297: page load completion for page showing search result.
16298: 
16299: Inputs: None
16300: 
16301: Returns: markup containing updateFilters() and hideSearching() javascript functions.
16302: 
16303: Side Effects: None
16304: 
16305: =cut
16306: 
16307: sub js_changer {
16308:     return <<ENDJS;
16309: <script type="text/javascript">
16310: // <![CDATA[
16311: function updateFilters(caller) {
16312:     if (typeof(caller) != "undefined") {
16313:         document.filterpicker.updater.value = caller.name;
16314:     }
16315:     document.filterpicker.submit();
16316: }
16317: 
16318: function hideSearching() {
16319:     if (document.getElementById('searching')) {
16320:         document.getElementById('searching').style.display = 'none';
16321:     }
16322:     return;
16323: }
16324: 
16325: // ]]>
16326: </script>
16327: 
16328: ENDJS
16329: }
16330: 
16331: =pod
16332: 
16333: =item * &search_courses()
16334: 
16335: Process selected filters form course search form and pass to lonnet::courseiddump
16336: to retrieve a hash for which keys are courseIDs which match the selected filters.
16337: 
16338: Inputs:
16339: 
16340: dom - domain being searched
16341: 
16342: type - course type ('Course' or 'Community' or '.' if any).
16343: 
16344: filter - anonymous hash of criteria and their values
16345: 
16346: numtitles - for institutional codes - number of categories
16347: 
16348: cloneruname - optional username of new course owner
16349: 
16350: clonerudom - optional domain of new course owner
16351: 
16352: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
16353:             (used when DC is using course creation form)
16354: 
16355: codetitles - reference to array of titles of components in institutional codes (official courses).
16356: 
16357: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
16358:            (and so can clone automatically)
16359: 
16360: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
16361: 
16362: reqinstcode - institutional code of new course, where search_courses is used to identify potential
16363:               courses to clone
16364: 
16365: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
16366: 
16367: 
16368: Side Effects: None
16369: 
16370: =cut
16371: 
16372: 
16373: sub search_courses {
16374:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
16375:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
16376:     my (%courses,%showcourses,$cloner);
16377:     if (($filter->{'ownerfilter'} ne '') ||
16378:         ($filter->{'ownerdomfilter'} ne '')) {
16379:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
16380:                                        $filter->{'ownerdomfilter'};
16381:     }
16382:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
16383:         if (!$filter->{$item}) {
16384:             $filter->{$item}='.';
16385:         }
16386:     }
16387:     my $now = time;
16388:     my $timefilter =
16389:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
16390:     my ($createdbefore,$createdafter);
16391:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
16392:         $createdbefore = $now;
16393:         $createdafter = $now-$filter->{'createdfilter'};
16394:     }
16395:     my ($instcodefilter,$regexpok);
16396:     if ($numtitles) {
16397:         if ($env{'form.official'} eq 'on') {
16398:             $instcodefilter =
16399:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
16400:             $regexpok = 1;
16401:         } elsif ($env{'form.official'} eq 'off') {
16402:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
16403:             unless ($instcodefilter eq '') {
16404:                 $regexpok = -1;
16405:             }
16406:         }
16407:     } else {
16408:         $instcodefilter = $filter->{'instcodefilter'};
16409:     }
16410:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
16411:     if ($type eq '') { $type = '.'; }
16412: 
16413:     if (($clonerudom ne '') && ($cloneruname ne '')) {
16414:         $cloner = $cloneruname.':'.$clonerudom;
16415:     }
16416:     %courses = &Apache::lonnet::courseiddump($dom,
16417:                                              $filter->{'descriptfilter'},
16418:                                              $timefilter,
16419:                                              $instcodefilter,
16420:                                              $filter->{'combownerfilter'},
16421:                                              $filter->{'coursefilter'},
16422:                                              undef,undef,$type,$regexpok,undef,undef,
16423:                                              undef,undef,$cloner,$cc_clone,
16424:                                              $filter->{'cloneableonly'},
16425:                                              $createdbefore,$createdafter,undef,
16426:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
16427:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
16428:         my $ccrole;
16429:         if ($type eq 'Community') {
16430:             $ccrole = 'co';
16431:         } else {
16432:             $ccrole = 'cc';
16433:         }
16434:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
16435:                                                      $filter->{'persondomfilter'},
16436:                                                      'userroles',undef,
16437:                                                      [$ccrole,'in','ad','ep','ta','cr'],
16438:                                                      $dom);
16439:         foreach my $role (keys(%rolehash)) {
16440:             my ($cnum,$cdom,$courserole) = split(':',$role);
16441:             my $cid = $cdom.'_'.$cnum;
16442:             if (exists($courses{$cid})) {
16443:                 if (ref($courses{$cid}) eq 'HASH') {
16444:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
16445:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
16446:                             push(@{$courses{$cid}{roles}},$courserole);
16447:                         }
16448:                     } else {
16449:                         $courses{$cid}{roles} = [$courserole];
16450:                     }
16451:                     $showcourses{$cid} = $courses{$cid};
16452:                 }
16453:             }
16454:         }
16455:         %courses = %showcourses;
16456:     }
16457:     return %courses;
16458: }
16459: 
16460: =pod
16461: 
16462: =back
16463: 
16464: =head1 Routines for version requirements for current course.
16465: 
16466: =over 4
16467: 
16468: =item * &check_release_required()
16469: 
16470: Compares required LON-CAPA version with version on server, and
16471: if required version is newer looks for a server with the required version.
16472: 
16473: Looks first at servers in user's owen domain; if none suitable, looks at
16474: servers in course's domain are permitted to host sessions for user's domain.
16475: 
16476: Inputs:
16477: 
16478: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
16479: 
16480: $courseid - Course ID of current course
16481: 
16482: $rolecode - User's current role in course (for switchserver query string).
16483: 
16484: $required - LON-CAPA version needed by course (format: Major.Minor).
16485: 
16486: 
16487: Returns:
16488: 
16489: $switchserver - query string tp append to /adm/switchserver call (if
16490:                 current server's LON-CAPA version is too old.
16491: 
16492: $warning - Message is displayed if no suitable server could be found.
16493: 
16494: =cut
16495: 
16496: sub check_release_required {
16497:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
16498:     my ($switchserver,$warning);
16499:     if ($required ne '') {
16500:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
16501:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
16502:         if ($reqdmajor ne '' && $reqdminor ne '') {
16503:             my $otherserver;
16504:             if (($major eq '' && $minor eq '') ||
16505:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
16506:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
16507:                 my $switchlcrev =
16508:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
16509:                                                            $userdomserver);
16510:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
16511:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
16512:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
16513:                     my $cdom = $env{'course.'.$courseid.'.domain'};
16514:                     if ($cdom ne $env{'user.domain'}) {
16515:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
16516:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
16517:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
16518:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
16519:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
16520:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
16521:                         my $canhost =
16522:                             &Apache::lonnet::can_host_session($env{'user.domain'},
16523:                                                               $coursedomserver,
16524:                                                               $remoterev,
16525:                                                               $udomdefaults{'remotesessions'},
16526:                                                               $defdomdefaults{'hostedsessions'});
16527: 
16528:                         if ($canhost) {
16529:                             $otherserver = $coursedomserver;
16530:                         } else {
16531:                             $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.");
16532:                         }
16533:                     } else {
16534:                         $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).");
16535:                     }
16536:                 } else {
16537:                     $otherserver = $userdomserver;
16538:                 }
16539:             }
16540:             if ($otherserver ne '') {
16541:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
16542:             }
16543:         }
16544:     }
16545:     return ($switchserver,$warning);
16546: }
16547: 
16548: =pod
16549: 
16550: =item * &check_release_result()
16551: 
16552: Inputs:
16553: 
16554: $switchwarning - Warning message if no suitable server found to host session.
16555: 
16556: $switchserver - query string to append to /adm/switchserver containing lonHostID
16557:                 and current role.
16558: 
16559: Returns: HTML to display with information about requirement to switch server.
16560:          Either displaying warning with link to Roles/Courses screen or
16561:          display link to switchserver.
16562: 
16563: =cut
16564: 
16565: sub check_release_result {
16566:     my ($switchwarning,$switchserver) = @_;
16567:     my $output = &start_page('Selected course unavailable on this server').
16568:                  '<p class="LC_warning">';
16569:     if ($switchwarning) {
16570:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
16571:         if (&show_course()) {
16572:             $output .= &mt('Display courses');
16573:         } else {
16574:             $output .= &mt('Display roles');
16575:         }
16576:         $output .= '</a>';
16577:     } elsif ($switchserver) {
16578:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
16579:                    '<br />'.
16580:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
16581:                    &mt('Switch Server').
16582:                    '</a>';
16583:     }
16584:     $output .= '</p>'.&end_page();
16585:     return $output;
16586: }
16587: 
16588: =pod
16589: 
16590: =item * &needs_coursereinit()
16591: 
16592: Determine if course contents stored for user's session needs to be
16593: refreshed, because content has changed since "Big Hash" last tied.
16594: 
16595: Check for change is made if time last checked is more than 10 minutes ago
16596: (by default).
16597: 
16598: Inputs:
16599: 
16600: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
16601: 
16602: $interval (optional) - Time which may elapse (in s) between last check for content
16603:                        change in current course. (default: 600 s).
16604: 
16605: Returns: an array; first element is:
16606: 
16607: =over 4
16608: 
16609: 'switch' - if content updates mean user's session
16610:            needs to be switched to a server running a newer LON-CAPA version
16611: 
16612: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
16613:            on current server hosting user's session
16614: 
16615: ''       - if no action required.
16616: 
16617: =back
16618: 
16619: If first item element is 'switch':
16620: 
16621: second item is $switchwarning - Warning message if no suitable server found to host session.
16622: 
16623: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
16624:                               and current role.
16625: 
16626: otherwise: no other elements returned.
16627: 
16628: =back
16629: 
16630: =cut
16631: 
16632: sub needs_coursereinit {
16633:     my ($loncaparev,$interval) = @_;
16634:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
16635:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
16636:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
16637:     my $now = time;
16638:     if ($interval eq '') {
16639:         $interval = 600;
16640:     }
16641:     if (($now-$env{'request.course.timechecked'})>$interval) {
16642:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
16643:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
16644:         if ($lastchange > $env{'request.course.tied'}) {
16645:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
16646:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
16647:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
16648:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
16649:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
16650:                                              $curr_reqd_hash{'internal.releaserequired'}});
16651:                     my ($switchserver,$switchwarning) =
16652:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
16653:                                                 $curr_reqd_hash{'internal.releaserequired'});
16654:                     if ($switchwarning ne '' || $switchserver ne '') {
16655:                         return ('switch',$switchwarning,$switchserver);
16656:                     }
16657:                 }
16658:             }
16659:             return ('update');
16660:         }
16661:     }
16662:     return ();
16663: }
16664: 
16665: sub update_content_constraints {
16666:     my ($cdom,$cnum,$chome,$cid) = @_;
16667:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
16668:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
16669:     my %checkresponsetypes;
16670:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
16671:         my ($item,$name,$value) = split(/:/,$key);
16672:         if ($item eq 'resourcetag') {
16673:             if ($name eq 'responsetype') {
16674:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
16675:             }
16676:         }
16677:     }
16678:     my $navmap = Apache::lonnavmaps::navmap->new();
16679:     if (defined($navmap)) {
16680:         my %allresponses;
16681:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
16682:             my %responses = $res->responseTypes();
16683:             foreach my $key (keys(%responses)) {
16684:                 next unless(exists($checkresponsetypes{$key}));
16685:                 $allresponses{$key} += $responses{$key};
16686:             }
16687:         }
16688:         foreach my $key (keys(%allresponses)) {
16689:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
16690:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
16691:                 ($reqdmajor,$reqdminor) = ($major,$minor);
16692:             }
16693:         }
16694:         undef($navmap);
16695:     }
16696:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
16697:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
16698:     }
16699:     return;
16700: }
16701: 
16702: sub allmaps_incourse {
16703:     my ($cdom,$cnum,$chome,$cid) = @_;
16704:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
16705:         $cid = $env{'request.course.id'};
16706:         $cdom = $env{'course.'.$cid.'.domain'};
16707:         $cnum = $env{'course.'.$cid.'.num'};
16708:         $chome = $env{'course.'.$cid.'.home'};
16709:     }
16710:     my %allmaps = ();
16711:     my $lastchange =
16712:         &Apache::lonnet::get_coursechange($cdom,$cnum);
16713:     if ($lastchange > $env{'request.course.tied'}) {
16714:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
16715:         unless ($ferr) {
16716:             &update_content_constraints($cdom,$cnum,$chome,$cid);
16717:         }
16718:     }
16719:     my $navmap = Apache::lonnavmaps::navmap->new();
16720:     if (defined($navmap)) {
16721:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
16722:             $allmaps{$res->src()} = 1;
16723:         }
16724:     }
16725:     return \%allmaps;
16726: }
16727: 
16728: sub parse_supplemental_title {
16729:     my ($title) = @_;
16730: 
16731:     my ($foldertitle,$renametitle);
16732:     if ($title =~ /&amp;&amp;&amp;/) {
16733:         $title = &HTML::Entites::decode($title);
16734:     }
16735:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
16736:         $renametitle=$4;
16737:         my ($time,$uname,$udom) = ($1,$2,$3);
16738:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
16739:         my $name =  &plainname($uname,$udom);
16740:         $name = &HTML::Entities::encode($name,'"<>&\'');
16741:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
16742:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
16743:             $name.': <br />'.$foldertitle;
16744:     }
16745:     if (wantarray) {
16746:         return ($title,$foldertitle,$renametitle);
16747:     }
16748:     return $title;
16749: }
16750: 
16751: sub recurse_supplemental {
16752:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
16753:     if ($suppmap) {
16754:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
16755:         if ($fatal) {
16756:             $errors ++;
16757:         } else {
16758:             if ($#LONCAPA::map::resources > 0) {
16759:                 foreach my $res (@LONCAPA::map::resources) {
16760:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
16761:                     if (($src ne '') && ($status eq 'res')) {
16762:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
16763:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
16764:                         } else {
16765:                             $numfiles ++;
16766:                         }
16767:                     }
16768:                 }
16769:             }
16770:         }
16771:     }
16772:     return ($numfiles,$errors);
16773: }
16774: 
16775: sub symb_to_docspath {
16776:     my ($symb,$navmapref) = @_;
16777:     return unless ($symb && ref($navmapref));
16778:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
16779:     if ($resurl=~/\.(sequence|page)$/) {
16780:         $mapurl=$resurl;
16781:     } elsif ($resurl eq 'adm/navmaps') {
16782:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
16783:     }
16784:     my $mapresobj;
16785:     unless (ref($$navmapref)) {
16786:         $$navmapref = Apache::lonnavmaps::navmap->new();
16787:     }
16788:     if (ref($$navmapref)) {
16789:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
16790:     }
16791:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
16792:     my $type=$2;
16793:     my $path;
16794:     if (ref($mapresobj)) {
16795:         my $pcslist = $mapresobj->map_hierarchy();
16796:         if ($pcslist ne '') {
16797:             foreach my $pc (split(/,/,$pcslist)) {
16798:                 next if ($pc <= 1);
16799:                 my $res = $$navmapref->getByMapPc($pc);
16800:                 if (ref($res)) {
16801:                     my $thisurl = $res->src();
16802:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
16803:                     my $thistitle = $res->title();
16804:                     $path .= '&'.
16805:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
16806:                              &escape($thistitle).
16807:                              ':'.$res->randompick().
16808:                              ':'.$res->randomout().
16809:                              ':'.$res->encrypted().
16810:                              ':'.$res->randomorder().
16811:                              ':'.$res->is_page();
16812:                 }
16813:             }
16814:         }
16815:         $path =~ s/^\&//;
16816:         my $maptitle = $mapresobj->title();
16817:         if ($mapurl eq 'default') {
16818:             $maptitle = 'Main Content';
16819:         }
16820:         $path .= (($path ne '')? '&' : '').
16821:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
16822:                  &escape($maptitle).
16823:                  ':'.$mapresobj->randompick().
16824:                  ':'.$mapresobj->randomout().
16825:                  ':'.$mapresobj->encrypted().
16826:                  ':'.$mapresobj->randomorder().
16827:                  ':'.$mapresobj->is_page();
16828:     } else {
16829:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
16830:         my $ispage = (($type eq 'page')? 1 : '');
16831:         if ($mapurl eq 'default') {
16832:             $maptitle = 'Main Content';
16833:         }
16834:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
16835:                 &escape($maptitle).':::::'.$ispage;
16836:     }
16837:     unless ($mapurl eq 'default') {
16838:         $path = 'default&'.
16839:                 &escape('Main Content').
16840:                 ':::::&'.$path;
16841:     }
16842:     return $path;
16843: }
16844: 
16845: sub captcha_display {
16846:     my ($context,$lonhost,$defdom) = @_;
16847:     my ($output,$error);
16848:     my ($captcha,$pubkey,$privkey,$version) =
16849:         &get_captcha_config($context,$lonhost,$defdom);
16850:     if ($captcha eq 'original') {
16851:         $output = &create_captcha();
16852:         unless ($output) {
16853:             $error = 'captcha';
16854:         }
16855:     } elsif ($captcha eq 'recaptcha') {
16856:         $output = &create_recaptcha($pubkey,$version);
16857:         unless ($output) {
16858:             $error = 'recaptcha';
16859:         }
16860:     }
16861:     return ($output,$error,$captcha,$version);
16862: }
16863: 
16864: sub captcha_response {
16865:     my ($context,$lonhost,$defdom) = @_;
16866:     my ($captcha_chk,$captcha_error);
16867:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
16868:     if ($captcha eq 'original') {
16869:         ($captcha_chk,$captcha_error) = &check_captcha();
16870:     } elsif ($captcha eq 'recaptcha') {
16871:         $captcha_chk = &check_recaptcha($privkey,$version);
16872:     } else {
16873:         $captcha_chk = 1;
16874:     }
16875:     return ($captcha_chk,$captcha_error);
16876: }
16877: 
16878: sub get_captcha_config {
16879:     my ($context,$lonhost,$dom_in_effect) = @_;
16880:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
16881:     my $hostname = &Apache::lonnet::hostname($lonhost);
16882:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
16883:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
16884:     if ($context eq 'usercreation') {
16885:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
16886:         if (ref($domconfig{$context}) eq 'HASH') {
16887:             $hashtocheck = $domconfig{$context}{'cancreate'};
16888:             if (ref($hashtocheck) eq 'HASH') {
16889:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
16890:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
16891:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
16892:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
16893:                     }
16894:                     if ($privkey && $pubkey) {
16895:                         $captcha = 'recaptcha';
16896:                         $version = $hashtocheck->{'recaptchaversion'};
16897:                         if ($version ne '2') {
16898:                             $version = 1;
16899:                         }
16900:                     } else {
16901:                         $captcha = 'original';
16902:                     }
16903:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
16904:                     $captcha = 'original';
16905:                 }
16906:             }
16907:         } else {
16908:             $captcha = 'captcha';
16909:         }
16910:     } elsif ($context eq 'login') {
16911:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
16912:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
16913:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
16914:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
16915:             if ($privkey && $pubkey) {
16916:                 $captcha = 'recaptcha';
16917:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
16918:                 if ($version ne '2') {
16919:                     $version = 1;
16920:                 }
16921:             } else {
16922:                 $captcha = 'original';
16923:             }
16924:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
16925:             $captcha = 'original';
16926:         }
16927:     } elsif ($context eq 'passwords') {
16928:         if ($dom_in_effect) {
16929:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
16930:             if ($passwdconf{'captcha'} eq 'recaptcha') {
16931:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
16932:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
16933:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
16934:                 }
16935:                 if ($privkey && $pubkey) {
16936:                     $captcha = 'recaptcha';
16937:                     $version = $passwdconf{'recaptchaversion'};
16938:                     if ($version ne '2') {
16939:                         $version = 1;
16940:                     }
16941:                 } else {
16942:                     $captcha = 'original';
16943:                 }
16944:             } elsif ($passwdconf{'captcha'} ne 'notused') {
16945:                 $captcha = 'original';
16946:             }
16947:         }
16948:     }
16949:     return ($captcha,$pubkey,$privkey,$version);
16950: }
16951: 
16952: sub create_captcha {
16953:     my %captcha_params = &captcha_settings();
16954:     my ($output,$maxtries,$tries) = ('',10,0);
16955:     while ($tries < $maxtries) {
16956:         $tries ++;
16957:         my $captcha = Authen::Captcha->new (
16958:                                            output_folder => $captcha_params{'output_dir'},
16959:                                            data_folder   => $captcha_params{'db_dir'},
16960:                                           );
16961:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
16962: 
16963:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
16964:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
16965:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
16966:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
16967:                       '<br />'.
16968:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
16969:             last;
16970:         }
16971:     }
16972:     return $output;
16973: }
16974: 
16975: sub captcha_settings {
16976:     my %captcha_params = (
16977:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
16978:                            www_output_dir => "/captchaspool",
16979:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
16980:                            numchars       => '5',
16981:                          );
16982:     return %captcha_params;
16983: }
16984: 
16985: sub check_captcha {
16986:     my ($captcha_chk,$captcha_error);
16987:     my $code = $env{'form.code'};
16988:     my $md5sum = $env{'form.crypt'};
16989:     my %captcha_params = &captcha_settings();
16990:     my $captcha = Authen::Captcha->new(
16991:                       output_folder => $captcha_params{'output_dir'},
16992:                       data_folder   => $captcha_params{'db_dir'},
16993:                   );
16994:     $captcha_chk = $captcha->check_code($code,$md5sum);
16995:     my %captcha_hash = (
16996:                         0       => 'Code not checked (file error)',
16997:                        -1      => 'Failed: code expired',
16998:                        -2      => 'Failed: invalid code (not in database)',
16999:                        -3      => 'Failed: invalid code (code does not match crypt)',
17000:     );
17001:     if ($captcha_chk != 1) {
17002:         $captcha_error = $captcha_hash{$captcha_chk}
17003:     }
17004:     return ($captcha_chk,$captcha_error);
17005: }
17006: 
17007: sub create_recaptcha {
17008:     my ($pubkey,$version) = @_;
17009:     if ($version >= 2) {
17010:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
17011:     } else {
17012:         my $use_ssl;
17013:         if ($ENV{'SERVER_PORT'} == 443) {
17014:             $use_ssl = 1;
17015:         }
17016:         my $captcha = Captcha::reCAPTCHA->new;
17017:         return $captcha->get_options_setter({theme => 'white'})."\n".
17018:                $captcha->get_html($pubkey,undef,$use_ssl).
17019:                &mt('If the text is hard to read, [_1] will replace them.',
17020:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
17021:                '<br /><br />';
17022:      }
17023: }
17024: 
17025: sub check_recaptcha {
17026:     my ($privkey,$version) = @_;
17027:     my $captcha_chk;
17028:     if ($version >= 2) {
17029:         my $ua = LWP::UserAgent->new;
17030:         $ua->timeout(10);
17031:         my %info = (
17032:                      secret   => $privkey,
17033:                      response => $env{'form.g-recaptcha-response'},
17034:                      remoteip => $ENV{'REMOTE_ADDR'},
17035:                    );
17036:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
17037:         if ($response->is_success)  {
17038:             my $data = JSON::DWIW->from_json($response->decoded_content);
17039:             if (ref($data) eq 'HASH') {
17040:                 if ($data->{'success'}) {
17041:                     $captcha_chk = 1;
17042:                 }
17043:             }
17044:         }
17045:     } else {
17046:         my $captcha = Captcha::reCAPTCHA->new;
17047:         my $captcha_result =
17048:             $captcha->check_answer(
17049:                                     $privkey,
17050:                                     $ENV{'REMOTE_ADDR'},
17051:                                     $env{'form.recaptcha_challenge_field'},
17052:                                     $env{'form.recaptcha_response_field'},
17053:                                   );
17054:         if ($captcha_result->{is_valid}) {
17055:             $captcha_chk = 1;
17056:         }
17057:     }
17058:     return $captcha_chk;
17059: }
17060: 
17061: sub emailusername_info {
17062:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
17063:     my %titles = &Apache::lonlocal::texthash (
17064:                      lastname      => 'Last Name',
17065:                      firstname     => 'First Name',
17066:                      institution   => 'School/college/university',
17067:                      location      => "School's city, state/province, country",
17068:                      web           => "School's web address",
17069:                      officialemail => 'E-mail address at institution (if different)',
17070:                      id            => 'Student/Employee ID',
17071:                  );
17072:     return (\@fields,\%titles);
17073: }
17074: 
17075: sub cleanup_html {
17076:     my ($incoming) = @_;
17077:     my $outgoing;
17078:     if ($incoming ne '') {
17079:         $outgoing = $incoming;
17080:         $outgoing =~ s/;/&#059;/g;
17081:         $outgoing =~ s/\#/&#035;/g;
17082:         $outgoing =~ s/\&/&#038;/g;
17083:         $outgoing =~ s/</&#060;/g;
17084:         $outgoing =~ s/>/&#062;/g;
17085:         $outgoing =~ s/\(/&#040/g;
17086:         $outgoing =~ s/\)/&#041;/g;
17087:         $outgoing =~ s/"/&#034;/g;
17088:         $outgoing =~ s/'/&#039;/g;
17089:         $outgoing =~ s/\$/&#036;/g;
17090:         $outgoing =~ s{/}{&#047;}g;
17091:         $outgoing =~ s/=/&#061;/g;
17092:         $outgoing =~ s/\\/&#092;/g
17093:     }
17094:     return $outgoing;
17095: }
17096: 
17097: # Checks for critical messages and returns a redirect url if one exists.
17098: # $interval indicates how often to check for messages.
17099: sub critical_redirect {
17100:     my ($interval) = @_;
17101:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
17102:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
17103:                                         $env{'user.name'});
17104:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
17105:         my $redirecturl;
17106:         if ($what[0]) {
17107:             if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
17108:                 $redirecturl='/adm/email?critical=display';
17109:                 my $url=&Apache::lonnet::absolute_url().$redirecturl;
17110:                 return (1, $url);
17111:             }
17112:         }
17113:     }
17114:     return ();
17115: }
17116: 
17117: # Use:
17118: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
17119: #
17120: ##################################################
17121: #          password associated functions         #
17122: ##################################################
17123: sub des_keys {
17124:     # Make a new key for DES encryption.
17125:     # Each key has two parts which are returned separately.
17126:     # Please note:  Each key must be passed through the &hex function
17127:     # before it is output to the web browser.  The hex versions cannot
17128:     # be used to decrypt.
17129:     my @hexstr=('0','1','2','3','4','5','6','7',
17130:                 '8','9','a','b','c','d','e','f');
17131:     my $lkey='';
17132:     for (0..7) {
17133:         $lkey.=$hexstr[rand(15)];
17134:     }
17135:     my $ukey='';
17136:     for (0..7) {
17137:         $ukey.=$hexstr[rand(15)];
17138:     }
17139:     return ($lkey,$ukey);
17140: }
17141: 
17142: sub des_decrypt {
17143:     my ($key,$cyphertext) = @_;
17144:     my $keybin=pack("H16",$key);
17145:     my $cypher;
17146:     if ($Crypt::DES::VERSION>=2.03) {
17147:         $cypher=new Crypt::DES $keybin;
17148:     } else {
17149:         $cypher=new DES $keybin;
17150:     }
17151:     my $plaintext='';
17152:     my $cypherlength = length($cyphertext);
17153:     my $numchunks = int($cypherlength/32);
17154:     for (my $j=0; $j<$numchunks; $j++) {
17155:         my $start = $j*32;
17156:         my $cypherblock = substr($cyphertext,$start,32);
17157:         my $chunk =
17158:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
17159:         $chunk .=
17160:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
17161:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
17162:         $plaintext .= $chunk;
17163:     }
17164:     return $plaintext;
17165: }
17166: 
17167: sub is_nonframeable {
17168:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
17169:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
17170:     return if (($remprotocol eq '') || ($remhost eq ''));
17171: 
17172:     $remprotocol = lc($remprotocol);
17173:     $remhost = lc($remhost);
17174:     my $remport = 80;
17175:     if ($remprotocol eq 'https') {
17176:         $remport = 443;
17177:     }
17178:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
17179:     if ($cached) {
17180:         unless ($nocache) {
17181:             if ($result) {
17182:                 return 1;
17183:             } else {
17184:                 return 0;
17185:             }
17186:         }
17187:     }
17188:     my $uselink;
17189:     my $request = new HTTP::Request('HEAD',$url);
17190:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
17191:     if ($response->is_success()) {
17192:         my $secpolicy = lc($response->header('content-security-policy'));
17193:         my $xframeop = lc($response->header('x-frame-options'));
17194:         $secpolicy =~ s/^\s+|\s+$//g;
17195:         $xframeop =~ s/^\s+|\s+$//g;
17196:         if (($secpolicy ne '') || ($xframeop ne '')) {
17197:             my $remotehost = $remprotocol.'://'.$remhost;
17198:             my ($origin,$protocol,$port);
17199:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
17200:                 $port = $ENV{'SERVER_PORT'};
17201:             } else {
17202:                 $port = 80;
17203:             }
17204:             if ($absolute eq '') {
17205:                 $protocol = 'http:';
17206:                 if ($port == 443) {
17207:                     $protocol = 'https:';
17208:                 }
17209:                 $origin = $protocol.'//'.lc($hostname);
17210:             } else {
17211:                 $origin = lc($absolute);
17212:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
17213:             }
17214:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
17215:                 my $framepolicy = $1;
17216:                 $framepolicy =~ s/^\s+|\s+$//g;
17217:                 my @policies = split(/\s+/,$framepolicy);
17218:                 if (@policies) {
17219:                     if (grep(/^\Q'none'\E$/,@policies)) {
17220:                         $uselink = 1;
17221:                     } else {
17222:                         $uselink = 1;
17223:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
17224:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
17225:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
17226:                             undef($uselink);
17227:                         }
17228:                         if ($uselink) {
17229:                             if (grep(/^\Q'self'\E$/,@policies)) {
17230:                                 if (($origin ne '') && ($remotehost eq $origin)) {
17231:                                     undef($uselink);
17232:                                 }
17233:                             }
17234:                         }
17235:                         if ($uselink) {
17236:                             my @possok;
17237:                             if ($ip ne '') {
17238:                                 push(@possok,$ip);
17239:                             }
17240:                             my $hoststr = '';
17241:                             foreach my $part (reverse(split(/\./,$hostname))) {
17242:                                 if ($hoststr eq '') {
17243:                                     $hoststr = $part;
17244:                                 } else {
17245:                                     $hoststr = "$part.$hoststr";
17246:                                 }
17247:                                 if ($hoststr eq $hostname) {
17248:                                     push(@possok,$hostname);
17249:                                 } else {
17250:                                     push(@possok,"*.$hoststr");
17251:                                 }
17252:                             }
17253:                             if (@possok) {
17254:                                 foreach my $poss (@possok) {
17255:                                     last if (!$uselink);
17256:                                     foreach my $policy (@policies) {
17257:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
17258:                                             undef($uselink);
17259:                                             last;
17260:                                         }
17261:                                     }
17262:                                 }
17263:                             }
17264:                         }
17265:                     }
17266:                 }
17267:             } elsif ($xframeop ne '') {
17268:                 $uselink = 1;
17269:                 my @policies = split(/\s*,\s*/,$xframeop);
17270:                 if (@policies) {
17271:                     unless (grep(/^deny$/,@policies)) {
17272:                         if ($origin ne '') {
17273:                             if (grep(/^sameorigin$/,@policies)) {
17274:                                 if ($remotehost eq $origin) {
17275:                                     undef($uselink);
17276:                                 }
17277:                             }
17278:                             if ($uselink) {
17279:                                 foreach my $policy (@policies) {
17280:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
17281:                                         my $allowfrom = $1;
17282:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
17283:                                             undef($uselink);
17284:                                             last;
17285:                                         }
17286:                                     }
17287:                                 }
17288:                             }
17289:                         }
17290:                     }
17291:                 }
17292:             }
17293:         }
17294:     }
17295:     if ($nocache) {
17296:         if ($cached) {
17297:             my $devalidate;
17298:             if ($uselink && !$result) {
17299:                 $devalidate = 1;
17300:             } elsif (!$uselink && $result) {
17301:                 $devalidate = 1;
17302:             }
17303:             if ($devalidate) {
17304:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
17305:             }
17306:         }
17307:     } else {
17308:         if ($uselink) {
17309:             $result = 1;
17310:         } else {
17311:             $result = 0;
17312:         }
17313:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
17314:     }
17315:     return $uselink;
17316: }
17317: 
17318: 1;
17319: __END__;
17320: 

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