File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1390: download - view: text, annotated - select for diffs
Tue Oct 18 23:28:00 2022 UTC (19 months, 2 weeks ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Hint to browsers to not autofill password fields.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1390 2022/10/18 23:28:00 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: # Makes a table out of the previous attempts
   30: # Inputs result_from_symbread, user, domain, course_id
   31: # Reads in non-network-related .tab files
   32: 
   33: # POD header:
   34: 
   35: =pod
   36: 
   37: =head1 NAME
   38: 
   39: Apache::loncommon - pile of common routines
   40: 
   41: =head1 SYNOPSIS
   42: 
   43: Common routines for manipulating connections, student answers,
   44:     domains, common Javascript fragments, etc.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: A collection of commonly used subroutines that don't have a natural
   49: home anywhere else. This collection helps remove
   50: redundancy from other modules and increase efficiency of memory usage.
   51: 
   52: =cut 
   53: 
   54: # End of POD header
   55: package Apache::loncommon;
   56: 
   57: use strict;
   58: use Apache::lonnet;
   59: use GDBM_File;
   60: use POSIX qw(strftime mktime);
   61: use Apache::lonmenu();
   62: use Apache::lonenc();
   63: use Apache::lonlocal;
   64: use Apache::lonnavmaps();
   65: use HTML::Entities;
   66: use Apache::lonhtmlcommon();
   67: use Apache::loncoursedata();
   68: use Apache::lontexconvert();
   69: use Apache::lonclonecourse();
   70: use Apache::lonuserutils();
   71: use Apache::lonuserstate();
   72: use Apache::courseclassifier();
   73: use LONCAPA qw(:DEFAULT :match);
   74: use LONCAPA::LWPReq;
   75: use HTTP::Request;
   76: use DateTime::TimeZone;
   77: use DateTime::Locale;
   78: use Encode();
   79: use Text::Aspell;
   80: use Authen::Captcha;
   81: use Captcha::reCAPTCHA;
   82: use JSON::DWIW;
   83: use Crypt::DES;
   84: use DynaLoader; # for Crypt::DES version
   85: use MIME::Lite;
   86: use MIME::Types;
   87: use File::Copy();
   88: use File::Path();
   89: use String::CRC32();
   90: use Short::URL();
   91: 
   92: # ---------------------------------------------- Designs
   93: use vars qw(%defaultdesign);
   94: 
   95: my $readit;
   96: 
   97: 
   98: ##
   99: ## Global Variables
  100: ##
  101: 
  102: 
  103: # ----------------------------------------------- SSI with retries:
  104: #
  105: 
  106: =pod
  107: 
  108: =head1 Server Side include with retries:
  109: 
  110: =over 4
  111: 
  112: =item * &ssi_with_retries(resource,retries form)
  113: 
  114: Performs an ssi with some number of retries.  Retries continue either
  115: until the result is ok or until the retry count supplied by the
  116: caller is exhausted.  
  117: 
  118: Inputs:
  119: 
  120: =over 4
  121: 
  122: resource   - Identifies the resource to insert.
  123: 
  124: retries    - Count of the number of retries allowed.
  125: 
  126: form       - Hash that identifies the rendering options.
  127: 
  128: =back
  129: 
  130: Returns:
  131: 
  132: =over 4
  133: 
  134: content    - The content of the response.  If retries were exhausted this is empty.
  135: 
  136: response   - The response from the last attempt (which may or may not have been successful.
  137: 
  138: =back
  139: 
  140: =back
  141: 
  142: =cut
  143: 
  144: sub ssi_with_retries {
  145:     my ($resource, $retries, %form) = @_;
  146: 
  147: 
  148:     my $ok = 0;			# True if we got a good response.
  149:     my $content;
  150:     my $response;
  151: 
  152:     # Try to get the ssi done. within the retries count:
  153: 
  154:     do {
  155: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  156: 	$ok      = $response->is_success;
  157:         if (!$ok) {
  158:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  159:         }
  160: 	$retries--;
  161:     } while (!$ok && ($retries > 0));
  162: 
  163:     if (!$ok) {
  164: 	$content = '';		# On error return an empty content.
  165:     }
  166:     return ($content, $response);
  167: 
  168: }
  169: 
  170: 
  171: 
  172: # ----------------------------------------------- Filetypes/Languages/Copyright
  173: my %language;
  174: my %supported_language;
  175: my %supported_codes;
  176: my %latex_language;		# For choosing hyphenation in <transl..>
  177: my %latex_language_bykey;	# for choosing hyphenation from metadata
  178: my %cprtag;
  179: my %scprtag;
  180: my %fe; my %fd; my %fm;
  181: my %category_extensions;
  182: 
  183: # ---------------------------------------------- Thesaurus variables
  184: #
  185: # %Keywords:
  186: #      A hash used by &keyword to determine if a word is considered a keyword.
  187: # $thesaurus_db_file 
  188: #      Scalar containing the full path to the thesaurus database.
  189: 
  190: my %Keywords;
  191: my $thesaurus_db_file;
  192: 
  193: #
  194: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  195: # thesaurus.tab, and filecategories.tab.
  196: #
  197: BEGIN {
  198:     # Variable initialization
  199:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  200:     #
  201:     unless ($readit) {
  202: # ------------------------------------------------------------------- languages
  203:     {
  204:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  205:                                    '/language.tab';
  206:         if ( open(my $fh,'<',$langtabfile) ) {
  207:             while (my $line = <$fh>) {
  208:                 next if ($line=~/^\#/);
  209:                 chomp($line);
  210:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  211:                 $language{$key}=$val.' - '.$enc;
  212:                 if ($sup) {
  213:                     $supported_language{$key}=$sup;
  214: 		    $supported_codes{$key}   = $code;
  215:                 }
  216: 		if ($latex) {
  217: 		    $latex_language_bykey{$key} = $latex;
  218: 		    $latex_language{$code} = $latex;
  219: 		}
  220:             }
  221:             close($fh);
  222:         }
  223:     }
  224: # ------------------------------------------------------------------ copyrights
  225:     {
  226:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  227:                                   '/copyright.tab';
  228:         if ( open (my $fh,'<',$copyrightfile) ) {
  229:             while (my $line = <$fh>) {
  230:                 next if ($line=~/^\#/);
  231:                 chomp($line);
  232:                 my ($key,$val)=(split(/\s+/,$line,2));
  233:                 $cprtag{$key}=$val;
  234:             }
  235:             close($fh);
  236:         }
  237:     }
  238: # ----------------------------------------------------------- source copyrights
  239:     {
  240:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  241:                                   '/source_copyright.tab';
  242:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
  243:             while (my $line = <$fh>) {
  244:                 next if ($line =~ /^\#/);
  245:                 chomp($line);
  246:                 my ($key,$val)=(split(/\s+/,$line,2));
  247:                 $scprtag{$key}=$val;
  248:             }
  249:             close($fh);
  250:         }
  251:     }
  252: 
  253: # -------------------------------------------------------------- default domain designs
  254:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  255:     my $designfile = $designdir.'/default.tab';
  256:     if ( open (my $fh,'<',$designfile) ) {
  257:         while (my $line = <$fh>) {
  258:             next if ($line =~ /^\#/);
  259:             chomp($line);
  260:             my ($key,$val)=(split(/\=/,$line));
  261:             if ($val) { $defaultdesign{$key}=$val; }
  262:         }
  263:         close($fh);
  264:     }
  265: 
  266: # ------------------------------------------------------------- file categories
  267:     {
  268:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  269:                                   '/filecategories.tab';
  270:         if ( open (my $fh,'<',$categoryfile) ) {
  271: 	    while (my $line = <$fh>) {
  272: 		next if ($line =~ /^\#/);
  273: 		chomp($line);
  274:                 my ($extension,$category)=(split(/\s+/,$line,2));
  275:                 push(@{$category_extensions{lc($category)}},$extension);
  276:             }
  277:             close($fh);
  278:         }
  279: 
  280:     }
  281: # ------------------------------------------------------------------ file types
  282:     {
  283:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  284:                '/filetypes.tab';
  285:         if ( open (my $fh,'<',$typesfile) ) {
  286:             while (my $line = <$fh>) {
  287: 		next if ($line =~ /^\#/);
  288: 		chomp($line);
  289:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  290:                 if ($descr ne '') {
  291:                     $fe{$ending}=lc($emb);
  292:                     $fd{$ending}=$descr;
  293:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  294:                 }
  295:             }
  296:             close($fh);
  297:         }
  298:     }
  299:     &Apache::lonnet::logthis(
  300:              "<span style='color:yellow;'>INFO: Read file types</span>");
  301:     $readit=1;
  302:     }  # end of unless($readit) 
  303:     
  304: }
  305: 
  306: ###############################################################
  307: ##           HTML and Javascript Helper Functions            ##
  308: ###############################################################
  309: 
  310: =pod 
  311: 
  312: =head1 HTML and Javascript Functions
  313: 
  314: =over 4
  315: 
  316: =item * &browser_and_searcher_javascript()
  317: 
  318: X<browsing, javascript>X<searching, javascript>Returns a string
  319: containing javascript with two functions, C<openbrowser> and
  320: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  321: tags.
  322: 
  323: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  324: 
  325: inputs: formname, elementname, only, omit
  326: 
  327: formname and elementname indicate the name of the html form and name of
  328: the element that the results of the browsing selection are to be placed in. 
  329: 
  330: Specifying 'only' will restrict the browser to displaying only files
  331: with the given extension.  Can be a comma separated list.
  332: 
  333: Specifying 'omit' will restrict the browser to NOT displaying files
  334: with the given extension.  Can be a comma separated list.
  335: 
  336: =item * &opensearcher(formname,elementname) [javascript]
  337: 
  338: Inputs: formname, elementname
  339: 
  340: formname and elementname specify the name of the html form and the name
  341: of the element the selection from the search results will be placed in.
  342: 
  343: =cut
  344: 
  345: sub browser_and_searcher_javascript {
  346:     my ($mode)=@_;
  347:     if (!defined($mode)) { $mode='edit'; }
  348:     my $resurl=&escape_single(&lastresurl());
  349:     return <<END;
  350: // <!-- BEGIN LON-CAPA Internal
  351:     var editbrowser = null;
  352:     function openbrowser(formname,elementname,only,omit,titleelement) {
  353:         var url = '$resurl/?';
  354:         if (editbrowser == null) {
  355:             url += 'launch=1&';
  356:         }
  357:         url += 'catalogmode=interactive&';
  358:         url += 'mode=$mode&';
  359:         url += 'inhibitmenu=yes&';
  360:         url += 'form=' + formname + '&';
  361:         if (only != null) {
  362:             url += 'only=' + only + '&';
  363:         } else {
  364:             url += 'only=&';
  365: 	}
  366:         if (omit != null) {
  367:             url += 'omit=' + omit + '&';
  368:         } else {
  369:             url += 'omit=&';
  370: 	}
  371:         if (titleelement != null) {
  372:             url += 'titleelement=' + titleelement + '&';
  373:         } else {
  374: 	    url += 'titleelement=&';
  375: 	}
  376:         url += 'element=' + elementname + '';
  377:         var title = 'Browser';
  378:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  379:         options += ',width=700,height=600';
  380:         editbrowser = open(url,title,options,'1');
  381:         editbrowser.focus();
  382:     }
  383:     var editsearcher;
  384:     function opensearcher(formname,elementname,titleelement) {
  385:         var url = '/adm/searchcat?';
  386:         if (editsearcher == null) {
  387:             url += 'launch=1&';
  388:         }
  389:         url += 'catalogmode=interactive&';
  390:         url += 'mode=$mode&';
  391:         url += 'form=' + formname + '&';
  392:         if (titleelement != null) {
  393:             url += 'titleelement=' + titleelement + '&';
  394:         } else {
  395: 	    url += 'titleelement=&';
  396: 	}
  397:         url += 'element=' + elementname + '';
  398:         var title = 'Search';
  399:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  400:         options += ',width=700,height=600';
  401:         editsearcher = open(url,title,options,'1');
  402:         editsearcher.focus();
  403:     }
  404: // END LON-CAPA Internal -->
  405: END
  406: }
  407: 
  408: sub lastresurl {
  409:     if ($env{'environment.lastresurl'}) {
  410: 	return $env{'environment.lastresurl'}
  411:     } else {
  412: 	return '/res';
  413:     }
  414: }
  415: 
  416: sub storeresurl {
  417:     my $resurl=&Apache::lonnet::clutter(shift);
  418:     unless ($resurl=~/^\/res/) { return 0; }
  419:     $resurl=~s/\/$//;
  420:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  421:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  422:     return 1;
  423: }
  424: 
  425: sub studentbrowser_javascript {
  426:    unless (
  427:             (($env{'request.course.id'}) && 
  428:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  429: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  430: 					  '/'.$env{'request.course.sec'})
  431: 	      ))
  432:          || ($env{'request.role'}=~/^(au|dc|su)/)
  433:           ) { return ''; }  
  434:    return (<<'ENDSTDBRW');
  435: <script type="text/javascript" language="Javascript">
  436: // <![CDATA[
  437:     var stdeditbrowser;
  438:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv) {
  439:         var url = '/adm/pickstudent?';
  440:         var filter;
  441: 	if (!ignorefilter) {
  442: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  443: 	}
  444:         if (filter != null) {
  445:            if (filter != '') {
  446:                url += 'filter='+filter+'&';
  447: 	   }
  448:         }
  449:         url += 'form=' + formname + '&unameelement='+uname+
  450:                                     '&udomelement='+udom+
  451:                                     '&clicker='+clicker;
  452: 	if (roleflag) { url+="&roles=1"; }
  453:         if (courseadv == 'condition') {
  454:             if (document.getElementById('courseadv')) {
  455:                 courseadv = document.getElementById('courseadv').value;
  456:             }
  457:         }
  458:         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
  459:         var title = 'Student_Browser';
  460:         var options = 'scrollbars=1,resizable=1,menubar=0';
  461:         options += ',width=700,height=600';
  462:         stdeditbrowser = open(url,title,options,'1');
  463:         stdeditbrowser.focus();
  464:     }
  465: // ]]>
  466: </script>
  467: ENDSTDBRW
  468: }
  469: 
  470: sub resourcebrowser_javascript {
  471:    unless ($env{'request.course.id'}) { return ''; }
  472:    return (<<'ENDRESBRW');
  473: <script type="text/javascript" language="Javascript">
  474: // <![CDATA[
  475:     var reseditbrowser;
  476:     function openresbrowser(formname,reslink) {
  477:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  478:         var title = 'Resource_Browser';
  479:         var options = 'scrollbars=1,resizable=1,menubar=0';
  480:         options += ',width=700,height=500';
  481:         reseditbrowser = open(url,title,options,'1');
  482:         reseditbrowser.focus();
  483:     }
  484: // ]]>
  485: </script>
  486: ENDRESBRW
  487: }
  488: 
  489: sub selectstudent_link {
  490:    my ($form,$unameele,$udomele,$courseadv,$clickerid)=@_;
  491:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  492:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  493:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  494:    if ($env{'request.course.id'}) {  
  495:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  496: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  497: 					'/'.$env{'request.course.sec'})) {
  498: 	   return '';
  499:        }
  500:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  501:        if ($courseadv eq 'only') {
  502:            $callargs .= ",'',1,'$courseadv'";
  503:        } elsif ($courseadv eq 'none') {
  504:            $callargs .= ",'','','$courseadv'";
  505:        } elsif ($courseadv eq 'condition') {
  506:            $callargs .= ",'','','$courseadv'";
  507:        }
  508:        return '<span class="LC_nobreak">'.
  509:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  510:               &mt('Select User').'</a></span>';
  511:    }
  512:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  513:        $callargs .= ",'',1"; 
  514:        return '<span class="LC_nobreak">'.
  515:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  516:               &mt('Select User').'</a></span>';
  517:    }
  518:    return '';
  519: }
  520: 
  521: sub selectresource_link {
  522:    my ($form,$reslink,$arg)=@_;
  523:    
  524:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  525:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  526:    unless ($env{'request.course.id'}) { return $arg; }
  527:    return '<span class="LC_nobreak">'.
  528:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  529:               $arg.'</a></span>';
  530: }
  531: 
  532: 
  533: 
  534: sub authorbrowser_javascript {
  535:     return <<"ENDAUTHORBRW";
  536: <script type="text/javascript" language="JavaScript">
  537: // <![CDATA[
  538: var stdeditbrowser;
  539: 
  540: function openauthorbrowser(formname,udom) {
  541:     var url = '/adm/pickauthor?';
  542:     url += 'form='+formname+'&roledom='+udom;
  543:     var title = 'Author_Browser';
  544:     var options = 'scrollbars=1,resizable=1,menubar=0';
  545:     options += ',width=700,height=600';
  546:     stdeditbrowser = open(url,title,options,'1');
  547:     stdeditbrowser.focus();
  548: }
  549: 
  550: // ]]>
  551: </script>
  552: ENDAUTHORBRW
  553: }
  554: 
  555: sub coursebrowser_javascript {
  556:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
  557:         $credits_element,$instcode) = @_;
  558:     my $wintitle = 'Course_Browser';
  559:     if ($crstype eq 'Community') {
  560:         $wintitle = 'Community_Browser';
  561:     }
  562:     my $id_functions = &javascript_index_functions();
  563:     my $output = '
  564: <script type="text/javascript" language="JavaScript">
  565: // <![CDATA[
  566:     var stdeditbrowser;'."\n";
  567: 
  568:     $output .= <<"ENDSTDBRW";
  569:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  570:         var url = '/adm/pickcourse?';
  571:         var formid = getFormIdByName(formname);
  572:         var domainfilter = getDomainFromSelectbox(formname,udom);
  573:         if (domainfilter != null) {
  574:            if (domainfilter != '') {
  575:                url += 'domainfilter='+domainfilter+'&';
  576: 	   }
  577:         }
  578:         url += 'form=' + formname + '&cnumelement='+uname+
  579: 	                            '&cdomelement='+udom+
  580:                                     '&cnameelement='+desc;
  581:         if (extra_element !=null && extra_element != '') {
  582:             if (formname == 'rolechoice' || formname == 'studentform') {
  583:                 url += '&roleelement='+extra_element;
  584:                 if (domainfilter == null || domainfilter == '') {
  585:                     url += '&domainfilter='+extra_element;
  586:                 }
  587:             }
  588:             else {
  589:                 if (formname == 'portform') {
  590:                     url += '&setroles='+extra_element;
  591:                 } else {
  592:                     if (formname == 'rules') {
  593:                         url += '&fixeddom='+extra_element; 
  594:                     }
  595:                 }
  596:             }     
  597:         }
  598:         if (type != null && type != '') {
  599:             url += '&type='+type;
  600:         }
  601:         if (type_elem != null && type_elem != '') {
  602:             url += '&typeelement='+type_elem;
  603:         }
  604:         if (formname == 'ccrs') {
  605:             var ownername = document.forms[formid].ccuname.value;
  606:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  607:             url += '&cloner='+ownername+':'+ownerdom;
  608:             if (type == 'Course') {
  609:                 url += '&crscode='+document.forms[formid].crscode.value;
  610:             }
  611:         }
  612:         if (formname == 'requestcrs') {
  613:             url += '&crsdom=$domainfilter&crscode=$instcode';
  614:         }
  615:         if (multflag !=null && multflag != '') {
  616:             url += '&multiple='+multflag;
  617:         }
  618:         var title = '$wintitle';
  619:         var options = 'scrollbars=1,resizable=1,menubar=0';
  620:         options += ',width=700,height=600';
  621:         stdeditbrowser = open(url,title,options,'1');
  622:         stdeditbrowser.focus();
  623:     }
  624: $id_functions
  625: ENDSTDBRW
  626:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
  627:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
  628:                                       $credits_element);
  629:     }
  630:     $output .= '
  631: // ]]>
  632: </script>';
  633:     return $output;
  634: }
  635: 
  636: sub javascript_index_functions {
  637:     return <<"ENDJS";
  638: 
  639: function getFormIdByName(formname) {
  640:     for (var i=0;i<document.forms.length;i++) {
  641:         if (document.forms[i].name == formname) {
  642:             return i;
  643:         }
  644:     }
  645:     return -1;
  646: }
  647: 
  648: function getIndexByName(formid,item) {
  649:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  650:         if (document.forms[formid].elements[i].name == item) {
  651:             return i;
  652:         }
  653:     }
  654:     return -1;
  655: }
  656: 
  657: function getDomainFromSelectbox(formname,udom) {
  658:     var userdom;
  659:     var formid = getFormIdByName(formname);
  660:     if (formid > -1) {
  661:         var domid = getIndexByName(formid,udom);
  662:         if (domid > -1) {
  663:             if (document.forms[formid].elements[domid].type == 'select-one') {
  664:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  665:             }
  666:             if (document.forms[formid].elements[domid].type == 'hidden') {
  667:                 userdom=document.forms[formid].elements[domid].value;
  668:             }
  669:         }
  670:     }
  671:     return userdom;
  672: }
  673: 
  674: ENDJS
  675: 
  676: }
  677: 
  678: sub javascript_array_indexof {
  679:     return <<ENDJS;
  680: <script type="text/javascript" language="JavaScript">
  681: // <![CDATA[
  682: 
  683: if (!Array.prototype.indexOf) {
  684:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  685:         "use strict";
  686:         if (this === void 0 || this === null) {
  687:             throw new TypeError();
  688:         }
  689:         var t = Object(this);
  690:         var len = t.length >>> 0;
  691:         if (len === 0) {
  692:             return -1;
  693:         }
  694:         var n = 0;
  695:         if (arguments.length > 0) {
  696:             n = Number(arguments[1]);
  697:             if (n !== n) { // shortcut for verifying if it is NaN
  698:                 n = 0;
  699:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  700:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  701:             }
  702:         }
  703:         if (n >= len) {
  704:             return -1;
  705:         }
  706:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  707:         for (; k < len; k++) {
  708:             if (k in t && t[k] === searchElement) {
  709:                 return k;
  710:             }
  711:         }
  712:         return -1;
  713:     }
  714: }
  715: 
  716: // ]]>
  717: </script>
  718: 
  719: ENDJS
  720: 
  721: }
  722: 
  723: sub userbrowser_javascript {
  724:     my $id_functions = &javascript_index_functions();
  725:     return <<"ENDUSERBRW";
  726: 
  727: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  728:     var url = '/adm/pickuser?';
  729:     var userdom = getDomainFromSelectbox(formname,udom);
  730:     if (userdom != null) {
  731:        if (userdom != '') {
  732:            url += 'srchdom='+userdom+'&';
  733:        }
  734:     }
  735:     url += 'form=' + formname + '&unameelement='+uname+
  736:                                 '&udomelement='+udom+
  737:                                 '&ulastelement='+ulast+
  738:                                 '&ufirstelement='+ufirst+
  739:                                 '&uemailelement='+uemail+
  740:                                 '&hideudomelement='+hideudom+
  741:                                 '&coursedom='+crsdom;
  742:     if ((caller != null) && (caller != undefined)) {
  743:         url += '&caller='+caller;
  744:     }
  745:     var title = 'User_Browser';
  746:     var options = 'scrollbars=1,resizable=1,menubar=0';
  747:     options += ',width=700,height=600';
  748:     var stdeditbrowser = open(url,title,options,'1');
  749:     stdeditbrowser.focus();
  750: }
  751: 
  752: function fix_domain (formname,udom,origdom,uname) {
  753:     var formid = getFormIdByName(formname);
  754:     if (formid > -1) {
  755:         var unameid = getIndexByName(formid,uname);
  756:         var domid = getIndexByName(formid,udom);
  757:         var hidedomid = getIndexByName(formid,origdom);
  758:         if (hidedomid > -1) {
  759:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  760:             var unameval = document.forms[formid].elements[unameid].value;
  761:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  762:                 if (domid > -1) {
  763:                     var slct = document.forms[formid].elements[domid];
  764:                     if (slct.type == 'select-one') {
  765:                         var i;
  766:                         for (i=0;i<slct.length;i++) {
  767:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  768:                         }
  769:                     }
  770:                     if (slct.type == 'hidden') {
  771:                         slct.value = fixeddom;
  772:                     }
  773:                 }
  774:             }
  775:         }
  776:     }
  777:     return;
  778: }
  779: 
  780: $id_functions
  781: ENDUSERBRW
  782: }
  783: 
  784: sub setsec_javascript {
  785:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
  786:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  787:         $communityrolestr);
  788:     if ($role_element ne '') {
  789:         my @allroles = ('st','ta','ep','in','ad');
  790:         foreach my $crstype ('Course','Community') {
  791:             if ($crstype eq 'Community') {
  792:                 foreach my $role (@allroles) {
  793:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  794:                 }
  795:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  796:             } else {
  797:                 foreach my $role (@allroles) {
  798:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  799:                 }
  800:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  801:             }
  802:         }
  803:         $rolestr = '"'.join('","',@allroles).'"';
  804:         $courserolestr = '"'.join('","',@courserolenames).'"';
  805:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  806:     }
  807:     my $setsections = qq|
  808: function setSect(sectionlist) {
  809:     var sectionsArray = new Array();
  810:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  811:         sectionsArray = sectionlist.split(",");
  812:     }
  813:     var numSections = sectionsArray.length;
  814:     document.$formname.$sec_element.length = 0;
  815:     if (numSections == 0) {
  816:         document.$formname.$sec_element.multiple=false;
  817:         document.$formname.$sec_element.size=1;
  818:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  819:     } else {
  820:         if (numSections == 1) {
  821:             document.$formname.$sec_element.multiple=false;
  822:             document.$formname.$sec_element.size=1;
  823:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  824:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  825:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  826:         } else {
  827:             for (var i=0; i<numSections; i++) {
  828:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  829:             }
  830:             document.$formname.$sec_element.multiple=true
  831:             if (numSections < 3) {
  832:                 document.$formname.$sec_element.size=numSections;
  833:             } else {
  834:                 document.$formname.$sec_element.size=3;
  835:             }
  836:             document.$formname.$sec_element.options[0].selected = false
  837:         }
  838:     }
  839: }
  840: 
  841: function setRole(crstype) {
  842: |;
  843:     if ($role_element eq '') {
  844:         $setsections .= '    return;
  845: }
  846: ';
  847:     } else {
  848:         $setsections .= qq|
  849:     var elementLength = document.$formname.$role_element.length;
  850:     var allroles = Array($rolestr);
  851:     var courserolenames = Array($courserolestr);
  852:     var communityrolenames = Array($communityrolestr);
  853:     if (elementLength != undefined) {
  854:         if (document.$formname.$role_element.options[5].value == 'cc') {
  855:             if (crstype == 'Course') {
  856:                 return;
  857:             } else {
  858:                 allroles[5] = 'co';
  859:                 for (var i=0; i<6; i++) {
  860:                     document.$formname.$role_element.options[i].value = allroles[i];
  861:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  862:                 }
  863:             }
  864:         } else {
  865:             if (crstype == 'Community') {
  866:                 return;
  867:             } else {
  868:                 allroles[5] = 'cc';
  869:                 for (var i=0; i<6; i++) {
  870:                     document.$formname.$role_element.options[i].value = allroles[i];
  871:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  872:                 }
  873:             }
  874:         }
  875:     }
  876:     return;
  877: }
  878: |;
  879:     }
  880:     if ($credits_element) {
  881:         $setsections .= qq|
  882: function setCredits(defaultcredits) {
  883:     document.$formname.$credits_element.value = defaultcredits;
  884:     return;
  885: }
  886: |;
  887:     }
  888:     return $setsections;
  889: }
  890: 
  891: sub selectcourse_link {
  892:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  893:        $typeelement) = @_;
  894:    my $type = $selecttype;
  895:    my $linktext = &mt('Select Course');
  896:    if ($selecttype eq 'Community') {
  897:        $linktext = &mt('Select Community');
  898:    } elsif ($selecttype eq 'Placement') {
  899:        $linktext = &mt('Select Placement Test'); 
  900:    } elsif ($selecttype eq 'Course/Community') {
  901:        $linktext = &mt('Select Course/Community');
  902:        $type = '';
  903:    } elsif ($selecttype eq 'Select') {
  904:        $linktext = &mt('Select');
  905:        $type = '';
  906:    }
  907:    return '<span class="LC_nobreak">'
  908:          ."<a href='"
  909:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  910:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  911:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  912:          ."'>".$linktext.'</a>'
  913:          .'</span>';
  914: }
  915: 
  916: sub selectauthor_link {
  917:    my ($form,$udom)=@_;
  918:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  919:           &mt('Select Author').'</a>';
  920: }
  921: 
  922: sub selectuser_link {
  923:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  924:         $coursedom,$linktext,$caller) = @_;
  925:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  926:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  927:            ');">'.$linktext.'</a>';
  928: }
  929: 
  930: sub check_uncheck_jscript {
  931:     my $jscript = <<"ENDSCRT";
  932: function checkAll(field) {
  933:     if (field.length > 0) {
  934:         for (i = 0; i < field.length; i++) {
  935:             if (!field[i].disabled) { 
  936:                 field[i].checked = true;
  937:             }
  938:         }
  939:     } else {
  940:         if (!field.disabled) { 
  941:             field.checked = true;
  942:         }
  943:     }
  944: }
  945:  
  946: function uncheckAll(field) {
  947:     if (field.length > 0) {
  948:         for (i = 0; i < field.length; i++) {
  949:             field[i].checked = false ;
  950:         }
  951:     } else {
  952:         field.checked = false ;
  953:     }
  954: }
  955: ENDSCRT
  956:     return $jscript;
  957: }
  958: 
  959: sub select_timezone {
  960:    my ($name,$selected,$onchange,$includeempty,$id,$disabled)=@_;
  961:    my $output='<select name="'.$name.'" '.$id.$onchange.$disabled.'>'."\n";
  962:    if ($includeempty) {
  963:        $output .= '<option value=""';
  964:        if (($selected eq '') || ($selected eq 'local')) {
  965:            $output .= ' selected="selected" ';
  966:        }
  967:        $output .= '> </option>';
  968:    }
  969:    my @timezones = DateTime::TimeZone->all_names;
  970:    foreach my $tzone (@timezones) {
  971:        $output.= '<option value="'.$tzone.'"';
  972:        if ($tzone eq $selected) {
  973:            $output.=' selected="selected"';
  974:        }
  975:        $output.=">$tzone</option>\n";
  976:    }
  977:    $output.="</select>";
  978:    return $output;
  979: }
  980: 
  981: sub select_datelocale {
  982:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  983:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  984:     if ($includeempty) {
  985:         $output .= '<option value=""';
  986:         if ($selected eq '') {
  987:             $output .= ' selected="selected" ';
  988:         }
  989:         $output .= '> </option>';
  990:     }
  991:     my @languages = &Apache::lonlocal::preferred_languages();
  992:     my (@possibles,%locale_names);
  993:     my @locales = DateTime::Locale->ids();
  994:     foreach my $id (@locales) {
  995:         if ($id ne '') {
  996:             my ($en_terr,$native_terr);
  997:             my $loc = DateTime::Locale->load($id);
  998:             if (ref($loc)) {
  999:                 $en_terr = $loc->name();
 1000:                 $native_terr = $loc->native_name();
 1001:                 if (grep(/^en$/,@languages) || !@languages) {
 1002:                     if ($en_terr ne '') {
 1003:                         $locale_names{$id} = '('.$en_terr.')';
 1004:                     } elsif ($native_terr ne '') {
 1005:                         $locale_names{$id} = $native_terr;
 1006:                     }
 1007:                 } else {
 1008:                     if ($native_terr ne '') {
 1009:                         $locale_names{$id} = $native_terr.' ';
 1010:                     } elsif ($en_terr ne '') {
 1011:                         $locale_names{$id} = '('.$en_terr.')';
 1012:                     }
 1013:                 }
 1014:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
 1015:                 push(@possibles,$id);
 1016:             } 
 1017:         }
 1018:     }
 1019:     foreach my $item (sort(@possibles)) {
 1020:         $output.= '<option value="'.$item.'"';
 1021:         if ($item eq $selected) {
 1022:             $output.=' selected="selected"';
 1023:         }
 1024:         $output.=">$item";
 1025:         if ($locale_names{$item} ne '') {
 1026:             $output.='  '.$locale_names{$item};
 1027:         }
 1028:         $output.="</option>\n";
 1029:     }
 1030:     $output.="</select>";
 1031:     return $output;
 1032: }
 1033: 
 1034: sub select_language {
 1035:     my ($name,$selected,$includeempty,$noedit) = @_;
 1036:     my %langchoices;
 1037:     if ($includeempty) {
 1038:         %langchoices = ('' => 'No language preference');
 1039:     }
 1040:     foreach my $id (&languageids()) {
 1041:         my $code = &supportedlanguagecode($id);
 1042:         if ($code) {
 1043:             $langchoices{$code} = &plainlanguagedescription($id);
 1044:         }
 1045:     }
 1046:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
 1047:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
 1048: }
 1049: 
 1050: =pod
 1051: 
 1052: 
 1053: =item * &list_languages()
 1054: 
 1055: Returns an array reference that is suitable for use in language prompters.
 1056: Each array element is itself a two element array.  The first element
 1057: is the language code.  The second element a descsriptiuon of the 
 1058: language itself.  This is suitable for use in e.g.
 1059: &Apache::edit::select_arg (once dereferenced that is).
 1060: 
 1061: =cut 
 1062: 
 1063: sub list_languages {
 1064:     my @lang_choices;
 1065: 
 1066:     foreach my $id (&languageids()) {
 1067: 	my $code = &supportedlanguagecode($id);
 1068: 	if ($code) {
 1069: 	    my $selector    = $supported_codes{$id};
 1070: 	    my $description = &plainlanguagedescription($id);
 1071: 	    push(@lang_choices, [$selector, $description]);
 1072: 	}
 1073:     }
 1074:     return \@lang_choices;
 1075: }
 1076: 
 1077: =pod
 1078: 
 1079: =item * &linked_select_forms(...)
 1080: 
 1081: linked_select_forms returns a string containing a <script></script> block
 1082: and html for two <select> menus.  The select menus will be linked in that
 1083: changing the value of the first menu will result in new values being placed
 1084: in the second menu.  The values in the select menu will appear in alphabetical
 1085: order unless a defined order is provided.
 1086: 
 1087: linked_select_forms takes the following ordered inputs:
 1088: 
 1089: =over 4
 1090: 
 1091: =item * $formname, the name of the <form> tag
 1092: 
 1093: =item * $middletext, the text which appears between the <select> tags
 1094: 
 1095: =item * $firstdefault, the default value for the first menu
 1096: 
 1097: =item * $firstselectname, the name of the first <select> tag
 1098: 
 1099: =item * $secondselectname, the name of the second <select> tag
 1100: 
 1101: =item * $hashref, a reference to a hash containing the data for the menus.
 1102: 
 1103: =item * $menuorder, the order of values in the first menu
 1104: 
 1105: =item * $onchangefirst, additional javascript call to execute for an onchange
 1106:         event for the first <select> tag
 1107: 
 1108: =item * $onchangesecond, additional javascript call to execute for an onchange
 1109:         event for the second <select> tag
 1110: 
 1111: =item * $suffix, to differentiate separate uses of select2data javascript
 1112:         objects in a page.
 1113: 
 1114: =back 
 1115: 
 1116: Below is an example of such a hash.  Only the 'text', 'default', and 
 1117: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1118: values for the first select menu.  The text that coincides with the 
 1119: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1120: and text for the second menu are given in the hash pointed to by 
 1121: $menu{$choice1}->{'select2'}.  
 1122: 
 1123:  my %menu = ( A1 => { text =>"Choice A1" ,
 1124:                        default => "B3",
 1125:                        select2 => { 
 1126:                            B1 => "Choice B1",
 1127:                            B2 => "Choice B2",
 1128:                            B3 => "Choice B3",
 1129:                            B4 => "Choice B4"
 1130:                            },
 1131:                        order => ['B4','B3','B1','B2'],
 1132:                    },
 1133:                A2 => { text =>"Choice A2" ,
 1134:                        default => "C2",
 1135:                        select2 => { 
 1136:                            C1 => "Choice C1",
 1137:                            C2 => "Choice C2",
 1138:                            C3 => "Choice C3"
 1139:                            },
 1140:                        order => ['C2','C1','C3'],
 1141:                    },
 1142:                A3 => { text =>"Choice A3" ,
 1143:                        default => "D6",
 1144:                        select2 => { 
 1145:                            D1 => "Choice D1",
 1146:                            D2 => "Choice D2",
 1147:                            D3 => "Choice D3",
 1148:                            D4 => "Choice D4",
 1149:                            D5 => "Choice D5",
 1150:                            D6 => "Choice D6",
 1151:                            D7 => "Choice D7"
 1152:                            },
 1153:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1154:                    }
 1155:                );
 1156: 
 1157: =cut
 1158: 
 1159: sub linked_select_forms {
 1160:     my ($formname,
 1161:         $middletext,
 1162:         $firstdefault,
 1163:         $firstselectname,
 1164:         $secondselectname, 
 1165:         $hashref,
 1166:         $menuorder,
 1167:         $onchangefirst,
 1168:         $onchangesecond,
 1169:         $suffix
 1170:         ) = @_;
 1171:     my $second = "document.$formname.$secondselectname";
 1172:     my $first = "document.$formname.$firstselectname";
 1173:     # output the javascript to do the changing
 1174:     my $result = '';
 1175:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1176:     $result.="// <![CDATA[\n";
 1177:     $result.="var select2data${suffix} = new Object();\n";
 1178:     $" = '","';
 1179:     my $debug = '';
 1180:     foreach my $s1 (sort(keys(%$hashref))) {
 1181:         $result.="select2data${suffix}['d_$s1'] = new Object();\n";        
 1182:         $result.="select2data${suffix}['d_$s1'].def = new String('".
 1183:             $hashref->{$s1}->{'default'}."');\n";
 1184:         $result.="select2data${suffix}['d_$s1'].values = new Array(";
 1185:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1186:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1187:             @s2values = @{$hashref->{$s1}->{'order'}};
 1188:         }
 1189:         $result.="\"@s2values\");\n";
 1190:         $result.="select2data${suffix}['d_$s1'].texts = new Array(";        
 1191:         my @s2texts;
 1192:         foreach my $value (@s2values) {
 1193:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
 1194:         }
 1195:         $result.="\"@s2texts\");\n";
 1196:     }
 1197:     $"=' ';
 1198:     $result.= <<"END";
 1199: 
 1200: function select1${suffix}_changed() {
 1201:     // Determine new choice
 1202:     var newvalue = "d_" + $first.options[$first.selectedIndex].value;
 1203:     // update select2
 1204:     var values     = select2data${suffix}[newvalue].values;
 1205:     var texts      = select2data${suffix}[newvalue].texts;
 1206:     var select2def = select2data${suffix}[newvalue].def;
 1207:     var i;
 1208:     // out with the old
 1209:     $second.options.length = 0;
 1210:     // in with the new
 1211:     for (i=0;i<values.length; i++) {
 1212:         $second.options[i] = new Option(values[i]);
 1213:         $second.options[i].value = values[i];
 1214:         $second.options[i].text = texts[i];
 1215:         if (values[i] == select2def) {
 1216:             $second.options[i].selected = true;
 1217:         }
 1218:     }
 1219: }
 1220: // ]]>
 1221: </script>
 1222: END
 1223:     # output the initial values for the selection lists
 1224:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
 1225:     my @order = sort(keys(%{$hashref}));
 1226:     if (ref($menuorder) eq 'ARRAY') {
 1227:         @order = @{$menuorder};
 1228:     }
 1229:     foreach my $value (@order) {
 1230:         $result.="    <option value=\"$value\" ";
 1231:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1232:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1233:     }
 1234:     $result .= "</select>\n";
 1235:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1236:     $result .= $middletext;
 1237:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
 1238:     if ($onchangesecond) {
 1239:         $result .= ' onchange="'.$onchangesecond.'"';
 1240:     }
 1241:     $result .= ">\n";
 1242:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1243:     
 1244:     my @secondorder = sort(keys(%select2));
 1245:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1246:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1247:     }
 1248:     foreach my $value (@secondorder) {
 1249:         $result.="    <option value=\"$value\" ";        
 1250:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1251:         $result.=">".&mt($select2{$value})."</option>\n";
 1252:     }
 1253:     $result .= "</select>\n";
 1254:     #    return $debug;
 1255:     return $result;
 1256: }   #  end of sub linked_select_forms {
 1257: 
 1258: =pod
 1259: 
 1260: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid,$links_target)
 1261: 
 1262: Returns a string corresponding to an HTML link to the given help
 1263: $topic, where $topic corresponds to the name of a .tex file in
 1264: /home/httpd/html/adm/help/tex, with underscores replaced by
 1265: spaces. 
 1266: 
 1267: $text will optionally be linked to the same topic, allowing you to
 1268: link text in addition to the graphic. If you do not want to link
 1269: text, but wish to specify one of the later parameters, pass an
 1270: empty string. 
 1271: 
 1272: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1273: the link will not open a new window. If false, the link will open
 1274: a new window using Javascript. (Default is false.) 
 1275: 
 1276: $width and $height are optional numerical parameters that will
 1277: override the width and height of the popped up window, which may
 1278: be useful for certain help topics with big pictures included.
 1279: 
 1280: $imgid is the id of the img tag used for the help icon. This may be
 1281: used in a javascript call to switch the image src.  See 
 1282: lonhtmlcommon::htmlareaselectactive() for an example.
 1283: 
 1284: $links_target will optionally be set to a target (_top, _parent or _self).
 1285: 
 1286: =cut
 1287: 
 1288: sub help_open_topic {
 1289:     my ($topic, $text, $stayOnPage, $width, $height, $imgid, $links_target) = @_;
 1290:     $text = "" if (not defined $text);
 1291:     $stayOnPage = 0 if (not defined $stayOnPage);
 1292:     $width = 500 if (not defined $width);
 1293:     $height = 400 if (not defined $height);
 1294:     my $filename = $topic;
 1295:     $filename =~ s/ /_/g;
 1296: 
 1297:     my $template = "";
 1298:     my $link;
 1299:     
 1300:     $topic=~s/\W/\_/g;
 1301: 
 1302:     if (!$stayOnPage) {
 1303: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1304:     } elsif ($stayOnPage eq 'popup') {
 1305:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1306:     } else {
 1307: 	$link = "/adm/help/${filename}.hlp";
 1308:     }
 1309: 
 1310:     # Add the text
 1311:     my $target = ' target="_top"';
 1312:     if ($links_target) {
 1313:         $target = ' target="'.$links_target.'"';
 1314:     } elsif ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
 1315:              (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
 1316:         $target = '';
 1317:     }
 1318:     if ($text ne "") {
 1319: 	$template.='<span class="LC_help_open_topic">'
 1320:                   .'<a'.$target.' href="'.$link.'">'
 1321:                   .$text.'</a>';
 1322:     }
 1323: 
 1324:     # (Always) Add the graphic
 1325:     my $title = &mt('Online Help');
 1326:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1327:     if ($imgid ne '') {
 1328:         $imgid = ' id="'.$imgid.'"';
 1329:     }
 1330:     $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
 1331:               .'<img src="'.$helpicon.'" border="0"'
 1332:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1333:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1334:               .' /></a>';
 1335:     if ($text ne "") {	
 1336:         $template.='</span>';
 1337:     }
 1338:     return $template;
 1339: 
 1340: }
 1341: 
 1342: # This is a quicky function for Latex cheatsheet editing, since it 
 1343: # appears in at least four places
 1344: sub helpLatexCheatsheet {
 1345:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1346:     my $out;
 1347:     my $addOther = '';
 1348:     if ($topic) {
 1349: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1350:     }
 1351:     $out = '<span>' # Start cheatsheet
 1352: 	  .$addOther
 1353:           .'<span>'
 1354: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1355: 	  .'</span> <span>'
 1356: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1357: 	  .'</span>';
 1358:     unless ($not_author) {
 1359:         $out .= '<span>'
 1360:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1361:                .'</span> <span>'
 1362:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
 1363: 	       .'</span>';
 1364:     }
 1365:     $out .= '</span>'; # End cheatsheet
 1366:     return $out;
 1367: }
 1368: 
 1369: sub general_help {
 1370:     my $helptopic='Student_Intro';
 1371:     if ($env{'request.role'}=~/^(ca|au)/) {
 1372: 	$helptopic='Authoring_Intro';
 1373:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1374: 	$helptopic='Course_Coordination_Intro';
 1375:     } elsif ($env{'request.role'}=~/^dc/) {
 1376:         $helptopic='Domain_Coordination_Intro';
 1377:     }
 1378:     return $helptopic;
 1379: }
 1380: 
 1381: sub update_help_link {
 1382:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1383:     my $origurl = $ENV{'REQUEST_URI'};
 1384:     $origurl=~s|^/~|/priv/|;
 1385:     my $timestamp = time;
 1386:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1387:         $$datum = &escape($$datum);
 1388:     }
 1389: 
 1390:     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";
 1391:     my $output .= <<"ENDOUTPUT";
 1392: <script type="text/javascript">
 1393: // <![CDATA[
 1394: banner_link = '$banner_link';
 1395: // ]]>
 1396: </script>
 1397: ENDOUTPUT
 1398:     return $output;
 1399: }
 1400: 
 1401: # now just updates the help link and generates a blue icon
 1402: sub help_open_menu {
 1403:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text,$links_target) 
 1404: 	= @_;    
 1405:     $stayOnPage = 1;
 1406:     my $output;
 1407:     if ($component_help) {
 1408: 	if (!$text) {
 1409: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1410: 				       $width,$height,'',$links_target);
 1411: 	} else {
 1412: 	    my $help_text;
 1413: 	    $help_text=&unescape($topic);
 1414: 	    $output='<table><tr><td>'.
 1415: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1416: 				 $width,$height,'',$links_target).'</td></tr></table>';
 1417: 	}
 1418:     }
 1419:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1420:     return $output.$banner_link;
 1421: }
 1422: 
 1423: sub top_nav_help {
 1424:     my ($text,$linkattr) = @_;
 1425:     $text = &mt($text);
 1426:     my $stay_on_page = 1;
 1427: 
 1428:     my ($link,$banner_link);
 1429:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
 1430:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1431: 	                         : "javascript:helpMenu('open')";
 1432:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1433:     }
 1434:     my $title = &mt('Get help');
 1435:     if ($link) {
 1436:         return <<"END";
 1437: $banner_link
 1438: <a href="$link" title="$title" $linkattr>$text</a>
 1439: END
 1440:     } else {
 1441:         return '&nbsp;'.$text.'&nbsp;';
 1442:     }
 1443: }
 1444: 
 1445: sub help_menu_js {
 1446:     my ($httphost) = @_;
 1447:     my $stayOnPage = 1;
 1448:     my $width = 620;
 1449:     my $height = 600;
 1450:     my $helptopic=&general_help();
 1451:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
 1452:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1453:     my $start_page =
 1454:         &Apache::loncommon::start_page('Help Menu', undef,
 1455: 				       {'frameset'    => 1,
 1456: 					'js_ready'    => 1,
 1457:                                         'use_absolute' => $httphost,
 1458: 					'add_entries' => {
 1459: 					    'border' => '0', 
 1460: 					    'rows'   => "110,*",},});
 1461:     my $end_page =
 1462:         &Apache::loncommon::end_page({'frameset' => 1,
 1463: 				      'js_ready' => 1,});
 1464: 
 1465:     my $template .= <<"ENDTEMPLATE";
 1466: <script type="text/javascript">
 1467: // <![CDATA[
 1468: // <!-- BEGIN LON-CAPA Internal
 1469: var banner_link = '';
 1470: function helpMenu(target) {
 1471:     var caller = this;
 1472:     if (target == 'open') {
 1473:         var newWindow = null;
 1474:         try {
 1475:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1476:         }
 1477:         catch(error) {
 1478:             writeHelp(caller);
 1479:             return;
 1480:         }
 1481:         if (newWindow) {
 1482:             caller = newWindow;
 1483:         }
 1484:     }
 1485:     writeHelp(caller);
 1486:     return;
 1487: }
 1488: function writeHelp(caller) {
 1489:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
 1490:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
 1491:     caller.document.close();
 1492:     caller.focus();
 1493: }
 1494: // END LON-CAPA Internal -->
 1495: // ]]>
 1496: </script>
 1497: ENDTEMPLATE
 1498:     return $template;
 1499: }
 1500: 
 1501: sub help_open_bug {
 1502:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1503:     unless ($env{'user.adv'}) { return ''; }
 1504:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1505:     $text = "" if (not defined $text);
 1506: 	$stayOnPage=1;
 1507:     $width = 600 if (not defined $width);
 1508:     $height = 600 if (not defined $height);
 1509: 
 1510:     $topic=~s/\W+/\+/g;
 1511:     my $link='';
 1512:     my $template='';
 1513:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1514: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1515:     if (!$stayOnPage)
 1516:     {
 1517: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1518:     }
 1519:     else
 1520:     {
 1521: 	$link = $url;
 1522:     }
 1523: 
 1524:     my $target = '_top';
 1525:     if ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
 1526:         (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
 1527:         $target = '_blank';
 1528:     }
 1529: 
 1530:     # Add the text
 1531:     if ($text ne "")
 1532:     {
 1533: 	$template .= 
 1534:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1535:   "<td bgcolor='#FF5555'><a target=\"$target\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1536:     }
 1537: 
 1538:     # Add the graphic
 1539:     my $title = &mt('Report a Bug');
 1540:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1541:     $template .= <<"ENDTEMPLATE";
 1542:  <a target="$target" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1543: ENDTEMPLATE
 1544:     if ($text ne '') { $template.='</td></tr></table>' };
 1545:     return $template;
 1546: 
 1547: }
 1548: 
 1549: sub help_open_faq {
 1550:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1551:     unless ($env{'user.adv'}) { return ''; }
 1552:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1553:     $text = "" if (not defined $text);
 1554: 	$stayOnPage=1;
 1555:     $width = 350 if (not defined $width);
 1556:     $height = 400 if (not defined $height);
 1557: 
 1558:     $topic=~s/\W+/\+/g;
 1559:     my $link='';
 1560:     my $template='';
 1561:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1562:     if (!$stayOnPage)
 1563:     {
 1564: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1565:     }
 1566:     else
 1567:     {
 1568: 	$link = $url;
 1569:     }
 1570: 
 1571:     # Add the text
 1572:     if ($text ne "")
 1573:     {
 1574: 	$template .= 
 1575:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1576:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1577:     }
 1578: 
 1579:     # Add the graphic
 1580:     my $title = &mt('View the FAQ');
 1581:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1582:     $template .= <<"ENDTEMPLATE";
 1583:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1584: ENDTEMPLATE
 1585:     if ($text ne '') { $template.='</td></tr></table>' };
 1586:     return $template;
 1587: 
 1588: }
 1589: 
 1590: ###############################################################
 1591: ###############################################################
 1592: 
 1593: =pod
 1594: 
 1595: =item * &change_content_javascript():
 1596: 
 1597: This and the next function allow you to create small sections of an
 1598: otherwise static HTML page that you can update on the fly with
 1599: Javascript, even in Netscape 4.
 1600: 
 1601: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1602: must be written to the HTML page once. It will prove the Javascript
 1603: function "change(name, content)". Calling the change function with the
 1604: name of the section 
 1605: you want to update, matching the name passed to C<changable_area>, and
 1606: the new content you want to put in there, will put the content into
 1607: that area.
 1608: 
 1609: B<Note>: Netscape 4 only reserves enough space for the changable area
 1610: to contain room for the original contents. You need to "make space"
 1611: for whatever changes you wish to make, and be B<sure> to check your
 1612: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1613: it's adequate for updating a one-line status display, but little more.
 1614: This script will set the space to 100% width, so you only need to
 1615: worry about height in Netscape 4.
 1616: 
 1617: Modern browsers are much less limiting, and if you can commit to the
 1618: user not using Netscape 4, this feature may be used freely with
 1619: pretty much any HTML.
 1620: 
 1621: =cut
 1622: 
 1623: sub change_content_javascript {
 1624:     # If we're on Netscape 4, we need to use Layer-based code
 1625:     if ($env{'browser.type'} eq 'netscape' &&
 1626: 	$env{'browser.version'} =~ /^4\./) {
 1627: 	return (<<NETSCAPE4);
 1628: 	function change(name, content) {
 1629: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1630: 	    doc.open();
 1631: 	    doc.write(content);
 1632: 	    doc.close();
 1633: 	}
 1634: NETSCAPE4
 1635:     } else {
 1636: 	# Otherwise, we need to use semi-standards-compliant code
 1637: 	# (technically, "innerHTML" isn't standard but the equivalent
 1638: 	# is really scary, and every useful browser supports it
 1639: 	return (<<DOMBASED);
 1640: 	function change(name, content) {
 1641: 	    element = document.getElementById(name);
 1642: 	    element.innerHTML = content;
 1643: 	}
 1644: DOMBASED
 1645:     }
 1646: }
 1647: 
 1648: =pod
 1649: 
 1650: =item * &changable_area($name,$origContent):
 1651: 
 1652: This provides a "changable area" that can be modified on the fly via
 1653: the Javascript code provided in C<change_content_javascript>. $name is
 1654: the name you will use to reference the area later; do not repeat the
 1655: same name on a given HTML page more then once. $origContent is what
 1656: the area will originally contain, which can be left blank.
 1657: 
 1658: =cut
 1659: 
 1660: sub changable_area {
 1661:     my ($name, $origContent) = @_;
 1662: 
 1663:     if ($env{'browser.type'} eq 'netscape' &&
 1664: 	$env{'browser.version'} =~ /^4\./) {
 1665: 	# If this is netscape 4, we need to use the Layer tag
 1666: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1667:     } else {
 1668: 	return "<span id='$name'>$origContent</span>";
 1669:     }
 1670: }
 1671: 
 1672: =pod
 1673: 
 1674: =item * &viewport_geometry_js 
 1675: 
 1676: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1677: 
 1678: =cut
 1679: 
 1680: 
 1681: sub viewport_geometry_js { 
 1682:     return <<"GEOMETRY";
 1683: var Geometry = {};
 1684: function init_geometry() {
 1685:     if (Geometry.init) { return };
 1686:     Geometry.init=1;
 1687:     if (window.innerHeight) {
 1688:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1689:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1690:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1691:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1692:     }
 1693:     else if (document.documentElement && document.documentElement.clientHeight) {
 1694:         Geometry.getViewportHeight =
 1695:             function() { return document.documentElement.clientHeight; };
 1696:         Geometry.getViewportWidth =
 1697:             function() { return document.documentElement.clientWidth; };
 1698: 
 1699:         Geometry.getHorizontalScroll =
 1700:             function() { return document.documentElement.scrollLeft; };
 1701:         Geometry.getVerticalScroll =
 1702:             function() { return document.documentElement.scrollTop; };
 1703:     }
 1704:     else if (document.body.clientHeight) {
 1705:         Geometry.getViewportHeight =
 1706:             function() { return document.body.clientHeight; };
 1707:         Geometry.getViewportWidth =
 1708:             function() { return document.body.clientWidth; };
 1709:         Geometry.getHorizontalScroll =
 1710:             function() { return document.body.scrollLeft; };
 1711:         Geometry.getVerticalScroll =
 1712:             function() { return document.body.scrollTop; };
 1713:     }
 1714: }
 1715: 
 1716: GEOMETRY
 1717: }
 1718: 
 1719: =pod
 1720: 
 1721: =item * &viewport_size_js()
 1722: 
 1723: 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. 
 1724: 
 1725: =cut
 1726: 
 1727: sub viewport_size_js {
 1728:     my $geometry = &viewport_geometry_js();
 1729:     return <<"DIMS";
 1730: 
 1731: $geometry
 1732: 
 1733: function getViewportDims(width,height) {
 1734:     init_geometry();
 1735:     width.value = Geometry.getViewportWidth();
 1736:     height.value = Geometry.getViewportHeight();
 1737:     return;
 1738: }
 1739: 
 1740: DIMS
 1741: }
 1742: 
 1743: =pod
 1744: 
 1745: =item * &resize_textarea_js()
 1746: 
 1747: emits the needed javascript to resize a textarea to be as big as possible
 1748: 
 1749: creates a function resize_textrea that takes two IDs first should be
 1750: the id of the element to resize, second should be the id of a div that
 1751: surrounds everything that comes after the textarea, this routine needs
 1752: to be attached to the <body> for the onload and onresize events.
 1753: 
 1754: =back
 1755: 
 1756: =cut
 1757: 
 1758: sub resize_textarea_js {
 1759:     my $geometry = &viewport_geometry_js();
 1760:     return <<"RESIZE";
 1761:     <script type="text/javascript">
 1762: // <![CDATA[
 1763: $geometry
 1764: 
 1765: function getX(element) {
 1766:     var x = 0;
 1767:     while (element) {
 1768: 	x += element.offsetLeft;
 1769: 	element = element.offsetParent;
 1770:     }
 1771:     return x;
 1772: }
 1773: function getY(element) {
 1774:     var y = 0;
 1775:     while (element) {
 1776: 	y += element.offsetTop;
 1777: 	element = element.offsetParent;
 1778:     }
 1779:     return y;
 1780: }
 1781: 
 1782: 
 1783: function resize_textarea(textarea_id,bottom_id) {
 1784:     init_geometry();
 1785:     var textarea        = document.getElementById(textarea_id);
 1786:     //alert(textarea);
 1787: 
 1788:     var textarea_top    = getY(textarea);
 1789:     var textarea_height = textarea.offsetHeight;
 1790:     var bottom          = document.getElementById(bottom_id);
 1791:     var bottom_top      = getY(bottom);
 1792:     var bottom_height   = bottom.offsetHeight;
 1793:     var window_height   = Geometry.getViewportHeight();
 1794:     var fudge           = 23;
 1795:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1796:     if (new_height < 300) {
 1797: 	new_height = 300;
 1798:     }
 1799:     textarea.style.height=new_height+'px';
 1800: }
 1801: // ]]>
 1802: </script>
 1803: RESIZE
 1804: 
 1805: }
 1806: 
 1807: sub colorfuleditor_js {
 1808:     my $browse_or_search;
 1809:     my $respath;
 1810:     my ($cnum,$cdom) = &crsauthor_url();
 1811:     if ($cnum) {
 1812:         $respath = "/res/$cdom/$cnum/";
 1813:         my %js_lt = &Apache::lonlocal::texthash(
 1814:             sunm => 'Sub-directory name',
 1815:             save => 'Save page to make this permanent',
 1816:         );
 1817:         &js_escape(\%js_lt);
 1818:         $browse_or_search = <<"END";
 1819: 
 1820:     function toggleChooser(form,element,titleid,only,search) {
 1821:         var disp = 'none';
 1822:         if (document.getElementById('chooser_'+element)) {
 1823:             var curr = document.getElementById('chooser_'+element).style.display;
 1824:             if (curr == 'none') {
 1825:                 disp='inline';
 1826:                 if (form.elements['chooser_'+element].length) {
 1827:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
 1828:                         form.elements['chooser_'+element][i].checked = false;
 1829:                     }
 1830:                 }
 1831:                 toggleResImport(form,element);
 1832:             }
 1833:             document.getElementById('chooser_'+element).style.display = disp;
 1834:         }
 1835:     }
 1836: 
 1837:     function toggleCrsFile(form,element,numdirs) {
 1838:         if (document.getElementById('chooser_'+element+'_crsres')) {
 1839:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
 1840:             if (curr == 'none') {
 1841:                 if (numdirs) {
 1842:                     form.elements['coursepath_'+element].selectedIndex = 0;
 1843:                     if (numdirs > 1) {
 1844:                         window['select1'+element+'_changed']();
 1845:                     }
 1846:                 }
 1847:             } 
 1848:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
 1849:             
 1850:         }
 1851:         if (document.getElementById('chooser_'+element+'_upload')) {
 1852:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
 1853:             if (document.getElementById('uploadcrsres_'+element)) {
 1854:                 document.getElementById('uploadcrsres_'+element).value = '';
 1855:             }
 1856:         }
 1857:         return;
 1858:     }
 1859: 
 1860:     function toggleCrsUpload(form,element,numcrsdirs) {
 1861:         if (document.getElementById('chooser_'+element+'_crsres')) {
 1862:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
 1863:         }
 1864:         if (document.getElementById('chooser_'+element+'_upload')) {
 1865:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
 1866:             if (curr == 'none') {
 1867:                 if (numcrsdirs) {
 1868:                    form.elements['crsauthorpath_'+element].selectedIndex = 0;
 1869:                    form.elements['newsubdir_'+element][0].checked = true;
 1870:                    toggleNewsubdir(form,element);
 1871:                 }
 1872:             }
 1873:             document.getElementById('chooser_'+element+'_upload').style.display = 'block';
 1874:         }
 1875:         return;
 1876:     }
 1877: 
 1878:     function toggleResImport(form,element) {
 1879:         var choices = new Array('crsres','upload');
 1880:         for (var i=0; i<choices.length; i++) {
 1881:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
 1882:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
 1883:             }
 1884:         }
 1885:     }
 1886: 
 1887:     function toggleNewsubdir(form,element) {
 1888:         var newsub = form.elements['newsubdir_'+element];
 1889:         if (newsub) {
 1890:             if (newsub.length) {
 1891:                 for (var j=0; j<newsub.length; j++) {
 1892:                     if (newsub[j].checked) {
 1893:                         if (document.getElementById('newsubdirname_'+element)) {
 1894:                             if (newsub[j].value == '1') {
 1895:                                 document.getElementById('newsubdirname_'+element).type = "text";
 1896:                                 if (document.getElementById('newsubdir_'+element)) {
 1897:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
 1898:                                 }
 1899:                             } else {
 1900:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
 1901:                                 document.getElementById('newsubdirname_'+element).value = "";
 1902:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
 1903:                             }
 1904:                         }
 1905:                         break; 
 1906:                     }
 1907:                 }
 1908:             }
 1909:         }
 1910:     }
 1911: 
 1912:     function updateCrsFile(form,element) {
 1913:         var directory = form.elements['coursepath_'+element];
 1914:         var filename = form.elements['coursefile_'+element];
 1915:         var path = directory.options[directory.selectedIndex].value;
 1916:         var file = filename.options[filename.selectedIndex].value;
 1917:         form.elements[element].value = '$respath';
 1918:         if (path == '/') {
 1919:             form.elements[element].value += file;
 1920:         } else {
 1921:             form.elements[element].value += path+'/'+file;
 1922:         }
 1923:         unClean();
 1924:         if (document.getElementById('previewimg_'+element)) {
 1925:             document.getElementById('previewimg_'+element).src = form.elements[element].value;
 1926:             var newsrc = document.getElementById('previewimg_'+element).src; 
 1927:         }
 1928:         if (document.getElementById('showimg_'+element)) {
 1929:             document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
 1930:         }
 1931:         toggleChooser(form,element);
 1932:         return;
 1933:     }
 1934: 
 1935:     function uploadDone(suffix,name) {
 1936:         if (name) {
 1937: 	    document.forms["lonhomework"].elements[suffix].value = name;
 1938:             unClean();
 1939:             toggleChooser(document.forms["lonhomework"],suffix);
 1940:         }
 1941:     }
 1942: 
 1943: \$(document).ready(function(){
 1944: 
 1945:     \$(document).delegate('form :submit', 'click', function( event ) {
 1946:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
 1947:             var buttonId = this.id;
 1948:             var suffix = buttonId.toString();
 1949:             suffix = suffix.replace(/^crsupload_/,'');
 1950:             event.preventDefault();
 1951:             document.lonhomework.target = 'crsupload_target_'+suffix;
 1952:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
 1953:             \$(this.form).submit();
 1954:             document.lonhomework.target = '';
 1955:             if (document.getElementById('crsuploadto_'+suffix)) {
 1956:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
 1957:             }
 1958:             return false;
 1959:         }
 1960:     });
 1961: });
 1962: END
 1963:     }
 1964:     return <<"COLORFULEDIT"
 1965: <script type="text/javascript">
 1966: // <![CDATA[>
 1967:     function fold_box(curDepth, lastresource){
 1968: 
 1969:     // we need a list because there can be several blocks you need to fold in one tag
 1970:         var block = document.getElementsByName('foldblock_'+curDepth);
 1971:     // but there is only one folding button per tag
 1972:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
 1973: 
 1974:         if(block.item(0).style.display == 'none'){
 1975: 
 1976:             foldbutton.value = '@{[&mt("Hide")]}';
 1977:             for (i = 0; i < block.length; i++){
 1978:                 block.item(i).style.display = '';
 1979:             }
 1980:         }else{
 1981: 
 1982:             foldbutton.value = '@{[&mt("Show")]}';
 1983:             for (i = 0; i < block.length; i++){
 1984:                 // block.item(i).style.visibility = 'collapse';
 1985:                 block.item(i).style.display = 'none';
 1986:             }
 1987:         };
 1988:         saveState(lastresource);
 1989:     }
 1990: 
 1991:     function saveState (lastresource) {
 1992: 
 1993:         var tag_list = getTagList();
 1994:         if(tag_list != null){
 1995:             var timestamp = new Date().getTime();
 1996:             var key = lastresource;
 1997: 
 1998:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
 1999:             // starting with timestamp
 2000:             var value = timestamp+';';
 2001: 
 2002:             // building the list of key-value pairs
 2003:             for(var i = 0; i < tag_list.length; i++){
 2004:                 value += tag_list[i]+',';
 2005:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
 2006:             }
 2007: 
 2008:             // only iterate whole storage if nothing to override
 2009:             if(localStorage.getItem(key) == null){        
 2010: 
 2011:                 // prevent storage from growing large
 2012:                 if(localStorage.length > 50){
 2013:                     var regex_getTimestamp = /^(?:\d)+;/;
 2014:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
 2015:                     var oldest_key;
 2016:                     
 2017:                     for(var i = 1; i < localStorage.length; i++){
 2018:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
 2019:                             oldest_key = localStorage.key(i);
 2020:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
 2021:                         }
 2022:                     }
 2023:                     localStorage.removeItem(oldest_key);
 2024:                 }
 2025:             }
 2026:             localStorage.setItem(key,value);
 2027:         }
 2028:     }
 2029: 
 2030:     // restore folding status of blocks (on page load)
 2031:     function restoreState (lastresource) {
 2032:         if(localStorage.getItem(lastresource) != null){
 2033:             var key = lastresource;
 2034:             var value = localStorage.getItem(key);
 2035:             var regex_delTimestamp = /^\d+;/;
 2036: 
 2037:             value.replace(regex_delTimestamp, '');
 2038: 
 2039:             var valueArr = value.split(';');
 2040:             var pairs;
 2041:             var elements;
 2042:             for (var i = 0; i < valueArr.length; i++){
 2043:                 pairs = valueArr[i].split(',');
 2044:                 elements = document.getElementsByName(pairs[0]);
 2045: 
 2046:                 for (var j = 0; j < elements.length; j++){  
 2047:                     elements[j].style.display = pairs[1];
 2048:                     if (pairs[1] == "none"){
 2049:                         var regex_id = /([_\\d]+)\$/;
 2050:                         regex_id.exec(pairs[0]);
 2051:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
 2052:                     }
 2053:                 }
 2054:             }
 2055:         }
 2056:     }
 2057: 
 2058:     function getTagList () {
 2059:         
 2060:         var stringToSearch = document.lonhomework.innerHTML;
 2061: 
 2062:         var ret = new Array();
 2063:         var regex_findBlock = /(foldblock_.*?)"/g;
 2064:         var tag_list = stringToSearch.match(regex_findBlock);
 2065: 
 2066:         if(tag_list != null){
 2067:             for(var i = 0; i < tag_list.length; i++){            
 2068:                 ret.push(tag_list[i].replace(/"/, ''));
 2069:             }
 2070:         }
 2071:         return ret;
 2072:     }
 2073: 
 2074:     function saveScrollPosition (resource) {
 2075:         var tag_list = getTagList();
 2076: 
 2077:         // we dont always want to jump to the first block
 2078:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
 2079:         if(\$(window).scrollTop() > 170){
 2080:             if(tag_list != null){
 2081:                 var result;
 2082:                 for(var i = 0; i < tag_list.length; i++){
 2083:                     if(isElementInViewport(tag_list[i])){
 2084:                         result += tag_list[i]+';';
 2085:                     }
 2086:                 }
 2087:                 sessionStorage.setItem('anchor_'+resource, result);
 2088:             }
 2089:         } else {
 2090:             // we dont need to save zero, just delete the item to leave everything tidy
 2091:             sessionStorage.removeItem('anchor_'+resource);
 2092:         }
 2093:     }
 2094: 
 2095:     function restoreScrollPosition(resource){
 2096: 
 2097:         var elem = sessionStorage.getItem('anchor_'+resource);
 2098:         if(elem != null){
 2099:             var tag_list = elem.split(';');
 2100:             var elem_list;
 2101: 
 2102:             for(var i = 0; i < tag_list.length; i++){
 2103:                 elem_list = document.getElementsByName(tag_list[i]);
 2104:                 
 2105:                 if(elem_list.length > 0){
 2106:                     elem = elem_list[0];
 2107:                     break;
 2108:                 }
 2109:             }
 2110:             elem.scrollIntoView();
 2111:         }
 2112:     }
 2113: 
 2114:     function isElementInViewport(el) {
 2115: 
 2116:         // change to last element instead of first
 2117:         var elem = document.getElementsByName(el);
 2118:         var rect = elem[0].getBoundingClientRect();
 2119: 
 2120:         return (
 2121:             rect.top >= 0 &&
 2122:             rect.left >= 0 &&
 2123:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
 2124:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
 2125:         );
 2126:     }
 2127:     
 2128:     function autosize(depth){
 2129:         var cmInst = window['cm'+depth];
 2130:         var fitsizeButton = document.getElementById('fitsize'+depth);
 2131: 
 2132:         // is fixed size, switching to dynamic
 2133:         if (sessionStorage.getItem("autosized_"+depth) == null) {
 2134:             cmInst.setSize("","auto");
 2135:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
 2136:             sessionStorage.setItem("autosized_"+depth, "yes");
 2137: 
 2138:         // is dynamic size, switching to fixed
 2139:         } else {
 2140:             cmInst.setSize("","300px");
 2141:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
 2142:             sessionStorage.removeItem("autosized_"+depth);
 2143:         }
 2144:     }
 2145: 
 2146: $browse_or_search
 2147: 
 2148: // ]]>
 2149: </script>
 2150: COLORFULEDIT
 2151: }
 2152: 
 2153: sub xmleditor_js {
 2154:     return <<XMLEDIT
 2155: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
 2156: <script type="text/javascript">
 2157: // <![CDATA[>
 2158: 
 2159:     function saveScrollPosition (resource) {
 2160: 
 2161:         var scrollPos = \$(window).scrollTop();
 2162:         sessionStorage.setItem(resource,scrollPos);
 2163:     }
 2164: 
 2165:     function restoreScrollPosition(resource){
 2166: 
 2167:         var scrollPos = sessionStorage.getItem(resource);
 2168:         \$(window).scrollTop(scrollPos);
 2169:     }
 2170: 
 2171:     // unless internet explorer
 2172:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
 2173: 
 2174:         \$(document).ready(function() {
 2175:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
 2176:         });
 2177:     }
 2178: 
 2179:     // inserts text at cursor position into codemirror (xml editor only)
 2180:     function insertText(text){
 2181:         cm.focus();
 2182:         var curPos = cm.getCursor();
 2183:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
 2184:     }
 2185: // ]]>
 2186: </script>
 2187: XMLEDIT
 2188: }
 2189: 
 2190: sub insert_folding_button {
 2191:     my $curDepth = $Apache::lonxml::curdepth;
 2192:     my $lastresource = $env{'request.ambiguous'};
 2193: 
 2194:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
 2195:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
 2196: }
 2197: 
 2198: sub crsauthor_url {
 2199:     my ($url) = @_;
 2200:     if ($url eq '') {
 2201:         $url = $ENV{'REQUEST_URI'};
 2202:     }
 2203:     my ($cnum,$cdom);
 2204:     if ($env{'request.course.id'}) {
 2205:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
 2206:         if ($audom ne '' && $auname ne '') {
 2207:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
 2208:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
 2209:                 $cnum = $auname;
 2210:                 $cdom = $audom;
 2211:             }
 2212:         }
 2213:     }
 2214:     return ($cnum,$cdom);
 2215: }
 2216: 
 2217: sub import_crsauthor_form {
 2218:     my ($form,$firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
 2219:     return (0) unless ($env{'request.course.id'});
 2220:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2221:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2222:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
 2223:     return (0) unless (($cnum ne '') && ($cdom ne ''));
 2224:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 2225:     my @ids=&Apache::lonnet::current_machine_ids();
 2226:     my ($output,$is_home,$relpath,%subdirs,%files,%selimport_menus);
 2227:     
 2228:     if (grep(/^\Q$crshome\E$/,@ids)) {
 2229:         $is_home = 1;
 2230:     }
 2231:     $relpath = "/priv/$cdom/$cnum";
 2232:     &Apache::lonnet::recursedirs($is_home,'priv',$londocroot,$relpath,'',\%subdirs,\%files);
 2233:     my %lt = &Apache::lonlocal::texthash (
 2234:         fnam => 'Filename',
 2235:         dire => 'Directory',
 2236:     );
 2237:     my $numdirs = scalar(keys(%files));
 2238:     my (%possexts,$singledir,@singledirfiles);
 2239:     if ($only) {
 2240:         map { $possexts{$_} = 1; } split(/\s*,\s*/,$only);
 2241:     }
 2242:     my (%nonemptydirs,$possdirs);
 2243:     if ($numdirs > 1) {
 2244:         my @order;
 2245:         foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
 2246:             if (ref($files{$key}) eq 'HASH') {
 2247:                 my $shown = $key;
 2248:                 if ($key eq '') {
 2249:                     $shown = '/';
 2250:                 }
 2251:                 my @ordered = ();
 2252:                 foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$key}}))) {
 2253:                     next if ($file =~ /\.rights$/);
 2254:                     if ($only) {
 2255:                         my ($ext) = ($file =~ /\.([^.]+)$/);
 2256:                         unless ($possexts{lc($ext)}) {
 2257:                             next;
 2258:                         }
 2259:                     }
 2260:                     $selimport_menus{$key}->{'select2'}->{$file} = $file;
 2261:                     push(@ordered,$file);
 2262:                 }
 2263:                 if (@ordered) {
 2264:                     push(@order,$key);
 2265:                     $nonemptydirs{$key} = 1;
 2266:                     $selimport_menus{$key}->{'text'} = $shown;
 2267:                     $selimport_menus{$key}->{'default'} = '';
 2268:                     $selimport_menus{$key}->{'select2'}->{''} = '';
 2269:                     $selimport_menus{$key}->{'order'} = \@ordered;
 2270:                 }
 2271:             }
 2272:         }
 2273:         $possdirs = scalar(keys(%nonemptydirs));
 2274:         if ($possdirs > 1) {
 2275:             my @order = sort { lc($a) cmp lc($b) } (keys(%nonemptydirs));
 2276:             $output = $lt{'dire'}.
 2277:                       &linked_select_forms($form,'<br />'.
 2278:                                            $lt{'fnam'},'',
 2279:                                            $firstselectname,$secondselectname,
 2280:                                            \%selimport_menus,\@order,
 2281:                                            $onchangefirst,'',$suffix).'<br />';
 2282:         } elsif ($possdirs == 1) {
 2283:             $singledir = (keys(%nonemptydirs))[0];
 2284:             if (ref($selimport_menus{$singledir}->{'order'}) eq 'ARRAY') {
 2285:                 @singledirfiles = @{$selimport_menus{$singledir}->{'order'}};
 2286:             }
 2287:             delete($selimport_menus{$singledir});
 2288:         }
 2289:     } elsif ($numdirs == 1) {
 2290:         $singledir = (keys(%files))[0];
 2291:         foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$singledir}}))) {
 2292:             if ($only) {
 2293:                 my ($ext) = ($file =~ /\.([^.]+)$/);
 2294:                 unless ($possexts{lc($ext)}) {
 2295:                     next;
 2296:                 }
 2297:             } else {
 2298:                 next if ($file =~ /\.rights$/);
 2299:             }
 2300:             push(@singledirfiles,$file);
 2301:         }
 2302:         if (@singledirfiles) {
 2303:             $possdirs = 1;
 2304:         }
 2305:     }
 2306:     if (($possdirs == 1) && (@singledirfiles)) {
 2307:         my $showdir = $singledir;
 2308:         if ($singledir eq '') {
 2309:             $showdir = '/';
 2310:         }
 2311:         $output = $lt{'dire'}.
 2312:                   '<select name="'.$firstselectname.'">'.
 2313:                   '<option value="'.$singledir.'">'.$showdir.'</option>'."\n".
 2314:                   '</select><br />'.
 2315:                   $lt{'fnam'}.'<select name="'.$secondselectname.'">'."\n".
 2316:                   '<option value="" selected="selected">'.$lt{'se'}.'</option>'."\n";
 2317:         foreach my $file (@singledirfiles) {
 2318:             $output .= '<option value="'.$file.'">'.$file.'</option>'."\n";
 2319:         }
 2320:         $output .= '</select><br />'."\n";
 2321:     }
 2322:     return ($possdirs,$output);
 2323: }
 2324: 
 2325: =pod
 2326: 
 2327: =head1 Excel and CSV file utility routines
 2328: 
 2329: =cut
 2330: 
 2331: ###############################################################
 2332: ###############################################################
 2333: 
 2334: =pod
 2335: 
 2336: =over 4
 2337: 
 2338: =item * &csv_translate($text) 
 2339: 
 2340: Translate $text to allow it to be output as a 'comma separated values' 
 2341: format.
 2342: 
 2343: =cut
 2344: 
 2345: ###############################################################
 2346: ###############################################################
 2347: sub csv_translate {
 2348:     my $text = shift;
 2349:     $text =~ s/\"/\"\"/g;
 2350:     $text =~ s/\n/ /g;
 2351:     return $text;
 2352: }
 2353: 
 2354: ###############################################################
 2355: ###############################################################
 2356: 
 2357: =pod
 2358: 
 2359: =item * &define_excel_formats()
 2360: 
 2361: Define some commonly used Excel cell formats.
 2362: 
 2363: Currently supported formats:
 2364: 
 2365: =over 4
 2366: 
 2367: =item header
 2368: 
 2369: =item bold
 2370: 
 2371: =item h1
 2372: 
 2373: =item h2
 2374: 
 2375: =item h3
 2376: 
 2377: =item h4
 2378: 
 2379: =item i
 2380: 
 2381: =item date
 2382: 
 2383: =back
 2384: 
 2385: Inputs: $workbook
 2386: 
 2387: Returns: $format, a hash reference.
 2388: 
 2389: 
 2390: =cut
 2391: 
 2392: ###############################################################
 2393: ###############################################################
 2394: sub define_excel_formats {
 2395:     my ($workbook) = @_;
 2396:     my $format;
 2397:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 2398:                                                 bottom    => 1,
 2399:                                                 align     => 'center');
 2400:     $format->{'bold'} = $workbook->add_format(bold=>1);
 2401:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 2402:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 2403:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 2404:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 2405:     $format->{'i'}    = $workbook->add_format(italic=>1);
 2406:     $format->{'date'} = $workbook->add_format(num_format=>
 2407:                                             'mm/dd/yyyy hh:mm:ss');
 2408:     return $format;
 2409: }
 2410: 
 2411: ###############################################################
 2412: ###############################################################
 2413: 
 2414: =pod
 2415: 
 2416: =item * &create_workbook()
 2417: 
 2418: Create an Excel worksheet.  If it fails, output message on the
 2419: request object and return undefs.
 2420: 
 2421: Inputs: Apache request object
 2422: 
 2423: Returns (undef) on failure, 
 2424:     Excel worksheet object, scalar with filename, and formats 
 2425:     from &Apache::loncommon::define_excel_formats on success
 2426: 
 2427: =cut
 2428: 
 2429: ###############################################################
 2430: ###############################################################
 2431: sub create_workbook {
 2432:     my ($r) = @_;
 2433:         #
 2434:     # Create the excel spreadsheet
 2435:     my $filename = '/prtspool/'.
 2436:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2437:         time.'_'.rand(1000000000).'.xls';
 2438:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 2439:     if (! defined($workbook)) {
 2440:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 2441:         $r->print(
 2442:             '<p class="LC_error">'
 2443:            .&mt('Problems occurred in creating the new Excel file.')
 2444:            .' '.&mt('This error has been logged.')
 2445:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2446:            .'</p>'
 2447:         );
 2448:         return (undef);
 2449:     }
 2450:     #
 2451:     $workbook->set_tempdir(LONCAPA::tempdir());
 2452:     #
 2453:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 2454:     return ($workbook,$filename,$format);
 2455: }
 2456: 
 2457: ###############################################################
 2458: ###############################################################
 2459: 
 2460: =pod
 2461: 
 2462: =item * &create_text_file()
 2463: 
 2464: Create a file to write to and eventually make available to the user.
 2465: If file creation fails, outputs an error message on the request object and 
 2466: return undefs.
 2467: 
 2468: Inputs: Apache request object, and file suffix
 2469: 
 2470: Returns (undef) on failure, 
 2471:     Filehandle and filename on success.
 2472: 
 2473: =cut
 2474: 
 2475: ###############################################################
 2476: ###############################################################
 2477: sub create_text_file {
 2478:     my ($r,$suffix) = @_;
 2479:     if (! defined($suffix)) { $suffix = 'txt'; };
 2480:     my $fh;
 2481:     my $filename = '/prtspool/'.
 2482:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2483:         time.'_'.rand(1000000000).'.'.$suffix;
 2484:     $fh = Apache::File->new('>/home/httpd'.$filename);
 2485:     if (! defined($fh)) {
 2486:         $r->log_error("Couldn't open $filename for output $!");
 2487:         $r->print(
 2488:             '<p class="LC_error">'
 2489:            .&mt('Problems occurred in creating the output file.')
 2490:            .' '.&mt('This error has been logged.')
 2491:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2492:            .'</p>'
 2493:         );
 2494:     }
 2495:     return ($fh,$filename)
 2496: }
 2497: 
 2498: 
 2499: =pod 
 2500: 
 2501: =back
 2502: 
 2503: =cut
 2504: 
 2505: ###############################################################
 2506: ##        Home server <option> list generating code          ##
 2507: ###############################################################
 2508: 
 2509: # ------------------------------------------
 2510: 
 2511: sub domain_select {
 2512:     my ($name,$value,$multiple,$incdoms,$excdoms)=@_;
 2513:     my @possdoms;
 2514:     if (ref($incdoms) eq 'ARRAY') {
 2515:         @possdoms = @{$incdoms};
 2516:     } else {
 2517:         @possdoms = &Apache::lonnet::all_domains();
 2518:     }
 2519: 
 2520:     my %domains=map { 
 2521: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 2522:     } @possdoms;
 2523: 
 2524:     if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
 2525:         foreach my $dom (@{$excdoms}) {
 2526:             delete($domains{$dom});
 2527:         }
 2528:     }
 2529: 
 2530:     if ($multiple) {
 2531: 	$domains{''}=&mt('Any domain');
 2532: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2533: 	return &multiple_select_form($name,$value,4,\%domains);
 2534:     } else {
 2535: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2536: 	return &select_form($name,$value,\%domains);
 2537:     }
 2538: }
 2539: 
 2540: #-------------------------------------------
 2541: 
 2542: =pod
 2543: 
 2544: =head1 Routines for form select boxes
 2545: 
 2546: =over 4
 2547: 
 2548: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 2549: 
 2550: Returns a string containing a <select> element int multiple mode
 2551: 
 2552: 
 2553: Args:
 2554:   $name - name of the <select> element
 2555:   $value - scalar or array ref of values that should already be selected
 2556:   $size - number of rows long the select element is
 2557:   $hash - the elements should be 'option' => 'shown text'
 2558:           (shown text should already have been &mt())
 2559:   $order - (optional) array ref of the order to show the elements in
 2560: 
 2561: =cut
 2562: 
 2563: #-------------------------------------------
 2564: sub multiple_select_form {
 2565:     my ($name,$value,$size,$hash,$order)=@_;
 2566:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 2567:     my $output='';
 2568:     if (! defined($size)) {
 2569:         $size = 4;
 2570:         if (scalar(keys(%$hash))<4) {
 2571:             $size = scalar(keys(%$hash));
 2572:         }
 2573:     }
 2574:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 2575:     my @order;
 2576:     if (ref($order) eq 'ARRAY')  {
 2577:         @order = @{$order};
 2578:     } else {
 2579:         @order = sort(keys(%$hash));
 2580:     }
 2581:     if (exists($$hash{'select_form_order'})) {
 2582:         @order = @{$$hash{'select_form_order'}};
 2583:     }
 2584:         
 2585:     foreach my $key (@order) {
 2586:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 2587:         $output.='selected="selected" ' if ($selected{$key});
 2588:         $output.='>'.$hash->{$key}."</option>\n";
 2589:     }
 2590:     $output.="</select>\n";
 2591:     return $output;
 2592: }
 2593: 
 2594: #-------------------------------------------
 2595: 
 2596: =pod
 2597: 
 2598: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
 2599: 
 2600: Returns a string containing a <select name='$name' size='1'> form to 
 2601: allow a user to select options from a ref to a hash containing:
 2602: option_name => displayed text. An optional $onchange can include
 2603: a javascript onchange item, e.g., onchange="this.form.submit();".
 2604: An optional arg -- $readonly -- if true will cause the select form
 2605: to be disabled, e.g., for the case where an instructor has a section-
 2606: specific role, and is viewing/modifying parameters. 
 2607: 
 2608: See lonrights.pm for an example invocation and use.
 2609: 
 2610: =cut
 2611: 
 2612: #-------------------------------------------
 2613: sub select_form {
 2614:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
 2615:     return unless (ref($hashref) eq 'HASH');
 2616:     if ($onchange) {
 2617:         $onchange = ' onchange="'.$onchange.'"';
 2618:     }
 2619:     my $disabled;
 2620:     if ($readonly) {
 2621:         $disabled = ' disabled="disabled"';
 2622:     }
 2623:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2624:     my @keys;
 2625:     if (exists($hashref->{'select_form_order'})) {
 2626: 	@keys=@{$hashref->{'select_form_order'}};
 2627:     } else {
 2628: 	@keys=sort(keys(%{$hashref}));
 2629:     }
 2630:     foreach my $key (@keys) {
 2631:         $selectform.=
 2632: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2633:             ($key eq $def ? 'selected="selected" ' : '').
 2634:                 ">".$hashref->{$key}."</option>\n";
 2635:     }
 2636:     $selectform.="</select>";
 2637:     return $selectform;
 2638: }
 2639: 
 2640: # For display filters
 2641: 
 2642: sub display_filter {
 2643:     my ($context) = @_;
 2644:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2645:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2646:     my $phraseinput = 'hidden';
 2647:     my $includeinput = 'hidden';
 2648:     my ($checked,$includetypestext);
 2649:     if ($env{'form.displayfilter'} eq 'containing') {
 2650:         $phraseinput = 'text'; 
 2651:         if ($context eq 'parmslog') {
 2652:             $includeinput = 'checkbox';
 2653:             if ($env{'form.includetypes'}) {
 2654:                 $checked = ' checked="checked"';
 2655:             }
 2656:             $includetypestext = &mt('Include parameter types');
 2657:         }
 2658:     } else {
 2659:         $includetypestext = '&nbsp;';
 2660:     }
 2661:     my ($additional,$secondid,$thirdid);
 2662:     if ($context eq 'parmslog') {
 2663:         $additional = 
 2664:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2665:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2666:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2667:             '</label>';
 2668:         $secondid = 'includetypes';
 2669:         $thirdid = 'includetypestext';
 2670:     }
 2671:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2672:                                                     '$secondid','$thirdid')";
 2673:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2674: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 2675: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2676: 	   '</label></span> <span class="LC_nobreak">'.
 2677:            &mt('Filter: [_1]',
 2678: 	   &select_form($env{'form.displayfilter'},
 2679: 			'displayfilter',
 2680: 			{'currentfolder' => 'Current folder/page',
 2681: 			 'containing' => 'Containing phrase',
 2682: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2683: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2684:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2685:                          '" />'.$additional;
 2686: }
 2687: 
 2688: sub display_filter_js {
 2689:     my $includetext = &mt('Include parameter types');
 2690:     return <<"ENDJS";
 2691:   
 2692: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2693:     var firstType = 'hidden';
 2694:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2695:         firstType = 'text';
 2696:     }
 2697:     firstObject = document.getElementById(firstid);
 2698:     if (typeof(firstObject) == 'object') {
 2699:         if (firstObject.type != firstType) {
 2700:             changeInputType(firstObject,firstType);
 2701:         }
 2702:     }
 2703:     if (context == 'parmslog') {
 2704:         var secondType = 'hidden';
 2705:         if (firstType == 'text') {
 2706:             secondType = 'checkbox';
 2707:         }
 2708:         secondObject = document.getElementById(secondid);  
 2709:         if (typeof(secondObject) == 'object') {
 2710:             if (secondObject.type != secondType) {
 2711:                 changeInputType(secondObject,secondType);
 2712:             }
 2713:         }
 2714:         var textItem = document.getElementById(thirdid);
 2715:         var currtext = textItem.innerHTML;
 2716:         var newtext;
 2717:         if (firstType == 'text') {
 2718:             newtext = '$includetext';
 2719:         } else {
 2720:             newtext = '&nbsp;';
 2721:         }
 2722:         if (currtext != newtext) {
 2723:             textItem.innerHTML = newtext;
 2724:         }
 2725:     }
 2726:     return;
 2727: }
 2728: 
 2729: function changeInputType(oldObject,newType) {
 2730:     var newObject = document.createElement('input');
 2731:     newObject.type = newType;
 2732:     if (oldObject.size) {
 2733:         newObject.size = oldObject.size;
 2734:     }
 2735:     if (oldObject.value) {
 2736:         newObject.value = oldObject.value;
 2737:     }
 2738:     if (oldObject.name) {
 2739:         newObject.name = oldObject.name;
 2740:     }
 2741:     if (oldObject.id) {
 2742:         newObject.id = oldObject.id;
 2743:     }
 2744:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2745:     return;
 2746: }
 2747: 
 2748: ENDJS
 2749: }
 2750: 
 2751: sub gradeleveldescription {
 2752:     my $gradelevel=shift;
 2753:     my %gradelevels=(0 => 'Not specified',
 2754: 		     1 => 'Grade 1',
 2755: 		     2 => 'Grade 2',
 2756: 		     3 => 'Grade 3',
 2757: 		     4 => 'Grade 4',
 2758: 		     5 => 'Grade 5',
 2759: 		     6 => 'Grade 6',
 2760: 		     7 => 'Grade 7',
 2761: 		     8 => 'Grade 8',
 2762: 		     9 => 'Grade 9',
 2763: 		     10 => 'Grade 10',
 2764: 		     11 => 'Grade 11',
 2765: 		     12 => 'Grade 12',
 2766: 		     13 => 'Grade 13',
 2767: 		     14 => '100 Level',
 2768: 		     15 => '200 Level',
 2769: 		     16 => '300 Level',
 2770: 		     17 => '400 Level',
 2771: 		     18 => 'Graduate Level');
 2772:     return &mt($gradelevels{$gradelevel});
 2773: }
 2774: 
 2775: sub select_level_form {
 2776:     my ($deflevel,$name)=@_;
 2777:     unless ($deflevel) { $deflevel=0; }
 2778:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2779:     for (my $i=0; $i<=18; $i++) {
 2780:         $selectform.="<option value=\"$i\" ".
 2781:             ($i==$deflevel ? 'selected="selected" ' : '').
 2782:                 ">".&gradeleveldescription($i)."</option>\n";
 2783:     }
 2784:     $selectform.="</select>";
 2785:     return $selectform;
 2786: }
 2787: 
 2788: #-------------------------------------------
 2789: 
 2790: =pod
 2791: 
 2792: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
 2793: 
 2794: Returns a string containing a <select name='$name' size='1'> form to 
 2795: allow a user to select the domain to preform an operation in.  
 2796: See loncreateuser.pm for an example invocation and use.
 2797: 
 2798: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2799: selected");
 2800: 
 2801: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2802: 
 2803: 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.
 2804: 
 2805: The optional $incdoms is a reference to an array of domains which will be the only available options.
 2806: 
 2807: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
 2808: 
 2809: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
 2810: 
 2811: =cut
 2812: 
 2813: #-------------------------------------------
 2814: sub select_dom_form {
 2815:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
 2816:     if ($onchange) {
 2817:         $onchange = ' onchange="'.$onchange.'"';
 2818:     }
 2819:     if ($disabled) {
 2820:         $disabled = ' disabled="disabled"';
 2821:     }
 2822:     my (@domains,%exclude);
 2823:     if (ref($incdoms) eq 'ARRAY') {
 2824:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2825:     } else {
 2826:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2827:     }
 2828:     if ($includeempty) { @domains=('',@domains); }
 2829:     if (ref($excdoms) eq 'ARRAY') {
 2830:         map { $exclude{$_} = 1; } @{$excdoms}; 
 2831:     }
 2832:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2833:     foreach my $dom (@domains) {
 2834:         next if ($exclude{$dom});
 2835:         $selectdomain.="<option value=\"$dom\" ".
 2836:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2837:         if ($showdomdesc) {
 2838:             if ($dom ne '') {
 2839:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2840:                 if ($domdesc ne '') {
 2841:                     $selectdomain .= ' ('.$domdesc.')';
 2842:                 }
 2843:             } 
 2844:         }
 2845:         $selectdomain .= "</option>\n";
 2846:     }
 2847:     $selectdomain.="</select>";
 2848:     return $selectdomain;
 2849: }
 2850: 
 2851: #-------------------------------------------
 2852: 
 2853: =pod
 2854: 
 2855: =item * &home_server_form_item($domain,$name,$defaultflag)
 2856: 
 2857: input: 4 arguments (two required, two optional) - 
 2858:     $domain - domain of new user
 2859:     $name - name of form element
 2860:     $default - Value of 'default' causes a default item to be first 
 2861:                             option, and selected by default. 
 2862:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2863:                             if 1 server found, or default, if 0 found.
 2864: output: returns 2 items: 
 2865: (a) form element which contains either:
 2866:    (i) <select name="$name">
 2867:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2868:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2869:        </select>
 2870:        form item if there are multiple library servers in $domain, or
 2871:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2872:        if there is only one library server in $domain.
 2873: 
 2874: (b) number of library servers found.
 2875: 
 2876: See loncreateuser.pm for example of use.
 2877: 
 2878: =cut
 2879: 
 2880: #-------------------------------------------
 2881: sub home_server_form_item {
 2882:     my ($domain,$name,$default,$hide) = @_;
 2883:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2884:     my $result;
 2885:     my $numlib = keys(%servers);
 2886:     if ($numlib > 1) {
 2887:         $result .= '<select name="'.$name.'" />'."\n";
 2888:         if ($default) {
 2889:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2890:                        '</option>'."\n";
 2891:         }
 2892:         foreach my $hostid (sort(keys(%servers))) {
 2893:             $result.= '<option value="'.$hostid.'">'.
 2894: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2895:         }
 2896:         $result .= '</select>'."\n";
 2897:     } elsif ($numlib == 1) {
 2898:         my $hostid;
 2899:         foreach my $item (keys(%servers)) {
 2900:             $hostid = $item;
 2901:         }
 2902:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2903:                    $hostid.'" />';
 2904:                    if (!$hide) {
 2905:                        $result .= $hostid.' '.$servers{$hostid};
 2906:                    }
 2907:                    $result .= "\n";
 2908:     } elsif ($default) {
 2909:         $result .= '<input type="hidden" name="'.$name.
 2910:                    '" value="default" />';
 2911:                    if (!$hide) {
 2912:                        $result .= &mt('default');
 2913:                    }
 2914:                    $result .= "\n";
 2915:     }
 2916:     return ($result,$numlib);
 2917: }
 2918: 
 2919: =pod
 2920: 
 2921: =back 
 2922: 
 2923: =cut
 2924: 
 2925: ###############################################################
 2926: ##                  Decoding User Agent                      ##
 2927: ###############################################################
 2928: 
 2929: =pod
 2930: 
 2931: =head1 Decoding the User Agent
 2932: 
 2933: =over 4
 2934: 
 2935: =item * &decode_user_agent()
 2936: 
 2937: Inputs: $r
 2938: 
 2939: Outputs:
 2940: 
 2941: =over 4
 2942: 
 2943: =item * $httpbrowser
 2944: 
 2945: =item * $clientbrowser
 2946: 
 2947: =item * $clientversion
 2948: 
 2949: =item * $clientmathml
 2950: 
 2951: =item * $clientunicode
 2952: 
 2953: =item * $clientos
 2954: 
 2955: =item * $clientmobile
 2956: 
 2957: =item * $clientinfo
 2958: 
 2959: =item * $clientosversion
 2960: 
 2961: =back
 2962: 
 2963: =back 
 2964: 
 2965: =cut
 2966: 
 2967: ###############################################################
 2968: ###############################################################
 2969: sub decode_user_agent {
 2970:     my ($r)=@_;
 2971:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2972:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2973:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2974:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2975:     my $clientbrowser='unknown';
 2976:     my $clientversion='0';
 2977:     my $clientmathml='';
 2978:     my $clientunicode='0';
 2979:     my $clientmobile=0;
 2980:     my $clientosversion='';
 2981:     for (my $i=0;$i<=$#browsertype;$i++) {
 2982:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
 2983: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2984: 	    $clientbrowser=$bname;
 2985:             $httpbrowser=~/$vreg/i;
 2986: 	    $clientversion=$1;
 2987:             $clientmathml=($clientversion>=$minv);
 2988:             $clientunicode=($clientversion>=$univ);
 2989: 	}
 2990:     }
 2991:     my $clientos='unknown';
 2992:     my $clientinfo;
 2993:     if (($httpbrowser=~/linux/i) ||
 2994:         ($httpbrowser=~/unix/i) ||
 2995:         ($httpbrowser=~/ux/i) ||
 2996:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2997:     if (($httpbrowser=~/vax/i) ||
 2998:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2999:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 3000:     if (($httpbrowser=~/mac/i) ||
 3001:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 3002:     if ($httpbrowser=~/win/i) {
 3003:         $clientos='win';
 3004:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
 3005:             $clientosversion = $1;
 3006:         }
 3007:     }
 3008:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 3009:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 3010:         $clientmobile=lc($1);
 3011:     }
 3012:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 3013:         $clientinfo = 'firefox-'.$1;
 3014:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 3015:         $clientinfo = 'chromeframe-'.$1;
 3016:     }
 3017:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 3018:             $clientunicode,$clientos,$clientmobile,$clientinfo,
 3019:             $clientosversion);
 3020: }
 3021: 
 3022: ###############################################################
 3023: ##    Authentication changing form generation subroutines    ##
 3024: ###############################################################
 3025: ##
 3026: ## All of the authform_xxxxxxx subroutines take their inputs in a
 3027: ## hash, and have reasonable default values.
 3028: ##
 3029: ##    formname = the name given in the <form> tag.
 3030: #-------------------------------------------
 3031: 
 3032: =pod
 3033: 
 3034: =head1 Authentication Routines
 3035: 
 3036: =over 4
 3037: 
 3038: =item * &authform_xxxxxx()
 3039: 
 3040: The authform_xxxxxx subroutines provide javascript and html forms which 
 3041: handle some of the conveniences required for authentication forms.  
 3042: This is not an optimal method, but it works.  
 3043: 
 3044: =over 4
 3045: 
 3046: =item * authform_header
 3047: 
 3048: =item * authform_authorwarning
 3049: 
 3050: =item * authform_nochange
 3051: 
 3052: =item * authform_kerberos
 3053: 
 3054: =item * authform_internal
 3055: 
 3056: =item * authform_filesystem
 3057: 
 3058: =item * authform_lti
 3059: 
 3060: =back
 3061: 
 3062: See loncreateuser.pm for invocation and use examples.
 3063: 
 3064: =cut
 3065: 
 3066: #-------------------------------------------
 3067: sub authform_header{  
 3068:     my %in = (
 3069:         formname => 'cu',
 3070:         kerb_def_dom => '',
 3071:         @_,
 3072:     );
 3073:     $in{'formname'} = 'document.' . $in{'formname'};
 3074:     my $result='';
 3075: 
 3076: #---------------------------------------------- Code for upper case translation
 3077:     my $Javascript_toUpperCase;
 3078:     unless ($in{kerb_def_dom}) {
 3079:         $Javascript_toUpperCase =<<"END";
 3080:         switch (choice) {
 3081:            case 'krb': currentform.elements[choicearg].value =
 3082:                currentform.elements[choicearg].value.toUpperCase();
 3083:                break;
 3084:            default:
 3085:         }
 3086: END
 3087:     } else {
 3088:         $Javascript_toUpperCase = "";
 3089:     }
 3090: 
 3091:     my $radioval = "'nochange'";
 3092:     if (defined($in{'curr_authtype'})) {
 3093:         if ($in{'curr_authtype'} ne '') {
 3094:             $radioval = "'".$in{'curr_authtype'}."arg'";
 3095:         }
 3096:     }
 3097:     my $argfield = 'null';
 3098:     if (defined($in{'mode'})) {
 3099:         if ($in{'mode'} eq 'modifycourse')  {
 3100:             if (defined($in{'curr_autharg'})) {
 3101:                 if ($in{'curr_autharg'} ne '') {
 3102:                     $argfield = "'$in{'curr_autharg'}'";
 3103:                 }
 3104:             }
 3105:         }
 3106:     }
 3107: 
 3108:     $result.=<<"END";
 3109: var current = new Object();
 3110: current.radiovalue = $radioval;
 3111: current.argfield = $argfield;
 3112: 
 3113: function changed_radio(choice,currentform) {
 3114:     var choicearg = choice + 'arg';
 3115:     // If a radio button in changed, we need to change the argfield
 3116:     if (current.radiovalue != choice) {
 3117:         current.radiovalue = choice;
 3118:         if (current.argfield != null) {
 3119:             currentform.elements[current.argfield].value = '';
 3120:         }
 3121:         if (choice == 'nochange') {
 3122:             current.argfield = null;
 3123:         } else {
 3124:             current.argfield = choicearg;
 3125:             switch(choice) {
 3126:                 case 'krb': 
 3127:                     currentform.elements[current.argfield].value = 
 3128:                         "$in{'kerb_def_dom'}";
 3129:                 break;
 3130:               default:
 3131:                 break;
 3132:             }
 3133:         }
 3134:     }
 3135:     return;
 3136: }
 3137: 
 3138: function changed_text(choice,currentform) {
 3139:     var choicearg = choice + 'arg';
 3140:     if (currentform.elements[choicearg].value !='') {
 3141:         $Javascript_toUpperCase
 3142:         // clear old field
 3143:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 3144:             currentform.elements[current.argfield].value = '';
 3145:         }
 3146:         current.argfield = choicearg;
 3147:     }
 3148:     set_auth_radio_buttons(choice,currentform);
 3149:     return;
 3150: }
 3151: 
 3152: function set_auth_radio_buttons(newvalue,currentform) {
 3153:     var numauthchoices = currentform.login.length;
 3154:     if (typeof numauthchoices  == "undefined") {
 3155:         return;
 3156:     } 
 3157:     var i=0;
 3158:     while (i < numauthchoices) {
 3159:         if (currentform.login[i].value == newvalue) { break; }
 3160:         i++;
 3161:     }
 3162:     if (i == numauthchoices) {
 3163:         return;
 3164:     }
 3165:     current.radiovalue = newvalue;
 3166:     currentform.login[i].checked = true;
 3167:     return;
 3168: }
 3169: END
 3170:     return $result;
 3171: }
 3172: 
 3173: sub authform_authorwarning {
 3174:     my $result='';
 3175:     $result='<i>'.
 3176:         &mt('As a general rule, only authors or co-authors should be '.
 3177:             'filesystem authenticated '.
 3178:             '(which allows access to the server filesystem).')."</i>\n";
 3179:     return $result;
 3180: }
 3181: 
 3182: sub authform_nochange {
 3183:     my %in = (
 3184:               formname => 'document.cu',
 3185:               kerb_def_dom => 'MSU.EDU',
 3186:               @_,
 3187:           );
 3188:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3189:     my $result;
 3190:     if (!$authnum) {
 3191:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 3192:     } else {
 3193:         $result = '<label>'.&mt('[_1] Do not change login data',
 3194:                   '<input type="radio" name="login" value="nochange" '.
 3195:                   'checked="checked" onclick="'.
 3196:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 3197: 	    '</label>';
 3198:     }
 3199:     return $result;
 3200: }
 3201: 
 3202: sub authform_kerberos {
 3203:     my %in = (
 3204:               formname => 'document.cu',
 3205:               kerb_def_dom => 'MSU.EDU',
 3206:               kerb_def_auth => 'krb4',
 3207:               @_,
 3208:               );
 3209:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 3210:         $autharg,$jscall,$disabled);
 3211:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3212:     if ($in{'kerb_def_auth'} eq 'krb5') {
 3213:        $check5 = ' checked="checked"';
 3214:     } else {
 3215:        $check4 = ' checked="checked"';
 3216:     }
 3217:     if ($in{'readonly'}) {
 3218:         $disabled = ' disabled="disabled"';
 3219:     }
 3220:     $krbarg = $in{'kerb_def_dom'};
 3221:     if (defined($in{'curr_authtype'})) {
 3222:         if ($in{'curr_authtype'} eq 'krb') {
 3223:             $krbcheck = ' checked="checked"';
 3224:             if (defined($in{'mode'})) {
 3225:                 if ($in{'mode'} eq 'modifyuser') {
 3226:                     $krbcheck = '';
 3227:                 }
 3228:             }
 3229:             if (defined($in{'curr_kerb_ver'})) {
 3230:                 if ($in{'curr_krb_ver'} eq '5') {
 3231:                     $check5 = ' checked="checked"';
 3232:                     $check4 = '';
 3233:                 } else {
 3234:                     $check4 = ' checked="checked"';
 3235:                     $check5 = '';
 3236:                 }
 3237:             }
 3238:             if (defined($in{'curr_autharg'})) {
 3239:                 $krbarg = $in{'curr_autharg'};
 3240:             }
 3241:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 3242:                 if (defined($in{'curr_autharg'})) {
 3243:                     $result = 
 3244:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 3245:         $in{'curr_autharg'},$krbver);
 3246:                 } else {
 3247:                     $result =
 3248:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 3249:                 }
 3250:                 return $result; 
 3251:             }
 3252:         }
 3253:     } else {
 3254:         if ($authnum == 1) {
 3255:             $authtype = '<input type="hidden" name="login" value="krb" />';
 3256:         }
 3257:     }
 3258:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 3259:         return;
 3260:     } elsif ($authtype eq '') {
 3261:         if (defined($in{'mode'})) {
 3262:             if ($in{'mode'} eq 'modifycourse') {
 3263:                 if ($authnum == 1) {
 3264:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
 3265:                 }
 3266:             }
 3267:         }
 3268:     }
 3269:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 3270:     if ($authtype eq '') {
 3271:         $authtype = '<input type="radio" name="login" value="krb" '.
 3272:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 3273:                     $krbcheck.$disabled.' />';
 3274:     }
 3275:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 3276:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 3277:          $in{'curr_authtype'} eq 'krb5') ||
 3278:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 3279:          $in{'curr_authtype'} eq 'krb4')) {
 3280:         $result .= &mt
 3281:         ('[_1] Kerberos authenticated with domain [_2] '.
 3282:          '[_3] Version 4 [_4] Version 5 [_5]',
 3283:          '<label>'.$authtype,
 3284:          '</label><input type="text" size="10" name="krbarg" '.
 3285:              'value="'.$krbarg.'" '.
 3286:              'onchange="'.$jscall.'"'.$disabled.' />',
 3287:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
 3288:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
 3289: 	 '</label>');
 3290:     } elsif ($can_assign{'krb4'}) {
 3291:         $result .= &mt
 3292:         ('[_1] Kerberos authenticated with domain [_2] '.
 3293:          '[_3] Version 4 [_4]',
 3294:          '<label>'.$authtype,
 3295:          '</label><input type="text" size="10" name="krbarg" '.
 3296:              'value="'.$krbarg.'" '.
 3297:              'onchange="'.$jscall.'"'.$disabled.' />',
 3298:          '<label><input type="hidden" name="krbver" value="4" />',
 3299:          '</label>');
 3300:     } elsif ($can_assign{'krb5'}) {
 3301:         $result .= &mt
 3302:         ('[_1] Kerberos authenticated with domain [_2] '.
 3303:          '[_3] Version 5 [_4]',
 3304:          '<label>'.$authtype,
 3305:          '</label><input type="text" size="10" name="krbarg" '.
 3306:              'value="'.$krbarg.'" '.
 3307:              'onchange="'.$jscall.'"'.$disabled.' />',
 3308:          '<label><input type="hidden" name="krbver" value="5" />',
 3309:          '</label>');
 3310:     }
 3311:     return $result;
 3312: }
 3313: 
 3314: sub authform_internal {
 3315:     my %in = (
 3316:                 formname => 'document.cu',
 3317:                 kerb_def_dom => 'MSU.EDU',
 3318:                 @_,
 3319:                 );
 3320:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
 3321:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3322:     if ($in{'readonly'}) {
 3323:         $disabled = ' disabled="disabled"';
 3324:     }
 3325:     if (defined($in{'curr_authtype'})) {
 3326:         if ($in{'curr_authtype'} eq 'int') {
 3327:             if ($can_assign{'int'}) {
 3328:                 $intcheck = 'checked="checked" ';
 3329:                 if (defined($in{'mode'})) {
 3330:                     if ($in{'mode'} eq 'modifyuser') {
 3331:                         $intcheck = '';
 3332:                     }
 3333:                 }
 3334:                 if (defined($in{'curr_autharg'})) {
 3335:                     $intarg = $in{'curr_autharg'};
 3336:                 }
 3337:             } else {
 3338:                 $result = &mt('Currently internally authenticated.');
 3339:                 return $result;
 3340:             }
 3341:         }
 3342:     } else {
 3343:         if ($authnum == 1) {
 3344:             $authtype = '<input type="hidden" name="login" value="int" />';
 3345:         }
 3346:     }
 3347:     if (!$can_assign{'int'}) {
 3348:         return;
 3349:     } elsif ($authtype eq '') {
 3350:         if (defined($in{'mode'})) {
 3351:             if ($in{'mode'} eq 'modifycourse') {
 3352:                 if ($authnum == 1) {
 3353:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
 3354:                 }
 3355:             }
 3356:         }
 3357:     }
 3358:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 3359:     if ($authtype eq '') {
 3360:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 3361:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
 3362:     }
 3363:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 3364:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3365:     $result = &mt
 3366:         ('[_1] Internally authenticated (with initial password [_2])',
 3367:          '<label>'.$authtype,'</label>'.$autharg);
 3368:     $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>';
 3369:     return $result;
 3370: }
 3371: 
 3372: sub authform_local {
 3373:     my %in = (
 3374:               formname => 'document.cu',
 3375:               kerb_def_dom => 'MSU.EDU',
 3376:               @_,
 3377:               );
 3378:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
 3379:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3380:     if ($in{'readonly'}) {
 3381:         $disabled = ' disabled="disabled"';
 3382:     } 
 3383:     if (defined($in{'curr_authtype'})) {
 3384:         if ($in{'curr_authtype'} eq 'loc') {
 3385:             if ($can_assign{'loc'}) {
 3386:                 $loccheck = 'checked="checked" ';
 3387:                 if (defined($in{'mode'})) {
 3388:                     if ($in{'mode'} eq 'modifyuser') {
 3389:                         $loccheck = '';
 3390:                     }
 3391:                 }
 3392:                 if (defined($in{'curr_autharg'})) {
 3393:                     $locarg = $in{'curr_autharg'};
 3394:                 }
 3395:             } else {
 3396:                 $result = &mt('Currently using local (institutional) authentication.');
 3397:                 return $result;
 3398:             }
 3399:         }
 3400:     } else {
 3401:         if ($authnum == 1) {
 3402:             $authtype = '<input type="hidden" name="login" value="loc" />';
 3403:         }
 3404:     }
 3405:     if (!$can_assign{'loc'}) {
 3406:         return;
 3407:     } elsif ($authtype eq '') {
 3408:         if (defined($in{'mode'})) {
 3409:             if ($in{'mode'} eq 'modifycourse') {
 3410:                 if ($authnum == 1) {
 3411:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
 3412:                 }
 3413:             }
 3414:         }
 3415:     }
 3416:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 3417:     if ($authtype eq '') {
 3418:         $authtype = '<input type="radio" name="login" value="loc" '.
 3419:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 3420:                     $jscall.'"'.$disabled.' />';
 3421:     }
 3422:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 3423:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3424:     $result = &mt('[_1] Local Authentication with argument [_2]',
 3425:                   '<label>'.$authtype,'</label>'.$autharg);
 3426:     return $result;
 3427: }
 3428: 
 3429: sub authform_filesystem {
 3430:     my %in = (
 3431:               formname => 'document.cu',
 3432:               kerb_def_dom => 'MSU.EDU',
 3433:               @_,
 3434:               );
 3435:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
 3436:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3437:     if ($in{'readonly'}) {
 3438:         $disabled = ' disabled="disabled"';
 3439:     }
 3440:     if (defined($in{'curr_authtype'})) {
 3441:         if ($in{'curr_authtype'} eq 'fsys') {
 3442:             if ($can_assign{'fsys'}) {
 3443:                 $fsyscheck = 'checked="checked" ';
 3444:                 if (defined($in{'mode'})) {
 3445:                     if ($in{'mode'} eq 'modifyuser') {
 3446:                         $fsyscheck = '';
 3447:                     }
 3448:                 }
 3449:             } else {
 3450:                 $result = &mt('Currently Filesystem Authenticated.');
 3451:                 return $result;
 3452:             }
 3453:         }
 3454:     } else {
 3455:         if ($authnum == 1) {
 3456:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 3457:         }
 3458:     }
 3459:     if (!$can_assign{'fsys'}) {
 3460:         return;
 3461:     } elsif ($authtype eq '') {
 3462:         if (defined($in{'mode'})) {
 3463:             if ($in{'mode'} eq 'modifycourse') {
 3464:                 if ($authnum == 1) {
 3465:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
 3466:                 }
 3467:             }
 3468:         }
 3469:     }
 3470:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 3471:     if ($authtype eq '') {
 3472:         $authtype = '<input type="radio" name="login" value="fsys" '.
 3473:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 3474:                     $jscall.'"'.$disabled.' />';
 3475:     }
 3476:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
 3477:                ' onchange="'.$jscall.'"'.$disabled.' />';
 3478:     $result = &mt
 3479:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 3480:          '<label>'.$authtype,'</label>'.$autharg);
 3481:     return $result;
 3482: }
 3483: 
 3484: sub authform_lti {
 3485:     my %in = (
 3486:               formname => 'document.cu',
 3487:               kerb_def_dom => 'MSU.EDU',
 3488:               @_,
 3489:               );
 3490:     my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
 3491:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3492:     if ($in{'readonly'}) {
 3493:         $disabled = ' disabled="disabled"';
 3494:     }
 3495:     if (defined($in{'curr_authtype'})) {
 3496:         if ($in{'curr_authtype'} eq 'lti') {
 3497:             if ($can_assign{'lti'}) {
 3498:                 $lticheck = 'checked="checked" ';
 3499:                 if (defined($in{'mode'})) {
 3500:                     if ($in{'mode'} eq 'modifyuser') {
 3501:                         $lticheck = '';
 3502:                     }
 3503:                 }
 3504:             } else {
 3505:                 $result = &mt('Currently LTI Authenticated.');
 3506:                 return $result;
 3507:             }
 3508:         }
 3509:     } else {
 3510:         if ($authnum == 1) {
 3511:             $authtype = '<input type="hidden" name="login" value="lti" />';
 3512:         }
 3513:     }
 3514:     if (!$can_assign{'lti'}) {
 3515:         return;
 3516:     } elsif ($authtype eq '') {
 3517:         if (defined($in{'mode'})) {
 3518:             if ($in{'mode'} eq 'modifycourse') {
 3519:                 if ($authnum == 1) {
 3520:                     $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
 3521:                 }
 3522:             }
 3523:         }
 3524:     }
 3525:     $jscall = "javascript:changed_radio('lti',$in{'formname'});";
 3526:     if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
 3527:         $authtype = '<input type="radio" name="login" value="lti" '.
 3528:                     $lticheck.' onchange="'.$jscall.'" onclick="'.
 3529:                     $jscall.'"'.$disabled.' />';
 3530:     }
 3531:     $autharg = '<input type="hidden" name="ltiarg" value="" />';
 3532:     if ($authtype) {
 3533:         $result = &mt('[_1] LTI Authenticated',
 3534:                       '<label>'.$authtype.'</label>'.$autharg);
 3535:     } else {
 3536:         $result = '<b>'.&mt('LTI Authenticated').'</b>'.
 3537:                   $autharg;
 3538:     }
 3539:     return $result;
 3540: }
 3541: 
 3542: sub get_assignable_auth {
 3543:     my ($dom) = @_;
 3544:     if ($dom eq '') {
 3545:         $dom = $env{'request.role.domain'};
 3546:     }
 3547:     my %can_assign = (
 3548:                           krb4 => 1,
 3549:                           krb5 => 1,
 3550:                           int  => 1,
 3551:                           loc  => 1,
 3552:                           lti  => 1,
 3553:                      );
 3554:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 3555:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 3556:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 3557:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 3558:             my $context;
 3559:             if ($env{'request.role'} =~ /^au/) {
 3560:                 $context = 'author';
 3561:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
 3562:                 $context = 'domain';
 3563:             } elsif ($env{'request.course.id'}) {
 3564:                 $context = 'course';
 3565:             }
 3566:             if ($context) {
 3567:                 if (ref($authhash->{$context}) eq 'HASH') {
 3568:                    %can_assign = %{$authhash->{$context}}; 
 3569:                 }
 3570:             }
 3571:         }
 3572:     }
 3573:     my $authnum = 0;
 3574:     foreach my $key (keys(%can_assign)) {
 3575:         if ($can_assign{$key}) {
 3576:             $authnum ++;
 3577:         }
 3578:     }
 3579:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 3580:         $authnum --;
 3581:     }
 3582:     return ($authnum,%can_assign);
 3583: }
 3584: 
 3585: sub check_passwd_rules {
 3586:     my ($domain,$plainpass) = @_;
 3587:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
 3588:     my ($min,$max,@chars,@brokerule,$warning);
 3589:     $min = $Apache::lonnet::passwdmin;
 3590:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
 3591:         if ($passwdconf{'min'} =~ /^\d+$/) {
 3592:             if ($passwdconf{'min'} > $min) {
 3593:                 $min = $passwdconf{'min'};
 3594:             }
 3595:         }
 3596:         if ($passwdconf{'max'} =~ /^\d+$/) {
 3597:             $max = $passwdconf{'max'};
 3598:         }
 3599:         @chars = @{$passwdconf{'chars'}};
 3600:     }
 3601:     if (($min) && (length($plainpass) < $min)) {
 3602:         push(@brokerule,'min');
 3603:     }
 3604:     if (($max) && (length($plainpass) > $max)) {
 3605:         push(@brokerule,'max');
 3606:     }
 3607:     if (@chars) {
 3608:         my %rules;
 3609:         map { $rules{$_} = 1; } @chars;
 3610:         if ($rules{'uc'}) {
 3611:             unless ($plainpass =~ /[A-Z]/) {
 3612:                 push(@brokerule,'uc');
 3613:             }
 3614:         }
 3615:         if ($rules{'lc'}) {
 3616:             unless ($plainpass =~ /[a-z]/) {
 3617:                 push(@brokerule,'lc');
 3618:             }
 3619:         }
 3620:         if ($rules{'num'}) {
 3621:             unless ($plainpass =~ /\d/) {
 3622:                 push(@brokerule,'num');
 3623:             }
 3624:         }
 3625:         if ($rules{'spec'}) {
 3626:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
 3627:                 push(@brokerule,'spec');
 3628:             }
 3629:         }
 3630:     }
 3631:     if (@brokerule) {
 3632:         my %rulenames = &Apache::lonlocal::texthash(
 3633:             uc   => 'At least one upper case letter',
 3634:             lc   => 'At least one lower case letter',
 3635:             num  => 'At least one number',
 3636:             spec => 'At least one non-alphanumeric',
 3637:         );
 3638:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
 3639:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
 3640:         $rulenames{'num'} .= ': 0123456789';
 3641:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
 3642:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
 3643:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
 3644:         $warning = &mt('Password did not satisfy the following:').'<ul>';
 3645:         foreach my $rule ('min','max','uc','lc','num','spec') {
 3646:             if (grep(/^$rule$/,@brokerule)) {
 3647:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
 3648:             }
 3649:         }
 3650:         $warning .= '</ul>';
 3651:     }
 3652:     if (wantarray) {
 3653:         return @brokerule;
 3654:     }
 3655:     return $warning;
 3656: }
 3657: 
 3658: sub passwd_validation_js {
 3659:     my ($currpasswdval,$domain,$context,$id) = @_;
 3660:     my (%passwdconf,$alertmsg);
 3661:     if ($context eq 'linkprot') {
 3662:         my %domconfig = &Apache::lonnet::get_dom('configuration',['ltisec'],$domain);
 3663:         if (ref($domconfig{'ltisec'}) eq 'HASH') {
 3664:             if (ref($domconfig{'ltisec'}{'rules'}) eq 'HASH') {
 3665:                 %passwdconf = %{$domconfig{'ltisec'}{'rules'}};
 3666:             }
 3667:         }
 3668:         if ($id eq 'add') {
 3669:             $alertmsg = &mt('Secret for added launcher did not satisfy requirement(s):').'\n\n';
 3670:         } elsif ($id =~ /^\d+$/) {
 3671:             my $pos = $id+1;
 3672:             $alertmsg = &mt('Secret for launcher [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
 3673:         } else {
 3674:             $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
 3675:         }
 3676:     } else {
 3677:         %passwdconf = &Apache::lonnet::get_passwdconf($domain);
 3678:         $alertmsg = &mt('Initial password did not satisfy requirement(s):').'\n\n';
 3679:     }
 3680:     my ($min,$max,@chars,$numrules,$intargjs,%alert);
 3681:     $numrules = 0;
 3682:     $min = $Apache::lonnet::passwdmin;
 3683:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
 3684:         if ($passwdconf{'min'} =~ /^\d+$/) {
 3685:             if ($passwdconf{'min'} > $min) {
 3686:                 $min = $passwdconf{'min'};
 3687:             }
 3688:         }
 3689:         if ($passwdconf{'max'} =~ /^\d+$/) {
 3690:             $max = $passwdconf{'max'};
 3691:             $numrules ++;
 3692:         }
 3693:         @chars = @{$passwdconf{'chars'}};
 3694:         if (@chars) {
 3695:             $numrules ++;
 3696:         }
 3697:     }
 3698:     if ($min > 0) {
 3699:         $numrules ++;
 3700:     }
 3701:     if (($min > 0) || ($max ne '') || (@chars > 0)) {
 3702:         if ($min) {
 3703:             $alert{'min'} = &mt('minimum [quant,_1,character]',$min).'\n';
 3704:         }
 3705:         if ($max) {
 3706:             $alert{'max'} = &mt('maximum [quant,_1,character]',$max).'\n';
 3707:         }
 3708:         my (@charalerts,@charrules);
 3709:         if (@chars) {
 3710:             if (grep(/^uc$/,@chars)) {
 3711:                 push(@charalerts,&mt('contain at least one upper case letter'));
 3712:                 push(@charrules,'uc');
 3713:             }
 3714:             if (grep(/^lc$/,@chars)) {
 3715:                 push(@charalerts,&mt('contain at least one lower case letter'));
 3716:                 push(@charrules,'lc');
 3717:             }
 3718:             if (grep(/^num$/,@chars)) {
 3719:                 push(@charalerts,&mt('contain at least one number'));
 3720:                 push(@charrules,'num');
 3721:             }
 3722:             if (grep(/^spec$/,@chars)) {
 3723:                 push(@charalerts,&mt('contain at least one non-alphanumeric'));
 3724:                 push(@charrules,'spec');
 3725:             }
 3726:         }
 3727:         $intargjs = qq|            var rulesmsg = '';\n|.
 3728:                     qq|            var currpwval = $currpasswdval;\n|;
 3729:             if ($min) {
 3730:                 $intargjs .= qq|
 3731:             if (currpwval.length < $min) {
 3732:                 rulesmsg += ' - $alert{min}';
 3733:             }
 3734: |;
 3735:             }
 3736:             if ($max) {
 3737:                 $intargjs .= qq|
 3738:             if (currpwval.length > $max) {
 3739:                 rulesmsg += ' - $alert{max}';
 3740:             }
 3741: |;
 3742:             }
 3743:             if (@chars > 0) {
 3744:                 my $charrulestr = '"'.join('","',@charrules).'"';
 3745:                 my $charalertstr = '"'.join('","',@charalerts).'"';
 3746:                 $intargjs .= qq|            var brokerules = new Array();\n|.
 3747:                              qq|            var charrules = new Array($charrulestr);\n|.
 3748:                              qq|            var charalerts = new Array($charalertstr);\n|;
 3749:                 my %rules;
 3750:                 map { $rules{$_} = 1; } @chars;
 3751:                 if ($rules{'uc'}) {
 3752:                     $intargjs .= qq|
 3753:             var ucRegExp = /[A-Z]/;
 3754:             if (!ucRegExp.test(currpwval)) {
 3755:                 brokerules.push('uc');
 3756:             }
 3757: |;
 3758:                 }
 3759:                 if ($rules{'lc'}) {
 3760:                     $intargjs .= qq|
 3761:             var lcRegExp = /[a-z]/;
 3762:             if (!lcRegExp.test(currpwval)) {
 3763:                 brokerules.push('lc');
 3764:             }
 3765: |;
 3766:                 }
 3767:                 if ($rules{'num'}) {
 3768:                      $intargjs .= qq|
 3769:             var numRegExp = /[0-9]/;
 3770:             if (!numRegExp.test(currpwval)) {
 3771:                 brokerules.push('num');
 3772:             }
 3773: |;
 3774:                 }
 3775:                 if ($rules{'spec'}) {
 3776:                      $intargjs .= q|
 3777:             var specRegExp = /[!"#$%&'()*+,\-.\/:;<=>?@[\\^\]_`{\|}~]/;
 3778:             if (!specRegExp.test(currpwval)) {
 3779:                 brokerules.push('spec');
 3780:             }
 3781: |;
 3782:                 }
 3783:                 $intargjs .= qq|
 3784:             if (brokerules.length > 0) {
 3785:                 for (var i=0; i<brokerules.length; i++) {
 3786:                     for (var j=0; j<charrules.length; j++) {
 3787:                         if (brokerules[i] == charrules[j]) {
 3788:                             rulesmsg += ' - '+charalerts[j]+'\\n';
 3789:                             break;
 3790:                         }
 3791:                     }
 3792:                 }
 3793:             }
 3794: |;
 3795:             }
 3796:             $intargjs .= qq|
 3797:             if (rulesmsg != '') {
 3798:                 rulesmsg = '$alertmsg'+rulesmsg;
 3799:                 alert(rulesmsg);
 3800:                 return false;
 3801:             }
 3802: |;
 3803:     }
 3804:     return ($numrules,$intargjs);
 3805: }
 3806: 
 3807: ###############################################################
 3808: ##    Get Kerberos Defaults for Domain                 ##
 3809: ###############################################################
 3810: ##
 3811: ## Returns default kerberos version and an associated argument
 3812: ## as listed in file domain.tab. If not listed, provides
 3813: ## appropriate default domain and kerberos version.
 3814: ##
 3815: #-------------------------------------------
 3816: 
 3817: =pod
 3818: 
 3819: =item * &get_kerberos_defaults()
 3820: 
 3821: get_kerberos_defaults($target_domain) returns the default kerberos
 3822: version and domain. If not found, it defaults to version 4 and the 
 3823: domain of the server.
 3824: 
 3825: =over 4
 3826: 
 3827: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 3828: 
 3829: =back
 3830: 
 3831: =back
 3832: 
 3833: =cut
 3834: 
 3835: #-------------------------------------------
 3836: sub get_kerberos_defaults {
 3837:     my $domain=shift;
 3838:     my ($krbdef,$krbdefdom);
 3839:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 3840:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 3841:         $krbdef = $domdefaults{'auth_def'};
 3842:         $krbdefdom = $domdefaults{'auth_arg_def'};
 3843:     } else {
 3844:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 3845:         my $krbdefdom=$1;
 3846:         $krbdefdom=~tr/a-z/A-Z/;
 3847:         $krbdef = "krb4";
 3848:     }
 3849:     return ($krbdef,$krbdefdom);
 3850: }
 3851: 
 3852: 
 3853: ###############################################################
 3854: ##                Thesaurus Functions                        ##
 3855: ###############################################################
 3856: 
 3857: =pod
 3858: 
 3859: =head1 Thesaurus Functions
 3860: 
 3861: =over 4
 3862: 
 3863: =item * &initialize_keywords()
 3864: 
 3865: Initializes the package variable %Keywords if it is empty.  Uses the
 3866: package variable $thesaurus_db_file.
 3867: 
 3868: =cut
 3869: 
 3870: ###################################################
 3871: 
 3872: sub initialize_keywords {
 3873:     return 1 if (scalar keys(%Keywords));
 3874:     # If we are here, %Keywords is empty, so fill it up
 3875:     #   Make sure the file we need exists...
 3876:     if (! -e $thesaurus_db_file) {
 3877:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 3878:                                  " failed because it does not exist");
 3879:         return 0;
 3880:     }
 3881:     #   Set up the hash as a database
 3882:     my %thesaurus_db;
 3883:     if (! tie(%thesaurus_db,'GDBM_File',
 3884:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3885:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 3886:                                  $thesaurus_db_file);
 3887:         return 0;
 3888:     } 
 3889:     #  Get the average number of appearances of a word.
 3890:     my $avecount = $thesaurus_db{'average.count'};
 3891:     #  Put keywords (those that appear > average) into %Keywords
 3892:     while (my ($word,$data)=each (%thesaurus_db)) {
 3893:         my ($count,undef) = split /:/,$data;
 3894:         $Keywords{$word}++ if ($count > $avecount);
 3895:     }
 3896:     untie %thesaurus_db;
 3897:     # Remove special values from %Keywords.
 3898:     foreach my $value ('total.count','average.count') {
 3899:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 3900:   }
 3901:     return 1;
 3902: }
 3903: 
 3904: ###################################################
 3905: 
 3906: =pod
 3907: 
 3908: =item * &keyword($word)
 3909: 
 3910: Returns true if $word is a keyword.  A keyword is a word that appears more 
 3911: than the average number of times in the thesaurus database.  Calls 
 3912: &initialize_keywords
 3913: 
 3914: =cut
 3915: 
 3916: ###################################################
 3917: 
 3918: sub keyword {
 3919:     return if (!&initialize_keywords());
 3920:     my $word=lc(shift());
 3921:     $word=~s/\W//g;
 3922:     return exists($Keywords{$word});
 3923: }
 3924: 
 3925: ###############################################################
 3926: 
 3927: =pod 
 3928: 
 3929: =item * &get_related_words()
 3930: 
 3931: Look up a word in the thesaurus.  Takes a scalar argument and returns
 3932: an array of words.  If the keyword is not in the thesaurus, an empty array
 3933: will be returned.  The order of the words returned is determined by the
 3934: database which holds them.
 3935: 
 3936: Uses global $thesaurus_db_file.
 3937: 
 3938: 
 3939: =cut
 3940: 
 3941: ###############################################################
 3942: sub get_related_words {
 3943:     my $keyword = shift;
 3944:     my %thesaurus_db;
 3945:     if (! -e $thesaurus_db_file) {
 3946:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 3947:                                  "failed because the file does not exist");
 3948:         return ();
 3949:     }
 3950:     if (! tie(%thesaurus_db,'GDBM_File',
 3951:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3952:         return ();
 3953:     } 
 3954:     my @Words=();
 3955:     my $count=0;
 3956:     if (exists($thesaurus_db{$keyword})) {
 3957: 	# The first element is the number of times
 3958: 	# the word appears.  We do not need it now.
 3959: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 3960: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 3961: 	my $threshold=$mostfrequentcount/10;
 3962:         foreach my $possibleword (@RelatedWords) {
 3963:             my ($word,$wordcount)=split(/\,/,$possibleword);
 3964:             if ($wordcount>$threshold) {
 3965: 		push(@Words,$word);
 3966:                 $count++;
 3967:                 if ($count>10) { last; }
 3968: 	    }
 3969:         }
 3970:     }
 3971:     untie %thesaurus_db;
 3972:     return @Words;
 3973: }
 3974: ###############################################################
 3975: #
 3976: #  Spell checking
 3977: #
 3978: 
 3979: =pod
 3980: 
 3981: =back
 3982: 
 3983: =head1 Spell checking
 3984: 
 3985: =over 4
 3986: 
 3987: =item * &check_spelling($wordlist $language)
 3988: 
 3989: Takes a string containing words and feeds it to an external
 3990: spellcheck program via a pipeline. Returns a string containing
 3991: them mis-spelled words.
 3992: 
 3993: Parameters:
 3994: 
 3995: =over 4
 3996: 
 3997: =item - $wordlist
 3998: 
 3999: String that will be fed into the spellcheck program.
 4000: 
 4001: =item - $language
 4002: 
 4003: Language string that specifies the language for which the spell
 4004: check will be performed.
 4005: 
 4006: =back
 4007: 
 4008: =back
 4009: 
 4010: Note: This sub assumes that aspell is installed.
 4011: 
 4012: 
 4013: =cut
 4014: 
 4015: 
 4016: sub check_spelling {
 4017:     my ($wordlist, $language) = @_;
 4018:     my @misspellings;
 4019:     
 4020:     # Generate the speller and set the langauge.
 4021:     # if explicitly selected:
 4022: 
 4023:     my $speller = Text::Aspell->new;
 4024:     if ($language) {
 4025: 	$speller->set_option('lang', $language);
 4026:     }
 4027: 
 4028:     # Turn the word list into an array of words by splittingon whitespace
 4029: 
 4030:     my @words = split(/\s+/, $wordlist);
 4031: 
 4032:     foreach my $word (@words) {
 4033: 	if(! $speller->check($word)) {
 4034: 	    push(@misspellings, $word);
 4035: 	}
 4036:     }
 4037:     return join(' ', @misspellings);
 4038:     
 4039: }
 4040: 
 4041: # -------------------------------------------------------------- Plaintext name
 4042: =pod
 4043: 
 4044: =head1 User Name Functions
 4045: 
 4046: =over 4
 4047: 
 4048: =item * &plainname($uname,$udom,$first)
 4049: 
 4050: Takes a users logon name and returns it as a string in
 4051: "first middle last generation" form 
 4052: if $first is set to 'lastname' then it returns it as
 4053: 'lastname generation, firstname middlename' if their is a lastname
 4054: 
 4055: =cut
 4056: 
 4057: 
 4058: ###############################################################
 4059: sub plainname {
 4060:     my ($uname,$udom,$first)=@_;
 4061:     return if (!defined($uname) || !defined($udom));
 4062:     my %names=&getnames($uname,$udom);
 4063:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 4064: 					  $names{'middlename'},
 4065: 					  $names{'lastname'},
 4066: 					  $names{'generation'},$first);
 4067:     $name=~s/^\s+//;
 4068:     $name=~s/\s+$//;
 4069:     $name=~s/\s+/ /g;
 4070:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 4071:     return $name;
 4072: }
 4073: 
 4074: # -------------------------------------------------------------------- Nickname
 4075: =pod
 4076: 
 4077: =item * &nickname($uname,$udom)
 4078: 
 4079: Gets a users name and returns it as a string as
 4080: 
 4081: "&quot;nickname&quot;"
 4082: 
 4083: if the user has a nickname or
 4084: 
 4085: "first middle last generation"
 4086: 
 4087: if the user does not
 4088: 
 4089: =cut
 4090: 
 4091: sub nickname {
 4092:     my ($uname,$udom)=@_;
 4093:     return if (!defined($uname) || !defined($udom));
 4094:     my %names=&getnames($uname,$udom);
 4095:     my $name=$names{'nickname'};
 4096:     if ($name) {
 4097:        $name='&quot;'.$name.'&quot;'; 
 4098:     } else {
 4099:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 4100: 	     $names{'lastname'}.' '.$names{'generation'};
 4101:        $name=~s/\s+$//;
 4102:        $name=~s/\s+/ /g;
 4103:     }
 4104:     return $name;
 4105: }
 4106: 
 4107: sub getnames {
 4108:     my ($uname,$udom)=@_;
 4109:     return if (!defined($uname) || !defined($udom));
 4110:     if ($udom eq 'public' && $uname eq 'public') {
 4111: 	return ('lastname' => &mt('Public'));
 4112:     }
 4113:     my $id=$uname.':'.$udom;
 4114:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 4115:     if ($cached) {
 4116: 	return %{$names};
 4117:     } else {
 4118: 	my %loadnames=&Apache::lonnet::get('environment',
 4119:                     ['firstname','middlename','lastname','generation','nickname'],
 4120: 					 $udom,$uname);
 4121: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 4122: 	return %loadnames;
 4123:     }
 4124: }
 4125: 
 4126: # -------------------------------------------------------------------- getemails
 4127: 
 4128: =pod
 4129: 
 4130: =item * &getemails($uname,$udom)
 4131: 
 4132: Gets a user's email information and returns it as a hash with keys:
 4133: notification, critnotification, permanentemail
 4134: 
 4135: For notification and critnotification, values are comma-separated lists 
 4136: of e-mail addresses; for permanentemail, value is a single e-mail address.
 4137:  
 4138: 
 4139: =cut
 4140: 
 4141: 
 4142: sub getemails {
 4143:     my ($uname,$udom)=@_;
 4144:     if ($udom eq 'public' && $uname eq 'public') {
 4145: 	return;
 4146:     }
 4147:     if (!$udom) { $udom=$env{'user.domain'}; }
 4148:     if (!$uname) { $uname=$env{'user.name'}; }
 4149:     my $id=$uname.':'.$udom;
 4150:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 4151:     if ($cached) {
 4152: 	return %{$names};
 4153:     } else {
 4154: 	my %loadnames=&Apache::lonnet::get('environment',
 4155:                     			   ['notification','critnotification',
 4156: 					    'permanentemail'],
 4157: 					   $udom,$uname);
 4158: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 4159: 	return %loadnames;
 4160:     }
 4161: }
 4162: 
 4163: sub flush_email_cache {
 4164:     my ($uname,$udom)=@_;
 4165:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4166:     if (!$uname) { $uname=$env{'user.name'};   }
 4167:     return if ($udom eq 'public' && $uname eq 'public');
 4168:     my $id=$uname.':'.$udom;
 4169:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 4170: }
 4171: 
 4172: # -------------------------------------------------------------------- getlangs
 4173: 
 4174: =pod
 4175: 
 4176: =item * &getlangs($uname,$udom)
 4177: 
 4178: Gets a user's language preference and returns it as a hash with key:
 4179: language.
 4180: 
 4181: =cut
 4182: 
 4183: 
 4184: sub getlangs {
 4185:     my ($uname,$udom) = @_;
 4186:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4187:     if (!$uname) { $uname=$env{'user.name'};   }
 4188:     my $id=$uname.':'.$udom;
 4189:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 4190:     if ($cached) {
 4191:         return %{$langs};
 4192:     } else {
 4193:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 4194:                                            $udom,$uname);
 4195:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 4196:         return %loadlangs;
 4197:     }
 4198: }
 4199: 
 4200: sub flush_langs_cache {
 4201:     my ($uname,$udom)=@_;
 4202:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4203:     if (!$uname) { $uname=$env{'user.name'};   }
 4204:     return if ($udom eq 'public' && $uname eq 'public');
 4205:     my $id=$uname.':'.$udom;
 4206:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 4207: }
 4208: 
 4209: # ------------------------------------------------------------------ Screenname
 4210: 
 4211: =pod
 4212: 
 4213: =item * &screenname($uname,$udom)
 4214: 
 4215: Gets a users screenname and returns it as a string
 4216: 
 4217: =cut
 4218: 
 4219: sub screenname {
 4220:     my ($uname,$udom)=@_;
 4221:     if ($uname eq $env{'user.name'} &&
 4222: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 4223:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 4224:     return $names{'screenname'};
 4225: }
 4226: 
 4227: 
 4228: # ------------------------------------------------------------- Confirm Wrapper
 4229: =pod
 4230: 
 4231: =item * &confirmwrapper($message)
 4232: 
 4233: Wrap messages about completion of operation in box
 4234: 
 4235: =cut
 4236: 
 4237: sub confirmwrapper {
 4238:     my ($message)=@_;
 4239:     if ($message) {
 4240:         return "\n".'<div class="LC_confirm_box">'."\n"
 4241:                .$message."\n"
 4242:                .'</div>'."\n";
 4243:     } else {
 4244:         return $message;
 4245:     }
 4246: }
 4247: 
 4248: # ------------------------------------------------------------- Message Wrapper
 4249: 
 4250: sub messagewrapper {
 4251:     my ($link,$username,$domain,$subject,$text)=@_;
 4252:     return 
 4253:         '<a href="/adm/email?compose=individual&amp;'.
 4254:         'recname='.$username.'&amp;recdom='.$domain.
 4255: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 4256:         'title="'.&mt('Send message').'">'.$link.'</a>';
 4257: }
 4258: 
 4259: # --------------------------------------------------------------- Notes Wrapper
 4260: 
 4261: sub noteswrapper {
 4262:     my ($link,$un,$do)=@_;
 4263:     return 
 4264: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 4265: }
 4266: 
 4267: # ------------------------------------------------------------- Aboutme Wrapper
 4268: 
 4269: sub aboutmewrapper {
 4270:     my ($link,$username,$domain,$target,$class)=@_;
 4271:     if (!defined($username)  && !defined($domain)) {
 4272:         return;
 4273:     }
 4274:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 4275: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 4276: }
 4277: 
 4278: # ------------------------------------------------------------ Syllabus Wrapper
 4279: 
 4280: sub syllabuswrapper {
 4281:     my ($linktext,$coursedir,$domain)=@_;
 4282:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 4283: }
 4284: 
 4285: # -----------------------------------------------------------------------------
 4286: 
 4287: sub track_student_link {
 4288:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 4289:     my $link ="/adm/trackstudent?";
 4290:     my $title = 'View recent activity';
 4291:     if (defined($sname) && $sname !~ /^\s*$/ &&
 4292:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 4293:         $link .= "selected_student=$sname:$sdom";
 4294:         $title .= ' of this student';
 4295:     } 
 4296:     if (defined($target) && $target !~ /^\s*$/) {
 4297:         $target = qq{target="$target"};
 4298:     } else {
 4299:         $target = '';
 4300:     }
 4301:     if ($start) { $link.='&amp;start='.$start; }
 4302:     if ($only_body) { $link .= '&amp;only_body=1'; }
 4303:     $title = &mt($title);
 4304:     $linktext = &mt($linktext);
 4305:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 4306: 	&help_open_topic('View_recent_activity');
 4307: }
 4308: 
 4309: sub slot_reservations_link {
 4310:     my ($linktext,$sname,$sdom,$target) = @_;
 4311:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 4312:     my $title = 'View slot reservation history';
 4313:     if (defined($sname) && $sname !~ /^\s*$/ &&
 4314:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 4315:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 4316:         $title .= ' of this student';
 4317:     }
 4318:     if (defined($target) && $target !~ /^\s*$/) {
 4319:         $target = qq{target="$target"};
 4320:     } else {
 4321:         $target = '';
 4322:     }
 4323:     $title = &mt($title);
 4324:     $linktext = &mt($linktext);
 4325:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 4326: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 4327: 
 4328: }
 4329: 
 4330: # ===================================================== Display a student photo
 4331: 
 4332: 
 4333: sub student_image_tag {
 4334:     my ($domain,$user)=@_;
 4335:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 4336:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 4337: 	return '<img src="'.$imgsrc.'" align="right" />';
 4338:     } else {
 4339: 	return '';
 4340:     }
 4341: }
 4342: 
 4343: =pod
 4344: 
 4345: =back
 4346: 
 4347: =head1 Access .tab File Data
 4348: 
 4349: =over 4
 4350: 
 4351: =item * &languageids() 
 4352: 
 4353: returns list of all language ids
 4354: 
 4355: =cut
 4356: 
 4357: sub languageids {
 4358:     return sort(keys(%language));
 4359: }
 4360: 
 4361: =pod
 4362: 
 4363: =item * &languagedescription() 
 4364: 
 4365: returns description of a specified language id
 4366: 
 4367: =cut
 4368: 
 4369: sub languagedescription {
 4370:     my $code=shift;
 4371:     return  ($supported_language{$code}?'* ':'').
 4372:             $language{$code}.
 4373: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 4374: }
 4375: 
 4376: =pod
 4377: 
 4378: =item * &plainlanguagedescription
 4379: 
 4380: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 4381: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 4382: 
 4383: =cut
 4384: 
 4385: sub plainlanguagedescription {
 4386:     my $code=shift;
 4387:     return $language{$code};
 4388: }
 4389: 
 4390: =pod
 4391: 
 4392: =item * &supportedlanguagecode
 4393: 
 4394: Returns the supported language code (e.g. sptutf maps to pt) given a language
 4395: code.
 4396: 
 4397: =cut
 4398: 
 4399: sub supportedlanguagecode {
 4400:     my $code=shift;
 4401:     return $supported_language{$code};
 4402: }
 4403: 
 4404: =pod
 4405: 
 4406: =item * &latexlanguage()
 4407: 
 4408: Given a language key code returns the correspondnig language to use
 4409: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 4410: is no supported hyphenation for the language code.
 4411: 
 4412: =cut
 4413: 
 4414: sub latexlanguage {
 4415:     my $code = shift;
 4416:     return $latex_language{$code};
 4417: }
 4418: 
 4419: =pod
 4420: 
 4421: =item * &latexhyphenation()
 4422: 
 4423: Same as above but what's supplied is the language as it might be stored
 4424: in the metadata.
 4425: 
 4426: =cut
 4427: 
 4428: sub latexhyphenation {
 4429:     my $key = shift;
 4430:     return $latex_language_bykey{$key};
 4431: }
 4432: 
 4433: =pod
 4434: 
 4435: =item * &copyrightids() 
 4436: 
 4437: returns list of all copyrights
 4438: 
 4439: =cut
 4440: 
 4441: sub copyrightids {
 4442:     return sort(keys(%cprtag));
 4443: }
 4444: 
 4445: =pod
 4446: 
 4447: =item * &copyrightdescription() 
 4448: 
 4449: returns description of a specified copyright id
 4450: 
 4451: =cut
 4452: 
 4453: sub copyrightdescription {
 4454:     return &mt($cprtag{shift(@_)});
 4455: }
 4456: 
 4457: =pod
 4458: 
 4459: =item * &source_copyrightids() 
 4460: 
 4461: returns list of all source copyrights
 4462: 
 4463: =cut
 4464: 
 4465: sub source_copyrightids {
 4466:     return sort(keys(%scprtag));
 4467: }
 4468: 
 4469: =pod
 4470: 
 4471: =item * &source_copyrightdescription() 
 4472: 
 4473: returns description of a specified source copyright id
 4474: 
 4475: =cut
 4476: 
 4477: sub source_copyrightdescription {
 4478:     return &mt($scprtag{shift(@_)});
 4479: }
 4480: 
 4481: =pod
 4482: 
 4483: =item * &filecategories() 
 4484: 
 4485: returns list of all file categories
 4486: 
 4487: =cut
 4488: 
 4489: sub filecategories {
 4490:     return sort(keys(%category_extensions));
 4491: }
 4492: 
 4493: =pod
 4494: 
 4495: =item * &filecategorytypes() 
 4496: 
 4497: returns list of file types belonging to a given file
 4498: category
 4499: 
 4500: =cut
 4501: 
 4502: sub filecategorytypes {
 4503:     my ($cat) = @_;
 4504:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
 4505:         return @{$category_extensions{lc($cat)}};
 4506:     } else {
 4507:         return ();
 4508:     }
 4509: }
 4510: 
 4511: =pod
 4512: 
 4513: =item * &fileembstyle() 
 4514: 
 4515: returns embedding style for a specified file type
 4516: 
 4517: =cut
 4518: 
 4519: sub fileembstyle {
 4520:     return $fe{lc(shift(@_))};
 4521: }
 4522: 
 4523: sub filemimetype {
 4524:     return $fm{lc(shift(@_))};
 4525: }
 4526: 
 4527: 
 4528: sub filecategoryselect {
 4529:     my ($name,$value)=@_;
 4530:     return &select_form($value,$name,
 4531:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 4532: }
 4533: 
 4534: =pod
 4535: 
 4536: =item * &filedescription() 
 4537: 
 4538: returns description for a specified file type
 4539: 
 4540: =cut
 4541: 
 4542: sub filedescription {
 4543:     my $file_description = $fd{lc(shift())};
 4544:     $file_description =~ s:([\[\]]):~$1:g;
 4545:     return &mt($file_description);
 4546: }
 4547: 
 4548: =pod
 4549: 
 4550: =item * &filedescriptionex() 
 4551: 
 4552: returns description for a specified file type with
 4553: extra formatting
 4554: 
 4555: =cut
 4556: 
 4557: sub filedescriptionex {
 4558:     my $ex=shift;
 4559:     my $file_description = $fd{lc($ex)};
 4560:     $file_description =~ s:([\[\]]):~$1:g;
 4561:     return '.'.$ex.' '.&mt($file_description);
 4562: }
 4563: 
 4564: # End of .tab access
 4565: =pod
 4566: 
 4567: =back
 4568: 
 4569: =cut
 4570: 
 4571: # ------------------------------------------------------------------ File Types
 4572: sub fileextensions {
 4573:     return sort(keys(%fe));
 4574: }
 4575: 
 4576: # ----------------------------------------------------------- Display Languages
 4577: # returns a hash with all desired display languages
 4578: #
 4579: 
 4580: sub display_languages {
 4581:     my %languages=();
 4582:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 4583: 	$languages{$lang}=1;
 4584:     }
 4585:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 4586:     if ($env{'form.displaylanguage'}) {
 4587: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 4588: 	    $languages{$lang}=1;
 4589:         }
 4590:     }
 4591:     return %languages;
 4592: }
 4593: 
 4594: sub languages {
 4595:     my ($possible_langs) = @_;
 4596:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 4597:     if (!ref($possible_langs)) {
 4598: 	if( wantarray ) {
 4599: 	    return @preferred_langs;
 4600: 	} else {
 4601: 	    return $preferred_langs[0];
 4602: 	}
 4603:     }
 4604:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 4605:     my @preferred_possibilities;
 4606:     foreach my $preferred_lang (@preferred_langs) {
 4607: 	if (exists($possibilities{$preferred_lang})) {
 4608: 	    push(@preferred_possibilities, $preferred_lang);
 4609: 	}
 4610:     }
 4611:     if( wantarray ) {
 4612: 	return @preferred_possibilities;
 4613:     }
 4614:     return $preferred_possibilities[0];
 4615: }
 4616: 
 4617: sub user_lang {
 4618:     my ($touname,$toudom,$fromcid) = @_;
 4619:     my @userlangs;
 4620:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 4621:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 4622:                     $env{'course.'.$fromcid.'.languages'}));
 4623:     } else {
 4624:         my %langhash = &getlangs($touname,$toudom);
 4625:         if ($langhash{'languages'} ne '') {
 4626:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 4627:         } else {
 4628:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 4629:             if ($domdefs{'lang_def'} ne '') {
 4630:                 @userlangs = ($domdefs{'lang_def'});
 4631:             }
 4632:         }
 4633:     }
 4634:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 4635:     my $user_lh = Apache::localize->get_handle(@languages);
 4636:     return $user_lh;
 4637: }
 4638: 
 4639: 
 4640: ###############################################################
 4641: ##               Student Answer Attempts                     ##
 4642: ###############################################################
 4643: 
 4644: =pod
 4645: 
 4646: =head1 Alternate Problem Views
 4647: 
 4648: =over 4
 4649: 
 4650: =item * &get_previous_attempt($symb, $username, $domain, $course,
 4651:     $getattempt, $regexp, $gradesub, $usec, $identifier)
 4652: 
 4653: Return string with previous attempt on problem. Arguments:
 4654: 
 4655: =over 4
 4656: 
 4657: =item * $symb: Problem, including path
 4658: 
 4659: =item * $username: username of the desired student
 4660: 
 4661: =item * $domain: domain of the desired student
 4662: 
 4663: =item * $course: Course ID
 4664: 
 4665: =item * $getattempt: Leave blank for all attempts, otherwise put
 4666:     something
 4667: 
 4668: =item * $regexp: if string matches this regexp, the string will be
 4669:     sent to $gradesub
 4670: 
 4671: =item * $gradesub: routine that processes the string if it matches $regexp
 4672: 
 4673: =item * $usec: section of the desired student
 4674: 
 4675: =item * $identifier: counter for student (multiple students one problem) or 
 4676:     problem (one student; whole sequence).
 4677: 
 4678: =back
 4679: 
 4680: The output string is a table containing all desired attempts, if any.
 4681: 
 4682: =cut
 4683: 
 4684: sub get_previous_attempt {
 4685:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
 4686:   my $prevattempts='';
 4687:   no strict 'refs';
 4688:   if ($symb) {
 4689:     my (%returnhash)=
 4690:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 4691:     if ($returnhash{'version'}) {
 4692:       my %lasthash=();
 4693:       my $version;
 4694:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 4695:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
 4696:             if ($key =~ /\.rawrndseed$/) {
 4697:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
 4698:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
 4699:             } else {
 4700:                 $lasthash{$key}=$returnhash{$version.':'.$key};
 4701:             }
 4702:         }
 4703:       }
 4704:       $prevattempts=&start_data_table().&start_data_table_header_row();
 4705:       $prevattempts.='<th>'.&mt('History').'</th>';
 4706:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
 4707:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 4708:       foreach my $key (sort(keys(%lasthash))) {
 4709: 	my ($ign,@parts) = split(/\./,$key);
 4710: 	if ($#parts > 0) {
 4711: 	  my $data=$parts[-1];
 4712:           next if ($data eq 'foilorder');
 4713: 	  pop(@parts);
 4714:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 4715:           if ($data eq 'type') {
 4716:               unless ($showsurv) {
 4717:                   my $id = join(',',@parts);
 4718:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 4719:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 4720:                       $lasthidden{$ign.'.'.$id} = 1;
 4721:                   }
 4722:               }
 4723:               if ($identifier ne '') {
 4724:                   my $id = join(',',@parts);
 4725:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
 4726:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
 4727:                       $hidestatus{$ign.'.'.$id} = 1;
 4728:                   }
 4729:               }
 4730:           } elsif ($data eq 'regrader') {
 4731:               if (($identifier ne '') && (@parts)) {
 4732:                   my $id = join(',',@parts);
 4733:                   $regraded{$ign.'.'.$id} = 1;
 4734:               }
 4735:           } 
 4736: 	} else {
 4737: 	  if ($#parts == 0) {
 4738: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 4739: 	  } else {
 4740: 	    $prevattempts.='<th>'.$ign.'</th>';
 4741: 	  }
 4742: 	}
 4743:       }
 4744:       $prevattempts.=&end_data_table_header_row();
 4745:       if ($getattempt eq '') {
 4746:         my (%solved,%resets,%probstatus);
 4747:         if (($identifier ne '') && (keys(%regraded) > 0)) {
 4748:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 4749:                 foreach my $id (keys(%regraded)) {
 4750:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
 4751:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
 4752:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
 4753:                         push(@{$resets{$id}},$version);
 4754:                     }
 4755:                 }
 4756:             }
 4757:         }
 4758: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 4759:             my (@hidden,@unsolved);
 4760:             if (%typeparts) {
 4761:                 foreach my $id (keys(%typeparts)) {
 4762:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
 4763:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 4764:                         push(@hidden,$id);
 4765:                     } elsif ($identifier ne '') {
 4766:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
 4767:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
 4768:                                 ($hidestatus{$id})) {
 4769:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
 4770:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
 4771:                                 push(@{$solved{$id}},$version);
 4772:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
 4773:                                      (ref($solved{$id}) eq 'ARRAY')) {
 4774:                                 my $skip;
 4775:                                 if (ref($resets{$id}) eq 'ARRAY') {
 4776:                                     foreach my $reset (@{$resets{$id}}) {
 4777:                                         if ($reset > $solved{$id}[-1]) {
 4778:                                             $skip=1;
 4779:                                             last;
 4780:                                         }
 4781:                                     }
 4782:                                 }
 4783:                                 unless ($skip) {
 4784:                                     my ($ign,$partslist) = split(/\./,$id,2);
 4785:                                     push(@unsolved,$partslist);
 4786:                                 }
 4787:                             }
 4788:                         }
 4789:                     }
 4790:                 }
 4791:             }
 4792:             $prevattempts.=&start_data_table_row().
 4793:                            '<td>'.&mt('Transaction [_1]',$version);
 4794:             if (@unsolved) {
 4795:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
 4796:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
 4797:                                  &mt('Hide').'</label></span>';
 4798:             }
 4799:             $prevattempts .= '</td>';
 4800:             if (@hidden) {
 4801:                 foreach my $key (sort(keys(%lasthash))) {
 4802:                     next if ($key =~ /\.foilorder$/);
 4803:                     my $hide;
 4804:                     foreach my $id (@hidden) {
 4805:                         if ($key =~ /^\Q$id\E/) {
 4806:                             $hide = 1;
 4807:                             last;
 4808:                         }
 4809:                     }
 4810:                     if ($hide) {
 4811:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4812:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 4813:                             my $value = &format_previous_attempt_value($key,
 4814:                                              $returnhash{$version.':'.$key});
 4815:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4816:                         } else {
 4817:                             $prevattempts.='<td>&nbsp;</td>';
 4818:                         }
 4819:                     } else {
 4820:                         if ($key =~ /\./) {
 4821:                             my $value = $returnhash{$version.':'.$key};
 4822:                             if ($key =~ /\.rndseed$/) {
 4823:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 4824:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4825:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4826:                                 }
 4827:                             }
 4828:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4829:                                            '&nbsp;</td>';
 4830:                         } else {
 4831:                             $prevattempts.='<td>&nbsp;</td>';
 4832:                         }
 4833:                     }
 4834:                 }
 4835:             } else {
 4836: 	        foreach my $key (sort(keys(%lasthash))) {
 4837:                     next if ($key =~ /\.foilorder$/);
 4838:                     my $value = $returnhash{$version.':'.$key};
 4839:                     if ($key =~ /\.rndseed$/) {
 4840:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 4841:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4842:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4843:                         }
 4844:                     }
 4845:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4846:                                    '&nbsp;</td>';
 4847: 	        }
 4848:             }
 4849: 	    $prevattempts.=&end_data_table_row();
 4850: 	 }
 4851:       }
 4852:       my @currhidden = keys(%lasthidden);
 4853:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 4854:       foreach my $key (sort(keys(%lasthash))) {
 4855:           next if ($key =~ /\.foilorder$/);
 4856:           if (%typeparts) {
 4857:               my $hidden;
 4858:               foreach my $id (@currhidden) {
 4859:                   if ($key =~ /^\Q$id\E/) {
 4860:                       $hidden = 1;
 4861:                       last;
 4862:                   }
 4863:               }
 4864:               if ($hidden) {
 4865:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4866:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 4867:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4868:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4869:                           $value = &$gradesub($value);
 4870:                       }
 4871:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
 4872:                   } else {
 4873:                       $prevattempts.='<td>&nbsp;</td>';
 4874:                   }
 4875:               } else {
 4876:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4877:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4878:                       $value = &$gradesub($value);
 4879:                   }
 4880:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4881:               }
 4882:           } else {
 4883: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4884: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4885:                   $value = &$gradesub($value);
 4886:               }
 4887: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4888:           }
 4889:       }
 4890:       $prevattempts.= &end_data_table_row().&end_data_table();
 4891:     } else {
 4892:       my $msg;
 4893:       if ($symb =~ /ext\.tool$/) {
 4894:           $msg = &mt('No grade passed back.');
 4895:       } else {
 4896:           $msg = &mt('Nothing submitted - no attempts.');
 4897:       }
 4898:       $prevattempts=
 4899: 	  &start_data_table().&start_data_table_row().
 4900: 	  '<td>'.$msg.'</td>'.
 4901: 	  &end_data_table_row().&end_data_table();
 4902:     }
 4903:   } else {
 4904:     $prevattempts=
 4905: 	  &start_data_table().&start_data_table_row().
 4906: 	  '<td>'.&mt('No data.').'</td>'.
 4907: 	  &end_data_table_row().&end_data_table();
 4908:   }
 4909: }
 4910: 
 4911: sub format_previous_attempt_value {
 4912:     my ($key,$value) = @_;
 4913:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 4914:         $value = &Apache::lonlocal::locallocaltime($value);
 4915:     } elsif (ref($value) eq 'ARRAY') {
 4916:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
 4917:     } elsif ($key =~ /answerstring$/) {
 4918:         my %answers = &Apache::lonnet::str2hash($value);
 4919:         my @answer = %answers;
 4920:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
 4921:         my @anskeys = sort(keys(%answers));
 4922:         if (@anskeys == 1) {
 4923:             my $answer = $answers{$anskeys[0]};
 4924:             if ($answer =~ m{\0}) {
 4925:                 $answer =~ s{\0}{,}g;
 4926:             }
 4927:             my $tag_internal_answer_name = 'INTERNAL';
 4928:             if ($anskeys[0] eq $tag_internal_answer_name) {
 4929:                 $value = $answer; 
 4930:             } else {
 4931:                 $value = $anskeys[0].'='.$answer;
 4932:             }
 4933:         } else {
 4934:             foreach my $ans (@anskeys) {
 4935:                 my $answer = $answers{$ans};
 4936:                 if ($answer =~ m{\0}) {
 4937:                     $answer =~ s{\0}{,}g;
 4938:                 }
 4939:                 $value .=  $ans.'='.$answer.'<br />';;
 4940:             } 
 4941:         }
 4942:     } else {
 4943:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
 4944:     }
 4945:     return $value;
 4946: }
 4947: 
 4948: 
 4949: sub relative_to_absolute {
 4950:     my ($url,$output)=@_;
 4951:     my $parser=HTML::TokeParser->new(\$output);
 4952:     my $token;
 4953:     my $thisdir=$url;
 4954:     my @rlinks=();
 4955:     while ($token=$parser->get_token) {
 4956: 	if ($token->[0] eq 'S') {
 4957: 	    if ($token->[1] eq 'a') {
 4958: 		if ($token->[2]->{'href'}) {
 4959: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 4960: 		}
 4961: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 4962: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 4963: 	    } elsif ($token->[1] eq 'base') {
 4964: 		$thisdir=$token->[2]->{'href'};
 4965: 	    }
 4966: 	}
 4967:     }
 4968:     $thisdir=~s-/[^/]*$--;
 4969:     foreach my $link (@rlinks) {
 4970: 	unless (($link=~/^https?\:\/\//i) ||
 4971: 		($link=~/^\//) ||
 4972: 		($link=~/^javascript:/i) ||
 4973: 		($link=~/^mailto:/i) ||
 4974: 		($link=~/^\#/)) {
 4975: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 4976: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 4977: 	}
 4978:     }
 4979: # -------------------------------------------------- Deal with Applet codebases
 4980:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 4981:     return $output;
 4982: }
 4983: 
 4984: =pod
 4985: 
 4986: =item * &get_student_view()
 4987: 
 4988: show a snapshot of what student was looking at
 4989: 
 4990: =cut
 4991: 
 4992: sub get_student_view {
 4993:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 4994:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4995:   my (%form);
 4996:   my @elements=('symb','courseid','domain','username');
 4997:   foreach my $element (@elements) {
 4998:       $form{'grade_'.$element}=eval '$'.$element #'
 4999:   }
 5000:   if (defined($moreenv)) {
 5001:       %form=(%form,%{$moreenv});
 5002:   }
 5003:   if (defined($target)) { $form{'grade_target'} = $target; }
 5004:   $feedurl=&Apache::lonnet::clutter($feedurl);
 5005:   if (($feedurl =~ /ext\.tool$/) && ($target eq 'tex')) {
 5006:       $feedurl =~ s{^/adm/wrapper}{};
 5007:   }
 5008:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 5009:   $userview=~s/\<body[^\>]*\>//gi;
 5010:   $userview=~s/\<\/body\>//gi;
 5011:   $userview=~s/\<html\>//gi;
 5012:   $userview=~s/\<\/html\>//gi;
 5013:   $userview=~s/\<head\>//gi;
 5014:   $userview=~s/\<\/head\>//gi;
 5015:   $userview=~s/action\s*\=/would_be_action\=/gi;
 5016:   $userview=&relative_to_absolute($feedurl,$userview);
 5017:   if (wantarray) {
 5018:      return ($userview,$response);
 5019:   } else {
 5020:      return $userview;
 5021:   }
 5022: }
 5023: 
 5024: sub get_student_view_with_retries {
 5025:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 5026: 
 5027:     my $ok = 0;                 # True if we got a good response.
 5028:     my $content;
 5029:     my $response;
 5030: 
 5031:     # Try to get the student_view done. within the retries count:
 5032:     
 5033:     do {
 5034:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 5035:          $ok      = $response->is_success;
 5036:          if (!$ok) {
 5037:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 5038:          }
 5039:          $retries--;
 5040:     } while (!$ok && ($retries > 0));
 5041:     
 5042:     if (!$ok) {
 5043:        $content = '';          # On error return an empty content.
 5044:     }
 5045:     if (wantarray) {
 5046:        return ($content, $response);
 5047:     } else {
 5048:        return $content;
 5049:     }
 5050: }
 5051: 
 5052: sub css_links {
 5053:     my ($currsymb,$level) = @_;
 5054:     my ($links,@symbs,%cssrefs,%httpref);
 5055:     if ($level eq 'map') {
 5056:         my $navmap = Apache::lonnavmaps::navmap->new();
 5057:         if (ref($navmap)) {
 5058:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
 5059:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
 5060:             foreach my $res (@resources) {
 5061:                 if (ref($res) && $res->symb()) {
 5062:                     push(@symbs,$res->symb());
 5063:                 }
 5064:             }
 5065:         }
 5066:     } else {
 5067:         @symbs = ($currsymb);
 5068:     }
 5069:     foreach my $symb (@symbs) {
 5070:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
 5071:         if ($css_href =~ /\S/) {
 5072:             unless ($css_href =~ m{https?://}) {
 5073:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
 5074:                 my $proburl =  &Apache::lonnet::clutter($url);
 5075:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
 5076:                 unless ($css_href =~ m{^/}) {
 5077:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
 5078:                 }
 5079:                 if ($css_href =~ m{^/(res|uploaded)/}) {
 5080:                     unless (($httpref{'httpref.'.$css_href}) ||
 5081:                             (&Apache::lonnet::is_on_map($css_href))) {
 5082:                         my $thisurl = $proburl;
 5083:                         if ($env{'httpref.'.$proburl}) {
 5084:                             $thisurl = $env{'httpref.'.$proburl};
 5085:                         }
 5086:                         $httpref{'httpref.'.$css_href} = $thisurl;
 5087:                     }
 5088:                 }
 5089:             }
 5090:             $cssrefs{$css_href} = 1;
 5091:         }
 5092:     }
 5093:     if (keys(%httpref)) {
 5094:         &Apache::lonnet::appenv(\%httpref);
 5095:     }
 5096:     if (keys(%cssrefs)) {
 5097:         foreach my $css_href (keys(%cssrefs)) {
 5098:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
 5099:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
 5100:         }
 5101:     }
 5102:     return $links;
 5103: }
 5104: 
 5105: =pod
 5106: 
 5107: =item * &get_student_answers() 
 5108: 
 5109: show a snapshot of how student was answering problem
 5110: 
 5111: =cut
 5112: 
 5113: sub get_student_answers {
 5114:   my ($symb,$username,$domain,$courseid,%form) = @_;
 5115:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 5116:   my (%moreenv);
 5117:   my @elements=('symb','courseid','domain','username');
 5118:   foreach my $element (@elements) {
 5119:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 5120:   }
 5121:   $moreenv{'grade_target'}='answer';
 5122:   %moreenv=(%form,%moreenv);
 5123:   $feedurl = &Apache::lonnet::clutter($feedurl);
 5124:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 5125:   return $userview;
 5126: }
 5127: 
 5128: =pod
 5129: 
 5130: =item * &submlink()
 5131: 
 5132: Inputs: $text $uname $udom $symb $target
 5133: 
 5134: Returns: A link to grades.pm such as to see the SUBM view of a student
 5135: 
 5136: =cut
 5137: 
 5138: ###############################################
 5139: sub submlink {
 5140:     my ($text,$uname,$udom,$symb,$target)=@_;
 5141:     if (!($uname && $udom)) {
 5142: 	(my $cursymb, my $courseid,$udom,$uname)=
 5143: 	    &Apache::lonnet::whichuser($symb);
 5144: 	if (!$symb) { $symb=$cursymb; }
 5145:     }
 5146:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 5147:     $symb=&escape($symb);
 5148:     if ($target) { $target=" target=\"$target\""; }
 5149:     return
 5150:         '<a href="/adm/grades?command=submission'.
 5151:         '&amp;symb='.$symb.
 5152:         '&amp;student='.$uname.
 5153:         '&amp;userdom='.$udom.'"'.
 5154:         $target.'>'.$text.'</a>';
 5155: }
 5156: ##############################################
 5157: 
 5158: =pod
 5159: 
 5160: =item * &pgrdlink()
 5161: 
 5162: Inputs: $text $uname $udom $symb $target
 5163: 
 5164: Returns: A link to grades.pm such as to see the PGRD view of a student
 5165: 
 5166: =cut
 5167: 
 5168: ###############################################
 5169: sub pgrdlink {
 5170:     my $link=&submlink(@_);
 5171:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 5172:     return $link;
 5173: }
 5174: ##############################################
 5175: 
 5176: =pod
 5177: 
 5178: =item * &pprmlink()
 5179: 
 5180: Inputs: $text $uname $udom $symb $target
 5181: 
 5182: Returns: A link to parmset.pm such as to see the PPRM view of a
 5183: student and a specific resource
 5184: 
 5185: =cut
 5186: 
 5187: ###############################################
 5188: sub pprmlink {
 5189:     my ($text,$uname,$udom,$symb,$target)=@_;
 5190:     if (!($uname && $udom)) {
 5191: 	(my $cursymb, my $courseid,$udom,$uname)=
 5192: 	    &Apache::lonnet::whichuser($symb);
 5193: 	if (!$symb) { $symb=$cursymb; }
 5194:     }
 5195:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 5196:     $symb=&escape($symb);
 5197:     if ($target) { $target="target=\"$target\""; }
 5198:     return '<a href="/adm/parmset?command=set&amp;'.
 5199: 	'symb='.$symb.'&amp;uname='.$uname.
 5200: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 5201: }
 5202: ##############################################
 5203: 
 5204: =pod
 5205: 
 5206: =back
 5207: 
 5208: =cut
 5209: 
 5210: ###############################################
 5211: 
 5212: 
 5213: sub timehash {
 5214:     my ($thistime) = @_;
 5215:     my $timezone = &Apache::lonlocal::gettimezone();
 5216:     my $dt = DateTime->from_epoch(epoch => $thistime)
 5217:                      ->set_time_zone($timezone);
 5218:     my $wday = $dt->day_of_week();
 5219:     if ($wday == 7) { $wday = 0; }
 5220:     return ( 'second' => $dt->second(),
 5221:              'minute' => $dt->minute(),
 5222:              'hour'   => $dt->hour(),
 5223:              'day'     => $dt->day_of_month(),
 5224:              'month'   => $dt->month(),
 5225:              'year'    => $dt->year(),
 5226:              'weekday' => $wday,
 5227:              'dayyear' => $dt->day_of_year(),
 5228:              'dlsav'   => $dt->is_dst() );
 5229: }
 5230: 
 5231: sub utc_string {
 5232:     my ($date)=@_;
 5233:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 5234: }
 5235: 
 5236: sub maketime {
 5237:     my %th=@_;
 5238:     my ($epoch_time,$timezone,$dt);
 5239:     $timezone = &Apache::lonlocal::gettimezone();
 5240:     eval {
 5241:         $dt = DateTime->new( year   => $th{'year'},
 5242:                              month  => $th{'month'},
 5243:                              day    => $th{'day'},
 5244:                              hour   => $th{'hour'},
 5245:                              minute => $th{'minute'},
 5246:                              second => $th{'second'},
 5247:                              time_zone => $timezone,
 5248:                          );
 5249:     };
 5250:     if (!$@) {
 5251:         $epoch_time = $dt->epoch;
 5252:         if ($epoch_time) {
 5253:             return $epoch_time;
 5254:         }
 5255:     }
 5256:     return POSIX::mktime(
 5257:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 5258:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 5259: }
 5260: 
 5261: #########################################
 5262: 
 5263: sub findallcourses {
 5264:     my ($roles,$uname,$udom) = @_;
 5265:     my %roles;
 5266:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 5267:     my %courses;
 5268:     my $now=time;
 5269:     if (!defined($uname)) {
 5270:         $uname = $env{'user.name'};
 5271:     }
 5272:     if (!defined($udom)) {
 5273:         $udom = $env{'user.domain'};
 5274:     }
 5275:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 5276:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 5277:         if (!%roles) {
 5278:             %roles = (
 5279:                        cc => 1,
 5280:                        co => 1,
 5281:                        in => 1,
 5282:                        ep => 1,
 5283:                        ta => 1,
 5284:                        cr => 1,
 5285:                        st => 1,
 5286:              );
 5287:         }
 5288:         foreach my $entry (keys(%roleshash)) {
 5289:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 5290:             if ($trole =~ /^cr/) { 
 5291:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 5292:             } else {
 5293:                 next if (!exists($roles{$trole}));
 5294:             }
 5295:             if ($tend) {
 5296:                 next if ($tend < $now);
 5297:             }
 5298:             if ($tstart) {
 5299:                 next if ($tstart > $now);
 5300:             }
 5301:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 5302:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 5303:             my $value = $trole.'/'.$cdom.'/';
 5304:             if ($secpart eq '') {
 5305:                 ($cnum,$role) = split(/_/,$cnumpart); 
 5306:                 $sec = 'none';
 5307:                 $value .= $cnum.'/';
 5308:             } else {
 5309:                 $cnum = $cnumpart;
 5310:                 ($sec,$role) = split(/_/,$secpart);
 5311:                 $value .= $cnum.'/'.$sec;
 5312:             }
 5313:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 5314:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 5315:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 5316:                 }
 5317:             } else {
 5318:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 5319:             }
 5320:         }
 5321:     } else {
 5322:         foreach my $key (keys(%env)) {
 5323: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 5324:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 5325: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 5326: 	        next if ($role eq 'ca' || $role eq 'aa');
 5327: 	        next if (%roles && !exists($roles{$role}));
 5328: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 5329:                 my $active=1;
 5330:                 if ($starttime) {
 5331: 		    if ($now<$starttime) { $active=0; }
 5332:                 }
 5333:                 if ($endtime) {
 5334:                     if ($now>$endtime) { $active=0; }
 5335:                 }
 5336:                 if ($active) {
 5337:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 5338:                     if ($sec eq '') {
 5339:                         $sec = 'none';
 5340:                     } else {
 5341:                         $value .= $sec;
 5342:                     }
 5343:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 5344:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 5345:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 5346:                         }
 5347:                     } else {
 5348:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 5349:                     }
 5350:                 }
 5351:             }
 5352:         }
 5353:     }
 5354:     return %courses;
 5355: }
 5356: 
 5357: ###############################################
 5358: 
 5359: sub blockcheck {
 5360:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
 5361:     unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
 5362:         my ($has_evb,$check_ipaccess);
 5363:         my $dom = $env{'user.domain'};
 5364:         if ($env{'request.course.id'}) {
 5365:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5366:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5367:             my $checkrole = "cm./$cdom/$cnum";
 5368:             my $sec = $env{'request.course.sec'};
 5369:             if ($sec ne '') {
 5370:                 $checkrole .= "/$sec";
 5371:             }
 5372:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 5373:                 ($env{'request.role'} !~ /^st/)) {
 5374:                 $has_evb = 1;
 5375:             }
 5376:             unless ($has_evb) {
 5377:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
 5378:                     ($activity eq 'boards') || ($activity eq 'groups') || ($activity eq 'chat')) {
 5379:                     if ($udom eq $cdom) {
 5380:                         $check_ipaccess = 1;
 5381:                     }
 5382:                 }
 5383:             }
 5384:         } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
 5385:                 ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
 5386:             my $checkrole;
 5387:             if ($env{'request.role.domain'} eq '') {
 5388:                 $checkrole = "cm./$env{'user.domain'}/";
 5389:             } else {
 5390:                 $checkrole = "cm./$env{'request.role.domain'}/";
 5391:             }
 5392:             if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
 5393:                 $has_evb = 1;
 5394:             }
 5395:         }
 5396:         unless ($has_evb || $check_ipaccess) {
 5397:             my @machinedoms = &Apache::lonnet::current_machine_domains();
 5398:             if (($dom eq 'public') && ($activity eq 'port')) {
 5399:                 $dom = $udom;
 5400:             }
 5401:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
 5402:                 $check_ipaccess = 1;
 5403:             } else {
 5404:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 5405:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
 5406:                 my $prim = &Apache::lonnet::domain($dom,'primary');
 5407:                 my $intdom = &Apache::lonnet::internet_dom($prim);
 5408:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
 5409:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
 5410:                         $check_ipaccess = 1;
 5411:                     }
 5412:                 }
 5413:             }
 5414:         }
 5415:         if ($check_ipaccess) {
 5416:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
 5417:             unless (defined($cached)) {
 5418:                 my %domconfig =
 5419:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
 5420:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
 5421:             }
 5422:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
 5423:                 foreach my $id (keys(%{$ipaccessref})) {
 5424:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
 5425:                         my $range = $ipaccessref->{$id}->{'ip'};
 5426:                         if ($range) {
 5427:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
 5428:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
 5429:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
 5430:                                         return ('','','',$id,$dom);
 5431:                                         last;
 5432:                                     }
 5433:                                 }
 5434:                             }
 5435:                         }
 5436:                     }
 5437:                 }
 5438:             }
 5439:         }
 5440:         if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
 5441:             return ();
 5442:         }
 5443:     }
 5444:     if (defined($udom) && defined($uname)) {
 5445:         # If uname and udom are for a course, check for blocks in the course.
 5446:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
 5447:             my ($startblock,$endblock,$triggerblock) =
 5448:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
 5449:             return ($startblock,$endblock,$triggerblock);
 5450:         }
 5451:     } else {
 5452:         $udom = $env{'user.domain'};
 5453:         $uname = $env{'user.name'};
 5454:     }
 5455: 
 5456:     my $startblock = 0;
 5457:     my $endblock = 0;
 5458:     my $triggerblock = '';
 5459:     my %live_courses;
 5460:     unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
 5461:         %live_courses = &findallcourses(undef,$uname,$udom);
 5462:     }
 5463: 
 5464:     # If uname is for a user, and activity is course-specific, i.e.,
 5465:     # boards, chat or groups, check for blocking in current course only.
 5466: 
 5467:     if (($activity eq 'boards' || $activity eq 'chat' ||
 5468:          $activity eq 'groups' || $activity eq 'printout' ||
 5469:          $activity eq 'search' || $activity eq 'reinit' ||
 5470:          $activity eq 'alert') &&
 5471:         ($env{'request.course.id'})) {
 5472:         foreach my $key (keys(%live_courses)) {
 5473:             if ($key ne $env{'request.course.id'}) {
 5474:                 delete($live_courses{$key});
 5475:             }
 5476:         }
 5477:     }
 5478: 
 5479:     my $otheruser = 0;
 5480:     my %own_courses;
 5481:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 5482:         # Resource belongs to user other than current user.
 5483:         $otheruser = 1;
 5484:         # Gather courses for current user
 5485:         %own_courses = 
 5486:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 5487:     }
 5488: 
 5489:     # Gather active course roles - course coordinator, instructor, 
 5490:     # exam proctor, ta, student, or custom role.
 5491: 
 5492:     foreach my $course (keys(%live_courses)) {
 5493:         my ($cdom,$cnum);
 5494:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 5495:             $cdom = $env{'course.'.$course.'.domain'};
 5496:             $cnum = $env{'course.'.$course.'.num'};
 5497:         } else {
 5498:             ($cdom,$cnum) = split(/_/,$course); 
 5499:         }
 5500:         my $no_ownblock = 0;
 5501:         my $no_userblock = 0;
 5502:         if ($otheruser && $activity ne 'com') {
 5503:             # Check if current user has 'evb' priv for this
 5504:             if (defined($own_courses{$course})) {
 5505:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 5506:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5507:                     if ($sec ne 'none') {
 5508:                         $checkrole .= '/'.$sec;
 5509:                     }
 5510:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5511:                         $no_ownblock = 1;
 5512:                         last;
 5513:                     }
 5514:                 }
 5515:             }
 5516:             # if they have 'evb' priv and are currently not playing student
 5517:             next if (($no_ownblock) &&
 5518:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 5519:         }
 5520:         foreach my $sec (keys(%{$live_courses{$course}})) {
 5521:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5522:             if ($sec ne 'none') {
 5523:                 $checkrole .= '/'.$sec;
 5524:             }
 5525:             if ($otheruser) {
 5526:                 # Resource belongs to user other than current user.
 5527:                 # Assemble privs for that user, and check for 'evb' priv.
 5528:                 my (%allroles,%userroles);
 5529:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 5530:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 5531:                         my ($trole,$tdom,$tnum,$tsec);
 5532:                         if ($entry =~ /^cr/) {
 5533:                             ($trole,$tdom,$tnum,$tsec) = 
 5534:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 5535:                         } else {
 5536:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 5537:                         }
 5538:                         my ($spec,$area,$trest);
 5539:                         $area = '/'.$tdom.'/'.$tnum;
 5540:                         $trest = $tnum;
 5541:                         if ($tsec ne '') {
 5542:                             $area .= '/'.$tsec;
 5543:                             $trest .= '/'.$tsec;
 5544:                         }
 5545:                         $spec = $trole.'.'.$area;
 5546:                         if ($trole =~ /^cr/) {
 5547:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 5548:                                                               $tdom,$spec,$trest,$area);
 5549:                         } else {
 5550:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 5551:                                                                 $tdom,$spec,$trest,$area);
 5552:                         }
 5553:                     }
 5554:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 5555:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 5556:                         if ($1) {
 5557:                             $no_userblock = 1;
 5558:                             last;
 5559:                         }
 5560:                     }
 5561:                 }
 5562:             } else {
 5563:                 # Resource belongs to current user
 5564:                 # Check for 'evb' priv via lonnet::allowed().
 5565:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5566:                     $no_ownblock = 1;
 5567:                     last;
 5568:                 }
 5569:             }
 5570:         }
 5571:         # if they have the evb priv and are currently not playing student
 5572:         next if (($no_ownblock) &&
 5573:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 5574:         next if ($no_userblock);
 5575: 
 5576:         # Retrieve blocking times and identity of blocker for course
 5577:         # of specified user, unless user has 'evb' privilege.
 5578: 
 5579:         my ($start,$end,$trigger) = 
 5580:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
 5581:         if (($start != 0) && 
 5582:             (($startblock == 0) || ($startblock > $start))) {
 5583:             $startblock = $start;
 5584:             if ($trigger ne '') {
 5585:                 $triggerblock = $trigger;
 5586:             }
 5587:         }
 5588:         if (($end != 0)  &&
 5589:             (($endblock == 0) || ($endblock < $end))) {
 5590:             $endblock = $end;
 5591:             if ($trigger ne '') {
 5592:                 $triggerblock = $trigger;
 5593:             }
 5594:         }
 5595:     }
 5596:     return ($startblock,$endblock,$triggerblock);
 5597: }
 5598: 
 5599: sub get_blocks {
 5600:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
 5601:     my $startblock = 0;
 5602:     my $endblock = 0;
 5603:     my $triggerblock = '';
 5604:     my $course = $cdom.'_'.$cnum;
 5605:     $setters->{$course} = {};
 5606:     $setters->{$course}{'staff'} = [];
 5607:     $setters->{$course}{'times'} = [];
 5608:     $setters->{$course}{'triggers'} = [];
 5609:     my (@blockers,%triggered);
 5610:     my $now = time;
 5611:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 5612:     if ($activity eq 'docs') {
 5613:         my ($blocked,$nosymbcache,$noenccheck);
 5614:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
 5615:             $blocked = 1;
 5616:             $nosymbcache = 1;
 5617:             $noenccheck = 1;
 5618:         }
 5619:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
 5620:         foreach my $block (@blockers) {
 5621:             if ($block =~ /^firstaccess____(.+)$/) {
 5622:                 my $item = $1;
 5623:                 my $type = 'map';
 5624:                 my $timersymb = $item;
 5625:                 if ($item eq 'course') {
 5626:                     $type = 'course';
 5627:                 } elsif ($item =~ /___\d+___/) {
 5628:                     $type = 'resource';
 5629:                 } else {
 5630:                     $timersymb = &Apache::lonnet::symbread($item);
 5631:                 }
 5632:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5633:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 5634:                 $triggered{$block} = {
 5635:                                        start => $start,
 5636:                                        end   => $end,
 5637:                                        type  => $type,
 5638:                                      };
 5639:             }
 5640:         }
 5641:     } else {
 5642:         foreach my $block (keys(%commblocks)) {
 5643:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 5644:                 my ($start,$end) = ($1,$2);
 5645:                 if ($start <= time && $end >= time) {
 5646:                     if (ref($commblocks{$block}) eq 'HASH') {
 5647:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5648:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5649:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 5650:                                     push(@blockers,$block);
 5651:                                 }
 5652:                             }
 5653:                         }
 5654:                     }
 5655:                 }
 5656:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 5657:                 my $item = $1;
 5658:                 my $timersymb = $item; 
 5659:                 my $type = 'map';
 5660:                 if ($item eq 'course') {
 5661:                     $type = 'course';
 5662:                 } elsif ($item =~ /___\d+___/) {
 5663:                     $type = 'resource';
 5664:                 } else {
 5665:                     $timersymb = &Apache::lonnet::symbread($item);
 5666:                 }
 5667:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5668:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 5669:                 if ($start && $end) {
 5670:                     if (($start <= time) && ($end >= time)) {
 5671:                         if (ref($commblocks{$block}) eq 'HASH') {
 5672:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5673:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5674:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
 5675:                                         push(@blockers,$block);
 5676:                                         $triggered{$block} = {
 5677:                                                                start => $start,
 5678:                                                                end   => $end,
 5679:                                                                type  => $type,
 5680:                                                              };
 5681:                                     }
 5682:                                 }
 5683:                             }
 5684:                         }
 5685:                     }
 5686:                 }
 5687:             }
 5688:         }
 5689:     }
 5690:     foreach my $blocker (@blockers) {
 5691:         my ($staff_name,$staff_dom,$title,$blocks) =
 5692:             &parse_block_record($commblocks{$blocker});
 5693:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 5694:         my ($start,$end,$triggertype);
 5695:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 5696:             ($start,$end) = ($1,$2);
 5697:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 5698:             $start = $triggered{$blocker}{'start'};
 5699:             $end = $triggered{$blocker}{'end'};
 5700:             $triggertype = $triggered{$blocker}{'type'};
 5701:         }
 5702:         if ($start) {
 5703:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 5704:             if ($triggertype) {
 5705:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 5706:             } else {
 5707:                 push(@{$$setters{$course}{'triggers'}},0);
 5708:             }
 5709:             if ( ($startblock == 0) || ($startblock > $start) ) {
 5710:                 $startblock = $start;
 5711:                 if ($triggertype) {
 5712:                     $triggerblock = $blocker;
 5713:                 }
 5714:             }
 5715:             if ( ($endblock == 0) || ($endblock < $end) ) {
 5716:                $endblock = $end;
 5717:                if ($triggertype) {
 5718:                    $triggerblock = $blocker;
 5719:                }
 5720:             }
 5721:         }
 5722:     }
 5723:     return ($startblock,$endblock,$triggerblock);
 5724: }
 5725: 
 5726: sub parse_block_record {
 5727:     my ($record) = @_;
 5728:     my ($setuname,$setudom,$title,$blocks);
 5729:     if (ref($record) eq 'HASH') {
 5730:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 5731:         $title = &unescape($record->{'event'});
 5732:         $blocks = $record->{'blocks'};
 5733:     } else {
 5734:         my @data = split(/:/,$record,3);
 5735:         if (scalar(@data) eq 2) {
 5736:             $title = $data[1];
 5737:             ($setuname,$setudom) = split(/@/,$data[0]);
 5738:         } else {
 5739:             ($setuname,$setudom,$title) = @data;
 5740:         }
 5741:         $blocks = { 'com' => 'on' };
 5742:     }
 5743:     return ($setuname,$setudom,$title,$blocks);
 5744: }
 5745: 
 5746: sub blocking_status {
 5747:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
 5748:     my %setters;
 5749: 
 5750: # check for active blocking
 5751:     if ($clientip eq '') {
 5752:         $clientip = &Apache::lonnet::get_requestor_ip();
 5753:     }
 5754:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
 5755:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
 5756:     my $blocked = 0;
 5757:     if (($startblock && $endblock) || ($by_ip)) {
 5758:         $blocked = 1;
 5759:     }
 5760: 
 5761: # caller just wants to know whether a block is active
 5762:     if (!wantarray) { return $blocked; }
 5763: 
 5764: # build a link to a popup window containing the details
 5765:     my $querystring  = "?activity=$activity";
 5766: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
 5767:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
 5768:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
 5769:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
 5770:     } elsif ($activity eq 'docs') {
 5771:         my $showurl = &Apache::lonenc::check_encrypt($url);
 5772:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
 5773:         if ($symb) {
 5774:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
 5775:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
 5776:         }
 5777:     }
 5778: 
 5779:     my $output .= <<'END_MYBLOCK';
 5780: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 5781:     var options = "width=" + w + ",height=" + h + ",";
 5782:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 5783:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 5784:     var newWin = window.open(url, wdwName, options);
 5785:     newWin.focus();
 5786: }
 5787: END_MYBLOCK
 5788: 
 5789:     $output = Apache::lonhtmlcommon::scripttag($output);
 5790:   
 5791:     my $popupUrl = "/adm/blockingstatus/$querystring";
 5792:     my $text = &mt('Communication Blocked');
 5793:     my $class = 'LC_comblock';
 5794:     if ($activity eq 'docs') {
 5795:         $text = &mt('Content Access Blocked');
 5796:         $class = '';
 5797:     } elsif ($activity eq 'printout') {
 5798:         $text = &mt('Printing Blocked');
 5799:     } elsif ($activity eq 'passwd') {
 5800:         $text = &mt('Password Changing Blocked');
 5801:     } elsif ($activity eq 'grades') {
 5802:         $text = &mt('Gradebook Blocked');
 5803:     } elsif ($activity eq 'search') {
 5804:         $text = &mt('Search Blocked');
 5805:     } elsif ($activity eq 'alert') {
 5806:         $text = &mt('Checking Critical Messages Blocked');
 5807:     } elsif ($activity eq 'reinit') {
 5808:         $text = &mt('Checking Course Update Blocked');
 5809:     } elsif ($activity eq 'about') {
 5810:         $text = &mt('Access to User Information Pages Blocked');
 5811:     } elsif ($activity eq 'wishlist') {
 5812:         $text = &mt('Access to Stored Links Blocked');
 5813:     } elsif ($activity eq 'annotate') {
 5814:         $text = &mt('Access to Annotations Blocked');
 5815:     }
 5816:     $output .= <<"END_BLOCK";
 5817: <div class='$class'>
 5818:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 5819:   title='$text'>
 5820:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 5821:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 5822:   title='$text'>$text</a>
 5823: </div>
 5824: 
 5825: END_BLOCK
 5826: 
 5827:     return ($blocked, $output);
 5828: }
 5829: 
 5830: ###############################################
 5831: 
 5832: sub check_ip_acc {
 5833:     my ($acc,$clientip)=@_;
 5834:     &Apache::lonxml::debug("acc is $acc");
 5835:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 5836:         return 1;
 5837:     }
 5838:     my ($ip,$allowed);
 5839:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
 5840:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
 5841:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
 5842:     } else {
 5843:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
 5844:         $ip = $remote_ip || $env{'request.host'} || $clientip;
 5845:     }
 5846: 
 5847:     my $name;
 5848:     my %access = (
 5849:                      allowfrom => 1,
 5850:                      denyfrom  => 0,
 5851:                  );
 5852:     my @allows;
 5853:     my @denies;
 5854:     foreach my $item (split(',',$acc)) {
 5855:         $item =~ s/^\s*//;
 5856:         $item =~ s/\s*$//;
 5857:         my $pattern;
 5858:         if ($item =~ /^\!(.+)$/) {
 5859:             push(@denies,$1);
 5860:         } else {
 5861:             push(@allows,$item);
 5862:         }
 5863:    }
 5864:    my $numdenies = scalar(@denies);
 5865:    my $numallows = scalar(@allows);
 5866:    my $count = 0;
 5867:    foreach my $pattern (@denies,@allows) {
 5868:         $count ++; 
 5869:         my $acctype = 'allowfrom';
 5870:         if ($count <= $numdenies) {
 5871:             $acctype = 'denyfrom';
 5872:         }
 5873:         if ($pattern =~ /\*$/) {
 5874:             #35.8.*
 5875:             $pattern=~s/\*//;
 5876:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 5877:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 5878:             #35.8.3.[34-56]
 5879:             my $low=$2;
 5880:             my $high=$3;
 5881:             $pattern=$1;
 5882:             if ($ip =~ /^\Q$pattern\E/) {
 5883:                 my $last=(split(/\./,$ip))[3];
 5884:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
 5885:             }
 5886:         } elsif ($pattern =~ /^\*/) {
 5887:             #*.msu.edu
 5888:             $pattern=~s/\*//;
 5889:             if (!defined($name)) {
 5890:                 use Socket;
 5891:                 my $netaddr=inet_aton($ip);
 5892:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5893:             }
 5894:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5895:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 5896:             #127.0.0.1
 5897:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 5898:         } else {
 5899:             #some.name.com
 5900:             if (!defined($name)) {
 5901:                 use Socket;
 5902:                 my $netaddr=inet_aton($ip);
 5903:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5904:             }
 5905:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5906:         }
 5907:         if ($allowed =~ /^(0|1)$/) { last; }
 5908:     }
 5909:     if ($allowed eq '') {
 5910:         if ($numdenies && !$numallows) {
 5911:             $allowed = 1;
 5912:         } else {
 5913:             $allowed = 0;
 5914:         }
 5915:     }
 5916:     return $allowed;
 5917: }
 5918: 
 5919: ###############################################
 5920: 
 5921: =pod
 5922: 
 5923: =head1 Domain Template Functions
 5924: 
 5925: =over 4
 5926: 
 5927: =item * &determinedomain()
 5928: 
 5929: Inputs: $domain (usually will be undef)
 5930: 
 5931: Returns: Determines which domain should be used for designs
 5932: 
 5933: =cut
 5934: 
 5935: ###############################################
 5936: sub determinedomain {
 5937:     my $domain=shift;
 5938:     if (! $domain) {
 5939:         # Determine domain if we have not been given one
 5940:         $domain = &Apache::lonnet::default_login_domain();
 5941:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 5942:         if ($env{'request.role.domain'}) { 
 5943:             $domain=$env{'request.role.domain'}; 
 5944:         }
 5945:     }
 5946:     return $domain;
 5947: }
 5948: ###############################################
 5949: 
 5950: sub devalidate_domconfig_cache {
 5951:     my ($udom)=@_;
 5952:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 5953: }
 5954: 
 5955: # ---------------------- Get domain configuration for a domain
 5956: sub get_domainconf {
 5957:     my ($udom) = @_;
 5958:     my $cachetime=1800;
 5959:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 5960:     if (defined($cached)) { return %{$result}; }
 5961: 
 5962:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 5963: 					     ['login','rolecolors','autoenroll'],$udom);
 5964:     my (%designhash,%legacy);
 5965:     if (keys(%domconfig) > 0) {
 5966:         if (ref($domconfig{'login'}) eq 'HASH') {
 5967:             if (keys(%{$domconfig{'login'}})) {
 5968:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 5969:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5970:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
 5971:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5972:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
 5973:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
 5974:                                         if ($key eq 'loginvia') {
 5975:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 5976:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 5977:                                                 $designhash{$udom.'.login.loginvia'} = $server;
 5978:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 5979: 
 5980:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 5981:                                                 } else {
 5982:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 5983:                                                 }
 5984:                                             }
 5985:                                         } elsif ($key eq 'headtag') {
 5986:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
 5987:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
 5988:                                             }
 5989:                                         }
 5990:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
 5991:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
 5992:                                         }
 5993:                                     }
 5994:                                 }
 5995:                             }
 5996:                         } elsif ($key eq 'saml') {
 5997:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5998:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
 5999:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
 6000:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
 6001:                                         foreach my $item ('text','img','alt','url','title','window','notsso') {
 6002:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
 6003:                                         }
 6004:                                     }
 6005:                                 }
 6006:                             }
 6007:                         } else {
 6008:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 6009:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 6010:                                     $domconfig{'login'}{$key}{$img};
 6011:                             }
 6012:                         }
 6013:                     } else {
 6014:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 6015:                     }
 6016:                 }
 6017:             } else {
 6018:                 $legacy{'login'} = 1;
 6019:             }
 6020:         } else {
 6021:             $legacy{'login'} = 1;
 6022:         }
 6023:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 6024:             if (keys(%{$domconfig{'rolecolors'}})) {
 6025:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 6026:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 6027:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 6028:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 6029:                         }
 6030:                     }
 6031:                 }
 6032:             } else {
 6033:                 $legacy{'rolecolors'} = 1;
 6034:             }
 6035:         } else {
 6036:             $legacy{'rolecolors'} = 1;
 6037:         }
 6038:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 6039:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 6040:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 6041:             }
 6042:         }
 6043:         if (keys(%legacy) > 0) {
 6044:             my %legacyhash = &get_legacy_domconf($udom);
 6045:             foreach my $item (keys(%legacyhash)) {
 6046:                 if ($item =~ /^\Q$udom\E\.login/) {
 6047:                     if ($legacy{'login'}) { 
 6048:                         $designhash{$item} = $legacyhash{$item};
 6049:                     }
 6050:                 } else {
 6051:                     if ($legacy{'rolecolors'}) {
 6052:                         $designhash{$item} = $legacyhash{$item};
 6053:                     }
 6054:                 }
 6055:             }
 6056:         }
 6057:     } else {
 6058:         %designhash = &get_legacy_domconf($udom); 
 6059:     }
 6060:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 6061: 				  $cachetime);
 6062:     return %designhash;
 6063: }
 6064: 
 6065: sub get_legacy_domconf {
 6066:     my ($udom) = @_;
 6067:     my %legacyhash;
 6068:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 6069:     my $designfile =  $designdir.'/'.$udom.'.tab';
 6070:     if (-e $designfile) {
 6071:         if ( open (my $fh,'<',$designfile) ) {
 6072:             while (my $line = <$fh>) {
 6073:                 next if ($line =~ /^\#/);
 6074:                 chomp($line);
 6075:                 my ($key,$val)=(split(/\=/,$line));
 6076:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 6077:             }
 6078:             close($fh);
 6079:         }
 6080:     }
 6081:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 6082:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 6083:     }
 6084:     return %legacyhash;
 6085: }
 6086: 
 6087: =pod
 6088: 
 6089: =item * &domainlogo()
 6090: 
 6091: Inputs: $domain (usually will be undef)
 6092: 
 6093: Returns: A link to a domain logo, if the domain logo exists.
 6094: If the domain logo does not exist, a description of the domain.
 6095: 
 6096: =cut
 6097: 
 6098: ###############################################
 6099: sub domainlogo {
 6100:     my $domain = &determinedomain(shift);
 6101:     my %designhash = &get_domainconf($domain);    
 6102:     # See if there is a logo
 6103:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 6104:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 6105:         if ($imgsrc =~ m{^/(adm|res)/}) {
 6106: 	    if ($imgsrc =~ m{^/res/}) {
 6107: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 6108: 		&Apache::lonnet::repcopy($local_name);
 6109: 	    }
 6110: 	   $imgsrc = &lonhttpdurl($imgsrc);
 6111:         }
 6112:         my $alttext = $domain;
 6113:         if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
 6114:             $alttext = $designhash{$domain.'.login.alttext_domlogo'};
 6115:         }
 6116:         return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
 6117:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 6118:         return &Apache::lonnet::domain($domain,'description');
 6119:     } else {
 6120:         return '';
 6121:     }
 6122: }
 6123: ##############################################
 6124: 
 6125: =pod
 6126: 
 6127: =item * &designparm()
 6128: 
 6129: Inputs: $which parameter; $domain (usually will be undef)
 6130: 
 6131: Returns: value of designparamter $which
 6132: 
 6133: =cut
 6134: 
 6135: 
 6136: ##############################################
 6137: sub designparm {
 6138:     my ($which,$domain)=@_;
 6139:     if (exists($env{'environment.color.'.$which})) {
 6140:         return $env{'environment.color.'.$which};
 6141:     }
 6142:     $domain=&determinedomain($domain);
 6143:     my %domdesign;
 6144:     unless ($domain eq 'public') {
 6145:         %domdesign = &get_domainconf($domain);
 6146:     }
 6147:     my $output;
 6148:     if ($domdesign{$domain.'.'.$which} ne '') {
 6149:         $output = $domdesign{$domain.'.'.$which};
 6150:     } else {
 6151:         $output = $defaultdesign{$which};
 6152:     }
 6153:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 6154:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 6155:         if ($output =~ m{^/(adm|res)/}) {
 6156:             if ($output =~ m{^/res/}) {
 6157:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 6158:                 &Apache::lonnet::repcopy($local_name);
 6159:             }
 6160:             $output = &lonhttpdurl($output);
 6161:         }
 6162:     }
 6163:     return $output;
 6164: }
 6165: 
 6166: ##############################################
 6167: =pod
 6168: 
 6169: =item * &authorspace()
 6170: 
 6171: Inputs: $url (usually will be undef).
 6172: 
 6173: Returns: Path to Authoring Space containing the resource or 
 6174:          directory being viewed (or for which action is being taken). 
 6175:          If $url is provided, and begins /priv/<domain>/<uname>
 6176:          the path will be that portion of the $context argument.
 6177:          Otherwise the path will be for the author space of the current
 6178:          user when the current role is author, or for that of the 
 6179:          co-author/assistant co-author space when the current role 
 6180:          is co-author or assistant co-author.
 6181: 
 6182: =cut
 6183: 
 6184: sub authorspace {
 6185:     my ($url) = @_;
 6186:     if ($url ne '') {
 6187:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 6188:            return $1;
 6189:         }
 6190:     }
 6191:     my $caname = '';
 6192:     my $cadom = '';
 6193:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 6194:         ($cadom,$caname) =
 6195:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 6196:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 6197:         $caname = $env{'user.name'};
 6198:         $cadom = $env{'user.domain'};
 6199:     }
 6200:     if (($caname ne '') && ($cadom ne '')) {
 6201:         return "/priv/$cadom/$caname/";
 6202:     }
 6203:     return;
 6204: }
 6205: 
 6206: ##############################################
 6207: =pod
 6208: 
 6209: =item * &head_subbox()
 6210: 
 6211: Inputs: $content (contains HTML code with page functions, etc.)
 6212: 
 6213: Returns: HTML div with $content
 6214:          To be included in page header
 6215: 
 6216: =cut
 6217: 
 6218: sub head_subbox {
 6219:     my ($content)=@_;
 6220:     my $output =
 6221:         '<div class="LC_head_subbox">'
 6222:        .$content
 6223:        .'</div>'
 6224: }
 6225: 
 6226: ##############################################
 6227: =pod
 6228: 
 6229: =item * &CSTR_pageheader()
 6230: 
 6231: Input: (optional) filename from which breadcrumb trail is built.
 6232:        In most cases no input as needed, as $env{'request.filename'}
 6233:        is appropriate for use in building the breadcrumb trail.
 6234:        frameset flag
 6235:        If page header is being requested for use in a frameset, then
 6236:        the second (option) argument -- frameset will be true, and
 6237:        the target attribute set for links should be target="_parent".
 6238: 
 6239: Returns: HTML div with CSTR path and recent box
 6240:          To be included on Authoring Space pages
 6241: 
 6242: =cut
 6243: 
 6244: sub CSTR_pageheader {
 6245:     my ($trailfile,$frameset) = @_;
 6246:     if ($trailfile eq '') {
 6247:         $trailfile = $env{'request.filename'};
 6248:     }
 6249: 
 6250: # this is for resources; directories have customtitle, and crumbs
 6251: # and select recent are created in lonpubdir.pm
 6252: 
 6253:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 6254:     my ($udom,$uname,$thisdisfn)=
 6255:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 6256:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 6257:     $formaction =~ s{/+}{/}g;
 6258: 
 6259:     my $parentpath = '';
 6260:     my $lastitem = '';
 6261:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 6262:         $parentpath = $1;
 6263:         $lastitem = $2;
 6264:     } else {
 6265:         $lastitem = $thisdisfn;
 6266:     }
 6267: 
 6268:     my ($crsauthor,$title);
 6269:     if (($env{'request.course.id'}) &&
 6270:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
 6271:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
 6272:         $crsauthor = 1;
 6273:         $title = &mt('Course Authoring Space');
 6274:     } else {
 6275:         $title = &mt('Authoring Space');
 6276:     }
 6277: 
 6278:     my ($target,$crumbtarget) = (' target="_top"','_top');
 6279:     if ($frameset) {
 6280:         $target = ' target="_parent"';
 6281:         $crumbtarget = '_parent';
 6282:     } elsif (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
 6283:         $target = '';
 6284:         $crumbtarget = '';
 6285:     } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
 6286:         $target = ' target="'.$env{'request.deeplink.target'}.'"';
 6287:         $crumbtarget = $env{'request.deeplink.target'};
 6288:     }
 6289: 
 6290:     my $output =
 6291:          '<div>'
 6292:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 6293:         .'<b>'.$title.'</b> '
 6294:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
 6295:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
 6296: 
 6297:     if ($lastitem) {
 6298:         $output .=
 6299:              '<span class="LC_filename">'
 6300:             .$lastitem
 6301:             .'</span>';
 6302:     }
 6303: 
 6304:     if ($crsauthor) {
 6305:         $output .= '</form>'.&Apache::lonmenu::constspaceform($frameset);
 6306:     } else {
 6307:         $output .=
 6308:              '<br />'
 6309:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
 6310:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 6311:             .'</form>'
 6312:             .&Apache::lonmenu::constspaceform($frameset);
 6313:     }
 6314:     $output .= '</div>';
 6315: 
 6316:     return $output;
 6317: }
 6318: 
 6319: ###############################################
 6320: ###############################################
 6321: 
 6322: =pod
 6323: 
 6324: =back
 6325: 
 6326: =head1 HTML Helpers
 6327: 
 6328: =over 4
 6329: 
 6330: =item * &bodytag()
 6331: 
 6332: Returns a uniform header for LON-CAPA web pages.
 6333: 
 6334: Inputs: 
 6335: 
 6336: =over 4
 6337: 
 6338: =item * $title, A title to be displayed on the page.
 6339: 
 6340: =item * $function, the current role (can be undef).
 6341: 
 6342: =item * $addentries, extra parameters for the <body> tag.
 6343: 
 6344: =item * $bodyonly, if defined, only return the <body> tag.
 6345: 
 6346: =item * $domain, if defined, force a given domain.
 6347: 
 6348: =item * $forcereg, if page should register as content page (relevant for 
 6349:             text interface only)
 6350: 
 6351: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 6352:                      navigational links
 6353: 
 6354: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 6355: 
 6356: =item * $args, optional argument valid values are
 6357:             no_auto_mt_title -> prevents &mt()ing the title arg
 6358:             use_absolute     -> for external resource or syllabus, this will
 6359:                                 contain https://<hostname> if server uses
 6360:                                 https (as per hosts.tab), but request is for http
 6361:             hostname         -> hostname, from $r->hostname().
 6362: 
 6363: =item * $advtoolsref, optional argument, ref to an array containing
 6364:             inlineremote items to be added in "Functions" menu below
 6365:             breadcrumbs.
 6366: 
 6367: =item * $ltiscope, optional argument, will be one of: resource, map or
 6368:             course, if LON-CAPA is in LTI Provider context. Value is
 6369:             the scope of use, i.e., launch was for access to a single, a map
 6370:             or the entire course.
 6371: 
 6372: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
 6373:             context, this will contain the URL for the landing item in
 6374:             the course, after launch from an LTI Consumer
 6375: 
 6376: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
 6377:             context, this will contain a reference to hash of items
 6378:             to be included in the page header and/or inline menu.
 6379: 
 6380: =item * $menucoll, optional argument, if specific menu collection is in
 6381:             effect, either set as the default for the course, or set for
 6382:             the deeplink paramater for $env{'request.deeplink.login'}
 6383:             then $menucoll will be the number of that collection. 
 6384: 
 6385: =item * $menuref, optional argument, reference to a hash, containing the
 6386:             menu options included for the menu in effect, based on the
 6387:             configuration for the numbered menu collection in use.  
 6388: 
 6389: =item * $showncrumbsref, reference to a scalar. Calls to lonmenu::innerregister
 6390:             within &bodytag() can result in calls to lonhtmlcommon::breadcrumbs(),
 6391:             if so, $showncrumbsref is set there to 1, and will propagate back
 6392:             via &bodytag() to &start_page(), to prevent lonhtmlcommon::breadcrumbs()
 6393:             being called a second time.
 6394: 
 6395: =back
 6396: 
 6397: Returns: A uniform header for LON-CAPA web pages.  
 6398: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 6399: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 6400: other decorations will be returned.
 6401: 
 6402: =cut
 6403: 
 6404: sub bodytag {
 6405:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 6406:         $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri,
 6407:         $ltimenu,$menucoll,$menuref,$showncrumbsref)=@_;
 6408: 
 6409:     my $public;
 6410:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 6411:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 6412:         $public = 1;
 6413:     }
 6414:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 6415:     my $httphost = $args->{'use_absolute'};
 6416:     my $hostname = $args->{'hostname'};
 6417: 
 6418:     $function = &get_users_function() if (!$function);
 6419:     my $img =    &designparm($function.'.img',$domain);
 6420:     my $font =   &designparm($function.'.font',$domain);
 6421:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 6422: 
 6423:     my %design = ( 'style'   => 'margin-top: 0',
 6424: 		   'bgcolor' => $pgbg,
 6425: 		   'text'    => $font,
 6426:                    'alink'   => &designparm($function.'.alink',$domain),
 6427: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 6428: 		   'link'    => &designparm($function.'.link',$domain),);
 6429:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 6430: 
 6431:  # role and realm
 6432:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
 6433:     if ($realm) {
 6434:         $realm = '/'.$realm;
 6435:     }
 6436:     if ($role eq 'ca') {
 6437:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 6438:         $realm = &plainname($rname,$rdom);
 6439:     } 
 6440: # realm
 6441:     my ($cid,$sec);
 6442:     if ($env{'request.course.id'}) {
 6443:         $cid = $env{'request.course.id'};
 6444:         if ($env{'request.course.sec'}) {
 6445:             $sec = $env{'request.course.sec'};
 6446:         }
 6447:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
 6448:         if (&Apache::lonnet::is_course($1,$2)) {
 6449:             $cid = $1.'_'.$2;
 6450:             $sec = $3;
 6451:         }
 6452:     }
 6453:     if ($cid) {
 6454:         if ($env{'request.role'} !~ /^cr/) {
 6455:             $role = &Apache::lonnet::plaintext($role,&course_type());
 6456:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
 6457:             if ($env{'request.role.desc'}) {
 6458:                 $role = $env{'request.role.desc'};
 6459:             } else {
 6460:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
 6461:             }
 6462:         } else {
 6463:             $role = (split(/\//,$role,4))[-1]; 
 6464:         }
 6465:         if ($sec) {
 6466:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
 6467:         }   
 6468: 	$realm = $env{'course.'.$cid.'.description'};
 6469:     } else {
 6470:         $role = &Apache::lonnet::plaintext($role);
 6471:     }
 6472: 
 6473:     if (!$realm) { $realm='&nbsp;'; }
 6474: 
 6475:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 6476: 
 6477: # construct main body tag
 6478:     my $bodytag = "<body $extra_body_attr>".
 6479: 	&Apache::lontexconvert::init_math_support();
 6480: 
 6481:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 6482: 
 6483:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 6484:         return $bodytag;
 6485:     }
 6486: 
 6487:     if ($public) {
 6488: 	undef($role);
 6489:     }
 6490: 
 6491:     my $showcrstitle = 1;
 6492:     if (($cid) && ($env{'request.lti.login'})) {
 6493:         if (ref($ltimenu) eq 'HASH') {
 6494:             unless ($ltimenu->{'role'}) {
 6495:                 undef($role);
 6496:             }
 6497:             unless ($ltimenu->{'coursetitle'}) {
 6498:                 $realm='&nbsp;';
 6499:                 $showcrstitle = 0;
 6500:             }
 6501:         }
 6502:     } elsif (($cid) && ($menucoll)) {
 6503:         if (ref($menuref) eq 'HASH') {
 6504:             unless ($menuref->{'role'}) {
 6505:                 undef($role);
 6506:             }
 6507:             unless ($menuref->{'crs'}) {
 6508:                 $realm='&nbsp;';
 6509:                 $showcrstitle = 0;
 6510:             }
 6511:         }
 6512:     }
 6513: 
 6514:     my $titleinfo = '<h1>'.$title.'</h1>';
 6515:     #
 6516:     # Extra info if you are the DC
 6517:     my $dc_info = '';
 6518:     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
 6519:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
 6520:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 6521:         $dc_info =~ s/\s+$//;
 6522:     }
 6523: 
 6524:     my $crstype;
 6525:     if ($cid) {
 6526:         $crstype = $env{'course.'.$cid.'.type'};
 6527:     } elsif ($args->{'crstype'}) {
 6528:         $crstype = $args->{'crstype'};
 6529:     }
 6530:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
 6531:         undef($role);
 6532:     } else {
 6533:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
 6534:     }
 6535: 
 6536:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 6537: 
 6538:         #    if ($env{'request.state'} eq 'construct') {
 6539:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 6540:         #    }
 6541: 
 6542:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 6543:             Apache::lonmenu::utilityfunctions($httphost), 'start');
 6544: 
 6545:         unless ($args->{'no_primary_menu'}) {
 6546:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
 6547:                                                               $args->{'links_disabled'},
 6548:                                                               $args->{'links_target'});
 6549: 
 6550:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 6551:                 if ($dc_info) {
 6552:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 6553:                 }
 6554:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 6555:                                <em>$realm</em> $dc_info</div>|;
 6556:                 return $bodytag;
 6557:             }
 6558: 
 6559:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 6560:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 6561:             }
 6562: 
 6563:             $bodytag .= $right;
 6564: 
 6565:             if ($dc_info) {
 6566:                 $dc_info = &dc_courseid_toggle($dc_info);
 6567:             }
 6568:             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 6569:         }
 6570: 
 6571:         #if directed to not display the secondary menu, don't.  
 6572:         if ($args->{'no_secondary_menu'}) {
 6573:             return $bodytag;
 6574:         }
 6575:         #don't show menus for public users
 6576:         if (!$public){
 6577:             unless ($args->{'no_inline_menu'}) {
 6578:                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
 6579:                                                             $args->{'no_primary_menu'},
 6580:                                                             $menucoll,$menuref,
 6581:                                                             $args->{'links_disabled'},
 6582:                                                             $args->{'links_target'});
 6583:             }
 6584:             $bodytag .= Apache::lonmenu::serverform();
 6585:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 6586:             if ($env{'request.state'} eq 'construct') {
 6587:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 6588:                                 $args->{'bread_crumbs'},'','',$hostname,
 6589:                                 $ltiscope,$ltiuri,$showncrumbsref);
 6590:             } elsif ($forcereg) {
 6591:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 6592:                                 $args->{'group'},$args->{'hide_buttons'},
 6593:                                 $hostname,$ltiscope,$ltiuri,$showncrumbsref);
 6594:             } else {
 6595:                 $bodytag .= 
 6596:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 6597:                                                         $forcereg,$args->{'group'},
 6598:                                                         $args->{'bread_crumbs'},
 6599:                                                         $advtoolsref,'',$hostname);
 6600:             }
 6601:         }else{
 6602:             # this is to seperate menu from content when there's no secondary
 6603:             # menu. Especially needed for public accessible ressources.
 6604:             $bodytag .= '<hr style="clear:both" />';
 6605:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 6606:         }
 6607: 
 6608:         return $bodytag;
 6609: }
 6610: 
 6611: sub dc_courseid_toggle {
 6612:     my ($dc_info) = @_;
 6613:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 6614:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 6615:            &mt('(More ...)').'</a></span>'.
 6616:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 6617: }
 6618: 
 6619: sub make_attr_string {
 6620:     my ($register,$attr_ref) = @_;
 6621: 
 6622:     if ($attr_ref && !ref($attr_ref)) {
 6623: 	die("addentries Must be a hash ref ".
 6624: 	    join(':',caller(1))." ".
 6625: 	    join(':',caller(0))." ");
 6626:     }
 6627: 
 6628:     if ($register) {
 6629: 	my ($on_load,$on_unload);
 6630: 	foreach my $key (keys(%{$attr_ref})) {
 6631: 	    if      (lc($key) eq 'onload') {
 6632: 		$on_load.=$attr_ref->{$key}.';';
 6633: 		delete($attr_ref->{$key});
 6634: 
 6635: 	    } elsif (lc($key) eq 'onunload') {
 6636: 		$on_unload.=$attr_ref->{$key}.';';
 6637: 		delete($attr_ref->{$key});
 6638: 	    }
 6639: 	}
 6640: 	$attr_ref->{'onload'}  = $on_load;
 6641: 	$attr_ref->{'onunload'}= $on_unload;
 6642:     }
 6643: 
 6644:     my $attr_string;
 6645:     foreach my $attr (sort(keys(%$attr_ref))) {
 6646: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 6647:     }
 6648:     return $attr_string;
 6649: }
 6650: 
 6651: 
 6652: ###############################################
 6653: ###############################################
 6654: 
 6655: =pod
 6656: 
 6657: =item * &endbodytag()
 6658: 
 6659: Returns a uniform footer for LON-CAPA web pages.
 6660: 
 6661: Inputs: 1 - optional reference to an args hash
 6662: If in the hash, key for noredirectlink has a value which evaluates to true,
 6663: a 'Continue' link is not displayed if the page contains an
 6664: internal redirect in the <head></head> section,
 6665: i.e., $env{'internal.head.redirect'} exists   
 6666: 
 6667: =cut
 6668: 
 6669: sub endbodytag {
 6670:     my ($args) = @_;
 6671:     my $endbodytag;
 6672:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 6673:         $endbodytag='</body>';
 6674:     }
 6675:     if ( exists( $env{'internal.head.redirect'} ) ) {
 6676:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 6677:             my ($endbodyjs,$idattr);
 6678:             if ($env{'internal.head.to_opener'}) {
 6679:                 my $linkid = 'LC_continue_link';
 6680:                 $idattr = ' id="'.$linkid.'"';
 6681:                 my $redirect_for_js = &js_escape($env{'internal.head.redirect'});
 6682:                 $endbodyjs=<<ENDJS;
 6683: <script type="text/javascript">
 6684: // <![CDATA[
 6685: function ebFunction(evt) {
 6686:     evt.preventDefault();
 6687:     var dest = '$redirect_for_js';
 6688:     if (window.opener != null && !window.opener.closed) {
 6689:         window.opener.location.href=dest;
 6690:         window.close();
 6691:     } else {
 6692:         window.location.href=dest;
 6693:     }
 6694:     return false;
 6695: }
 6696: 
 6697: \$(document).ready(function () {
 6698:   if (document.getElementById('$linkid')) {
 6699:     var clickelem = document.getElementById('$linkid');
 6700:     clickelem.addEventListener('click',ebFunction,false);
 6701:   }
 6702: });
 6703: // ]]>
 6704: </script>
 6705: ENDJS
 6706:             }
 6707: 	    $endbodytag=
 6708: 	        "$endbodyjs<br /><a href=\"$env{'internal.head.redirect'}\"$idattr>".
 6709: 	        &mt('Continue').'</a>'.
 6710: 	        $endbodytag;
 6711:         }
 6712:     }
 6713:     return $endbodytag;
 6714: }
 6715: 
 6716: =pod
 6717: 
 6718: =item * &standard_css()
 6719: 
 6720: Returns a style sheet
 6721: 
 6722: Inputs: (all optional)
 6723:             domain         -> force to color decorate a page for a specific
 6724:                                domain
 6725:             function       -> force usage of a specific rolish color scheme
 6726:             bgcolor        -> override the default page bgcolor
 6727: 
 6728: =cut
 6729: 
 6730: sub standard_css {
 6731:     my ($function,$domain,$bgcolor) = @_;
 6732:     $function  = &get_users_function() if (!$function);
 6733:     my $img    = &designparm($function.'.img',   $domain);
 6734:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 6735:     my $font   = &designparm($function.'.font',  $domain);
 6736:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 6737: #second colour for later usage
 6738:     my $sidebg = &designparm($function.'.sidebg',$domain);
 6739:     my $pgbg_or_bgcolor =
 6740: 	         $bgcolor ||
 6741: 	         &designparm($function.'.pgbg',  $domain);
 6742:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 6743:     my $alink  = &designparm($function.'.alink', $domain);
 6744:     my $vlink  = &designparm($function.'.vlink', $domain);
 6745:     my $link   = &designparm($function.'.link',  $domain);
 6746: 
 6747:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 6748:     my $mono                 = 'monospace';
 6749:     my $data_table_head      = $sidebg;
 6750:     my $data_table_light     = '#FAFAFA';
 6751:     my $data_table_dark      = '#E0E0E0';
 6752:     my $data_table_darker    = '#CCCCCC';
 6753:     my $data_table_highlight = '#FFFF00';
 6754:     my $mail_new             = '#FFBB77';
 6755:     my $mail_new_hover       = '#DD9955';
 6756:     my $mail_read            = '#BBBB77';
 6757:     my $mail_read_hover      = '#999944';
 6758:     my $mail_replied         = '#AAAA88';
 6759:     my $mail_replied_hover   = '#888855';
 6760:     my $mail_other           = '#99BBBB';
 6761:     my $mail_other_hover     = '#669999';
 6762:     my $table_header         = '#DDDDDD';
 6763:     my $feedback_link_bg     = '#BBBBBB';
 6764:     my $lg_border_color      = '#C8C8C8';
 6765:     my $button_hover         = '#BF2317';
 6766: 
 6767:     my $border = ($env{'browser.type'} eq 'explorer' ||
 6768:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 6769:                                              : '0 3px 0 4px';
 6770: 
 6771: 
 6772:     return <<END;
 6773: 
 6774: /* needed for iframe to allow 100% height in FF */
 6775: body, html { 
 6776:     margin: 0;
 6777:     padding: 0 0.5%;
 6778:     height: 99%; /* to avoid scrollbars */
 6779: }
 6780: 
 6781: body {
 6782:   font-family: $sans;
 6783:   line-height:130%;
 6784:   font-size:0.83em;
 6785:   color:$font;
 6786: }
 6787: 
 6788: a:focus,
 6789: a:focus img {
 6790:   color: red;
 6791: }
 6792: 
 6793: form, .inline {
 6794:   display: inline;
 6795: }
 6796: 
 6797: .LC_right {
 6798:   text-align:right;
 6799: }
 6800: 
 6801: .LC_middle {
 6802:   vertical-align:middle;
 6803: }
 6804: 
 6805: .LC_floatleft {
 6806:   float: left;
 6807: }
 6808: 
 6809: .LC_floatright {
 6810:   float: right;
 6811: }
 6812: 
 6813: .LC_400Box {
 6814:   width:400px;
 6815: }
 6816: 
 6817: .LC_iframecontainer {
 6818:     width: 98%;
 6819:     margin: 0;
 6820:     position: fixed;
 6821:     top: 8.5em;
 6822:     bottom: 0;
 6823: }
 6824: 
 6825: .LC_iframecontainer iframe{
 6826:     border: none;
 6827:     width: 100%;
 6828:     height: 100%;
 6829: }
 6830: 
 6831: .LC_filename {
 6832:   font-family: $mono;
 6833:   white-space:pre;
 6834:   font-size: 120%;
 6835: }
 6836: 
 6837: .LC_fileicon {
 6838:   border: none;
 6839:   height: 1.3em;
 6840:   vertical-align: text-bottom;
 6841:   margin-right: 0.3em;
 6842:   text-decoration:none;
 6843: }
 6844: 
 6845: .LC_setting {
 6846:   text-decoration:underline;
 6847: }
 6848: 
 6849: .LC_error {
 6850:   color: red;
 6851: }
 6852: 
 6853: .LC_warning {
 6854:   color: darkorange;
 6855: }
 6856: 
 6857: .LC_diff_removed {
 6858:   color: red;
 6859: }
 6860: 
 6861: .LC_info,
 6862: .LC_success,
 6863: .LC_diff_added {
 6864:   color: green;
 6865: }
 6866: 
 6867: div.LC_confirm_box {
 6868:   background-color: #FAFAFA;
 6869:   border: 1px solid $lg_border_color;
 6870:   margin-right: 0;
 6871:   padding: 5px;
 6872: }
 6873: 
 6874: div.LC_confirm_box .LC_error img,
 6875: div.LC_confirm_box .LC_success img {
 6876:   vertical-align: middle;
 6877: }
 6878: 
 6879: .LC_maxwidth {
 6880:   max-width: 100%;
 6881:   height: auto;
 6882: }
 6883: 
 6884: .LC_textsize_mobile {
 6885:   \@media only screen and (max-device-width: 480px) {
 6886:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
 6887:   }
 6888: }
 6889: 
 6890: .LC_icon {
 6891:   border: none;
 6892:   vertical-align: middle;
 6893: }
 6894: 
 6895: .LC_docs_spacer {
 6896:   width: 25px;
 6897:   height: 1px;
 6898:   border: none;
 6899: }
 6900: 
 6901: .LC_internal_info {
 6902:   color: #999999;
 6903: }
 6904: 
 6905: .LC_discussion {
 6906:   background: $data_table_dark;
 6907:   border: 1px solid black;
 6908:   margin: 2px;
 6909: }
 6910: 
 6911: .LC_disc_action_left {
 6912:   background: $sidebg;
 6913:   text-align: left;
 6914:   padding: 4px;
 6915:   margin: 2px;
 6916: }
 6917: 
 6918: .LC_disc_action_right {
 6919:   background: $sidebg;
 6920:   text-align: right;
 6921:   padding: 4px;
 6922:   margin: 2px;
 6923: }
 6924: 
 6925: .LC_disc_new_item {
 6926:   background: white;
 6927:   border: 2px solid red;
 6928:   margin: 4px;
 6929:   padding: 4px;
 6930: }
 6931: 
 6932: .LC_disc_old_item {
 6933:   background: white;
 6934:   margin: 4px;
 6935:   padding: 4px;
 6936: }
 6937: 
 6938: table.LC_pastsubmission {
 6939:   border: 1px solid black;
 6940:   margin: 2px;
 6941: }
 6942: 
 6943: table#LC_menubuttons {
 6944:   width: 100%;
 6945:   background: $pgbg;
 6946:   border: 2px;
 6947:   border-collapse: separate;
 6948:   padding: 0;
 6949: }
 6950: 
 6951: table#LC_title_bar a {
 6952:   color: $fontmenu;
 6953: }
 6954: 
 6955: table#LC_title_bar {
 6956:   clear: both;
 6957:   display: none;
 6958: }
 6959: 
 6960: table#LC_title_bar,
 6961: table.LC_breadcrumbs, /* obsolete? */
 6962: table#LC_title_bar.LC_with_remote {
 6963:   width: 100%;
 6964:   border-color: $pgbg;
 6965:   border-style: solid;
 6966:   border-width: $border;
 6967:   background: $pgbg;
 6968:   color: $fontmenu;
 6969:   border-collapse: collapse;
 6970:   padding: 0;
 6971:   margin: 0;
 6972: }
 6973: 
 6974: ul.LC_breadcrumb_tools_outerlist {
 6975:     margin: 0;
 6976:     padding: 0;
 6977:     position: relative;
 6978:     list-style: none;
 6979: }
 6980: ul.LC_breadcrumb_tools_outerlist li {
 6981:     display: inline;
 6982: }
 6983: 
 6984: .LC_breadcrumb_tools_navigation {
 6985:     padding: 0;
 6986:     margin: 0;
 6987:     float: left;
 6988: }
 6989: .LC_breadcrumb_tools_tools {
 6990:     padding: 0;
 6991:     margin: 0;
 6992:     float: right;
 6993: }
 6994: 
 6995: .LC_placement_prog {
 6996:     padding-right: 20px;
 6997:     font-weight: bold;
 6998:     font-size: 90%;
 6999: }
 7000: 
 7001: table#LC_title_bar td {
 7002:   background: $tabbg;
 7003: }
 7004: 
 7005: table#LC_menubuttons img {
 7006:   border: none;
 7007: }
 7008: 
 7009: .LC_breadcrumbs_component {
 7010:   float: right;
 7011:   margin: 0 1em;
 7012: }
 7013: .LC_breadcrumbs_component img {
 7014:   vertical-align: middle;
 7015: }
 7016: 
 7017: .LC_breadcrumbs_hoverable {
 7018:   background: $sidebg;
 7019: }
 7020: 
 7021: td.LC_table_cell_checkbox {
 7022:   text-align: center;
 7023: }
 7024: 
 7025: .LC_fontsize_small {
 7026:   font-size: 70%;
 7027: }
 7028: 
 7029: #LC_breadcrumbs {
 7030:   clear:both;
 7031:   background: $sidebg;
 7032:   border-bottom: 1px solid $lg_border_color;
 7033:   line-height: 2.5em;
 7034:   overflow: hidden;
 7035:   margin: 0;
 7036:   padding: 0;
 7037:   text-align: left;
 7038: }
 7039: 
 7040: .LC_head_subbox, .LC_actionbox {
 7041:   clear:both;
 7042:   background: #F8F8F8; /* $sidebg; */
 7043:   border: 1px solid $sidebg;
 7044:   margin: 0 0 10px 0;
 7045:   padding: 3px;
 7046:   text-align: left;
 7047: }
 7048: 
 7049: .LC_fontsize_medium {
 7050:   font-size: 85%;
 7051: }
 7052: 
 7053: .LC_fontsize_large {
 7054:   font-size: 120%;
 7055: }
 7056: 
 7057: .LC_menubuttons_inline_text {
 7058:   color: $font;
 7059:   font-size: 90%;
 7060:   padding-left:3px;
 7061: }
 7062: 
 7063: .LC_menubuttons_inline_text img{
 7064:   vertical-align: middle;
 7065: }
 7066: 
 7067: li.LC_menubuttons_inline_text img {
 7068:   cursor:pointer;
 7069:   text-decoration: none;
 7070: }
 7071: 
 7072: .LC_menubuttons_link {
 7073:   text-decoration: none;
 7074: }
 7075: 
 7076: .LC_menubuttons_category {
 7077:   color: $font;
 7078:   background: $pgbg;
 7079:   font-size: larger;
 7080:   font-weight: bold;
 7081: }
 7082: 
 7083: td.LC_menubuttons_text {
 7084:   color: $font;
 7085: }
 7086: 
 7087: .LC_current_location {
 7088:   background: $tabbg;
 7089: }
 7090: 
 7091: td.LC_zero_height {
 7092:   line-height: 0; 
 7093:   cellpadding: 0;
 7094: }
 7095: 
 7096: table.LC_data_table {
 7097:   border: 1px solid #000000;
 7098:   border-collapse: separate;
 7099:   border-spacing: 1px;
 7100:   background: $pgbg;
 7101: }
 7102: 
 7103: .LC_data_table_dense {
 7104:   font-size: small;
 7105: }
 7106: 
 7107: table.LC_nested_outer {
 7108:   border: 1px solid #000000;
 7109:   border-collapse: collapse;
 7110:   border-spacing: 0;
 7111:   width: 100%;
 7112: }
 7113: 
 7114: table.LC_innerpickbox,
 7115: table.LC_nested {
 7116:   border: none;
 7117:   border-collapse: collapse;
 7118:   border-spacing: 0;
 7119:   width: 100%;
 7120: }
 7121: 
 7122: table.LC_data_table tr th,
 7123: table.LC_calendar tr th,
 7124: table.LC_prior_tries tr th,
 7125: table.LC_innerpickbox tr th {
 7126:   font-weight: bold;
 7127:   background-color: $data_table_head;
 7128:   color:$fontmenu;
 7129:   font-size:90%;
 7130: }
 7131: 
 7132: table.LC_innerpickbox tr th,
 7133: table.LC_innerpickbox tr td {
 7134:   vertical-align: top;
 7135: }
 7136: 
 7137: table.LC_data_table tr.LC_info_row > td {
 7138:   background-color: #CCCCCC;
 7139:   font-weight: bold;
 7140:   text-align: left;
 7141: }
 7142: 
 7143: table.LC_data_table tr.LC_odd_row > td {
 7144:   background-color: $data_table_light;
 7145:   padding: 2px;
 7146:   vertical-align: top;
 7147: }
 7148: 
 7149: table.LC_pick_box tr > td.LC_odd_row {
 7150:   background-color: $data_table_light;
 7151:   vertical-align: top;
 7152: }
 7153: 
 7154: table.LC_data_table tr.LC_even_row > td {
 7155:   background-color: $data_table_dark;
 7156:   padding: 2px;
 7157:   vertical-align: top;
 7158: }
 7159: 
 7160: table.LC_pick_box tr > td.LC_even_row {
 7161:   background-color: $data_table_dark;
 7162:   vertical-align: top;
 7163: }
 7164: 
 7165: table.LC_data_table tr.LC_data_table_highlight td {
 7166:   background-color: $data_table_darker;
 7167: }
 7168: 
 7169: table.LC_data_table tr td.LC_leftcol_header {
 7170:   background-color: $data_table_head;
 7171:   font-weight: bold;
 7172: }
 7173: 
 7174: table.LC_data_table tr.LC_empty_row td,
 7175: table.LC_nested tr.LC_empty_row td {
 7176:   font-weight: bold;
 7177:   font-style: italic;
 7178:   text-align: center;
 7179:   padding: 8px;
 7180: }
 7181: 
 7182: table.LC_data_table tr.LC_empty_row td,
 7183: table.LC_data_table tr.LC_footer_row td {
 7184:   background-color: $sidebg;
 7185: }
 7186: 
 7187: table.LC_nested tr.LC_empty_row td {
 7188:   background-color: #FFFFFF;
 7189: }
 7190: 
 7191: table.LC_caption {
 7192: }
 7193: 
 7194: table.LC_nested tr.LC_empty_row td {
 7195:   padding: 4ex
 7196: }
 7197: 
 7198: table.LC_nested_outer tr th {
 7199:   font-weight: bold;
 7200:   color:$fontmenu;
 7201:   background-color: $data_table_head;
 7202:   font-size: small;
 7203:   border-bottom: 1px solid #000000;
 7204: }
 7205: 
 7206: table.LC_nested_outer tr td.LC_subheader {
 7207:   background-color: $data_table_head;
 7208:   font-weight: bold;
 7209:   font-size: small;
 7210:   border-bottom: 1px solid #000000;
 7211:   text-align: right;
 7212: }
 7213: 
 7214: table.LC_nested tr.LC_info_row td {
 7215:   background-color: #CCCCCC;
 7216:   font-weight: bold;
 7217:   font-size: small;
 7218:   text-align: center;
 7219: }
 7220: 
 7221: table.LC_nested tr.LC_info_row td.LC_left_item,
 7222: table.LC_nested_outer tr th.LC_left_item {
 7223:   text-align: left;
 7224: }
 7225: 
 7226: table.LC_nested td {
 7227:   background-color: #FFFFFF;
 7228:   font-size: small;
 7229: }
 7230: 
 7231: table.LC_nested_outer tr th.LC_right_item,
 7232: table.LC_nested tr.LC_info_row td.LC_right_item,
 7233: table.LC_nested tr.LC_odd_row td.LC_right_item,
 7234: table.LC_nested tr td.LC_right_item {
 7235:   text-align: right;
 7236: }
 7237: 
 7238: table.LC_nested tr.LC_odd_row td {
 7239:   background-color: #EEEEEE;
 7240: }
 7241: 
 7242: table.LC_createuser {
 7243: }
 7244: 
 7245: table.LC_createuser tr.LC_section_row td {
 7246:   font-size: small;
 7247: }
 7248: 
 7249: table.LC_createuser tr.LC_info_row td  {
 7250:   background-color: #CCCCCC;
 7251:   font-weight: bold;
 7252:   text-align: center;
 7253: }
 7254: 
 7255: table.LC_calendar {
 7256:   border: 1px solid #000000;
 7257:   border-collapse: collapse;
 7258:   width: 98%;
 7259: }
 7260: 
 7261: table.LC_calendar_pickdate {
 7262:   font-size: xx-small;
 7263: }
 7264: 
 7265: table.LC_calendar tr td {
 7266:   border: 1px solid #000000;
 7267:   vertical-align: top;
 7268:   width: 14%;
 7269: }
 7270: 
 7271: table.LC_calendar tr td.LC_calendar_day_empty {
 7272:   background-color: $data_table_dark;
 7273: }
 7274: 
 7275: table.LC_calendar tr td.LC_calendar_day_current {
 7276:   background-color: $data_table_highlight;
 7277: }
 7278: 
 7279: table.LC_data_table tr td.LC_mail_new {
 7280:   background-color: $mail_new;
 7281: }
 7282: 
 7283: table.LC_data_table tr.LC_mail_new:hover {
 7284:   background-color: $mail_new_hover;
 7285: }
 7286: 
 7287: table.LC_data_table tr td.LC_mail_read {
 7288:   background-color: $mail_read;
 7289: }
 7290: 
 7291: /*
 7292: table.LC_data_table tr.LC_mail_read:hover {
 7293:   background-color: $mail_read_hover;
 7294: }
 7295: */
 7296: 
 7297: table.LC_data_table tr td.LC_mail_replied {
 7298:   background-color: $mail_replied;
 7299: }
 7300: 
 7301: /*
 7302: table.LC_data_table tr.LC_mail_replied:hover {
 7303:   background-color: $mail_replied_hover;
 7304: }
 7305: */
 7306: 
 7307: table.LC_data_table tr td.LC_mail_other {
 7308:   background-color: $mail_other;
 7309: }
 7310: 
 7311: /*
 7312: table.LC_data_table tr.LC_mail_other:hover {
 7313:   background-color: $mail_other_hover;
 7314: }
 7315: */
 7316: 
 7317: table.LC_data_table tr > td.LC_browser_file,
 7318: table.LC_data_table tr > td.LC_browser_file_published {
 7319:   background: #AAEE77;
 7320: }
 7321: 
 7322: table.LC_data_table tr > td.LC_browser_file_locked,
 7323: table.LC_data_table tr > td.LC_browser_file_unpublished {
 7324:   background: #FFAA99;
 7325: }
 7326: 
 7327: table.LC_data_table tr > td.LC_browser_file_obsolete {
 7328:   background: #888888;
 7329: }
 7330: 
 7331: table.LC_data_table tr > td.LC_browser_file_modified,
 7332: table.LC_data_table tr > td.LC_browser_file_metamodified {
 7333:   background: #F8F866;
 7334: }
 7335: 
 7336: table.LC_data_table tr.LC_browser_folder > td {
 7337:   background: #E0E8FF;
 7338: }
 7339: 
 7340: table.LC_data_table tr > td.LC_roles_is {
 7341:   /* background: #77FF77; */
 7342: }
 7343: 
 7344: table.LC_data_table tr > td.LC_roles_future {
 7345:   border-right: 8px solid #FFFF77;
 7346: }
 7347: 
 7348: table.LC_data_table tr > td.LC_roles_will {
 7349:   border-right: 8px solid #FFAA77;
 7350: }
 7351: 
 7352: table.LC_data_table tr > td.LC_roles_expired {
 7353:   border-right: 8px solid #FF7777;
 7354: }
 7355: 
 7356: table.LC_data_table tr > td.LC_roles_will_not {
 7357:   border-right: 8px solid #AAFF77;
 7358: }
 7359: 
 7360: table.LC_data_table tr > td.LC_roles_selected {
 7361:   border-right: 8px solid #11CC55;
 7362: }
 7363: 
 7364: span.LC_current_location {
 7365:   font-size:larger;
 7366:   background: $pgbg;
 7367: }
 7368: 
 7369: span.LC_current_nav_location {
 7370:   font-weight:bold;
 7371:   background: $sidebg;
 7372: }
 7373: 
 7374: span.LC_parm_menu_item {
 7375:   font-size: larger;
 7376: }
 7377: 
 7378: span.LC_parm_scope_all {
 7379:   color: red;
 7380: }
 7381: 
 7382: span.LC_parm_scope_folder {
 7383:   color: green;
 7384: }
 7385: 
 7386: span.LC_parm_scope_resource {
 7387:   color: orange;
 7388: }
 7389: 
 7390: span.LC_parm_part {
 7391:   color: blue;
 7392: }
 7393: 
 7394: span.LC_parm_folder,
 7395: span.LC_parm_symb {
 7396:   font-size: x-small;
 7397:   font-family: $mono;
 7398:   color: #AAAAAA;
 7399: }
 7400: 
 7401: ul.LC_parm_parmlist li {
 7402:   display: inline-block;
 7403:   padding: 0.3em 0.8em;
 7404:   vertical-align: top;
 7405:   width: 150px;
 7406:   border-top:1px solid $lg_border_color;
 7407: }
 7408: 
 7409: td.LC_parm_overview_level_menu,
 7410: td.LC_parm_overview_map_menu,
 7411: td.LC_parm_overview_parm_selectors,
 7412: td.LC_parm_overview_restrictions  {
 7413:   border: 1px solid black;
 7414:   border-collapse: collapse;
 7415: }
 7416: 
 7417: span.LC_parm_recursive,
 7418: td.LC_parm_recursive {
 7419:   font-weight: bold;
 7420:   font-size: smaller;
 7421: }
 7422: 
 7423: table.LC_parm_overview_restrictions td {
 7424:   border-width: 1px 4px 1px 4px;
 7425:   border-style: solid;
 7426:   border-color: $pgbg;
 7427:   text-align: center;
 7428: }
 7429: 
 7430: table.LC_parm_overview_restrictions th {
 7431:   background: $tabbg;
 7432:   border-width: 1px 4px 1px 4px;
 7433:   border-style: solid;
 7434:   border-color: $pgbg;
 7435: }
 7436: 
 7437: table#LC_helpmenu {
 7438:   border: none;
 7439:   height: 55px;
 7440:   border-spacing: 0;
 7441: }
 7442: 
 7443: table#LC_helpmenu fieldset legend {
 7444:   font-size: larger;
 7445: }
 7446: 
 7447: table#LC_helpmenu_links {
 7448:   width: 100%;
 7449:   border: 1px solid black;
 7450:   background: $pgbg;
 7451:   padding: 0;
 7452:   border-spacing: 1px;
 7453: }
 7454: 
 7455: table#LC_helpmenu_links tr td {
 7456:   padding: 1px;
 7457:   background: $tabbg;
 7458:   text-align: center;
 7459:   font-weight: bold;
 7460: }
 7461: 
 7462: table#LC_helpmenu_links a:link,
 7463: table#LC_helpmenu_links a:visited,
 7464: table#LC_helpmenu_links a:active {
 7465:   text-decoration: none;
 7466:   color: $font;
 7467: }
 7468: 
 7469: table#LC_helpmenu_links a:hover {
 7470:   text-decoration: underline;
 7471:   color: $vlink;
 7472: }
 7473: 
 7474: .LC_chrt_popup_exists {
 7475:   border: 1px solid #339933;
 7476:   margin: -1px;
 7477: }
 7478: 
 7479: .LC_chrt_popup_up {
 7480:   border: 1px solid yellow;
 7481:   margin: -1px;
 7482: }
 7483: 
 7484: .LC_chrt_popup {
 7485:   border: 1px solid #8888FF;
 7486:   background: #CCCCFF;
 7487: }
 7488: 
 7489: table.LC_pick_box {
 7490:   border-collapse: separate;
 7491:   background: white;
 7492:   border: 1px solid black;
 7493:   border-spacing: 1px;
 7494: }
 7495: 
 7496: table.LC_pick_box td.LC_pick_box_title {
 7497:   background: $sidebg;
 7498:   font-weight: bold;
 7499:   text-align: left;
 7500:   vertical-align: top;
 7501:   width: 184px;
 7502:   padding: 8px;
 7503: }
 7504: 
 7505: table.LC_pick_box td.LC_pick_box_value {
 7506:   text-align: left;
 7507:   padding: 8px;
 7508: }
 7509: 
 7510: table.LC_pick_box td.LC_pick_box_select {
 7511:   text-align: left;
 7512:   padding: 8px;
 7513: }
 7514: 
 7515: table.LC_pick_box td.LC_pick_box_separator {
 7516:   padding: 0;
 7517:   height: 1px;
 7518:   background: black;
 7519: }
 7520: 
 7521: table.LC_pick_box td.LC_pick_box_submit {
 7522:   text-align: right;
 7523: }
 7524: 
 7525: table.LC_pick_box td.LC_evenrow_value {
 7526:   text-align: left;
 7527:   padding: 8px;
 7528:   background-color: $data_table_light;
 7529: }
 7530: 
 7531: table.LC_pick_box td.LC_oddrow_value {
 7532:   text-align: left;
 7533:   padding: 8px;
 7534:   background-color: $data_table_light;
 7535: }
 7536: 
 7537: span.LC_helpform_receipt_cat {
 7538:   font-weight: bold;
 7539: }
 7540: 
 7541: table.LC_group_priv_box {
 7542:   background: white;
 7543:   border: 1px solid black;
 7544:   border-spacing: 1px;
 7545: }
 7546: 
 7547: table.LC_group_priv_box td.LC_pick_box_title {
 7548:   background: $tabbg;
 7549:   font-weight: bold;
 7550:   text-align: right;
 7551:   width: 184px;
 7552: }
 7553: 
 7554: table.LC_group_priv_box td.LC_groups_fixed {
 7555:   background: $data_table_light;
 7556:   text-align: center;
 7557: }
 7558: 
 7559: table.LC_group_priv_box td.LC_groups_optional {
 7560:   background: $data_table_dark;
 7561:   text-align: center;
 7562: }
 7563: 
 7564: table.LC_group_priv_box td.LC_groups_functionality {
 7565:   background: $data_table_darker;
 7566:   text-align: center;
 7567:   font-weight: bold;
 7568: }
 7569: 
 7570: table.LC_group_priv td {
 7571:   text-align: left;
 7572:   padding: 0;
 7573: }
 7574: 
 7575: .LC_navbuttons {
 7576:   margin: 2ex 0ex 2ex 0ex;
 7577: }
 7578: 
 7579: .LC_topic_bar {
 7580:   font-weight: bold;
 7581:   background: $tabbg;
 7582:   margin: 1em 0em 1em 2em;
 7583:   padding: 3px;
 7584:   font-size: 1.2em;
 7585: }
 7586: 
 7587: .LC_topic_bar span {
 7588:   left: 0.5em;
 7589:   position: absolute;
 7590:   vertical-align: middle;
 7591:   font-size: 1.2em;
 7592: }
 7593: 
 7594: table.LC_course_group_status {
 7595:   margin: 20px;
 7596: }
 7597: 
 7598: table.LC_status_selector td {
 7599:   vertical-align: top;
 7600:   text-align: center;
 7601:   padding: 4px;
 7602: }
 7603: 
 7604: div.LC_feedback_link {
 7605:   clear: both;
 7606:   background: $sidebg;
 7607:   width: 100%;
 7608:   padding-bottom: 10px;
 7609:   border: 1px $tabbg solid;
 7610:   height: 22px;
 7611:   line-height: 22px;
 7612:   padding-top: 5px;
 7613: }
 7614: 
 7615: div.LC_feedback_link img {
 7616:   height: 22px;
 7617:   vertical-align:middle;
 7618: }
 7619: 
 7620: div.LC_feedback_link a {
 7621:   text-decoration: none;
 7622: }
 7623: 
 7624: div.LC_comblock {
 7625:   display:inline;
 7626:   color:$font;
 7627:   font-size:90%;
 7628: }
 7629: 
 7630: div.LC_feedback_link div.LC_comblock {
 7631:   padding-left:5px;
 7632: }
 7633: 
 7634: div.LC_feedback_link div.LC_comblock a {
 7635:   color:$font;
 7636: }
 7637: 
 7638: span.LC_feedback_link {
 7639:   /* background: $feedback_link_bg; */
 7640:   font-size: larger;
 7641: }
 7642: 
 7643: span.LC_message_link {
 7644:   /* background: $feedback_link_bg; */
 7645:   font-size: larger;
 7646:   position: absolute;
 7647:   right: 1em;
 7648: }
 7649: 
 7650: table.LC_prior_tries {
 7651:   border: 1px solid #000000;
 7652:   border-collapse: separate;
 7653:   border-spacing: 1px;
 7654: }
 7655: 
 7656: table.LC_prior_tries td {
 7657:   padding: 2px;
 7658: }
 7659: 
 7660: .LC_answer_correct {
 7661:   background: lightgreen;
 7662:   color: darkgreen;
 7663:   padding: 6px;
 7664: }
 7665: 
 7666: .LC_answer_charged_try {
 7667:   background: #FFAAAA;
 7668:   color: darkred;
 7669:   padding: 6px;
 7670: }
 7671: 
 7672: .LC_answer_not_charged_try,
 7673: .LC_answer_no_grade,
 7674: .LC_answer_late {
 7675:   background: lightyellow;
 7676:   color: black;
 7677:   padding: 6px;
 7678: }
 7679: 
 7680: .LC_answer_previous {
 7681:   background: lightblue;
 7682:   color: darkblue;
 7683:   padding: 6px;
 7684: }
 7685: 
 7686: .LC_answer_no_message {
 7687:   background: #FFFFFF;
 7688:   color: black;
 7689:   padding: 6px;
 7690: }
 7691: 
 7692: .LC_answer_unknown,
 7693: .LC_answer_warning {
 7694:   background: orange;
 7695:   color: black;
 7696:   padding: 6px;
 7697: }
 7698: 
 7699: span.LC_prior_numerical,
 7700: span.LC_prior_string,
 7701: span.LC_prior_custom,
 7702: span.LC_prior_reaction,
 7703: span.LC_prior_math {
 7704:   font-family: $mono;
 7705:   white-space: pre;
 7706: }
 7707: 
 7708: span.LC_prior_string {
 7709:   font-family: $mono;
 7710:   white-space: pre;
 7711: }
 7712: 
 7713: table.LC_prior_option {
 7714:   width: 100%;
 7715:   border-collapse: collapse;
 7716: }
 7717: 
 7718: table.LC_prior_rank,
 7719: table.LC_prior_match {
 7720:   border-collapse: collapse;
 7721: }
 7722: 
 7723: table.LC_prior_option tr td,
 7724: table.LC_prior_rank tr td,
 7725: table.LC_prior_match tr td {
 7726:   border: 1px solid #000000;
 7727: }
 7728: 
 7729: .LC_nobreak {
 7730:   white-space: nowrap;
 7731: }
 7732: 
 7733: span.LC_cusr_emph {
 7734:   font-style: italic;
 7735: }
 7736: 
 7737: span.LC_cusr_subheading {
 7738:   font-weight: normal;
 7739:   font-size: 85%;
 7740: }
 7741: 
 7742: div.LC_docs_entry_move {
 7743:   border: 1px solid #BBBBBB;
 7744:   background: #DDDDDD;
 7745:   width: 22px;
 7746:   padding: 1px;
 7747:   margin: 0;
 7748: }
 7749: 
 7750: table.LC_data_table tr > td.LC_docs_entry_commands,
 7751: table.LC_data_table tr > td.LC_docs_entry_parameter {
 7752:   font-size: x-small;
 7753: }
 7754: 
 7755: .LC_docs_entry_parameter {
 7756:   white-space: nowrap;
 7757: }
 7758: 
 7759: .LC_docs_copy {
 7760:   color: #000099;
 7761: }
 7762: 
 7763: .LC_docs_cut {
 7764:   color: #550044;
 7765: }
 7766: 
 7767: .LC_docs_rename {
 7768:   color: #009900;
 7769: }
 7770: 
 7771: .LC_docs_remove {
 7772:   color: #990000;
 7773: }
 7774: 
 7775: .LC_docs_alias {
 7776:   color: #440055;  
 7777: }
 7778: 
 7779: .LC_domprefs_email,
 7780: .LC_docs_alias_name,
 7781: .LC_docs_reinit_warn,
 7782: .LC_docs_ext_edit {
 7783:   font-size: x-small;
 7784: }
 7785: 
 7786: table.LC_docs_adddocs td,
 7787: table.LC_docs_adddocs th {
 7788:   border: 1px solid #BBBBBB;
 7789:   padding: 4px;
 7790:   background: #DDDDDD;
 7791: }
 7792: 
 7793: table.LC_sty_begin {
 7794:   background: #BBFFBB;
 7795: }
 7796: 
 7797: table.LC_sty_end {
 7798:   background: #FFBBBB;
 7799: }
 7800: 
 7801: table.LC_double_column {
 7802:   border-width: 0;
 7803:   border-collapse: collapse;
 7804:   width: 100%;
 7805:   padding: 2px;
 7806: }
 7807: 
 7808: table.LC_double_column tr td.LC_left_col {
 7809:   top: 2px;
 7810:   left: 2px;
 7811:   width: 47%;
 7812:   vertical-align: top;
 7813: }
 7814: 
 7815: table.LC_double_column tr td.LC_right_col {
 7816:   top: 2px;
 7817:   right: 2px;
 7818:   width: 47%;
 7819:   vertical-align: top;
 7820: }
 7821: 
 7822: div.LC_left_float {
 7823:   float: left;
 7824:   padding-right: 5%;
 7825:   padding-bottom: 4px;
 7826: }
 7827: 
 7828: div.LC_clear_float_header {
 7829:   padding-bottom: 2px;
 7830: }
 7831: 
 7832: div.LC_clear_float_footer {
 7833:   padding-top: 10px;
 7834:   clear: both;
 7835: }
 7836: 
 7837: div.LC_grade_show_user {
 7838: /*  border-left: 5px solid $sidebg; */
 7839:   border-top: 5px solid #000000;
 7840:   margin: 50px 0 0 0;
 7841:   padding: 15px 0 5px 10px;
 7842: }
 7843: 
 7844: div.LC_grade_show_user_odd_row {
 7845: /*  border-left: 5px solid #000000; */
 7846: }
 7847: 
 7848: div.LC_grade_show_user div.LC_Box {
 7849:   margin-right: 50px;
 7850: }
 7851: 
 7852: div.LC_grade_submissions,
 7853: div.LC_grade_message_center,
 7854: div.LC_grade_info_links {
 7855:   margin: 5px;
 7856:   width: 99%;
 7857:   background: #FFFFFF;
 7858: }
 7859: 
 7860: div.LC_grade_submissions_header,
 7861: div.LC_grade_message_center_header {
 7862:   font-weight: bold;
 7863:   font-size: large;
 7864: }
 7865: 
 7866: div.LC_grade_submissions_body,
 7867: div.LC_grade_message_center_body {
 7868:   border: 1px solid black;
 7869:   width: 99%;
 7870:   background: #FFFFFF;
 7871: }
 7872: 
 7873: table.LC_scantron_action {
 7874:   width: 100%;
 7875: }
 7876: 
 7877: table.LC_scantron_action tr th {
 7878:   font-weight:bold;
 7879:   font-style:normal;
 7880: }
 7881: 
 7882: .LC_edit_problem_header,
 7883: div.LC_edit_problem_footer {
 7884:   font-weight: normal;
 7885:   font-size:  medium;
 7886:   margin: 2px;
 7887:   background-color: $sidebg;
 7888: }
 7889: 
 7890: div.LC_edit_problem_header,
 7891: div.LC_edit_problem_header div,
 7892: div.LC_edit_problem_footer,
 7893: div.LC_edit_problem_footer div,
 7894: div.LC_edit_problem_editxml_header,
 7895: div.LC_edit_problem_editxml_header div {
 7896:   z-index: 100;
 7897: }
 7898: 
 7899: div.LC_edit_problem_header_title {
 7900:   font-weight: bold;
 7901:   font-size: larger;
 7902:   background: $tabbg;
 7903:   padding: 3px;
 7904:   margin: 0 0 5px 0;
 7905: }
 7906: 
 7907: table.LC_edit_problem_header_title {
 7908:   width: 100%;
 7909:   background: $tabbg;
 7910: }
 7911: 
 7912: div.LC_edit_actionbar {
 7913:     background-color: $sidebg;
 7914:     margin: 0;
 7915:     padding: 0;
 7916:     line-height: 200%;
 7917: }
 7918: 
 7919: div.LC_edit_actionbar div{
 7920:     padding: 0;
 7921:     margin: 0;
 7922:     display: inline-block;
 7923: }
 7924: 
 7925: .LC_edit_opt {
 7926:   padding-left: 1em;
 7927:   white-space: nowrap;
 7928: }
 7929: 
 7930: .LC_edit_problem_latexhelper{
 7931:     text-align: right;
 7932: }
 7933: 
 7934: #LC_edit_problem_colorful div{
 7935:     margin-left: 40px;
 7936: }
 7937: 
 7938: #LC_edit_problem_codemirror div{
 7939:     margin-left: 0px;
 7940: }
 7941: 
 7942: img.stift {
 7943:   border-width: 0;
 7944:   vertical-align: middle;
 7945: }
 7946: 
 7947: table td.LC_mainmenu_col_fieldset {
 7948:   vertical-align: top;
 7949: }
 7950: 
 7951: div.LC_createcourse {
 7952:   margin: 10px 10px 10px 10px;
 7953: }
 7954: 
 7955: .LC_dccid {
 7956:   float: right;
 7957:   margin: 0.2em 0 0 0;
 7958:   padding: 0;
 7959:   font-size: 90%;
 7960:   display:none;
 7961: }
 7962: 
 7963: ol.LC_primary_menu a:hover,
 7964: ol#LC_MenuBreadcrumbs a:hover,
 7965: ol#LC_PathBreadcrumbs a:hover,
 7966: ul#LC_secondary_menu a:hover,
 7967: .LC_FormSectionClearButton input:hover
 7968: ul.LC_TabContent   li:hover a {
 7969:   color:$button_hover;
 7970:   text-decoration:none;
 7971: }
 7972: 
 7973: h1 {
 7974:   padding: 0;
 7975:   line-height:130%;
 7976: }
 7977: 
 7978: h2,
 7979: h3,
 7980: h4,
 7981: h5,
 7982: h6 {
 7983:   margin: 5px 0 5px 0;
 7984:   padding: 0;
 7985:   line-height:130%;
 7986: }
 7987: 
 7988: .LC_hcell {
 7989:   padding:3px 15px 3px 15px;
 7990:   margin: 0;
 7991:   background-color:$tabbg;
 7992:   color:$fontmenu;
 7993:   border-bottom:solid 1px $lg_border_color;
 7994: }
 7995: 
 7996: .LC_Box > .LC_hcell {
 7997:   margin: 0 -10px 10px -10px;
 7998: }
 7999: 
 8000: .LC_noBorder {
 8001:   border: 0;
 8002: }
 8003: 
 8004: .LC_FormSectionClearButton input {
 8005:   background-color:transparent;
 8006:   border: none;
 8007:   cursor:pointer;
 8008:   text-decoration:underline;
 8009: }
 8010: 
 8011: .LC_help_open_topic {
 8012:   color: #FFFFFF;
 8013:   background-color: #EEEEFF;
 8014:   margin: 1px;
 8015:   padding: 4px;
 8016:   border: 1px solid #000033;
 8017:   white-space: nowrap;
 8018:   /* vertical-align: middle; */
 8019: }
 8020: 
 8021: dl,
 8022: ul,
 8023: div,
 8024: fieldset {
 8025:   margin: 10px 10px 10px 0;
 8026:   /* overflow: hidden; */
 8027: }
 8028: 
 8029: article.geogebraweb div {
 8030:     margin: 0;
 8031: }
 8032: 
 8033: fieldset > legend {
 8034:   font-weight: bold;
 8035:   padding: 0 5px 0 5px;
 8036: }
 8037: 
 8038: #LC_nav_bar {
 8039:   float: left;
 8040:   background-color: $pgbg_or_bgcolor;
 8041:   margin: 0 0 2px 0;
 8042: }
 8043: 
 8044: #LC_realm {
 8045:   margin: 0.2em 0 0 0;
 8046:   padding: 0;
 8047:   font-weight: bold;
 8048:   text-align: center;
 8049:   background-color: $pgbg_or_bgcolor;
 8050: }
 8051: 
 8052: #LC_nav_bar em {
 8053:   font-weight: bold;
 8054:   font-style: normal;
 8055: }
 8056: 
 8057: ol.LC_primary_menu {
 8058:   margin: 0;
 8059:   padding: 0;
 8060: }
 8061: 
 8062: ol#LC_PathBreadcrumbs {
 8063:   margin: 0;
 8064: }
 8065: 
 8066: ol.LC_primary_menu li {
 8067:   color: RGB(80, 80, 80);
 8068:   vertical-align: middle;
 8069:   text-align: left;
 8070:   list-style: none;
 8071:   position: relative;
 8072:   float: left;
 8073:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
 8074:   line-height: 1.5em;
 8075: }
 8076: 
 8077: ol.LC_primary_menu li a,
 8078: ol.LC_primary_menu li p {
 8079:   display: block;
 8080:   margin: 0;
 8081:   padding: 0 5px 0 10px;
 8082:   text-decoration: none;
 8083: }
 8084: 
 8085: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
 8086:   display: inline-block;
 8087:   width: 95%;
 8088:   text-align: left;
 8089: }
 8090: 
 8091: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
 8092:   display: inline-block;	
 8093:   width: 5%;
 8094:   float: right;
 8095:   text-align: right;
 8096:   font-size: 70%;
 8097: }
 8098: 
 8099: ol.LC_primary_menu ul {
 8100:   display: none;
 8101:   width: 15em;
 8102:   background-color: $data_table_light;
 8103:   position: absolute;
 8104:   top: 100%;
 8105: }
 8106: 
 8107: ol.LC_primary_menu ul ul {
 8108:   left: 100%;
 8109:   top: 0;
 8110: }
 8111: 
 8112: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
 8113:   display: block;
 8114:   position: absolute;
 8115:   margin: 0;
 8116:   padding: 0;
 8117:   z-index: 2;
 8118: }
 8119: 
 8120: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 8121: /* First Submenu -> size should be smaller than the menu title of the whole menu */
 8122:   font-size: 90%;
 8123:   vertical-align: top;
 8124:   float: none;
 8125:   border-left: 1px solid black;
 8126:   border-right: 1px solid black;
 8127: /* A dark bottom border to visualize different menu options; 
 8128: overwritten in the create_submenu routine for the last border-bottom of the menu */
 8129:   border-bottom: 1px solid $data_table_dark; 
 8130: }
 8131: 
 8132: ol.LC_primary_menu li li p:hover {
 8133:   color:$button_hover;
 8134:   text-decoration:none;
 8135:   background-color:$data_table_dark;
 8136: }
 8137: 
 8138: ol.LC_primary_menu li li a:hover {
 8139:    color:$button_hover;
 8140:    background-color:$data_table_dark;
 8141: }
 8142: 
 8143: /* Font-size equal to the size of the predecessors*/
 8144: ol.LC_primary_menu li:hover li li {
 8145:   font-size: 100%;
 8146: }
 8147: 
 8148: ol.LC_primary_menu li img {
 8149:   vertical-align: bottom;
 8150:   height: 1.1em;
 8151:   margin: 0.2em 0 0 0;
 8152: }
 8153: 
 8154: ol.LC_primary_menu a {
 8155:   color: RGB(80, 80, 80);
 8156:   text-decoration: none;
 8157: }
 8158: 
 8159: ol.LC_primary_menu a.LC_new_message {
 8160:   font-weight:bold;
 8161:   color: darkred;
 8162: }
 8163: 
 8164: ol.LC_docs_parameters {
 8165:   margin-left: 0;
 8166:   padding: 0;
 8167:   list-style: none;
 8168: }
 8169: 
 8170: ol.LC_docs_parameters li {
 8171:   margin: 0;
 8172:   padding-right: 20px;
 8173:   display: inline;
 8174: }
 8175: 
 8176: ol.LC_docs_parameters li:before {
 8177:   content: "\\002022 \\0020";
 8178: }
 8179: 
 8180: li.LC_docs_parameters_title {
 8181:   font-weight: bold;
 8182: }
 8183: 
 8184: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 8185:   content: "";
 8186: }
 8187: 
 8188: ul#LC_secondary_menu {
 8189:   clear: right;
 8190:   color: $fontmenu;
 8191:   background: $tabbg;
 8192:   list-style: none;
 8193:   padding: 0;
 8194:   margin: 0;
 8195:   width: 100%;
 8196:   text-align: left;
 8197:   float: left;
 8198: }
 8199: 
 8200: ul#LC_secondary_menu li {
 8201:   font-weight: bold;
 8202:   line-height: 1.8em;
 8203:   border-right: 1px solid black;
 8204:   float: left;
 8205: }
 8206: 
 8207: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 8208:   background-color: $data_table_light;
 8209: }
 8210: 
 8211: ul#LC_secondary_menu li a {
 8212:   padding: 0 0.8em;
 8213: }
 8214: 
 8215: ul#LC_secondary_menu li ul {
 8216:   display: none;
 8217: }
 8218: 
 8219: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 8220:   display: block;
 8221:   position: absolute;
 8222:   margin: 0;
 8223:   padding: 0;
 8224:   list-style:none;
 8225:   float: none;
 8226:   background-color: $data_table_light;
 8227:   z-index: 2;
 8228:   margin-left: -1px;
 8229: }
 8230: 
 8231: ul#LC_secondary_menu li ul li {
 8232:   font-size: 90%;
 8233:   vertical-align: top;
 8234:   border-left: 1px solid black;
 8235:   border-right: 1px solid black;
 8236:   background-color: $data_table_light;
 8237:   list-style:none;
 8238:   float: none;
 8239: }
 8240: 
 8241: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 8242:   background-color: $data_table_dark;
 8243: }
 8244: 
 8245: ul.LC_TabContent {
 8246:   display:block;
 8247:   background: $sidebg;
 8248:   border-bottom: solid 1px $lg_border_color;
 8249:   list-style:none;
 8250:   margin: -1px -10px 0 -10px;
 8251:   padding: 0;
 8252: }
 8253: 
 8254: ul.LC_TabContent li,
 8255: ul.LC_TabContentBigger li {
 8256:   float:left;
 8257: }
 8258: 
 8259: ul#LC_secondary_menu li a {
 8260:   color: $fontmenu;
 8261:   text-decoration: none;
 8262: }
 8263: 
 8264: ul.LC_TabContent {
 8265:   min-height:20px;
 8266: }
 8267: 
 8268: ul.LC_TabContent li {
 8269:   vertical-align:middle;
 8270:   padding: 0 16px 0 10px;
 8271:   background-color:$tabbg;
 8272:   border-bottom:solid 1px $lg_border_color;
 8273:   border-left: solid 1px $font;
 8274: }
 8275: 
 8276: ul.LC_TabContent .right {
 8277:   float:right;
 8278: }
 8279: 
 8280: ul.LC_TabContent li a,
 8281: ul.LC_TabContent li {
 8282:   color:rgb(47,47,47);
 8283:   text-decoration:none;
 8284:   font-size:95%;
 8285:   font-weight:bold;
 8286:   min-height:20px;
 8287: }
 8288: 
 8289: ul.LC_TabContent li a:hover,
 8290: ul.LC_TabContent li a:focus {
 8291:   color: $button_hover;
 8292:   background:none;
 8293:   outline:none;
 8294: }
 8295: 
 8296: ul.LC_TabContent li:hover {
 8297:   color: $button_hover;
 8298:   cursor:pointer;
 8299: }
 8300: 
 8301: ul.LC_TabContent li.active {
 8302:   color: $font;
 8303:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 8304:   border-bottom:solid 1px #FFFFFF;
 8305:   cursor: default;
 8306: }
 8307: 
 8308: ul.LC_TabContent li.active a {
 8309:   color:$font;
 8310:   background:#FFFFFF;
 8311:   outline: none;
 8312: }
 8313: 
 8314: ul.LC_TabContent li.goback {
 8315:   float: left;
 8316:   border-left: none;
 8317: }
 8318: 
 8319: #maincoursedoc {
 8320:   clear:both;
 8321: }
 8322: 
 8323: ul.LC_TabContentBigger {
 8324:   display:block;
 8325:   list-style:none;
 8326:   padding: 0;
 8327: }
 8328: 
 8329: ul.LC_TabContentBigger li {
 8330:   vertical-align:bottom;
 8331:   height: 30px;
 8332:   font-size:110%;
 8333:   font-weight:bold;
 8334:   color: #737373;
 8335: }
 8336: 
 8337: ul.LC_TabContentBigger li.active {
 8338:   position: relative;
 8339:   top: 1px;
 8340: }
 8341: 
 8342: ul.LC_TabContentBigger li a {
 8343:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 8344:   height: 30px;
 8345:   line-height: 30px;
 8346:   text-align: center;
 8347:   display: block;
 8348:   text-decoration: none;
 8349:   outline: none;  
 8350: }
 8351: 
 8352: ul.LC_TabContentBigger li.active a {
 8353:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 8354:   color:$font;
 8355: }
 8356: 
 8357: ul.LC_TabContentBigger li b {
 8358:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 8359:   display: block;
 8360:   float: left;
 8361:   padding: 0 30px;
 8362:   border-bottom: 1px solid $lg_border_color;
 8363: }
 8364: 
 8365: ul.LC_TabContentBigger li:hover b {
 8366:   color:$button_hover;
 8367: }
 8368: 
 8369: ul.LC_TabContentBigger li.active b {
 8370:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 8371:   color:$font;
 8372:   border: 0;
 8373: }
 8374: 
 8375: 
 8376: ul.LC_CourseBreadcrumbs {
 8377:   background: $sidebg;
 8378:   height: 2em;
 8379:   padding-left: 10px;
 8380:   margin: 0;
 8381:   list-style-position: inside;
 8382: }
 8383: 
 8384: ol#LC_MenuBreadcrumbs,
 8385: ol#LC_PathBreadcrumbs {
 8386:   padding-left: 10px;
 8387:   margin: 0;
 8388:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 8389: }
 8390: 
 8391: ol#LC_MenuBreadcrumbs li,
 8392: ol#LC_PathBreadcrumbs li,
 8393: ul.LC_CourseBreadcrumbs li {
 8394:   display: inline;
 8395:   white-space: normal;  
 8396: }
 8397: 
 8398: ol#LC_MenuBreadcrumbs li a,
 8399: ul.LC_CourseBreadcrumbs li a {
 8400:   text-decoration: none;
 8401:   font-size:90%;
 8402: }
 8403: 
 8404: ol#LC_MenuBreadcrumbs h1 {
 8405:   display: inline;
 8406:   font-size: 90%;
 8407:   line-height: 2.5em;
 8408:   margin: 0;
 8409:   padding: 0;
 8410: }
 8411: 
 8412: ol#LC_PathBreadcrumbs li a {
 8413:   text-decoration:none;
 8414:   font-size:100%;
 8415:   font-weight:bold;
 8416: }
 8417: 
 8418: .LC_Box {
 8419:   border: solid 1px $lg_border_color;
 8420:   padding: 0 10px 10px 10px;
 8421: }
 8422: 
 8423: .LC_DocsBox {
 8424:   border: solid 1px $lg_border_color;
 8425:   padding: 0 0 10px 10px;
 8426: }
 8427: 
 8428: .LC_AboutMe_Image {
 8429:   float:left;
 8430:   margin-right:10px;
 8431: }
 8432: 
 8433: .LC_Clear_AboutMe_Image {
 8434:   clear:left;
 8435: }
 8436: 
 8437: dl.LC_ListStyleClean dt {
 8438:   padding-right: 5px;
 8439:   display: table-header-group;
 8440: }
 8441: 
 8442: dl.LC_ListStyleClean dd {
 8443:   display: table-row;
 8444: }
 8445: 
 8446: .LC_ListStyleClean,
 8447: .LC_ListStyleSimple,
 8448: .LC_ListStyleNormal,
 8449: .LC_ListStyleSpecial {
 8450:   /* display:block; */
 8451:   list-style-position: inside;
 8452:   list-style-type: none;
 8453:   overflow: hidden;
 8454:   padding: 0;
 8455: }
 8456: 
 8457: .LC_ListStyleSimple li,
 8458: .LC_ListStyleSimple dd,
 8459: .LC_ListStyleNormal li,
 8460: .LC_ListStyleNormal dd,
 8461: .LC_ListStyleSpecial li,
 8462: .LC_ListStyleSpecial dd {
 8463:   margin: 0;
 8464:   padding: 5px 5px 5px 10px;
 8465:   clear: both;
 8466: }
 8467: 
 8468: .LC_ListStyleClean li,
 8469: .LC_ListStyleClean dd {
 8470:   padding-top: 0;
 8471:   padding-bottom: 0;
 8472: }
 8473: 
 8474: .LC_ListStyleSimple dd,
 8475: .LC_ListStyleSimple li {
 8476:   border-bottom: solid 1px $lg_border_color;
 8477: }
 8478: 
 8479: .LC_ListStyleSpecial li,
 8480: .LC_ListStyleSpecial dd {
 8481:   list-style-type: none;
 8482:   background-color: RGB(220, 220, 220);
 8483:   margin-bottom: 4px;
 8484: }
 8485: 
 8486: table.LC_SimpleTable {
 8487:   margin:5px;
 8488:   border:solid 1px $lg_border_color;
 8489: }
 8490: 
 8491: table.LC_SimpleTable tr {
 8492:   padding: 0;
 8493:   border:solid 1px $lg_border_color;
 8494: }
 8495: 
 8496: table.LC_SimpleTable thead {
 8497:   background:rgb(220,220,220);
 8498: }
 8499: 
 8500: div.LC_columnSection {
 8501:   display: block;
 8502:   clear: both;
 8503:   overflow: hidden;
 8504:   margin: 0;
 8505: }
 8506: 
 8507: div.LC_columnSection>* {
 8508:   float: left;
 8509:   margin: 10px 20px 10px 0;
 8510:   overflow:hidden;
 8511: }
 8512: 
 8513: table em {
 8514:   font-weight: bold;
 8515:   font-style: normal;
 8516: }
 8517: 
 8518: table.LC_tableBrowseRes,
 8519: table.LC_tableOfContent {
 8520:   border:none;
 8521:   border-spacing: 1px;
 8522:   padding: 3px;
 8523:   background-color: #FFFFFF;
 8524:   font-size: 90%;
 8525: }
 8526: 
 8527: table.LC_tableOfContent {
 8528:   border-collapse: collapse;
 8529: }
 8530: 
 8531: table.LC_tableBrowseRes a,
 8532: table.LC_tableOfContent a {
 8533:   background-color: transparent;
 8534:   text-decoration: none;
 8535: }
 8536: 
 8537: table.LC_tableOfContent img {
 8538:   border: none;
 8539:   height: 1.3em;
 8540:   vertical-align: text-bottom;
 8541:   margin-right: 0.3em;
 8542: }
 8543: 
 8544: a#LC_content_toolbar_firsthomework {
 8545:   background-image:url(/res/adm/pages/open-first-problem.gif);
 8546: }
 8547: 
 8548: a#LC_content_toolbar_everything {
 8549:   background-image:url(/res/adm/pages/show-all.gif);
 8550: }
 8551: 
 8552: a#LC_content_toolbar_uncompleted {
 8553:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 8554: }
 8555: 
 8556: #LC_content_toolbar_clearbubbles {
 8557:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 8558: }
 8559: 
 8560: a#LC_content_toolbar_changefolder {
 8561:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 8562: }
 8563: 
 8564: a#LC_content_toolbar_changefolder_toggled {
 8565:   background-image:url(/res/adm/pages/open-all-folders.gif);
 8566: }
 8567: 
 8568: a#LC_content_toolbar_edittoplevel {
 8569:   background-image:url(/res/adm/pages/edittoplevel.gif);
 8570: }
 8571: 
 8572: a#LC_content_toolbar_printout {
 8573:   background-image:url(/res/adm/pages/printout.gif);
 8574: }
 8575: 
 8576: ul#LC_toolbar li a:hover {
 8577:   background-position: bottom center;
 8578: }
 8579: 
 8580: ul#LC_toolbar {
 8581:   padding: 0;
 8582:   margin: 2px;
 8583:   list-style:none;
 8584:   position:relative;
 8585:   background-color:white;
 8586:   overflow: auto;
 8587: }
 8588: 
 8589: ul#LC_toolbar li {
 8590:   border:1px solid white;
 8591:   padding: 0;
 8592:   margin: 0;
 8593:   float: left;
 8594:   display:inline;
 8595:   vertical-align:middle;
 8596:   white-space: nowrap;
 8597: }
 8598: 
 8599: 
 8600: a.LC_toolbarItem {
 8601:   display:block;
 8602:   padding: 0;
 8603:   margin: 0;
 8604:   height: 32px;
 8605:   width: 32px;
 8606:   color:white;
 8607:   border: none;
 8608:   background-repeat:no-repeat;
 8609:   background-color:transparent;
 8610: }
 8611: 
 8612: ul.LC_funclist {
 8613:     margin: 0;
 8614:     padding: 0.5em 1em 0.5em 0;
 8615: }
 8616: 
 8617: ul.LC_funclist > li:first-child {
 8618:     font-weight:bold; 
 8619:     margin-left:0.8em;
 8620: }
 8621: 
 8622: ul.LC_funclist + ul.LC_funclist {
 8623:     /* 
 8624:        left border as a seperator if we have more than
 8625:        one list 
 8626:     */
 8627:     border-left: 1px solid $sidebg;
 8628:     /* 
 8629:        this hides the left border behind the border of the 
 8630:        outer box if element is wrapped to the next 'line' 
 8631:     */
 8632:     margin-left: -1px;
 8633: }
 8634: 
 8635: ul.LC_funclist li {
 8636:   display: inline;
 8637:   white-space: nowrap;
 8638:   margin: 0 0 0 25px;
 8639:   line-height: 150%;
 8640: }
 8641: 
 8642: .LC_hidden {
 8643:   display: none;
 8644: }
 8645: 
 8646: .LCmodal-overlay {
 8647: 		position:fixed;
 8648: 		top:0;
 8649: 		right:0;
 8650: 		bottom:0;
 8651: 		left:0;
 8652: 		height:100%;
 8653: 		width:100%;
 8654: 		margin:0;
 8655: 		padding:0;
 8656: 		background:#999;
 8657: 		opacity:.75;
 8658: 		filter: alpha(opacity=75);
 8659: 		-moz-opacity: 0.75;
 8660: 		z-index:101;
 8661: }
 8662: 
 8663: * html .LCmodal-overlay {   
 8664: 		position: absolute;
 8665: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 8666: }
 8667: 
 8668: .LCmodal-window {
 8669: 		position:fixed;
 8670: 		top:50%;
 8671: 		left:50%;
 8672: 		margin:0;
 8673: 		padding:0;
 8674: 		z-index:102;
 8675: 	}
 8676: 
 8677: * html .LCmodal-window {
 8678: 		position:absolute;
 8679: }
 8680: 
 8681: .LCclose-window {
 8682: 		position:absolute;
 8683: 		width:32px;
 8684: 		height:32px;
 8685: 		right:8px;
 8686: 		top:8px;
 8687: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 8688: 		text-indent:-99999px;
 8689: 		overflow:hidden;
 8690: 		cursor:pointer;
 8691: }
 8692: 
 8693: .LCisDisabled {
 8694:   cursor: not-allowed;
 8695:   opacity: 0.5;
 8696: }
 8697: 
 8698: a[aria-disabled="true"] {
 8699:   color: currentColor;
 8700:   display: inline-block;  /* For IE11/ MS Edge bug */
 8701:   pointer-events: none;
 8702:   text-decoration: none;
 8703: }
 8704: 
 8705: pre.LC_wordwrap {
 8706:   white-space: pre-wrap;
 8707:   white-space: -moz-pre-wrap;
 8708:   white-space: -pre-wrap;
 8709:   white-space: -o-pre-wrap;
 8710:   word-wrap: break-word;
 8711: }
 8712: 
 8713: /*
 8714:   styles used for response display
 8715: */
 8716: div.LC_radiofoil, div.LC_rankfoil {
 8717:   margin: .5em 0em .5em 0em;
 8718: }
 8719: table.LC_itemgroup {
 8720:   margin-top: 1em;
 8721: }
 8722: 
 8723: /*
 8724:   styles used by TTH when "Default set of options to pass to tth/m
 8725:   when converting TeX" in course settings has been set
 8726: 
 8727:   option passed: -t
 8728: 
 8729: */
 8730: 
 8731: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 8732: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 8733: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 8734: td div.norm {line-height:normal;}
 8735: 
 8736: /*
 8737:   option passed -y3
 8738: */
 8739: 
 8740: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 8741: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 8742: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 8743: 
 8744: /*
 8745:   sections with roles, for content only
 8746: */
 8747: section[class^="role-"] {
 8748:   padding-left: 10px;
 8749:   padding-right: 5px;
 8750:   margin-top: 8px;
 8751:   margin-bottom: 8px;
 8752:   border: 1px solid #2A4;
 8753:   border-radius: 5px;
 8754:   box-shadow: 0px 1px 1px #BBB;
 8755: }
 8756: section[class^="role-"]>h1 {
 8757:   position: relative;
 8758:   margin: 0px;
 8759:   padding-top: 10px;
 8760:   padding-left: 40px;
 8761: }
 8762: section[class^="role-"]>h1:before {
 8763:   position: absolute;
 8764:   left: -5px;
 8765:   top: 5px;
 8766: }
 8767: section.role-activity>h1:before {
 8768:   content:url('/adm/daxe/images/section_icons/activity.png');
 8769: }
 8770: section.role-advice>h1:before {
 8771:   content:url('/adm/daxe/images/section_icons/advice.png');
 8772: }
 8773: section.role-bibliography>h1:before {
 8774:   content:url('/adm/daxe/images/section_icons/bibliography.png');
 8775: }
 8776: section.role-citation>h1:before {
 8777:   content:url('/adm/daxe/images/section_icons/citation.png');
 8778: }
 8779: section.role-conclusion>h1:before {
 8780:   content:url('/adm/daxe/images/section_icons/conclusion.png');
 8781: }
 8782: section.role-definition>h1:before {
 8783:   content:url('/adm/daxe/images/section_icons/definition.png');
 8784: }
 8785: section.role-demonstration>h1:before {
 8786:   content:url('/adm/daxe/images/section_icons/demonstration.png');
 8787: }
 8788: section.role-example>h1:before {
 8789:   content:url('/adm/daxe/images/section_icons/example.png');
 8790: }
 8791: section.role-explanation>h1:before {
 8792:   content:url('/adm/daxe/images/section_icons/explanation.png');
 8793: }
 8794: section.role-introduction>h1:before {
 8795:   content:url('/adm/daxe/images/section_icons/introduction.png');
 8796: }
 8797: section.role-method>h1:before {
 8798:   content:url('/adm/daxe/images/section_icons/method.png');
 8799: }
 8800: section.role-more_information>h1:before {
 8801:   content:url('/adm/daxe/images/section_icons/more_information.png');
 8802: }
 8803: section.role-objectives>h1:before {
 8804:   content:url('/adm/daxe/images/section_icons/objectives.png');
 8805: }
 8806: section.role-prerequisites>h1:before {
 8807:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
 8808: }
 8809: section.role-remark>h1:before {
 8810:   content:url('/adm/daxe/images/section_icons/remark.png');
 8811: }
 8812: section.role-reminder>h1:before {
 8813:   content:url('/adm/daxe/images/section_icons/reminder.png');
 8814: }
 8815: section.role-summary>h1:before {
 8816:   content:url('/adm/daxe/images/section_icons/summary.png');
 8817: }
 8818: section.role-syntax>h1:before {
 8819:   content:url('/adm/daxe/images/section_icons/syntax.png');
 8820: }
 8821: section.role-warning>h1:before {
 8822:   content:url('/adm/daxe/images/section_icons/warning.png');
 8823: }
 8824: 
 8825: #LC_minitab_header {
 8826:   float:left;
 8827:   width:100%;
 8828:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
 8829:   font-size:93%;
 8830:   line-height:normal;
 8831:   margin: 0.5em 0 0.5em 0;
 8832: }
 8833: #LC_minitab_header ul {
 8834:   margin:0;
 8835:   padding:10px 10px 0;
 8836:   list-style:none;
 8837: }
 8838: #LC_minitab_header li {
 8839:   float:left;
 8840:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
 8841:   margin:0;
 8842:   padding:0 0 0 9px;
 8843: }
 8844: #LC_minitab_header a {
 8845:   display:block;
 8846:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
 8847:   padding:5px 15px 4px 6px;
 8848: }
 8849: #LC_minitab_header #LC_current_minitab {
 8850:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
 8851: }
 8852: #LC_minitab_header #LC_current_minitab a {
 8853:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
 8854:   padding-bottom:5px;
 8855: }
 8856: 
 8857: 
 8858: END
 8859: }
 8860: 
 8861: =pod
 8862: 
 8863: =item * &headtag()
 8864: 
 8865: Returns a uniform footer for LON-CAPA web pages.
 8866: 
 8867: Inputs: $title - optional title for the head
 8868:         $head_extra - optional extra HTML to put inside the <head>
 8869:         $args - optional arguments
 8870:             force_register - if is true call registerurl so the remote is 
 8871:                              informed
 8872:             redirect       -> array ref of
 8873:                                    1- seconds before redirect occurs
 8874:                                    2- url to redirect to
 8875:                                    3- whether the side effect should occur
 8876:                            (side effect of setting 
 8877:                                $env{'internal.head.redirect'} to the url 
 8878:                                redirected to)
 8879:                                    4- whether the redirect target should be
 8880:                                       the opener of the current (pop-up)
 8881:                                       window (side effect of setting
 8882:                                       $env{'internal.head.to_opener'} to
 8883:                                       1, if true.
 8884:                                    5- whether encrypt check should be skipped
 8885:             domain         -> force to color decorate a page for a specific
 8886:                                domain
 8887:             function       -> force usage of a specific rolish color scheme
 8888:             bgcolor        -> override the default page bgcolor
 8889:             no_auto_mt_title
 8890:                            -> prevent &mt()ing the title arg
 8891: 
 8892: =cut
 8893: 
 8894: sub headtag {
 8895:     my ($title,$head_extra,$args) = @_;
 8896:     
 8897:     my $function = $args->{'function'} || &get_users_function();
 8898:     my $domain   = $args->{'domain'}   || &determinedomain();
 8899:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 8900:     my $httphost = $args->{'use_absolute'};
 8901:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 8902: 		   $Apache::lonnet::perlvar{'lonVersion'},
 8903: 		   #time(),
 8904: 		   $env{'environment.color.timestamp'},
 8905: 		   $function,$domain,$bgcolor);
 8906: 
 8907:     $url = '/adm/css/'.&escape($url).'.css';
 8908: 
 8909:     my $result =
 8910: 	'<head>'.
 8911: 	&font_settings($args);
 8912: 
 8913:     my $inhibitprint;
 8914:     if ($args->{'print_suppress'}) {
 8915:         $inhibitprint = &print_suppression();
 8916:     }
 8917: 
 8918:     if (!$args->{'frameset'}) {
 8919: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 8920:     }
 8921:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
 8922:         $result .= Apache::lonxml::display_title();
 8923:     }
 8924:     if (!$args->{'no_nav_bar'} 
 8925: 	&& !$args->{'only_body'}
 8926: 	&& !$args->{'frameset'}) {
 8927: 	$result .= &help_menu_js($httphost);
 8928:         $result.=&modal_window();
 8929:         $result.=&togglebox_script();
 8930:         $result.=&wishlist_window();
 8931:         $result.=&LCprogressbarUpdate_script();
 8932:     } else {
 8933:         if ($args->{'add_modal'}) {
 8934:            $result.=&modal_window();
 8935:         }
 8936:         if ($args->{'add_wishlist'}) {
 8937:            $result.=&wishlist_window();
 8938:         }
 8939:         if ($args->{'add_togglebox'}) {
 8940:            $result.=&togglebox_script();
 8941:         }
 8942:         if ($args->{'add_progressbar'}) {
 8943:            $result.=&LCprogressbarUpdate_script();
 8944:         }
 8945:     }
 8946:     if (ref($args->{'redirect'})) {
 8947: 	my ($time,$url,$inhibit_continue,$to_opener,$skip_enc_check) = @{$args->{'redirect'}};
 8948:         if (!$skip_enc_check) {
 8949:             $url = &Apache::lonenc::check_encrypt($url);
 8950:         }
 8951: 	if (!$inhibit_continue) {
 8952: 	    $env{'internal.head.redirect'} = $url;
 8953: 	}
 8954: 	$result.=<<"ADDMETA";
 8955: <meta http-equiv="pragma" content="no-cache" />
 8956: ADDMETA
 8957:         if ($to_opener) {
 8958:             $env{'internal.head.to_opener'} = 1;
 8959:             my $dest = &js_escape($url);
 8960:             my $timeout = int($time * 1000);
 8961:             $result .=<<"ENDJS";
 8962: <script type="text/javascript">
 8963: // <![CDATA[
 8964: function LC_To_Opener() {
 8965:     var dest = '$dest';
 8966:     if (dest != '') {
 8967:         if (window.opener != null && !window.opener.closed) {
 8968:             window.opener.location.href=dest;
 8969:             window.close();
 8970:         } else {
 8971:             window.location.href=dest;
 8972:         }
 8973:     }
 8974: }
 8975: \$(document).ready(function () {
 8976:     setTimeout('LC_To_Opener()',$timeout);
 8977: });
 8978: // ]]>
 8979: </script>
 8980: ENDJS
 8981:         } else {
 8982:             $result.=<<"ADDMETA";
 8983: <meta http-equiv="Refresh" content="$time; url=$url" />
 8984: ADDMETA
 8985:         }
 8986:     } else {
 8987:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
 8988:             my $requrl = $env{'request.uri'};
 8989:             if ($requrl eq '') {
 8990:                 $requrl = $ENV{'REQUEST_URI'};
 8991:                 $requrl =~ s/\?.+$//;
 8992:             }
 8993:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
 8994:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
 8995:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
 8996:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
 8997:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
 8998:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
 8999:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 9000:                     my ($offload,$offloadoth);
 9001:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
 9002:                         if ($domdefs{'offloadnow'}{$lonhost}) {
 9003:                             $offload = 1;
 9004:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
 9005:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
 9006:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
 9007:                                     $offloadoth = 1;
 9008:                                     $dom_in_use = $env{'user.domain'};
 9009:                                 }
 9010:                             }
 9011:                         }
 9012:                     }
 9013:                     unless ($offload) {
 9014:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
 9015:                             if ($domdefs{'offloadoth'}{$lonhost}) {
 9016:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
 9017:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
 9018:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
 9019:                                         $offload = 1;
 9020:                                         $offloadoth = 1;
 9021:                                         $dom_in_use = $env{'user.domain'};
 9022:                                     }
 9023:                                 }
 9024:                             }
 9025:                         }
 9026:                     }
 9027:                     if ($offload) {
 9028:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
 9029:                         if (($newserver eq '') && ($offloadoth)) {
 9030:                             my @domains = &Apache::lonnet::current_machine_domains();
 9031:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) { 
 9032:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
 9033:                             }
 9034:                         }
 9035:                         if (($newserver) && ($newserver ne $lonhost)) {
 9036:                             my $numsec = 5;
 9037:                             my $timeout = $numsec * 1000;
 9038:                             my ($newurl,$locknum,%locks,$msg);
 9039:                             if ($env{'request.role.adv'}) {
 9040:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
 9041:                             }
 9042:                             my $disable_submit = 0;
 9043:                             if ($requrl =~ /$LONCAPA::assess_re/) {
 9044:                                 $disable_submit = 1;
 9045:                             }
 9046:                             if ($locknum) {
 9047:                                 my @lockinfo = sort(values(%locks));
 9048:                                 $msg = &mt('Once the following tasks are complete:')." \n".
 9049:                                        join(", ",sort(values(%locks)))."\n";
 9050:                                 if (&show_course()) {
 9051:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
 9052:                                 } else {
 9053:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
 9054:                                 }
 9055:                             } else {
 9056:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
 9057:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
 9058:                                 }
 9059:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
 9060:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
 9061:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
 9062:                                     $newurl .= '&role='.$env{'request.role'};
 9063:                                 }
 9064:                                 if ($env{'request.symb'}) {
 9065:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
 9066:                                     if ($shownsymb =~ m{^/enc/}) {
 9067:                                         my $reqdmajor = 2;
 9068:                                         my $reqdminor = 11;
 9069:                                         my $reqdsubminor = 3;
 9070:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
 9071:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
 9072:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
 9073:                                         if (($major eq '' && $minor eq '') ||
 9074:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
 9075:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
 9076:                                              ($reqdsubminor > $subminor))))) {
 9077:                                             undef($shownsymb);
 9078:                                         }
 9079:                                     }
 9080:                                     if ($shownsymb) {
 9081:                                         &js_escape(\$shownsymb);
 9082:                                         $newurl .= '&symb='.$shownsymb;
 9083:                                     }
 9084:                                 } else {
 9085:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
 9086:                                     &js_escape(\$shownurl);
 9087:                                     $newurl .= '&origurl='.$shownurl;
 9088:                                 }
 9089:                             }
 9090:                             &js_escape(\$msg);
 9091:                             $result.=<<OFFLOAD
 9092: <meta http-equiv="pragma" content="no-cache" />
 9093: <script type="text/javascript">
 9094: // <![CDATA[
 9095: function LC_Offload_Now() {
 9096:     var dest = "$newurl";
 9097:     if (dest != '') {
 9098:         window.location.href="$newurl";
 9099:     }
 9100: }
 9101: \$(document).ready(function () {
 9102:     window.alert('$msg');
 9103:     if ($disable_submit) {
 9104:         \$(".LC_hwk_submit").prop("disabled", true);
 9105:         \$( ".LC_textline" ).prop( "readonly", "readonly");
 9106:     }
 9107:     setTimeout('LC_Offload_Now()', $timeout);
 9108: });
 9109: // ]]>
 9110: </script>
 9111: OFFLOAD
 9112:                         }
 9113:                     }
 9114:                 }
 9115:             }
 9116:         }
 9117:     }
 9118:     if (!defined($title)) {
 9119: 	$title = 'The LearningOnline Network with CAPA';
 9120:     }
 9121:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 9122:     $result .= '<title> LON-CAPA '.$title.'</title>'
 9123: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
 9124:     if (!$args->{'frameset'}) {
 9125:         $result .= ' /';
 9126:     }
 9127:     $result .= '>' 
 9128:         .$inhibitprint
 9129: 	.$head_extra;
 9130:     my $clientmobile;
 9131:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 9132:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
 9133:     } else {
 9134:         $clientmobile = $env{'browser.mobile'};
 9135:     }
 9136:     if ($clientmobile) {
 9137:         $result .= '
 9138: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 9139: <meta name="apple-mobile-web-app-capable" content="yes" />';
 9140:     }
 9141:     $result .= '<meta name="google" content="notranslate" />'."\n";
 9142:     return $result.'</head>';
 9143: }
 9144: 
 9145: =pod
 9146: 
 9147: =item * &font_settings()
 9148: 
 9149: Returns neccessary <meta> to set the proper encoding
 9150: 
 9151: Inputs: optional reference to HASH -- $args passed to &headtag()
 9152: 
 9153: =cut
 9154: 
 9155: sub font_settings {
 9156:     my ($args) = @_;
 9157:     my $headerstring='';
 9158:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
 9159:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
 9160:         $headerstring.=
 9161:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
 9162:         if (!$args->{'frameset'}) {
 9163: 	    $headerstring.= ' /';
 9164:         }
 9165: 	$headerstring .= '>'."\n";
 9166:     }
 9167:     return $headerstring;
 9168: }
 9169: 
 9170: =pod
 9171: 
 9172: =item * &print_suppression()
 9173: 
 9174: In course context returns css which causes the body to be blank when media="print",
 9175: if printout generation is unavailable for the current resource.
 9176: 
 9177: This could be because:
 9178: 
 9179: (a) printstartdate is in the future
 9180: 
 9181: (b) printenddate is in the past
 9182: 
 9183: (c) there is an active exam block with "printout"
 9184: functionality blocked
 9185: 
 9186: Users with pav, pfo or evb privileges are exempt.
 9187: 
 9188: Inputs: none
 9189: 
 9190: =cut
 9191: 
 9192: 
 9193: sub print_suppression {
 9194:     my $noprint;
 9195:     if ($env{'request.course.id'}) {
 9196:         my $scope = $env{'request.course.id'};
 9197:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 9198:             (&Apache::lonnet::allowed('pfo',$scope))) {
 9199:             return;
 9200:         }
 9201:         if ($env{'request.course.sec'} ne '') {
 9202:             $scope .= "/$env{'request.course.sec'}";
 9203:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 9204:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 9205:                 return;
 9206:             }
 9207:         }
 9208:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9209:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9210:         my $clientip = &Apache::lonnet::get_requestor_ip();
 9211:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
 9212:         if ($blocked) {
 9213:             my $checkrole = "cm./$cdom/$cnum";
 9214:             if ($env{'request.course.sec'} ne '') {
 9215:                 $checkrole .= "/$env{'request.course.sec'}";
 9216:             }
 9217:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 9218:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 9219:                 $noprint = 1;
 9220:             }
 9221:         }
 9222:         unless ($noprint) {
 9223:             my $symb = &Apache::lonnet::symbread();
 9224:             if ($symb ne '') {
 9225:                 my $navmap = Apache::lonnavmaps::navmap->new();
 9226:                 if (ref($navmap)) {
 9227:                     my $res = $navmap->getBySymb($symb);
 9228:                     if (ref($res)) {
 9229:                         if (!$res->resprintable()) {
 9230:                             $noprint = 1;
 9231:                         }
 9232:                     }
 9233:                 }
 9234:             }
 9235:         }
 9236:         if ($noprint) {
 9237:             return <<"ENDSTYLE";
 9238: <style type="text/css" media="print">
 9239:     body { display:none }
 9240: </style>
 9241: ENDSTYLE
 9242:         }
 9243:     }
 9244:     return;
 9245: }
 9246: 
 9247: =pod
 9248: 
 9249: =item * &xml_begin()
 9250: 
 9251: Returns the needed doctype and <html>
 9252: 
 9253: Inputs: none
 9254: 
 9255: =cut
 9256: 
 9257: sub xml_begin {
 9258:     my ($is_frameset) = @_;
 9259:     my $output='';
 9260: 
 9261:     if ($env{'browser.mathml'}) {
 9262: 	$output='<?xml version="1.0"?>'
 9263:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 9264: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 9265:             
 9266: #	    .'<!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">] >'
 9267: 	    .'<!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">'
 9268:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 9269: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 9270:     } elsif ($is_frameset) {
 9271:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
 9272:                 '<html>'."\n";
 9273:     } else {
 9274: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
 9275:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
 9276:     }
 9277:     return $output;
 9278: }
 9279: 
 9280: =pod
 9281: 
 9282: =item * &start_page()
 9283: 
 9284: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 9285: 
 9286: Inputs:
 9287: 
 9288: =over 4
 9289: 
 9290: $title - optional title for the page
 9291: 
 9292: $head_extra - optional extra HTML to incude inside the <head>
 9293: 
 9294: $args - additional optional args supported are:
 9295: 
 9296: =over 8
 9297: 
 9298:              only_body      -> is true will set &bodytag() onlybodytag
 9299:                                     arg on
 9300:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 9301:              add_entries    -> additional attributes to add to the  <body>
 9302:              domain         -> force to color decorate a page for a 
 9303:                                     specific domain
 9304:              function       -> force usage of a specific rolish color
 9305:                                     scheme
 9306:              redirect       -> see &headtag()
 9307:              bgcolor        -> override the default page bg color
 9308:              js_ready       -> return a string ready for being used in 
 9309:                                     a javascript writeln
 9310:              html_encode    -> return a string ready for being used in 
 9311:                                     a html attribute
 9312:              force_register -> if is true will turn on the &bodytag()
 9313:                                     $forcereg arg
 9314:              frameset       -> if true will start with a <frameset>
 9315:                                     rather than <body>
 9316:              skip_phases    -> hash ref of 
 9317:                                     head -> skip the <html><head> generation
 9318:                                     body -> skip all <body> generation
 9319:              no_auto_mt_title -> prevent &mt()ing the title arg
 9320:              bread_crumbs ->             Array containing breadcrumbs
 9321:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 9322:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
 9323:                                     to lonhtmlcommon::breadcrumbs
 9324:              group          -> includes the current group, if page is for a 
 9325:                                specific group
 9326:              use_absolute   -> for request for external resource or syllabus, this
 9327:                                will contain https://<hostname> if server uses
 9328:                                https (as per hosts.tab), but request is for http
 9329:              hostname       -> hostname, originally from $r->hostname(), (optional).
 9330:              links_disabled -> Links in primary and secondary menus are disabled
 9331:                                (Can enable them once page has loaded - see lonroles.pm
 9332:                                for an example).
 9333:              links_target   -> Target for links, e.g., _parent (optional).
 9334: 
 9335: =back
 9336: 
 9337: =back
 9338: 
 9339: =cut
 9340: 
 9341: sub start_page {
 9342:     my ($title,$head_extra,$args) = @_;
 9343:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 9344: 
 9345:     $env{'internal.start_page'}++;
 9346:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
 9347: 
 9348:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 9349:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
 9350:     }
 9351: 
 9352:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
 9353:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
 9354:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
 9355:                 $args->{'no_primary_menu'} = 1;
 9356:             }
 9357:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
 9358:                 $args->{'no_inline_menu'} = 1;
 9359:             }
 9360:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
 9361:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
 9362:             }
 9363:         } else {
 9364:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9365:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
 9366:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
 9367:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
 9368:                     $args->{'no_primary_menu'} = 1;
 9369:                 }
 9370:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
 9371:                     $args->{'no_inline_menu'} = 1;
 9372:                 }
 9373:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
 9374:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
 9375:                 }
 9376:             }
 9377:         }
 9378:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
 9379:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
 9380:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
 9381:     } elsif ($env{'request.course.id'}) {
 9382:         my $expiretime=600;
 9383:         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
 9384:             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
 9385:         }
 9386:         my ($deeplinkmenu,$menuref);
 9387:         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
 9388:         if ($menucoll) {
 9389:             if (ref($menuref) eq 'HASH') {
 9390:                 %menu = %{$menuref};
 9391:             }
 9392:             if ($menu{'top'} eq 'n') {
 9393:                 $args->{'no_primary_menu'} = 1;
 9394:             }
 9395:             if ($menu{'inline'} eq 'n') {
 9396:                 unless (&Apache::lonnet::allowed('opa')) {
 9397:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9398:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9399:                     my $crstype = &course_type();
 9400:                     my $now = time;
 9401:                     my $ccrole;
 9402:                     if ($crstype eq 'Community') {
 9403:                         $ccrole = 'co';
 9404:                     } else {
 9405:                         $ccrole = 'cc';
 9406:                     }
 9407:                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
 9408:                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
 9409:                         if ((($start) && ($start<0)) ||
 9410:                             (($end) && ($end<$now))  ||
 9411:                             (($start) && ($now<$start))) {
 9412:                             $args->{'no_inline_menu'} = 1;
 9413:                         }
 9414:                     } else {
 9415:                         $args->{'no_inline_menu'} = 1;
 9416:                     }
 9417:                 }
 9418:             }
 9419:         }
 9420:     }
 9421: 
 9422:     my $showncrumbs;
 9423:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 9424: 	if ($args->{'frameset'}) {
 9425: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 9426: 						$args->{'add_entries'});
 9427: 	    $result .= "\n<frameset $attr_string>\n";
 9428:         } else {
 9429:             $result .=
 9430:                 &bodytag($title, 
 9431:                          $args->{'function'},       $args->{'add_entries'},
 9432:                          $args->{'only_body'},      $args->{'domain'},
 9433:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 9434:                          $args->{'bgcolor'},        $args,
 9435:                          \@advtools,$ltiscope,$ltiuri,\%ltimenu,$menucoll,
 9436:                          \%menu,\$showncrumbs);
 9437:         }
 9438:     }
 9439: 
 9440:     if ($args->{'js_ready'}) {
 9441: 		$result = &js_ready($result);
 9442:     }
 9443:     if ($args->{'html_encode'}) {
 9444: 		$result = &html_encode($result);
 9445:     }
 9446: 
 9447:     # Preparation for new and consistent functionlist at top of screen
 9448:     # if ($args->{'functionlist'}) {
 9449:     #            $result .= &build_functionlist();
 9450:     #}
 9451: 
 9452:     # Don't add anything more if only_body wanted or in const space
 9453:     return $result if    $args->{'only_body'} 
 9454:                       || $env{'request.state'} eq 'construct';
 9455: 
 9456:     #Breadcrumbs
 9457:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 9458:         unless ($showncrumbs) {
 9459: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 9460: 		#if any br links exists, add them to the breadcrumbs
 9461: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 9462: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 9463: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 9464: 			}
 9465: 		}
 9466:                 # if @advtools array contains items add then to the breadcrumbs
 9467:                 if (@advtools > 0) {
 9468:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 9469:                 }
 9470:                 my $menulink;
 9471:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
 9472:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
 9473:                      ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
 9474:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
 9475:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
 9476:                      (!$env{'request.role.adv'}))) {
 9477:                     $menulink = 0;
 9478:                 } else {
 9479:                     undef($menulink);
 9480:                 }
 9481:                 my $linkprotout;
 9482:                 if ($env{'request.deeplink.login'}) {
 9483:                     my $linkprotout = &Apache::lonmenu::linkprot_exit();
 9484:                     if ($linkprotout) {
 9485:                         &Apache::lonhtmlcommon::add_breadcrumb_tool('tools',$linkprotout);
 9486:                     }
 9487:                 }
 9488: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 9489: 		if(exists($args->{'bread_crumbs_component'})){
 9490: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
 9491:                 } else {
 9492: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
 9493: 		}
 9494:         }
 9495:     }
 9496:     return $result;
 9497: }
 9498: 
 9499: sub end_page {
 9500:     my ($args) = @_;
 9501:     $env{'internal.end_page'}++;
 9502:     my $result;
 9503:     if ($args->{'discussion'}) {
 9504: 	my ($target,$parser);
 9505: 	if (ref($args->{'discussion'})) {
 9506: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 9507: 				$args->{'discussion'}{'parser'});
 9508: 	}
 9509: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 9510:     }
 9511:     if ($args->{'frameset'}) {
 9512: 	$result .= '</frameset>';
 9513:     } else {
 9514: 	$result .= &endbodytag($args);
 9515:     }
 9516:     unless ($args->{'notbody'}) {
 9517:         $result .= "\n</html>";
 9518:     }
 9519: 
 9520:     if ($args->{'js_ready'}) {
 9521: 	$result = &js_ready($result);
 9522:     }
 9523: 
 9524:     if ($args->{'html_encode'}) {
 9525: 	$result = &html_encode($result);
 9526:     }
 9527: 
 9528:     return $result;
 9529: }
 9530: 
 9531: sub menucoll_in_effect {
 9532:     my ($menucoll,$deeplinkmenu,%menu);
 9533:     if ($env{'request.course.id'}) {
 9534:         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
 9535:         if ($env{'request.deeplink.login'}) {
 9536:             my ($deeplink_symb,$deeplink,$check_login_symb);
 9537:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9538:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9539:             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
 9540:                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
 9541:                     my $navmap = Apache::lonnavmaps::navmap->new();
 9542:                     if (ref($navmap)) {
 9543:                         $deeplink = $navmap->get_mapparam(undef,
 9544:                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
 9545:                                                           '0.deeplink');
 9546:                     } else {
 9547:                         $check_login_symb = 1;
 9548:                     }
 9549:                 } else {
 9550:                     my $symb = &Apache::lonnet::symbread();
 9551:                     if ($symb) {
 9552:                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
 9553:                     } else {
 9554:                         $check_login_symb = 1;
 9555:                     }
 9556:                 }
 9557:             } else {
 9558:                 $check_login_symb = 1;
 9559:             }
 9560:             if ($check_login_symb) {
 9561:                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
 9562:                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
 9563:                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
 9564:                     my $navmap = Apache::lonnavmaps::navmap->new();
 9565:                     if (ref($navmap)) {
 9566:                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
 9567:                     }
 9568:                 } else {
 9569:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
 9570:                 }
 9571:             }
 9572:             if ($deeplink ne '') {
 9573:                 my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
 9574:                 if ($display =~ /^\d+$/) {
 9575:                     $deeplinkmenu = 1;
 9576:                     $menucoll = $display;
 9577:                 }
 9578:             }
 9579:         }
 9580:         if ($menucoll) {
 9581:             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
 9582:         }
 9583:     }
 9584:     return ($menucoll,$deeplinkmenu,\%menu);
 9585: }
 9586: 
 9587: sub deeplink_login_symb {
 9588:     my ($cnum,$cdom) = @_;
 9589:     my $login_symb;
 9590:     if ($env{'request.deeplink.login'}) {
 9591:         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
 9592:     }
 9593:     return $login_symb;
 9594: }
 9595: 
 9596: sub symb_from_tinyurl {
 9597:     my ($url,$cnum,$cdom) = @_;
 9598:     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
 9599:         my $key = $1;
 9600:         my ($tinyurl,$login);
 9601:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
 9602:         if (defined($cached)) {
 9603:             $tinyurl = $result;
 9604:         } else {
 9605:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
 9606:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
 9607:             if ($currtiny{$key} ne '') {
 9608:                 $tinyurl = $currtiny{$key};
 9609:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
 9610:             }
 9611:         }
 9612:         if ($tinyurl ne '') {
 9613:             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
 9614:             if (wantarray) {
 9615:                 return ($cnumreq,$symb);
 9616:             } elsif ($cnumreq eq $cnum) {
 9617:                 return $symb;
 9618:             }
 9619:         }
 9620:     }
 9621:     if (wantarray) {
 9622:         return ();
 9623:     } else {
 9624:         return;
 9625:     }
 9626: }
 9627: 
 9628: sub wishlist_window {
 9629:     return(<<'ENDWISHLIST');
 9630: <script type="text/javascript">
 9631: // <![CDATA[
 9632: // <!-- BEGIN LON-CAPA Internal
 9633: function set_wishlistlink(title, path) {
 9634:     if (!title) {
 9635:         title = document.title;
 9636:         title = title.replace(/^LON-CAPA /,'');
 9637:     }
 9638:     title = encodeURIComponent(title);
 9639:     title = title.replace("'","\\\'");
 9640:     if (!path) {
 9641:         path = location.pathname;
 9642:     }
 9643:     path = encodeURIComponent(path);
 9644:     path = path.replace("'","\\\'");
 9645:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 9646:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 9647: }
 9648: // END LON-CAPA Internal -->
 9649: // ]]>
 9650: </script>
 9651: ENDWISHLIST
 9652: }
 9653: 
 9654: sub modal_window {
 9655:     return(<<'ENDMODAL');
 9656: <script type="text/javascript">
 9657: // <![CDATA[
 9658: // <!-- BEGIN LON-CAPA Internal
 9659: var modalWindow = {
 9660: 	parent:"body",
 9661: 	windowId:null,
 9662: 	content:null,
 9663: 	width:null,
 9664: 	height:null,
 9665: 	close:function()
 9666: 	{
 9667: 	        $(".LCmodal-window").remove();
 9668: 	        $(".LCmodal-overlay").remove();
 9669: 	},
 9670: 	open:function()
 9671: 	{
 9672: 		var modal = "";
 9673: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 9674: 		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;\">";
 9675: 		modal += this.content;
 9676: 		modal += "</div>";	
 9677: 
 9678: 		$(this.parent).append(modal);
 9679: 
 9680: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 9681: 		$(".LCclose-window").click(function(){modalWindow.close();});
 9682: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 9683: 	}
 9684: };
 9685: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
 9686: 	{
 9687:                 source = source.replace(/'/g,"&#39;");
 9688: 		modalWindow.windowId = "myModal";
 9689: 		modalWindow.width = width;
 9690: 		modalWindow.height = height;
 9691: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
 9692: 		modalWindow.open();
 9693: 	};
 9694: // END LON-CAPA Internal -->
 9695: // ]]>
 9696: </script>
 9697: ENDMODAL
 9698: }
 9699: 
 9700: sub modal_link {
 9701:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
 9702:     unless ($width) { $width=480; }
 9703:     unless ($height) { $height=400; }
 9704:     unless ($scrolling) { $scrolling='yes'; }
 9705:     unless ($transparency) { $transparency='true'; }
 9706: 
 9707:     my $target_attr;
 9708:     if (defined($target)) {
 9709:         $target_attr = 'target="'.$target.'"';
 9710:     }
 9711:     return <<"ENDLINK";
 9712: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
 9713: ENDLINK
 9714: }
 9715: 
 9716: sub modal_adhoc_script {
 9717:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
 9718:     my $mathjax;
 9719:     if ($possmathjax) {
 9720:         $mathjax = <<'ENDJAX';
 9721:                if (typeof MathJax == 'object') {
 9722:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
 9723:                }
 9724: ENDJAX
 9725:     }
 9726:     return (<<ENDADHOC);
 9727: <script type="text/javascript">
 9728: // <![CDATA[
 9729:         var $funcname = function()
 9730:         {
 9731:                 modalWindow.windowId = "myModal";
 9732:                 modalWindow.width = $width;
 9733:                 modalWindow.height = $height;
 9734:                 modalWindow.content = '$content';
 9735:                 modalWindow.open();
 9736:                 $mathjax
 9737:         };  
 9738: // ]]>
 9739: </script>
 9740: ENDADHOC
 9741: }
 9742: 
 9743: sub modal_adhoc_inner {
 9744:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
 9745:     my $innerwidth=$width-20;
 9746:     $content=&js_ready(
 9747:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 9748:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
 9749:                  $content.
 9750:                  &end_scrollbox().
 9751:                  &end_page()
 9752:              );
 9753:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
 9754: }
 9755: 
 9756: sub modal_adhoc_window {
 9757:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
 9758:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
 9759:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 9760: }
 9761: 
 9762: sub modal_adhoc_launch {
 9763:     my ($funcname,$width,$height,$content)=@_;
 9764:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 9765: <script type="text/javascript">
 9766: // <![CDATA[
 9767: $funcname();
 9768: // ]]>
 9769: </script>
 9770: ENDLAUNCH
 9771: }
 9772: 
 9773: sub modal_adhoc_close {
 9774:     return (<<ENDCLOSE);
 9775: <script type="text/javascript">
 9776: // <![CDATA[
 9777: modalWindow.close();
 9778: // ]]>
 9779: </script>
 9780: ENDCLOSE
 9781: }
 9782: 
 9783: sub togglebox_script {
 9784:    return(<<ENDTOGGLE);
 9785: <script type="text/javascript"> 
 9786: // <![CDATA[
 9787: function LCtoggleDisplay(id,hidetext,showtext) {
 9788:    link = document.getElementById(id + "link").childNodes[0];
 9789:    with (document.getElementById(id).style) {
 9790:       if (display == "none" ) {
 9791:           display = "inline";
 9792:           link.nodeValue = hidetext;
 9793:         } else {
 9794:           display = "none";
 9795:           link.nodeValue = showtext;
 9796:        }
 9797:    }
 9798: }
 9799: // ]]>
 9800: </script>
 9801: ENDTOGGLE
 9802: }
 9803: 
 9804: sub start_togglebox {
 9805:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 9806:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 9807:     unless ($showtext) { $showtext=&mt('show'); }
 9808:     unless ($hidetext) { $hidetext=&mt('hide'); }
 9809:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 9810:     return &start_data_table().
 9811:            &start_data_table_header_row().
 9812:            '<td bgcolor="'.$headerbg.'">'.$heading.
 9813:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 9814:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 9815:            &end_data_table_header_row().
 9816:            '<tr id="'.$id.'" style="display:none""><td>';
 9817: }
 9818: 
 9819: sub end_togglebox {
 9820:     return '</td></tr>'.&end_data_table();
 9821: }
 9822: 
 9823: sub LCprogressbar_script {
 9824:    my ($id,$number_to_do)=@_;
 9825:    if ($number_to_do) {
 9826:        return(<<ENDPROGRESS);
 9827: <script type="text/javascript">
 9828: // <![CDATA[
 9829: \$('#progressbar$id').progressbar({
 9830:   value: 0,
 9831:   change: function(event, ui) {
 9832:     var newVal = \$(this).progressbar('option', 'value');
 9833:     \$('.pblabel', this).text(LCprogressTxt);
 9834:   }
 9835: });
 9836: // ]]>
 9837: </script>
 9838: ENDPROGRESS
 9839:    } else {
 9840:        return(<<ENDPROGRESS);
 9841: <script type="text/javascript">
 9842: // <![CDATA[
 9843: \$('#progressbar$id').progressbar({
 9844:   value: false,
 9845:   create: function(event, ui) {
 9846:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
 9847:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
 9848:   }
 9849: });
 9850: // ]]>
 9851: </script>
 9852: ENDPROGRESS
 9853:    }
 9854: }
 9855: 
 9856: sub LCprogressbarUpdate_script {
 9857:    return(<<ENDPROGRESSUPDATE);
 9858: <style type="text/css">
 9859: .ui-progressbar { position:relative; }
 9860: .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%; }
 9861: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 9862: </style>
 9863: <script type="text/javascript">
 9864: // <![CDATA[
 9865: var LCprogressTxt='---';
 9866: 
 9867: function LCupdateProgress(percent,progresstext,id,maxnum) {
 9868:    LCprogressTxt=progresstext;
 9869:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
 9870:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
 9871:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
 9872:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
 9873:    } else {
 9874:        \$('#progressbar'+id).progressbar('value',percent);
 9875:    }
 9876: }
 9877: // ]]>
 9878: </script>
 9879: ENDPROGRESSUPDATE
 9880: }
 9881: 
 9882: my $LClastpercent;
 9883: my $LCidcnt;
 9884: my $LCcurrentid;
 9885: 
 9886: sub LCprogressbar {
 9887:     my ($r,$number_to_do,$preamble)=@_;
 9888:     $LClastpercent=0;
 9889:     $LCidcnt++;
 9890:     $LCcurrentid=$$.'_'.$LCidcnt;
 9891:     my ($starting,$content);
 9892:     if ($number_to_do) {
 9893:         $starting=&mt('Starting');
 9894:         $content=(<<ENDPROGBAR);
 9895: $preamble
 9896:   <div id="progressbar$LCcurrentid">
 9897:     <span class="pblabel">$starting</span>
 9898:   </div>
 9899: ENDPROGBAR
 9900:     } else {
 9901:         $starting=&mt('Loading...');
 9902:         $LClastpercent='false';
 9903:         $content=(<<ENDPROGBAR);
 9904: $preamble
 9905:   <div id="progressbar$LCcurrentid">
 9906:       <div class="progress-label">$starting</div>
 9907:   </div>
 9908: ENDPROGBAR
 9909:     }
 9910:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
 9911: }
 9912: 
 9913: sub LCprogressbarUpdate {
 9914:     my ($r,$val,$text,$number_to_do)=@_;
 9915:     if ($number_to_do) {
 9916:         unless ($val) { 
 9917:             if ($LClastpercent) {
 9918:                 $val=$LClastpercent;
 9919:             } else {
 9920:                 $val=0;
 9921:             }
 9922:         }
 9923:         if ($val<0) { $val=0; }
 9924:         if ($val>100) { $val=0; }
 9925:         $LClastpercent=$val;
 9926:         unless ($text) { $text=$val.'%'; }
 9927:     } else {
 9928:         $val = 'false';
 9929:     }
 9930:     $text=&js_ready($text);
 9931:     &r_print($r,<<ENDUPDATE);
 9932: <script type="text/javascript">
 9933: // <![CDATA[
 9934: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
 9935: // ]]>
 9936: </script>
 9937: ENDUPDATE
 9938: }
 9939: 
 9940: sub LCprogressbarClose {
 9941:     my ($r)=@_;
 9942:     $LClastpercent=0;
 9943:     &r_print($r,<<ENDCLOSE);
 9944: <script type="text/javascript">
 9945: // <![CDATA[
 9946: \$("#progressbar$LCcurrentid").hide('slow'); 
 9947: // ]]>
 9948: </script>
 9949: ENDCLOSE
 9950: }
 9951: 
 9952: sub r_print {
 9953:     my ($r,$to_print)=@_;
 9954:     if ($r) {
 9955:       $r->print($to_print);
 9956:       $r->rflush();
 9957:     } else {
 9958:       print($to_print);
 9959:     }
 9960: }
 9961: 
 9962: sub html_encode {
 9963:     my ($result) = @_;
 9964: 
 9965:     $result = &HTML::Entities::encode($result,'<>&"');
 9966:     
 9967:     return $result;
 9968: }
 9969: 
 9970: sub js_ready {
 9971:     my ($result) = @_;
 9972: 
 9973:     $result =~ s/[\n\r]/ /xmsg;
 9974:     $result =~ s/\\/\\\\/xmsg;
 9975:     $result =~ s/'/\\'/xmsg;
 9976:     $result =~ s{</}{<\\/}xmsg;
 9977:     
 9978:     return $result;
 9979: }
 9980: 
 9981: sub validate_page {
 9982:     if (  exists($env{'internal.start_page'})
 9983: 	  &&     $env{'internal.start_page'} > 1) {
 9984: 	&Apache::lonnet::logthis('start_page called multiple times '.
 9985: 				 $env{'internal.start_page'}.' '.
 9986: 				 $ENV{'request.filename'});
 9987:     }
 9988:     if (  exists($env{'internal.end_page'})
 9989: 	  &&     $env{'internal.end_page'} > 1) {
 9990: 	&Apache::lonnet::logthis('end_page called multiple times '.
 9991: 				 $env{'internal.end_page'}.' '.
 9992: 				 $env{'request.filename'});
 9993:     }
 9994:     if (     exists($env{'internal.start_page'})
 9995: 	&& ! exists($env{'internal.end_page'})) {
 9996: 	&Apache::lonnet::logthis('start_page called without end_page '.
 9997: 				 $env{'request.filename'});
 9998:     }
 9999:     if (   ! exists($env{'internal.start_page'})
10000: 	&&   exists($env{'internal.end_page'})) {
10001: 	&Apache::lonnet::logthis('end_page called without start_page'.
10002: 				 $env{'request.filename'});
10003:     }
10004: }
10005: 
10006: 
10007: sub start_scrollbox {
10008:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
10009:     unless ($outerwidth) { $outerwidth='520px'; }
10010:     unless ($width) { $width='500px'; }
10011:     unless ($height) { $height='200px'; }
10012:     my ($table_id,$div_id,$tdcol);
10013:     if ($id ne '') {
10014:         $table_id = ' id="table_'.$id.'"';
10015:         $div_id = ' id="div_'.$id.'"';
10016:     }
10017:     if ($bgcolor ne '') {
10018:         $tdcol = "background-color: $bgcolor;";
10019:     }
10020:     my $nicescroll_js;
10021:     if ($env{'browser.mobile'}) {
10022:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
10023:     }
10024:     return <<"END";
10025: $nicescroll_js
10026: 
10027: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
10028: <div style="overflow:auto; width:$width; height:$height;"$div_id>
10029: END
10030: }
10031: 
10032: sub end_scrollbox {
10033:     return '</div></td></tr></table>';
10034: }
10035: 
10036: sub nicescroll_javascript {
10037:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
10038:     my %options;
10039:     if (ref($cursor) eq 'HASH') {
10040:         %options = %{$cursor};
10041:     }
10042:     unless ($options{'railalign'} =~ /^left|right$/) {
10043:         $options{'railalign'} = 'left';
10044:     }
10045:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
10046:         my $function  = &get_users_function();
10047:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
10048:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
10049:             $options{'cursorcolor'} = '#00F';
10050:         }
10051:     }
10052:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
10053:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
10054:             $options{'cursoropacity'}='1.0';
10055:         }
10056:     } else {
10057:         $options{'cursoropacity'}='1.0';
10058:     }
10059:     if ($options{'cursorfixedheight'} eq 'none') {
10060:         delete($options{'cursorfixedheight'});
10061:     } else {
10062:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
10063:     }
10064:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
10065:         delete($options{'railoffset'});
10066:     }
10067:     my @niceoptions;
10068:     while (my($key,$value) = each(%options)) {
10069:         if ($value =~ /^\{.+\}$/) {
10070:             push(@niceoptions,$key.':'.$value);
10071:         } else {
10072:             push(@niceoptions,$key.':"'.$value.'"');
10073:         }
10074:     }
10075:     my $nicescroll_js = '
10076: $(document).ready(
10077:       function() {
10078:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
10079:       }
10080: );
10081: ';
10082:     if ($framecheck) {
10083:         $nicescroll_js .= '
10084: function expand_div(caller) {
10085:     if (top === self) {
10086:         document.getElementById("'.$id.'").style.width = "auto";
10087:         document.getElementById("'.$id.'").style.height = "auto";
10088:     } else {
10089:         try {
10090:             if (parent.frames) {
10091:                 if (parent.frames.length > 1) {
10092:                     var framesrc = parent.frames[1].location.href;
10093:                     var currsrc = framesrc.replace(/\#.*$/,"");
10094:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
10095:                         document.getElementById("'.$id.'").style.width = "auto";
10096:                         document.getElementById("'.$id.'").style.height = "auto";
10097:                     }
10098:                 }
10099:             }
10100:         } catch (e) {
10101:             return;
10102:         }
10103:     }
10104:     return;
10105: }
10106: ';
10107:     }
10108:     if ($needjsready) {
10109:         $nicescroll_js = '
10110: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
10111:     } else {
10112:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
10113:     }
10114:     return $nicescroll_js;
10115: }
10116: 
10117: sub simple_error_page {
10118:     my ($r,$title,$msg,$args) = @_;
10119:     my %displayargs;
10120:     if (ref($args) eq 'HASH') {
10121:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
10122:         if ($args->{'only_body'}) {
10123:             $displayargs{'only_body'} = 1;
10124:         }
10125:         if ($args->{'no_nav_bar'}) {
10126:             $displayargs{'no_nav_bar'} = 1;
10127:         }
10128:     } else {
10129:         $msg = &mt($msg);
10130:     }
10131: 
10132:     my $page =
10133: 	&Apache::loncommon::start_page($title,'',\%displayargs).
10134: 	'<p class="LC_error">'.$msg.'</p>'.
10135: 	&Apache::loncommon::end_page();
10136:     if (ref($r)) {
10137: 	$r->print($page);
10138: 	return;
10139:     }
10140:     return $page;
10141: }
10142: 
10143: {
10144:     my @row_count;
10145: 
10146:     sub start_data_table_count {
10147:         unshift(@row_count, 0);
10148:         return;
10149:     }
10150: 
10151:     sub end_data_table_count {
10152:         shift(@row_count);
10153:         return;
10154:     }
10155: 
10156:     sub start_data_table {
10157: 	my ($add_class,$id) = @_;
10158: 	my $css_class = (join(' ','LC_data_table',$add_class));
10159:         my $table_id;
10160:         if (defined($id)) {
10161:             $table_id = ' id="'.$id.'"';
10162:         }
10163: 	&start_data_table_count();
10164: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
10165:     }
10166: 
10167:     sub end_data_table {
10168: 	&end_data_table_count();
10169: 	return '</table>'."\n";;
10170:     }
10171: 
10172:     sub start_data_table_row {
10173: 	my ($add_class, $id) = @_;
10174: 	$row_count[0]++;
10175: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
10176: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
10177:         $id = (' id="'.$id.'"') unless ($id eq '');
10178:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
10179:     }
10180:     
10181:     sub continue_data_table_row {
10182: 	my ($add_class, $id) = @_;
10183: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
10184: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
10185:         $id = (' id="'.$id.'"') unless ($id eq '');
10186:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
10187:     }
10188: 
10189:     sub end_data_table_row {
10190: 	return '</tr>'."\n";;
10191:     }
10192: 
10193:     sub start_data_table_empty_row {
10194: #	$row_count[0]++;
10195: 	return  '<tr class="LC_empty_row" >'."\n";;
10196:     }
10197: 
10198:     sub end_data_table_empty_row {
10199: 	return '</tr>'."\n";;
10200:     }
10201: 
10202:     sub start_data_table_header_row {
10203: 	return  '<tr class="LC_header_row">'."\n";;
10204:     }
10205: 
10206:     sub end_data_table_header_row {
10207: 	return '</tr>'."\n";;
10208:     }
10209: 
10210:     sub data_table_caption {
10211:         my $caption = shift;
10212:         return "<caption class=\"LC_caption\">$caption</caption>";
10213:     }
10214: }
10215: 
10216: =pod
10217: 
10218: =item * &inhibit_menu_check($arg)
10219: 
10220: Checks for a inhibitmenu state and generates output to preserve it
10221: 
10222: Inputs:         $arg - can be any of
10223:                      - undef - in which case the return value is a string 
10224:                                to add  into arguments list of a uri
10225:                      - 'input' - in which case the return value is a HTML
10226:                                  <form> <input> field of type hidden to
10227:                                  preserve the value
10228:                      - a url - in which case the return value is the url with
10229:                                the neccesary cgi args added to preserve the
10230:                                inhibitmenu state
10231:                      - a ref to a url - no return value, but the string is
10232:                                         updated to include the neccessary cgi
10233:                                         args to preserve the inhibitmenu state
10234: 
10235: =cut
10236: 
10237: sub inhibit_menu_check {
10238:     my ($arg) = @_;
10239:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
10240:     if ($arg eq 'input') {
10241: 	if ($env{'form.inhibitmenu'}) {
10242: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
10243: 	} else {
10244: 	    return
10245: 	}
10246:     }
10247:     if ($env{'form.inhibitmenu'}) {
10248: 	if (ref($arg)) {
10249: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
10250: 	} elsif ($arg eq '') {
10251: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
10252: 	} else {
10253: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
10254: 	}
10255:     }
10256:     if (!ref($arg)) {
10257: 	return $arg;
10258:     }
10259: }
10260: 
10261: ###############################################
10262: 
10263: =pod
10264: 
10265: =back
10266: 
10267: =head1 User Information Routines
10268: 
10269: =over 4
10270: 
10271: =item * &get_users_function()
10272: 
10273: Used by &bodytag to determine the current users primary role.
10274: Returns either 'student','coordinator','admin', or 'author'.
10275: 
10276: =cut
10277: 
10278: ###############################################
10279: sub get_users_function {
10280:     my $function = 'norole';
10281:     if ($env{'request.role'}=~/^(st)/) {
10282:         $function='student';
10283:     }
10284:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
10285:         $function='coordinator';
10286:     }
10287:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
10288:         $function='admin';
10289:     }
10290:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
10291:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
10292:         $function='author';
10293:     }
10294:     return $function;
10295: }
10296: 
10297: ###############################################
10298: 
10299: =pod
10300: 
10301: =item * &show_course()
10302: 
10303: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
10304: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
10305: 
10306: Inputs:
10307: None
10308: 
10309: Outputs:
10310: Scalar: 1 if 'Course' to be used, 0 otherwise.
10311: 
10312: =cut
10313: 
10314: ###############################################
10315: sub show_course {
10316:     my $course = !$env{'user.adv'};
10317:     if (!$env{'user.adv'}) {
10318:         foreach my $env (keys(%env)) {
10319:             next if ($env !~ m/^user\.priv\./);
10320:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
10321:                 $course = 0;
10322:                 last;
10323:             }
10324:         }
10325:     }
10326:     return $course;
10327: }
10328: 
10329: ###############################################
10330: 
10331: =pod
10332: 
10333: =item * &check_user_status()
10334: 
10335: Determines current status of supplied role for a
10336: specific user. Roles can be active, previous or future.
10337: 
10338: Inputs: 
10339: user's domain, user's username, course's domain,
10340: course's number, optional section ID.
10341: 
10342: Outputs:
10343: role status: active, previous or future. 
10344: 
10345: =cut
10346: 
10347: sub check_user_status {
10348:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
10349:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
10350:     my @uroles = keys(%userinfo);
10351:     my $srchstr;
10352:     my $active_chk = 'none';
10353:     my $now = time;
10354:     if (@uroles > 0) {
10355:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
10356:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
10357:         } else {
10358:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
10359:         }
10360:         if (grep/^\Q$srchstr\E$/,@uroles) {
10361:             my $role_end = 0;
10362:             my $role_start = 0;
10363:             $active_chk = 'active';
10364:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
10365:                 $role_end = $1;
10366:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
10367:                     $role_start = $1;
10368:                 }
10369:             }
10370:             if ($role_start > 0) {
10371:                 if ($now < $role_start) {
10372:                     $active_chk = 'future';
10373:                 }
10374:             }
10375:             if ($role_end > 0) {
10376:                 if ($now > $role_end) {
10377:                     $active_chk = 'previous';
10378:                 }
10379:             }
10380:         }
10381:     }
10382:     return $active_chk;
10383: }
10384: 
10385: ###############################################
10386: 
10387: =pod
10388: 
10389: =item * &get_sections()
10390: 
10391: Determines all the sections for a course including
10392: sections with students and sections containing other roles.
10393: Incoming parameters: 
10394: 
10395: 1. domain
10396: 2. course number 
10397: 3. reference to array containing roles for which sections should 
10398: be gathered (optional).
10399: 4. reference to array containing status types for which sections 
10400: should be gathered (optional).
10401: 
10402: If the third argument is undefined, sections are gathered for any role. 
10403: If the fourth argument is undefined, sections are gathered for any status.
10404: Permissible values are 'active' or 'future' or 'previous'.
10405:  
10406: Returns section hash (keys are section IDs, values are
10407: number of users in each section), subject to the
10408: optional roles filter, optional status filter 
10409: 
10410: =cut
10411: 
10412: ###############################################
10413: sub get_sections {
10414:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
10415:     if (!defined($cdom) || !defined($cnum)) {
10416:         my $cid =  $env{'request.course.id'};
10417: 
10418: 	return if (!defined($cid));
10419: 
10420:         $cdom = $env{'course.'.$cid.'.domain'};
10421:         $cnum = $env{'course.'.$cid.'.num'};
10422:     }
10423: 
10424:     my %sectioncount;
10425:     my $now = time;
10426: 
10427:     my $check_students = 1;
10428:     my $only_students = 0;
10429:     if (ref($possible_roles) eq 'ARRAY') {
10430:         if (grep(/^st$/,@{$possible_roles})) {
10431:             if (@{$possible_roles} == 1) {
10432:                 $only_students = 1;
10433:             }
10434:         } else {
10435:             $check_students = 0;
10436:         }
10437:     }
10438: 
10439:     if ($check_students) { 
10440: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
10441: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
10442: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
10443:         my $start_index = &Apache::loncoursedata::CL_START();
10444:         my $end_index = &Apache::loncoursedata::CL_END();
10445:         my $status;
10446: 	while (my ($student,$data) = each(%$classlist)) {
10447: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
10448: 				                     $data->[$status_index],
10449:                                                      $data->[$start_index],
10450:                                                      $data->[$end_index]);
10451:             if ($stu_status eq 'Active') {
10452:                 $status = 'active';
10453:             } elsif ($end < $now) {
10454:                 $status = 'previous';
10455:             } elsif ($start > $now) {
10456:                 $status = 'future';
10457:             } 
10458: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
10459:                 if ((!defined($possible_status)) || (($status ne '') && 
10460:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
10461: 		    $sectioncount{$section}++;
10462:                 }
10463: 	    }
10464: 	}
10465:     }
10466:     if ($only_students) {
10467:         return %sectioncount;
10468:     }
10469:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10470:     foreach my $user (sort(keys(%courseroles))) {
10471: 	if ($user !~ /^(\w{2})/) { next; }
10472: 	my ($role) = ($user =~ /^(\w{2})/);
10473: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
10474: 	my ($section,$status);
10475: 	if ($role eq 'cr' &&
10476: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
10477: 	    $section=$1;
10478: 	}
10479: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
10480: 	if (!defined($section) || $section eq '-1') { next; }
10481:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
10482:         if ($end == -1 && $start == -1) {
10483:             next; #deleted role
10484:         }
10485:         if (!defined($possible_status)) { 
10486:             $sectioncount{$section}++;
10487:         } else {
10488:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
10489:                 $status = 'active';
10490:             } elsif ($end < $now) {
10491:                 $status = 'future';
10492:             } elsif ($start > $now) {
10493:                 $status = 'previous';
10494:             }
10495:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
10496:                 $sectioncount{$section}++;
10497:             }
10498:         }
10499:     }
10500:     return %sectioncount;
10501: }
10502: 
10503: ###############################################
10504: 
10505: =pod
10506: 
10507: =item * &get_course_users()
10508: 
10509: Retrieves usernames:domains for users in the specified course
10510: with specific role(s), and access status. 
10511: 
10512: Incoming parameters:
10513: 1. course domain
10514: 2. course number
10515: 3. access status: users must have - either active, 
10516: previous, future, or all.
10517: 4. reference to array of permissible roles
10518: 5. reference to array of section restrictions (optional)
10519: 6. reference to results object (hash of hashes).
10520: 7. reference to optional userdata hash
10521: 8. reference to optional statushash
10522: 9. flag if privileged users (except those set to unhide in
10523:    course settings) should be excluded    
10524: Keys of top level results hash are roles.
10525: Keys of inner hashes are username:domain, with 
10526: values set to access type.
10527: Optional userdata hash returns an array with arguments in the 
10528: same order as loncoursedata::get_classlist() for student data.
10529: 
10530: Optional statushash returns
10531: 
10532: Entries for end, start, section and status are blank because
10533: of the possibility of multiple values for non-student roles.
10534: 
10535: =cut
10536: 
10537: ###############################################
10538: 
10539: sub get_course_users {
10540:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
10541:     my %idx = ();
10542:     my %seclists;
10543: 
10544:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
10545:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
10546:     $idx{end} = &Apache::loncoursedata::CL_END();
10547:     $idx{start} = &Apache::loncoursedata::CL_START();
10548:     $idx{id} = &Apache::loncoursedata::CL_ID();
10549:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
10550:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
10551:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
10552: 
10553:     if (grep(/^st$/,@{$roles})) {
10554:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
10555:         my $now = time;
10556:         foreach my $student (keys(%{$classlist})) {
10557:             my $match = 0;
10558:             my $secmatch = 0;
10559:             my $section = $$classlist{$student}[$idx{section}];
10560:             my $status = $$classlist{$student}[$idx{status}];
10561:             if ($section eq '') {
10562:                 $section = 'none';
10563:             }
10564:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
10565:                 if (grep(/^all$/,@{$sections})) {
10566:                     $secmatch = 1;
10567:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
10568:                     if (grep(/^none$/,@{$sections})) {
10569:                         $secmatch = 1;
10570:                     }
10571:                 } else {  
10572: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
10573: 		        $secmatch = 1;
10574:                     }
10575: 		}
10576:                 if (!$secmatch) {
10577:                     next;
10578:                 }
10579:             }
10580:             if (defined($$types{'active'})) {
10581:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
10582:                     push(@{$$users{st}{$student}},'active');
10583:                     $match = 1;
10584:                 }
10585:             }
10586:             if (defined($$types{'previous'})) {
10587:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
10588:                     push(@{$$users{st}{$student}},'previous');
10589:                     $match = 1;
10590:                 }
10591:             }
10592:             if (defined($$types{'future'})) {
10593:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
10594:                     push(@{$$users{st}{$student}},'future');
10595:                     $match = 1;
10596:                 }
10597:             }
10598:             if ($match) {
10599:                 push(@{$seclists{$student}},$section);
10600:                 if (ref($userdata) eq 'HASH') {
10601:                     $$userdata{$student} = $$classlist{$student};
10602:                 }
10603:                 if (ref($statushash) eq 'HASH') {
10604:                     $statushash->{$student}{'st'}{$section} = $status;
10605:                 }
10606:             }
10607:         }
10608:     }
10609:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
10610:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10611:         my $now = time;
10612:         my %displaystatus = ( previous => 'Expired',
10613:                               active   => 'Active',
10614:                               future   => 'Future',
10615:                             );
10616:         my (%nothide,@possdoms);
10617:         if ($hidepriv) {
10618:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
10619:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
10620:                 if ($user !~ /:/) {
10621:                     $nothide{join(':',split(/[\@]/,$user))}=1;
10622:                 } else {
10623:                     $nothide{$user} = 1;
10624:                 }
10625:             }
10626:             my @possdoms = ($cdom);
10627:             if ($coursehash{'checkforpriv'}) {
10628:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
10629:             }
10630:         }
10631:         foreach my $person (sort(keys(%coursepersonnel))) {
10632:             my $match = 0;
10633:             my $secmatch = 0;
10634:             my $status;
10635:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
10636:             $user =~ s/:$//;
10637:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
10638:             if ($end == -1 || $start == -1) {
10639:                 next;
10640:             }
10641:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
10642:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
10643:                 my ($uname,$udom) = split(/:/,$user);
10644:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
10645:                     if (grep(/^all$/,@{$sections})) {
10646:                         $secmatch = 1;
10647:                     } elsif ($usec eq '') {
10648:                         if (grep(/^none$/,@{$sections})) {
10649:                             $secmatch = 1;
10650:                         }
10651:                     } else {
10652:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
10653:                             $secmatch = 1;
10654:                         }
10655:                     }
10656:                     if (!$secmatch) {
10657:                         next;
10658:                     }
10659:                 }
10660:                 if ($usec eq '') {
10661:                     $usec = 'none';
10662:                 }
10663:                 if ($uname ne '' && $udom ne '') {
10664:                     if ($hidepriv) {
10665:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
10666:                             (!$nothide{$uname.':'.$udom})) {
10667:                             next;
10668:                         }
10669:                     }
10670:                     if ($end > 0 && $end < $now) {
10671:                         $status = 'previous';
10672:                     } elsif ($start > $now) {
10673:                         $status = 'future';
10674:                     } else {
10675:                         $status = 'active';
10676:                     }
10677:                     foreach my $type (keys(%{$types})) { 
10678:                         if ($status eq $type) {
10679:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
10680:                                 push(@{$$users{$role}{$user}},$type);
10681:                             }
10682:                             $match = 1;
10683:                         }
10684:                     }
10685:                     if (($match) && (ref($userdata) eq 'HASH')) {
10686:                         if (!exists($$userdata{$uname.':'.$udom})) {
10687: 			    &get_user_info($udom,$uname,\%idx,$userdata);
10688:                         }
10689:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
10690:                             push(@{$seclists{$uname.':'.$udom}},$usec);
10691:                         }
10692:                         if (ref($statushash) eq 'HASH') {
10693:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
10694:                         }
10695:                     }
10696:                 }
10697:             }
10698:         }
10699:         if (grep(/^ow$/,@{$roles})) {
10700:             if ((defined($cdom)) && (defined($cnum))) {
10701:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
10702:                 if ( defined($csettings{'internal.courseowner'}) ) {
10703:                     my $owner = $csettings{'internal.courseowner'};
10704:                     next if ($owner eq '');
10705:                     my ($ownername,$ownerdom);
10706:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
10707:                         $ownername = $1;
10708:                         $ownerdom = $2;
10709:                     } else {
10710:                         $ownername = $owner;
10711:                         $ownerdom = $cdom;
10712:                         $owner = $ownername.':'.$ownerdom;
10713:                     }
10714:                     @{$$users{'ow'}{$owner}} = 'any';
10715:                     if (defined($userdata) && 
10716: 			!exists($$userdata{$owner})) {
10717: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
10718:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
10719:                             push(@{$seclists{$owner}},'none');
10720:                         }
10721:                         if (ref($statushash) eq 'HASH') {
10722:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
10723:                         }
10724: 		    }
10725:                 }
10726:             }
10727:         }
10728:         foreach my $user (keys(%seclists)) {
10729:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
10730:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
10731:         }
10732:     }
10733:     return;
10734: }
10735: 
10736: sub get_user_info {
10737:     my ($udom,$uname,$idx,$userdata) = @_;
10738:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
10739: 	&plainname($uname,$udom,'lastname');
10740:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
10741:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
10742:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
10743:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
10744:     return;
10745: }
10746: 
10747: ###############################################
10748: 
10749: =pod
10750: 
10751: =item * &get_user_quota()
10752: 
10753: Retrieves quota assigned for storage of user files.
10754: Default is to report quota for portfolio files.
10755: 
10756: Incoming parameters:
10757: 1. user's username
10758: 2. user's domain
10759: 3. quota name - portfolio, author, or course
10760:    (if no quota name provided, defaults to portfolio).
10761: 4. crstype - official, unofficial, textbook, placement or community, 
10762:    if quota name is course
10763: 
10764: Returns:
10765: 1. Disk quota (in MB) assigned to student.
10766: 2. (Optional) Type of setting: custom or default
10767:    (individually assigned or default for user's 
10768:    institutional status).
10769: 3. (Optional) - User's institutional status (e.g., faculty, staff
10770:    or student - types as defined in localenroll::inst_usertypes 
10771:    for user's domain, which determines default quota for user.
10772: 4. (Optional) - Default quota which would apply to the user.
10773: 
10774: If a value has been stored in the user's environment, 
10775: it will return that, otherwise it returns the maximal default
10776: defined for the user's institutional status(es) in the domain.
10777: 
10778: =cut
10779: 
10780: ###############################################
10781: 
10782: 
10783: sub get_user_quota {
10784:     my ($uname,$udom,$quotaname,$crstype) = @_;
10785:     my ($quota,$quotatype,$settingstatus,$defquota);
10786:     if (!defined($udom)) {
10787:         $udom = $env{'user.domain'};
10788:     }
10789:     if (!defined($uname)) {
10790:         $uname = $env{'user.name'};
10791:     }
10792:     if (($udom eq '' || $uname eq '') ||
10793:         ($udom eq 'public') && ($uname eq 'public')) {
10794:         $quota = 0;
10795:         $quotatype = 'default';
10796:         $defquota = 0; 
10797:     } else {
10798:         my $inststatus;
10799:         if ($quotaname eq 'course') {
10800:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
10801:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
10802:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
10803:             } else {
10804:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
10805:                 $quota = $cenv{'internal.uploadquota'};
10806:             }
10807:         } else {
10808:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
10809:                 if ($quotaname eq 'author') {
10810:                     $quota = $env{'environment.authorquota'};
10811:                 } else {
10812:                     $quota = $env{'environment.portfolioquota'};
10813:                 }
10814:                 $inststatus = $env{'environment.inststatus'};
10815:             } else {
10816:                 my %userenv = 
10817:                     &Apache::lonnet::get('environment',['portfolioquota',
10818:                                          'authorquota','inststatus'],$udom,$uname);
10819:                 my ($tmp) = keys(%userenv);
10820:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10821:                     if ($quotaname eq 'author') {
10822:                         $quota = $userenv{'authorquota'};
10823:                     } else {
10824:                         $quota = $userenv{'portfolioquota'};
10825:                     }
10826:                     $inststatus = $userenv{'inststatus'};
10827:                 } else {
10828:                     undef(%userenv);
10829:                 }
10830:             }
10831:         }
10832:         if ($quota eq '' || wantarray) {
10833:             if ($quotaname eq 'course') {
10834:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
10835:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
10836:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
10837:                     ($crstype eq 'placement')) { 
10838:                     $defquota = $domdefs{$crstype.'quota'};
10839:                 }
10840:                 if ($defquota eq '') {
10841:                     $defquota = 500;
10842:                 }
10843:             } else {
10844:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
10845:             }
10846:             if ($quota eq '') {
10847:                 $quota = $defquota;
10848:                 $quotatype = 'default';
10849:             } else {
10850:                 $quotatype = 'custom';
10851:             }
10852:         }
10853:     }
10854:     if (wantarray) {
10855:         return ($quota,$quotatype,$settingstatus,$defquota);
10856:     } else {
10857:         return $quota;
10858:     }
10859: }
10860: 
10861: ###############################################
10862: 
10863: =pod
10864: 
10865: =item * &default_quota()
10866: 
10867: Retrieves default quota assigned for storage of user portfolio files,
10868: given an (optional) user's institutional status.
10869: 
10870: Incoming parameters:
10871: 
10872: 1. domain
10873: 2. (Optional) institutional status(es).  This is a : separated list of 
10874:    status types (e.g., faculty, staff, student etc.)
10875:    which apply to the user for whom the default is being retrieved.
10876:    If the institutional status string in undefined, the domain
10877:    default quota will be returned.
10878: 3.  quota name - portfolio, author, or course
10879:    (if no quota name provided, defaults to portfolio).
10880: 
10881: Returns:
10882: 
10883: 1. Default disk quota (in MB) for user portfolios in the domain.
10884: 2. (Optional) institutional type which determined the value of the
10885:    default quota.
10886: 
10887: If a value has been stored in the domain's configuration db,
10888: it will return that, otherwise it returns 20 (for backwards 
10889: compatibility with domains which have not set up a configuration
10890: db file; the original statically defined portfolio quota was 20 MB). 
10891: 
10892: If the user's status includes multiple types (e.g., staff and student),
10893: the largest default quota which applies to the user determines the
10894: default quota returned.
10895: 
10896: =cut
10897: 
10898: ###############################################
10899: 
10900: 
10901: sub default_quota {
10902:     my ($udom,$inststatus,$quotaname) = @_;
10903:     my ($defquota,$settingstatus);
10904:     my %quotahash = &Apache::lonnet::get_dom('configuration',
10905:                                             ['quotas'],$udom);
10906:     my $key = 'defaultquota';
10907:     if ($quotaname eq 'author') {
10908:         $key = 'authorquota';
10909:     }
10910:     if (ref($quotahash{'quotas'}) eq 'HASH') {
10911:         if ($inststatus ne '') {
10912:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
10913:             foreach my $item (@statuses) {
10914:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
10915:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
10916:                         if ($defquota eq '') {
10917:                             $defquota = $quotahash{'quotas'}{$key}{$item};
10918:                             $settingstatus = $item;
10919:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
10920:                             $defquota = $quotahash{'quotas'}{$key}{$item};
10921:                             $settingstatus = $item;
10922:                         }
10923:                     }
10924:                 } elsif ($key eq 'defaultquota') {
10925:                     if ($quotahash{'quotas'}{$item} ne '') {
10926:                         if ($defquota eq '') {
10927:                             $defquota = $quotahash{'quotas'}{$item};
10928:                             $settingstatus = $item;
10929:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
10930:                             $defquota = $quotahash{'quotas'}{$item};
10931:                             $settingstatus = $item;
10932:                         }
10933:                     }
10934:                 }
10935:             }
10936:         }
10937:         if ($defquota eq '') {
10938:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
10939:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
10940:             } elsif ($key eq 'defaultquota') {
10941:                 $defquota = $quotahash{'quotas'}{'default'};
10942:             }
10943:             $settingstatus = 'default';
10944:             if ($defquota eq '') {
10945:                 if ($quotaname eq 'author') {
10946:                     $defquota = 500;
10947:                 }
10948:             }
10949:         }
10950:     } else {
10951:         $settingstatus = 'default';
10952:         if ($quotaname eq 'author') {
10953:             $defquota = 500;
10954:         } else {
10955:             $defquota = 20;
10956:         }
10957:     }
10958:     if (wantarray) {
10959:         return ($defquota,$settingstatus);
10960:     } else {
10961:         return $defquota;
10962:     }
10963: }
10964: 
10965: ###############################################
10966: 
10967: =pod
10968: 
10969: =item * &excess_filesize_warning()
10970: 
10971: Returns warning message if upload of file to authoring space, or copying
10972: of existing file within authoring space will cause quota for the authoring
10973: space to be exceeded.
10974: 
10975: Same, if upload of a file directly to a course/community via Course Editor
10976: will cause quota for uploaded content for the course to be exceeded.
10977: 
10978: Inputs: 7 
10979: 1. username or coursenum
10980: 2. domain
10981: 3. context ('author' or 'course')
10982: 4. filename of file for which action is being requested
10983: 5. filesize (kB) of file
10984: 6. action being taken: copy or upload.
10985: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
10986: 
10987: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
10988:          otherwise return null.
10989: 
10990: =back
10991: 
10992: =cut
10993: 
10994: sub excess_filesize_warning {
10995:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
10996:     my $current_disk_usage = 0;
10997:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
10998:     if ($context eq 'author') {
10999:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
11000:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
11001:     } else {
11002:         foreach my $subdir ('docs','supplemental') {
11003:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
11004:         }
11005:     }
11006:     $disk_quota = int($disk_quota * 1000);
11007:     if (($current_disk_usage + $filesize) > $disk_quota) {
11008:         return '<p class="LC_warning">'.
11009:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
11010:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
11011:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
11012:                             $disk_quota,$current_disk_usage).
11013:                '</p>';
11014:     }
11015:     return;
11016: }
11017: 
11018: ###############################################
11019: 
11020: 
11021: 
11022: 
11023: sub get_secgrprole_info {
11024:     my ($cdom,$cnum,$needroles,$type)  = @_;
11025:     my %sections_count = &get_sections($cdom,$cnum);
11026:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
11027:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
11028:     my @groups = sort(keys(%curr_groups));
11029:     my $allroles = [];
11030:     my $rolehash;
11031:     my $accesshash = {
11032:                      active => 'Currently has access',
11033:                      future => 'Will have future access',
11034:                      previous => 'Previously had access',
11035:                   };
11036:     if ($needroles) {
11037:         $rolehash = {'all' => 'all'};
11038:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
11039: 	if (&Apache::lonnet::error(%user_roles)) {
11040: 	    undef(%user_roles);
11041: 	}
11042:         foreach my $item (keys(%user_roles)) {
11043:             my ($role)=split(/\:/,$item,2);
11044:             if ($role eq 'cr') { next; }
11045:             if ($role =~ /^cr/) {
11046:                 $$rolehash{$role} = (split('/',$role))[3];
11047:             } else {
11048:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
11049:             }
11050:         }
11051:         foreach my $key (sort(keys(%{$rolehash}))) {
11052:             push(@{$allroles},$key);
11053:         }
11054:         push (@{$allroles},'st');
11055:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
11056:     }
11057:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
11058: }
11059: 
11060: sub user_picker {
11061:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
11062:     my $currdom = $dom;
11063:     my @alldoms = &Apache::lonnet::all_domains();
11064:     if (@alldoms == 1) {
11065:         my %domsrch = &Apache::lonnet::get_dom('configuration',
11066:                                                ['directorysrch'],$alldoms[0]);
11067:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
11068:         my $showdom = $domdesc;
11069:         if ($showdom eq '') {
11070:             $showdom = $dom;
11071:         }
11072:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
11073:             if ((!$domsrch{'directorysrch'}{'available'}) &&
11074:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
11075:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
11076:             }
11077:         }
11078:     }
11079:     my %curr_selected = (
11080:                         srchin => 'dom',
11081:                         srchby => 'lastname',
11082:                       );
11083:     my $srchterm;
11084:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
11085:         if ($srch->{'srchby'} ne '') {
11086:             $curr_selected{'srchby'} = $srch->{'srchby'};
11087:         }
11088:         if ($srch->{'srchin'} ne '') {
11089:             $curr_selected{'srchin'} = $srch->{'srchin'};
11090:         }
11091:         if ($srch->{'srchtype'} ne '') {
11092:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
11093:         }
11094:         if ($srch->{'srchdomain'} ne '') {
11095:             $currdom = $srch->{'srchdomain'};
11096:         }
11097:         $srchterm = $srch->{'srchterm'};
11098:     }
11099:     my %html_lt=&Apache::lonlocal::texthash(
11100:                     'usr'       => 'Search criteria',
11101:                     'doma'      => 'Domain/institution to search',
11102:                     'uname'     => 'username',
11103:                     'lastname'  => 'last name',
11104:                     'lastfirst' => 'last name, first name',
11105:                     'crs'       => 'in this course',
11106:                     'dom'       => 'in selected LON-CAPA domain', 
11107:                     'alc'       => 'all LON-CAPA',
11108:                     'instd'     => 'in institutional directory for selected domain',
11109:                     'exact'     => 'is',
11110:                     'contains'  => 'contains',
11111:                     'begins'    => 'begins with',
11112:                                        );
11113:     my %js_lt=&Apache::lonlocal::texthash(
11114:                     'youm'      => "You must include some text to search for.",
11115:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
11116:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
11117:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
11118:                     'ymcd'      => "You must choose a domain when using a domain search.",
11119:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
11120:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
11121:                      'thfo'     => "The following need to be corrected before the search can be run:",
11122:                                        );
11123:     &html_escape(\%html_lt);
11124:     &js_escape(\%js_lt);
11125:     my $domform;
11126:     my $allow_blank = 1;
11127:     if ($fixeddom) {
11128:         $allow_blank = 0;
11129:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
11130:     } else {
11131:         my $defdom = $env{'request.role.domain'};
11132:         my ($trusted,$untrusted);
11133:         if (($context eq 'requestcrs') || ($context eq 'course')) {
11134:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
11135:         } elsif ($context eq 'author') {
11136:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
11137:         } elsif ($context eq 'domain') {
11138:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
11139:         }
11140:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
11141:     }
11142:     my $srchinsel = ' <select name="srchin">';
11143: 
11144:     my @srchins = ('crs','dom','alc','instd');
11145: 
11146:     foreach my $option (@srchins) {
11147:         # FIXME 'alc' option unavailable until 
11148:         #       loncreateuser::print_user_query_page()
11149:         #       has been completed.
11150:         next if ($option eq 'alc');
11151:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
11152:         next if ($option eq 'crs' && !$env{'request.course.id'});
11153:         next if (($option eq 'instd') && ($noinstd));
11154:         if ($curr_selected{'srchin'} eq $option) {
11155:             $srchinsel .= ' 
11156:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
11157:         } else {
11158:             $srchinsel .= '
11159:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
11160:         }
11161:     }
11162:     $srchinsel .= "\n  </select>\n";
11163: 
11164:     my $srchbysel =  ' <select name="srchby">';
11165:     foreach my $option ('lastname','lastfirst','uname') {
11166:         if ($curr_selected{'srchby'} eq $option) {
11167:             $srchbysel .= '
11168:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
11169:         } else {
11170:             $srchbysel .= '
11171:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
11172:          }
11173:     }
11174:     $srchbysel .= "\n  </select>\n";
11175: 
11176:     my $srchtypesel = ' <select name="srchtype">';
11177:     foreach my $option ('begins','contains','exact') {
11178:         if ($curr_selected{'srchtype'} eq $option) {
11179:             $srchtypesel .= '
11180:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
11181:         } else {
11182:             $srchtypesel .= '
11183:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
11184:         }
11185:     }
11186:     $srchtypesel .= "\n  </select>\n";
11187: 
11188:     my ($newuserscript,$new_user_create);
11189:     my $context_dom = $env{'request.role.domain'};
11190:     if ($context eq 'requestcrs') {
11191:         if ($env{'form.coursedom'} ne '') { 
11192:             $context_dom = $env{'form.coursedom'};
11193:         }
11194:     }
11195:     if ($forcenewuser) {
11196:         if (ref($srch) eq 'HASH') {
11197:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
11198:                 if ($cancreate) {
11199:                     $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>';
11200:                 } else {
11201:                     my $helplink = 'javascript:helpMenu('."'display'".')';
11202:                     my %usertypetext = (
11203:                         official   => 'institutional',
11204:                         unofficial => 'non-institutional',
11205:                     );
11206:                     $new_user_create = '<p class="LC_warning">'
11207:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
11208:                                       .' '
11209:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
11210:                                           ,'<a href="'.$helplink.'">','</a>')
11211:                                       .'</p><br />';
11212:                 }
11213:             }
11214:         }
11215: 
11216:         $newuserscript = <<"ENDSCRIPT";
11217: 
11218: function setSearch(createnew,callingForm) {
11219:     if (createnew == 1) {
11220:         for (var i=0; i<callingForm.srchby.length; i++) {
11221:             if (callingForm.srchby.options[i].value == 'uname') {
11222:                 callingForm.srchby.selectedIndex = i;
11223:             }
11224:         }
11225:         for (var i=0; i<callingForm.srchin.length; i++) {
11226:             if ( callingForm.srchin.options[i].value == 'dom') {
11227: 		callingForm.srchin.selectedIndex = i;
11228:             }
11229:         }
11230:         for (var i=0; i<callingForm.srchtype.length; i++) {
11231:             if (callingForm.srchtype.options[i].value == 'exact') {
11232:                 callingForm.srchtype.selectedIndex = i;
11233:             }
11234:         }
11235:         for (var i=0; i<callingForm.srchdomain.length; i++) {
11236:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
11237:                 callingForm.srchdomain.selectedIndex = i;
11238:             }
11239:         }
11240:     }
11241: }
11242: ENDSCRIPT
11243: 
11244:     }
11245: 
11246:     my $output = <<"END_BLOCK";
11247: <script type="text/javascript">
11248: // <![CDATA[
11249: function validateEntry(callingForm) {
11250: 
11251:     var checkok = 1;
11252:     var srchin;
11253:     for (var i=0; i<callingForm.srchin.length; i++) {
11254: 	if ( callingForm.srchin[i].checked ) {
11255: 	    srchin = callingForm.srchin[i].value;
11256: 	}
11257:     }
11258: 
11259:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
11260:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
11261:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
11262:     var srchterm =  callingForm.srchterm.value;
11263:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
11264:     var msg = "";
11265: 
11266:     if (srchterm == "") {
11267:         checkok = 0;
11268:         msg += "$js_lt{'youm'}\\n";
11269:     }
11270: 
11271:     if (srchtype== 'begins') {
11272:         if (srchterm.length < 2) {
11273:             checkok = 0;
11274:             msg += "$js_lt{'thte'}\\n";
11275:         }
11276:     }
11277: 
11278:     if (srchtype== 'contains') {
11279:         if (srchterm.length < 3) {
11280:             checkok = 0;
11281:             msg += "$js_lt{'thet'}\\n";
11282:         }
11283:     }
11284:     if (srchin == 'instd') {
11285:         if (srchdomain == '') {
11286:             checkok = 0;
11287:             msg += "$js_lt{'yomc'}\\n";
11288:         }
11289:     }
11290:     if (srchin == 'dom') {
11291:         if (srchdomain == '') {
11292:             checkok = 0;
11293:             msg += "$js_lt{'ymcd'}\\n";
11294:         }
11295:     }
11296:     if (srchby == 'lastfirst') {
11297:         if (srchterm.indexOf(",") == -1) {
11298:             checkok = 0;
11299:             msg += "$js_lt{'whus'}\\n";
11300:         }
11301:         if (srchterm.indexOf(",") == srchterm.length -1) {
11302:             checkok = 0;
11303:             msg += "$js_lt{'whse'}\\n";
11304:         }
11305:     }
11306:     if (checkok == 0) {
11307:         alert("$js_lt{'thfo'}\\n"+msg);
11308:         return;
11309:     }
11310:     if (checkok == 1) {
11311:         callingForm.submit();
11312:     }
11313: }
11314: 
11315: $newuserscript
11316: 
11317: // ]]>
11318: </script>
11319: 
11320: $new_user_create
11321: 
11322: END_BLOCK
11323: 
11324:     $output .= &Apache::lonhtmlcommon::start_pick_box().
11325:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
11326:                $domform.
11327:                &Apache::lonhtmlcommon::row_closure().
11328:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
11329:                $srchbysel.
11330:                $srchtypesel. 
11331:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
11332:                $srchinsel.
11333:                &Apache::lonhtmlcommon::row_closure(1). 
11334:                &Apache::lonhtmlcommon::end_pick_box().
11335:                '<br />';
11336:     return ($output,1);
11337: }
11338: 
11339: sub user_rule_check {
11340:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
11341:     my ($response,%inst_response);
11342:     if (ref($usershash) eq 'HASH') {
11343:         if (keys(%{$usershash}) > 1) {
11344:             my (%by_username,%by_id,%userdoms);
11345:             my $checkid; 
11346:             if (ref($checks) eq 'HASH') {
11347:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
11348:                     $checkid = 1;
11349:                 }
11350:             }
11351:             foreach my $user (keys(%{$usershash})) {
11352:                 my ($uname,$udom) = split(/:/,$user);
11353:                 if ($checkid) {
11354:                     if (ref($usershash->{$user}) eq 'HASH') {
11355:                         if ($usershash->{$user}->{'id'} ne '') {
11356:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
11357:                             $userdoms{$udom} = 1;
11358:                             if (ref($inst_results) eq 'HASH') {
11359:                                 $inst_results->{$uname.':'.$udom} = {};
11360:                             }
11361:                         }
11362:                     }
11363:                 } else {
11364:                     $by_username{$udom}{$uname} = 1;
11365:                     $userdoms{$udom} = 1;
11366:                     if (ref($inst_results) eq 'HASH') {
11367:                         $inst_results->{$uname.':'.$udom} = {};
11368:                     }
11369:                 }
11370:             }
11371:             foreach my $udom (keys(%userdoms)) {
11372:                 if (!$got_rules->{$udom}) {
11373:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
11374:                                                              ['usercreation'],$udom);
11375:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
11376:                         foreach my $item ('username','id') {
11377:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
11378:                                 $$curr_rules{$udom}{$item} =
11379:                                     $domconfig{'usercreation'}{$item.'_rule'};
11380:                             }
11381:                         }
11382:                     }
11383:                     $got_rules->{$udom} = 1;
11384:                 }
11385:             }
11386:             if ($checkid) {
11387:                 foreach my $udom (keys(%by_id)) {
11388:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
11389:                     if ($outcome eq 'ok') {
11390:                         foreach my $id (keys(%{$by_id{$udom}})) {
11391:                             my $uname = $by_id{$udom}{$id};
11392:                             $inst_response{$uname.':'.$udom} = $outcome;
11393:                         }
11394:                         if (ref($results) eq 'HASH') {
11395:                             foreach my $uname (keys(%{$results})) {
11396:                                 if (exists($inst_response{$uname.':'.$udom})) {
11397:                                     $inst_response{$uname.':'.$udom} = $outcome;
11398:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
11399:                                 }
11400:                             }
11401:                         }
11402:                     }
11403:                 }
11404:             } else {
11405:                 foreach my $udom (keys(%by_username)) {
11406:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
11407:                     if ($outcome eq 'ok') {
11408:                         foreach my $uname (keys(%{$by_username{$udom}})) {
11409:                             $inst_response{$uname.':'.$udom} = $outcome;
11410:                         }
11411:                         if (ref($results) eq 'HASH') {
11412:                             foreach my $uname (keys(%{$results})) {
11413:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
11414:                             }
11415:                         }
11416:                     }
11417:                 }
11418:             }
11419:         } elsif (keys(%{$usershash}) == 1) {
11420:             my $user = (keys(%{$usershash}))[0];
11421:             my ($uname,$udom) = split(/:/,$user);
11422:             if (($udom ne '') && ($uname ne '')) {
11423:                 if (ref($usershash->{$user}) eq 'HASH') {
11424:                     if (ref($checks) eq 'HASH') {
11425:                         if (defined($checks->{'username'})) {
11426:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
11427:                                 &Apache::lonnet::get_instuser($udom,$uname);
11428:                         } elsif (defined($checks->{'id'})) {
11429:                             if ($usershash->{$user}->{'id'} ne '') {
11430:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
11431:                                     &Apache::lonnet::get_instuser($udom,undef,
11432:                                                                   $usershash->{$user}->{'id'});
11433:                             } else {
11434:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
11435:                                     &Apache::lonnet::get_instuser($udom,$uname);
11436:                             }
11437:                         }
11438:                     } else {
11439:                        ($inst_response{$user},%{$inst_results->{$user}}) =
11440:                             &Apache::lonnet::get_instuser($udom,$uname);
11441:                        return;
11442:                     }
11443:                     if (!$got_rules->{$udom}) {
11444:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
11445:                                                                  ['usercreation'],$udom);
11446:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
11447:                             foreach my $item ('username','id') {
11448:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
11449:                                    $$curr_rules{$udom}{$item} = 
11450:                                        $domconfig{'usercreation'}{$item.'_rule'};
11451:                                 }
11452:                             }
11453:                         }
11454:                         $got_rules->{$udom} = 1;
11455:                     }
11456:                 }
11457:             } else {
11458:                 return;
11459:             }
11460:         } else {
11461:             return;
11462:         }
11463:         foreach my $user (keys(%{$usershash})) {
11464:             my ($uname,$udom) = split(/:/,$user);
11465:             next if (($udom eq '') || ($uname eq ''));
11466:             my $id;
11467:             if (ref($inst_results) eq 'HASH') {
11468:                 if (ref($inst_results->{$user}) eq 'HASH') {
11469:                     $id = $inst_results->{$user}->{'id'};
11470:                 }
11471:             }
11472:             if ($id eq '') { 
11473:                 if (ref($usershash->{$user})) {
11474:                     $id = $usershash->{$user}->{'id'};
11475:                 }
11476:             }
11477:             foreach my $item (keys(%{$checks})) {
11478:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
11479:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
11480:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
11481:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
11482:                                                                              $$curr_rules{$udom}{$item});
11483:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
11484:                                 if ($rule_check{$rule}) {
11485:                                     $$rulematch{$user}{$item} = $rule;
11486:                                     if ($inst_response{$user} eq 'ok') {
11487:                                         if (ref($inst_results) eq 'HASH') {
11488:                                             if (ref($inst_results->{$user}) eq 'HASH') {
11489:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
11490:                                                     $$alerts{$item}{$udom}{$uname} = 1;
11491:                                                 } elsif ($item eq 'id') {
11492:                                                     if ($inst_results->{$user}->{'id'} eq '') {
11493:                                                         $$alerts{$item}{$udom}{$uname} = 1;
11494:                                                     }
11495:                                                 }
11496:                                             }
11497:                                         }
11498:                                     }
11499:                                     last;
11500:                                 }
11501:                             }
11502:                         }
11503:                     }
11504:                 }
11505:             }
11506:         }
11507:     }
11508:     return;
11509: }
11510: 
11511: sub user_rule_formats {
11512:     my ($domain,$domdesc,$curr_rules,$check) = @_;
11513:     my %text = ( 
11514:                  'username' => 'Usernames',
11515:                  'id'       => 'IDs',
11516:                );
11517:     my $output;
11518:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
11519:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
11520:         if (@{$ruleorder} > 0) {
11521:             $output = '<br />'.
11522:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
11523:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
11524:                       ' <ul>';
11525:             foreach my $rule (@{$ruleorder}) {
11526:                 if (ref($curr_rules) eq 'ARRAY') {
11527:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
11528:                         if (ref($rules->{$rule}) eq 'HASH') {
11529:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
11530:                                         $rules->{$rule}{'desc'}.'</li>';
11531:                         }
11532:                     }
11533:                 }
11534:             }
11535:             $output .= '</ul>';
11536:         }
11537:     }
11538:     return $output;
11539: }
11540: 
11541: sub instrule_disallow_msg {
11542:     my ($checkitem,$domdesc,$count,$mode) = @_;
11543:     my $response;
11544:     my %text = (
11545:                   item   => 'username',
11546:                   items  => 'usernames',
11547:                   match  => 'matches',
11548:                   do     => 'does',
11549:                   action => 'a username',
11550:                   one    => 'one',
11551:                );
11552:     if ($count > 1) {
11553:         $text{'item'} = 'usernames';
11554:         $text{'match'} ='match';
11555:         $text{'do'} = 'do';
11556:         $text{'action'} = 'usernames',
11557:         $text{'one'} = 'ones';
11558:     }
11559:     if ($checkitem eq 'id') {
11560:         $text{'items'} = 'IDs';
11561:         $text{'item'} = 'ID';
11562:         $text{'action'} = 'an ID';
11563:         if ($count > 1) {
11564:             $text{'item'} = 'IDs';
11565:             $text{'action'} = 'IDs';
11566:         }
11567:     }
11568:     $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 />';
11569:     if ($mode eq 'upload') {
11570:         if ($checkitem eq 'username') {
11571:             $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'}.");
11572:         } elsif ($checkitem eq 'id') {
11573:             $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.");
11574:         }
11575:     } elsif ($mode eq 'selfcreate') {
11576:         if ($checkitem eq 'id') {
11577:             $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.");
11578:         }
11579:     } else {
11580:         if ($checkitem eq 'username') {
11581:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
11582:         } elsif ($checkitem eq 'id') {
11583:             $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.");
11584:         }
11585:     }
11586:     return $response;
11587: }
11588: 
11589: sub personal_data_fieldtitles {
11590:     my %fieldtitles = &Apache::lonlocal::texthash (
11591:                         id => 'Student/Employee ID',
11592:                         permanentemail => 'E-mail address',
11593:                         lastname => 'Last Name',
11594:                         firstname => 'First Name',
11595:                         middlename => 'Middle Name',
11596:                         generation => 'Generation',
11597:                         gen => 'Generation',
11598:                         inststatus => 'Affiliation',
11599:                    );
11600:     return %fieldtitles;
11601: }
11602: 
11603: sub sorted_inst_types {
11604:     my ($dom) = @_;
11605:     my ($usertypes,$order);
11606:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
11607:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
11608:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
11609:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
11610:     } else {
11611:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
11612:     }
11613:     my $othertitle = &mt('All users');
11614:     if ($env{'request.course.id'}) {
11615:         $othertitle  = &mt('Any users');
11616:     }
11617:     my @types;
11618:     if (ref($order) eq 'ARRAY') {
11619:         @types = @{$order};
11620:     }
11621:     if (@types == 0) {
11622:         if (ref($usertypes) eq 'HASH') {
11623:             @types = sort(keys(%{$usertypes}));
11624:         }
11625:     }
11626:     if (keys(%{$usertypes}) > 0) {
11627:         $othertitle = &mt('Other users');
11628:     }
11629:     return ($othertitle,$usertypes,\@types);
11630: }
11631: 
11632: sub get_institutional_codes {
11633:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
11634: # Get complete list of course sections to update
11635:     my @currsections = ();
11636:     my @currxlists = ();
11637:     my (%unclutteredsec,%unclutteredlcsec);
11638:     my $coursecode = $$settings{'internal.coursecode'};
11639:     my $crskey = $crs.':'.$coursecode;
11640:     @{$unclutteredsec{$crskey}} = ();
11641:     @{$unclutteredlcsec{$crskey}} = ();
11642: 
11643:     if ($$settings{'internal.sectionnums'} ne '') {
11644:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
11645:     }
11646: 
11647:     if ($$settings{'internal.crosslistings'} ne '') {
11648:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
11649:     }
11650: 
11651:     if (@currxlists > 0) {
11652:         foreach my $xl (@currxlists) {
11653:             if ($xl =~ /^([^:]+):(\w*)$/) {
11654:                 unless (grep/^$1$/,@{$allcourses}) {
11655:                     push(@{$allcourses},$1);
11656:                     $$LC_code{$1} = $2;
11657:                 }
11658:             }
11659:         }
11660:     }
11661: 
11662:     if (@currsections > 0) {
11663:         foreach my $sec (@currsections) {
11664:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
11665:                 my $instsec = $1;
11666:                 my $lc_sec = $2;
11667:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
11668:                     push(@{$unclutteredsec{$crskey}},$instsec);
11669:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
11670:                 }
11671:             }
11672:         }
11673:     }
11674: 
11675:     if (@{$unclutteredsec{$crskey}} > 0) {
11676:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
11677:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
11678:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
11679:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
11680:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
11681:                     push(@{$allcourses},$sec);
11682:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
11683:                 }
11684:             }
11685:         }
11686:     }
11687:     return;
11688: }
11689: 
11690: sub get_standard_codeitems {
11691:     return ('Year','Semester','Department','Number','Section');
11692: }
11693: 
11694: =pod
11695: 
11696: =head1 Slot Helpers
11697: 
11698: =over 4
11699: 
11700: =item * sorted_slots()
11701: 
11702: Sorts an array of slot names in order of an optional sort key,
11703: default sort is by slot start time (earliest first). 
11704: 
11705: Inputs:
11706: 
11707: =over 4
11708: 
11709: slotsarr  - Reference to array of unsorted slot names.
11710: 
11711: slots     - Reference to hash of hash, where outer hash keys are slot names.
11712: 
11713: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
11714: 
11715: =back
11716: 
11717: Returns:
11718: 
11719: =over 4
11720: 
11721: sorted   - An array of slot names sorted by a specified sort key 
11722:            (default sort key is start time of the slot).
11723: 
11724: =back
11725: 
11726: =cut
11727: 
11728: 
11729: sub sorted_slots {
11730:     my ($slotsarr,$slots,$sortkey) = @_;
11731:     if ($sortkey eq '') {
11732:         $sortkey = 'starttime';
11733:     }
11734:     my @sorted;
11735:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
11736:         @sorted =
11737:             sort {
11738:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
11739:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
11740:                      }
11741:                      if (ref($slots->{$a})) { return -1;}
11742:                      if (ref($slots->{$b})) { return 1;}
11743:                      return 0;
11744:                  } @{$slotsarr};
11745:     }
11746:     return @sorted;
11747: }
11748: 
11749: =pod
11750: 
11751: =item * get_future_slots()
11752: 
11753: Inputs:
11754: 
11755: =over 4
11756: 
11757: cnum - course number
11758: 
11759: cdom - course domain
11760: 
11761: now - current UNIX time
11762: 
11763: symb - optional symb
11764: 
11765: =back
11766: 
11767: Returns:
11768: 
11769: =over 4
11770: 
11771: sorted_reservable - ref to array of student_schedulable slots currently 
11772:                     reservable, ordered by end date of reservation period.
11773: 
11774: reservable_now - ref to hash of student_schedulable slots currently
11775:                  reservable.
11776: 
11777:     Keys in inner hash are:
11778:     (a) symb: either blank or symb to which slot use is restricted.
11779:     (b) endreserve: end date of reservation period.
11780:     (c) uniqueperiod: start,end dates when slot is to be uniquely
11781:         selected.
11782: 
11783: sorted_future - ref to array of student_schedulable slots reservable in
11784:                 the future, ordered by start date of reservation period.
11785: 
11786: future_reservable - ref to hash of student_schedulable slots reservable
11787:                     in the future.
11788: 
11789:     Keys in inner hash are:
11790:     (a) symb: either blank or symb to which slot use is restricted.
11791:     (b) startreserve: start date of reservation period.
11792:     (c) uniqueperiod: start,end dates when slot is to be uniquely
11793:         selected.
11794: 
11795: =back
11796: 
11797: =cut
11798: 
11799: sub get_future_slots {
11800:     my ($cnum,$cdom,$now,$symb) = @_;
11801:     my $map;
11802:     if ($symb) {
11803:         ($map) = &Apache::lonnet::decode_symb($symb);
11804:     }
11805:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
11806:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
11807:     foreach my $slot (keys(%slots)) {
11808:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
11809:         if ($symb) {
11810:             if ($slots{$slot}->{'symb'} ne '') {
11811:                 my $canuse;
11812:                 my %oksymbs;
11813:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
11814:                 map { $oksymbs{$_} = 1; } @slotsymbs;
11815:                 if ($oksymbs{$symb}) {
11816:                     $canuse = 1;
11817:                 } else {
11818:                     foreach my $item (@slotsymbs) {
11819:                         if ($item =~ /\.(page|sequence)$/) {
11820:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
11821:                             if (($map ne '') && ($map eq $sloturl)) {
11822:                                 $canuse = 1;
11823:                                 last;
11824:                             }
11825:                         }
11826:                     }
11827:                 }
11828:                 next unless ($canuse);
11829:             }
11830:         }
11831:         if (($slots{$slot}->{'starttime'} > $now) &&
11832:             ($slots{$slot}->{'endtime'} > $now)) {
11833:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
11834:                 my $userallowed = 0;
11835:                 if ($slots{$slot}->{'allowedsections'}) {
11836:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
11837:                     if (!defined($env{'request.role.sec'})
11838:                         && grep(/^No section assigned$/,@allowed_sec)) {
11839:                         $userallowed=1;
11840:                     } else {
11841:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
11842:                             $userallowed=1;
11843:                         }
11844:                     }
11845:                     unless ($userallowed) {
11846:                         if (defined($env{'request.course.groups'})) {
11847:                             my @groups = split(/:/,$env{'request.course.groups'});
11848:                             foreach my $group (@groups) {
11849:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
11850:                                     $userallowed=1;
11851:                                     last;
11852:                                 }
11853:                             }
11854:                         }
11855:                     }
11856:                 }
11857:                 if ($slots{$slot}->{'allowedusers'}) {
11858:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
11859:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
11860:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
11861:                         $userallowed = 1;
11862:                     }
11863:                 }
11864:                 next unless($userallowed);
11865:             }
11866:             my $startreserve = $slots{$slot}->{'startreserve'};
11867:             my $endreserve = $slots{$slot}->{'endreserve'};
11868:             my $symb = $slots{$slot}->{'symb'};
11869:             my $uniqueperiod;
11870:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
11871:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
11872:             }
11873:             if (($startreserve < $now) &&
11874:                 (!$endreserve || $endreserve > $now)) {
11875:                 my $lastres = $endreserve;
11876:                 if (!$lastres) {
11877:                     $lastres = $slots{$slot}->{'starttime'};
11878:                 }
11879:                 $reservable_now{$slot} = {
11880:                                            symb       => $symb,
11881:                                            endreserve => $lastres,
11882:                                            uniqueperiod => $uniqueperiod,
11883:                                          };
11884:             } elsif (($startreserve > $now) &&
11885:                      (!$endreserve || $endreserve > $startreserve)) {
11886:                 $future_reservable{$slot} = {
11887:                                               symb         => $symb,
11888:                                               startreserve => $startreserve,
11889:                                               uniqueperiod => $uniqueperiod,
11890:                                             };
11891:             }
11892:         }
11893:     }
11894:     my @unsorted_reservable = keys(%reservable_now);
11895:     if (@unsorted_reservable > 0) {
11896:         @sorted_reservable = 
11897:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
11898:     }
11899:     my @unsorted_future = keys(%future_reservable);
11900:     if (@unsorted_future > 0) {
11901:         @sorted_future =
11902:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
11903:     }
11904:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
11905: }
11906: 
11907: =pod
11908: 
11909: =back
11910: 
11911: =head1 HTTP Helpers
11912: 
11913: =over 4
11914: 
11915: =item * &get_unprocessed_cgi($query,$possible_names)
11916: 
11917: Modify the %env hash to contain unprocessed CGI form parameters held in
11918: $query.  The parameters listed in $possible_names (an array reference),
11919: will be set in $env{'form.name'} if they do not already exist.
11920: 
11921: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
11922: $possible_names is an ref to an array of form element names.  As an example:
11923: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
11924: will result in $env{'form.uname'} and $env{'form.udom'} being set.
11925: 
11926: =cut
11927: 
11928: sub get_unprocessed_cgi {
11929:   my ($query,$possible_names)= @_;
11930:   # $Apache::lonxml::debug=1;
11931:   foreach my $pair (split(/&/,$query)) {
11932:     my ($name, $value) = split(/=/,$pair);
11933:     $name = &unescape($name);
11934:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
11935:       $value =~ tr/+/ /;
11936:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
11937:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
11938:     }
11939:   }
11940: }
11941: 
11942: =pod
11943: 
11944: =item * &cacheheader() 
11945: 
11946: returns cache-controlling header code
11947: 
11948: =cut
11949: 
11950: sub cacheheader {
11951:     unless ($env{'request.method'} eq 'GET') { return ''; }
11952:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
11953:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
11954:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
11955:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
11956:     return $output;
11957: }
11958: 
11959: =pod
11960: 
11961: =item * &no_cache($r) 
11962: 
11963: specifies header code to not have cache
11964: 
11965: =cut
11966: 
11967: sub no_cache {
11968:     my ($r) = @_;
11969:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
11970: 	$env{'request.method'} ne 'GET') { return ''; }
11971:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
11972:     $r->no_cache(1);
11973:     $r->header_out("Expires" => $date);
11974:     $r->header_out("Pragma" => "no-cache");
11975: }
11976: 
11977: sub content_type {
11978:     my ($r,$type,$charset) = @_;
11979:     if ($r) {
11980: 	#  Note that printout.pl calls this with undef for $r.
11981: 	&no_cache($r);
11982:     }
11983:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
11984:     unless ($charset) {
11985: 	$charset=&Apache::lonlocal::current_encoding;
11986:     }
11987:     if ($charset) { $type.='; charset='.$charset; }
11988:     if ($r) {
11989: 	$r->content_type($type);
11990:     } else {
11991: 	print("Content-type: $type\n\n");
11992:     }
11993: }
11994: 
11995: =pod
11996: 
11997: =item * &add_to_env($name,$value) 
11998: 
11999: adds $name to the %env hash with value
12000: $value, if $name already exists, the entry is converted to an array
12001: reference and $value is added to the array.
12002: 
12003: =cut
12004: 
12005: sub add_to_env {
12006:   my ($name,$value)=@_;
12007:   if (defined($env{$name})) {
12008:     if (ref($env{$name})) {
12009:       #already have multiple values
12010:       push(@{ $env{$name} },$value);
12011:     } else {
12012:       #first time seeing multiple values, convert hash entry to an arrayref
12013:       my $first=$env{$name};
12014:       undef($env{$name});
12015:       push(@{ $env{$name} },$first,$value);
12016:     }
12017:   } else {
12018:     $env{$name}=$value;
12019:   }
12020: }
12021: 
12022: =pod
12023: 
12024: =item * &get_env_multiple($name) 
12025: 
12026: gets $name from the %env hash, it seemlessly handles the cases where multiple
12027: values may be defined and end up as an array ref.
12028: 
12029: returns an array of values
12030: 
12031: =cut
12032: 
12033: sub get_env_multiple {
12034:     my ($name) = @_;
12035:     my @values;
12036:     if (defined($env{$name})) {
12037:         # exists is it an array
12038:         if (ref($env{$name})) {
12039:             @values=@{ $env{$name} };
12040:         } else {
12041:             $values[0]=$env{$name};
12042:         }
12043:     }
12044:     return(@values);
12045: }
12046: 
12047: # Looks at given dependencies, and returns something depending on the context.
12048: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
12049: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
12050: # For all other contexts, returns ($output, $counter, $numpathchg).
12051: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
12052: # $counter: integer with the number of existing dependencies when no HTML output is returned, and the number of missing dependencies when an HTML output is returned.
12053: # $numpathchg: integer with the number of cleaned up dependency paths.
12054: # \%existing: hash reference clean path -> 1 only for existing dependencies.
12055: # \%mapping: hash reference clean path -> original path for all dependencies.
12056: # @param {string} actionurl - The path to the handler, indicative of the context.
12057: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
12058: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
12059: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
12060: # @param {hash reference} args - More parameters ! Possible keys: error_on_invalid_names (boolean), ignore_remote_references (boolean), current_path (string), docs_url (string), docs_title (string), context (string)
12061: # @return {Array} - array depending on the context (not a reference)
12062: sub ask_for_embedded_content {
12063:     # NOTE: documentation was added afterwards, it could be wrong
12064:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
12065:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
12066:         %currsubfile,%unused,$rem);
12067:     my $counter = 0;
12068:     my $numnew = 0;
12069:     my $numremref = 0;
12070:     my $numinvalid = 0;
12071:     my $numpathchg = 0;
12072:     my $numexisting = 0;
12073:     my $numunused = 0;
12074:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
12075:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
12076:     my $heading = &mt('Upload embedded files');
12077:     my $buttontext = &mt('Upload');
12078: 
12079:     # fills these variables based on the context:
12080:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
12081:     # $path, $fileloc, $title, $rem, $filename
12082:     if ($env{'request.course.id'}) {
12083:         if ($actionurl eq '/adm/dependencies') {
12084:             $navmap = Apache::lonnavmaps::navmap->new();
12085:         }
12086:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12087:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12088:     }
12089:     if (($actionurl eq '/adm/portfolio') || 
12090:         ($actionurl eq '/adm/coursegrp_portfolio')) {
12091:         my $current_path='/';
12092:         if ($env{'form.currentpath'}) {
12093:             $current_path = $env{'form.currentpath'};
12094:         }
12095:         if ($actionurl eq '/adm/coursegrp_portfolio') {
12096:             $udom = $cdom;
12097:             $uname = $cnum;
12098:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
12099:         } else {
12100:             $udom = $env{'user.domain'};
12101:             $uname = $env{'user.name'};
12102:             $url = '/userfiles/portfolio';
12103:         }
12104:         $toplevel = $url.'/';
12105:         $url .= $current_path;
12106:         $getpropath = 1;
12107:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
12108:              ($actionurl eq '/adm/imsimport')) { 
12109:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
12110:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
12111:         $toplevel = $url;
12112:         if ($rest ne '') {
12113:             $url .= $rest;
12114:         }
12115:     } elsif ($actionurl eq '/adm/coursedocs') {
12116:         if (ref($args) eq 'HASH') {
12117:             $url = $args->{'docs_url'};
12118:             $toplevel = $url;
12119:             if ($args->{'context'} eq 'paste') {
12120:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
12121:                 ($path) = 
12122:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
12123:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
12124:                 $fileloc =~ s{^/}{};
12125:             }
12126:         }
12127:     } elsif ($actionurl eq '/adm/dependencies')  {
12128:         if ($env{'request.course.id'} ne '') {
12129:             if (ref($args) eq 'HASH') {
12130:                 $url = $args->{'docs_url'};
12131:                 $title = $args->{'docs_title'};
12132:                 $toplevel = $url; 
12133:                 unless ($toplevel =~ m{^/}) {
12134:                     $toplevel = "/$url";
12135:                 }
12136:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
12137:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
12138:                     $path = $1;
12139:                 } else {
12140:                     ($path) =
12141:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
12142:                 }
12143:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
12144:                     $fileloc = $toplevel;
12145:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
12146:                     my ($udom,$uname,$fname) =
12147:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
12148:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
12149:                 } else {
12150:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
12151:                 }
12152:                 $fileloc =~ s{^/}{};
12153:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
12154:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
12155:             }
12156:         }
12157:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
12158:         $udom = $cdom;
12159:         $uname = $cnum;
12160:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
12161:         $toplevel = $url;
12162:         $path = $url;
12163:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
12164:         $fileloc =~ s{^/}{};
12165:     }
12166:     
12167:     # parses the dependency paths to get some info
12168:     # fills $newfiles, $mapping, $subdependencies, $dependencies
12169:     # $newfiles: hash URL -> 1 for new files or external URLs
12170:     # (will be completed later)
12171:     # $mapping:
12172:     #   for external URLs: external URL -> external URL
12173:     #   for relative paths: clean path -> original path
12174:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
12175:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
12176:     foreach my $file (keys(%{$allfiles})) {
12177:         my $embed_file;
12178:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
12179:             $embed_file = $1;
12180:         } else {
12181:             $embed_file = $file;
12182:         }
12183:         my ($absolutepath,$cleaned_file);
12184:         if ($embed_file =~ m{^\w+://}) {
12185:             $cleaned_file = $embed_file;
12186:             $newfiles{$cleaned_file} = 1;
12187:             $mapping{$cleaned_file} = $embed_file;
12188:         } else {
12189:             $cleaned_file = &clean_path($embed_file);
12190:             if ($embed_file =~ m{^/}) {
12191:                 $absolutepath = $embed_file;
12192:             }
12193:             if ($cleaned_file =~ m{/}) {
12194:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
12195:                 $path = &check_for_traversal($path,$url,$toplevel);
12196:                 my $item = $fname;
12197:                 if ($path ne '') {
12198:                     $item = $path.'/'.$fname;
12199:                     $subdependencies{$path}{$fname} = 1;
12200:                 } else {
12201:                     $dependencies{$item} = 1;
12202:                 }
12203:                 if ($absolutepath) {
12204:                     $mapping{$item} = $absolutepath;
12205:                 } else {
12206:                     $mapping{$item} = $embed_file;
12207:                 }
12208:             } else {
12209:                 $dependencies{$embed_file} = 1;
12210:                 if ($absolutepath) {
12211:                     $mapping{$cleaned_file} = $absolutepath;
12212:                 } else {
12213:                     $mapping{$cleaned_file} = $embed_file;
12214:                 }
12215:             }
12216:         }
12217:     }
12218:     
12219:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
12220:     # and lists
12221:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
12222:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
12223:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
12224:     #                                    the path had to be cleaned up
12225:     # $existing: hash clean path -> 1 if the file exists
12226:     # $numexisting: number of keys in $existing
12227:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
12228:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
12229:     #                                      dependency subdirectories that are
12230:     #                                      not listed as dependencies, with some exceptions using $rem
12231:     my $dirptr = 16384;
12232:     foreach my $path (keys(%subdependencies)) {
12233:         $currsubfile{$path} = {};
12234:         if (($actionurl eq '/adm/portfolio') || 
12235:             ($actionurl eq '/adm/coursegrp_portfolio')) {
12236:             my ($sublistref,$listerror) =
12237:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
12238:             if (ref($sublistref) eq 'ARRAY') {
12239:                 foreach my $line (@{$sublistref}) {
12240:                     my ($file_name,$rest) = split(/\&/,$line,2);
12241:                     $currsubfile{$path}{$file_name} = 1;
12242:                 }
12243:             }
12244:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12245:             if (opendir(my $dir,$url.'/'.$path)) {
12246:                 my @subdir_list = grep(!/^\./,readdir($dir));
12247:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
12248:             }
12249:         } elsif (($actionurl eq '/adm/dependencies') ||
12250:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
12251:                   ($args->{'context'} eq 'paste')) ||
12252:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
12253:             if ($env{'request.course.id'} ne '') {
12254:                 my $dir;
12255:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
12256:                     $dir = $fileloc;
12257:                 } else {
12258:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
12259:                 }
12260:                 if ($dir ne '') {
12261:                     my ($sublistref,$listerror) =
12262:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
12263:                     if (ref($sublistref) eq 'ARRAY') {
12264:                         foreach my $line (@{$sublistref}) {
12265:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
12266:                                 undef,$mtime)=split(/\&/,$line,12);
12267:                             unless (($testdir&$dirptr) ||
12268:                                     ($file_name =~ /^\.\.?$/)) {
12269:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
12270:                             }
12271:                         }
12272:                     }
12273:                 }
12274:             }
12275:         }
12276:         foreach my $file (keys(%{$subdependencies{$path}})) {
12277:             if (exists($currsubfile{$path}{$file})) {
12278:                 my $item = $path.'/'.$file;
12279:                 unless ($mapping{$item} eq $item) {
12280:                     $pathchanges{$item} = 1;
12281:                 }
12282:                 $existing{$item} = 1;
12283:                 $numexisting ++;
12284:             } else {
12285:                 $newfiles{$path.'/'.$file} = 1;
12286:             }
12287:         }
12288:         if ($actionurl eq '/adm/dependencies') {
12289:             foreach my $path (keys(%currsubfile)) {
12290:                 if (ref($currsubfile{$path}) eq 'HASH') {
12291:                     foreach my $file (keys(%{$currsubfile{$path}})) {
12292:                          unless ($subdependencies{$path}{$file}) {
12293:                              next if (($rem ne '') &&
12294:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
12295:                                        (ref($navmap) &&
12296:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
12297:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
12298:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
12299:                              $unused{$path.'/'.$file} = 1; 
12300:                          }
12301:                     }
12302:                 }
12303:             }
12304:         }
12305:     }
12306:     
12307:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
12308:     # for files in $url or $fileloc (target directory) in some contexts
12309:     my %currfile;
12310:     if (($actionurl eq '/adm/portfolio') ||
12311:         ($actionurl eq '/adm/coursegrp_portfolio')) {
12312:         my ($dirlistref,$listerror) =
12313:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
12314:         if (ref($dirlistref) eq 'ARRAY') {
12315:             foreach my $line (@{$dirlistref}) {
12316:                 my ($file_name,$rest) = split(/\&/,$line,2);
12317:                 $currfile{$file_name} = 1;
12318:             }
12319:         }
12320:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12321:         if (opendir(my $dir,$url)) {
12322:             my @dir_list = grep(!/^\./,readdir($dir));
12323:             map {$currfile{$_} = 1;} @dir_list;
12324:         }
12325:     } elsif (($actionurl eq '/adm/dependencies') ||
12326:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
12327:               ($args->{'context'} eq 'paste')) ||
12328:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
12329:         if ($env{'request.course.id'} ne '') {
12330:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
12331:             if ($dir ne '') {
12332:                 my ($dirlistref,$listerror) =
12333:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
12334:                 if (ref($dirlistref) eq 'ARRAY') {
12335:                     foreach my $line (@{$dirlistref}) {
12336:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
12337:                             $size,undef,$mtime)=split(/\&/,$line,12);
12338:                         unless (($testdir&$dirptr) ||
12339:                                 ($file_name =~ /^\.\.?$/)) {
12340:                             $currfile{$file_name} = [$size,$mtime];
12341:                         }
12342:                     }
12343:                 }
12344:             }
12345:         }
12346:     }
12347:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
12348:     # are not in subdirectories, using $currfile
12349:     foreach my $file (keys(%dependencies)) {
12350:         if (exists($currfile{$file})) {
12351:             unless ($mapping{$file} eq $file) {
12352:                 $pathchanges{$file} = 1;
12353:             }
12354:             $existing{$file} = 1;
12355:             $numexisting ++;
12356:         } else {
12357:             $newfiles{$file} = 1;
12358:         }
12359:     }
12360:     foreach my $file (keys(%currfile)) {
12361:         unless (($file eq $filename) ||
12362:                 ($file eq $filename.'.bak') ||
12363:                 ($dependencies{$file})) {
12364:             if ($actionurl eq '/adm/dependencies') {
12365:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
12366:                     next if (($rem ne '') &&
12367:                              (($env{"httpref.$rem".$file} ne '') ||
12368:                               (ref($navmap) &&
12369:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
12370:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
12371:                                 ($navmap->getResourceByUrl($rem.$1)))))));
12372:                 }
12373:             }
12374:             $unused{$file} = 1;
12375:         }
12376:     }
12377:     
12378:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
12379:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
12380:         ($args->{'context'} eq 'paste')) {
12381:         $counter = scalar(keys(%existing));
12382:         $numpathchg = scalar(keys(%pathchanges));
12383:         return ($output,$counter,$numpathchg,\%existing);
12384:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
12385:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
12386:         $counter = scalar(keys(%existing));
12387:         $numpathchg = scalar(keys(%pathchanges));
12388:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
12389:     }
12390:     
12391:     # returns HTML otherwise, with dependency results and to ask for more uploads
12392:     
12393:     # $upload_output: missing dependencies (with upload form)
12394:     # $modify_output: uploaded dependencies (in use)
12395:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
12396:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
12397:         if ($actionurl eq '/adm/dependencies') {
12398:             next if ($embed_file =~ m{^\w+://});
12399:         }
12400:         $upload_output .= &start_data_table_row().
12401:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
12402:                           '<span class="LC_filename">'.$embed_file.'</span>';
12403:         unless ($mapping{$embed_file} eq $embed_file) {
12404:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
12405:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
12406:         }
12407:         $upload_output .= '</td>';
12408:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
12409:             $upload_output.='<td align="right">'.
12410:                             '<span class="LC_info LC_fontsize_medium">'.
12411:                             &mt("URL points to web address").'</span>';
12412:             $numremref++;
12413:         } elsif ($args->{'error_on_invalid_names'}
12414:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
12415:             $upload_output.='<td align="right"><span class="LC_warning">'.
12416:                             &mt('Invalid characters').'</span>';
12417:             $numinvalid++;
12418:         } else {
12419:             $upload_output .= '<td>'.
12420:                               &embedded_file_element('upload_embedded',$counter,
12421:                                                      $embed_file,\%mapping,
12422:                                                      $allfiles,$codebase,'upload');
12423:             $counter ++;
12424:             $numnew ++;
12425:         }
12426:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
12427:     }
12428:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
12429:         if ($actionurl eq '/adm/dependencies') {
12430:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
12431:             $modify_output .= &start_data_table_row().
12432:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
12433:                               '<img src="'.&icon($embed_file).'" border="0" />'.
12434:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
12435:                               '<td>'.$size.'</td>'.
12436:                               '<td>'.$mtime.'</td>'.
12437:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
12438:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
12439:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
12440:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
12441:                               &embedded_file_element('upload_embedded',$counter,
12442:                                                      $embed_file,\%mapping,
12443:                                                      $allfiles,$codebase,'modify').
12444:                               '</div></td>'.
12445:                               &end_data_table_row()."\n";
12446:             $counter ++;
12447:         } else {
12448:             $upload_output .= &start_data_table_row().
12449:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
12450:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
12451:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
12452:                               &Apache::loncommon::end_data_table_row()."\n";
12453:         }
12454:     }
12455:     my $delidx = $counter;
12456:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
12457:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
12458:         $delete_output .= &start_data_table_row().
12459:                           '<td><img src="'.&icon($oldfile).'" />'.
12460:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
12461:                           '<td>'.$size.'</td>'.
12462:                           '<td>'.$mtime.'</td>'.
12463:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
12464:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
12465:                           &embedded_file_element('upload_embedded',$delidx,
12466:                                                  $oldfile,\%mapping,$allfiles,
12467:                                                  $codebase,'delete').'</td>'.
12468:                           &end_data_table_row()."\n"; 
12469:         $numunused ++;
12470:         $delidx ++;
12471:     }
12472:     if ($upload_output) {
12473:         $upload_output = &start_data_table().
12474:                          $upload_output.
12475:                          &end_data_table()."\n";
12476:     }
12477:     if ($modify_output) {
12478:         $modify_output = &start_data_table().
12479:                          &start_data_table_header_row().
12480:                          '<th>'.&mt('File').'</th>'.
12481:                          '<th>'.&mt('Size (KB)').'</th>'.
12482:                          '<th>'.&mt('Modified').'</th>'.
12483:                          '<th>'.&mt('Upload replacement?').'</th>'.
12484:                          &end_data_table_header_row().
12485:                          $modify_output.
12486:                          &end_data_table()."\n";
12487:     }
12488:     if ($delete_output) {
12489:         $delete_output = &start_data_table().
12490:                          &start_data_table_header_row().
12491:                          '<th>'.&mt('File').'</th>'.
12492:                          '<th>'.&mt('Size (KB)').'</th>'.
12493:                          '<th>'.&mt('Modified').'</th>'.
12494:                          '<th>'.&mt('Delete?').'</th>'.
12495:                          &end_data_table_header_row().
12496:                          $delete_output.
12497:                          &end_data_table()."\n";
12498:     }
12499:     my $applies = 0;
12500:     if ($numremref) {
12501:         $applies ++;
12502:     }
12503:     if ($numinvalid) {
12504:         $applies ++;
12505:     }
12506:     if ($numexisting) {
12507:         $applies ++;
12508:     }
12509:     if ($counter || $numunused) {
12510:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
12511:                   ' method="post" enctype="multipart/form-data">'."\n".
12512:                   $state.'<h3>'.$heading.'</h3>'; 
12513:         if ($actionurl eq '/adm/dependencies') {
12514:             if ($numnew) {
12515:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
12516:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
12517:                            $upload_output.'<br />'."\n";
12518:             }
12519:             if ($numexisting) {
12520:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
12521:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
12522:                            $modify_output.'<br />'."\n";
12523:                            $buttontext = &mt('Save changes');
12524:             }
12525:             if ($numunused) {
12526:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
12527:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
12528:                            $delete_output.'<br />'."\n";
12529:                            $buttontext = &mt('Save changes');
12530:             }
12531:         } else {
12532:             $output .= $upload_output.'<br />'."\n";
12533:         }
12534:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
12535:                    $counter.'" />'."\n";
12536:         if ($actionurl eq '/adm/dependencies') { 
12537:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
12538:                        $numnew.'" />'."\n";
12539:         } elsif ($actionurl eq '') {
12540:             $output .=  '<input type="hidden" name="phase" value="three" />';
12541:         }
12542:     } elsif ($applies) {
12543:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
12544:         if ($applies > 1) {
12545:             $output .=  
12546:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
12547:             if ($numremref) {
12548:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
12549:             }
12550:             if ($numinvalid) {
12551:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
12552:             }
12553:             if ($numexisting) {
12554:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
12555:             }
12556:             $output .= '</ul><br />';
12557:         } elsif ($numremref) {
12558:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
12559:         } elsif ($numinvalid) {
12560:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
12561:         } elsif ($numexisting) {
12562:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
12563:         }
12564:         $output .= $upload_output.'<br />';
12565:     }
12566:     my ($pathchange_output,$chgcount);
12567:     $chgcount = $counter;
12568:     if (keys(%pathchanges) > 0) {
12569:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
12570:             if ($counter) {
12571:                 $output .= &embedded_file_element('pathchange',$chgcount,
12572:                                                   $embed_file,\%mapping,
12573:                                                   $allfiles,$codebase,'change');
12574:             } else {
12575:                 $pathchange_output .= 
12576:                     &start_data_table_row().
12577:                     '<td><input type ="checkbox" name="namechange" value="'.
12578:                     $chgcount.'" checked="checked" /></td>'.
12579:                     '<td>'.$mapping{$embed_file}.'</td>'.
12580:                     '<td>'.$embed_file.
12581:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
12582:                                            \%mapping,$allfiles,$codebase,'change').
12583:                     '</td>'.&end_data_table_row();
12584:             }
12585:             $numpathchg ++;
12586:             $chgcount ++;
12587:         }
12588:     }
12589:     if (($counter) || ($numunused)) {
12590:         if ($numpathchg) {
12591:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
12592:                        $numpathchg.'" />'."\n";
12593:         }
12594:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
12595:             ($actionurl eq '/adm/imsimport')) {
12596:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
12597:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
12598:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
12599:         } elsif ($actionurl eq '/adm/dependencies') {
12600:             $output .= '<input type="hidden" name="action" value="process_changes" />';
12601:         }
12602:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
12603:     } elsif ($numpathchg) {
12604:         my %pathchange = ();
12605:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
12606:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
12607:             $output .= '<p>'.&mt('or').'</p>'; 
12608:         }
12609:     }
12610:     return ($output,$counter,$numpathchg);
12611: }
12612: 
12613: =pod
12614: 
12615: =item * clean_path($name)
12616: 
12617: Performs clean-up of directories, subdirectories and filename in an
12618: embedded object, referenced in an HTML file which is being uploaded
12619: to a course or portfolio, where 
12620: "Upload embedded images/multimedia files if HTML file" checkbox was
12621: checked.
12622: 
12623: Clean-up is similar to replacements in lonnet::clean_filename()
12624: except each / between sub-directory and next level is preserved.
12625: 
12626: =cut
12627: 
12628: sub clean_path {
12629:     my ($embed_file) = @_;
12630:     $embed_file =~s{^/+}{};
12631:     my @contents;
12632:     if ($embed_file =~ m{/}) {
12633:         @contents = split(/\//,$embed_file);
12634:     } else {
12635:         @contents = ($embed_file);
12636:     }
12637:     my $lastidx = scalar(@contents)-1;
12638:     for (my $i=0; $i<=$lastidx; $i++) { 
12639:         $contents[$i]=~s{\\}{/}g;
12640:         $contents[$i]=~s/\s+/\_/g;
12641:         $contents[$i]=~s{[^/\w\.\-]}{}g;
12642:         if ($i == $lastidx) {
12643:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
12644:         }
12645:     }
12646:     if ($lastidx > 0) {
12647:         return join('/',@contents);
12648:     } else {
12649:         return $contents[0];
12650:     }
12651: }
12652: 
12653: sub embedded_file_element {
12654:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
12655:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
12656:                    (ref($codebase) eq 'HASH'));
12657:     my $output;
12658:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
12659:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
12660:     }
12661:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
12662:                &escape($embed_file).'" />';
12663:     unless (($context eq 'upload_embedded') && 
12664:             ($mapping->{$embed_file} eq $embed_file)) {
12665:         $output .='
12666:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
12667:     }
12668:     my $attrib;
12669:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
12670:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
12671:     }
12672:     $output .=
12673:         "\n\t\t".
12674:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
12675:         $attrib.'" />';
12676:     if (exists($codebase->{$mapping->{$embed_file}})) {
12677:         $output .=
12678:             "\n\t\t".
12679:             '<input name="codebase_'.$num.'" type="hidden" value="'.
12680:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
12681:     }
12682:     return $output;
12683: }
12684: 
12685: sub get_dependency_details {
12686:     my ($currfile,$currsubfile,$embed_file) = @_;
12687:     my ($size,$mtime,$showsize,$showmtime);
12688:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
12689:         if ($embed_file =~ m{/}) {
12690:             my ($path,$fname) = split(/\//,$embed_file);
12691:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
12692:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
12693:             }
12694:         } else {
12695:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
12696:                 ($size,$mtime) = @{$currfile->{$embed_file}};
12697:             }
12698:         }
12699:         $showsize = $size/1024.0;
12700:         $showsize = sprintf("%.1f",$showsize);
12701:         if ($mtime > 0) {
12702:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
12703:         }
12704:     }
12705:     return ($showsize,$showmtime);
12706: }
12707: 
12708: sub ask_embedded_js {
12709:     return <<"END";
12710: <script type="text/javascript"">
12711: // <![CDATA[
12712: function toggleBrowse(counter) {
12713:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
12714:     var fileid = document.getElementById('embedded_item_'+counter);
12715:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
12716:     if (chkboxid.checked == true) {
12717:         uploaddivid.style.display='block';
12718:     } else {
12719:         uploaddivid.style.display='none';
12720:         fileid.value = '';
12721:     }
12722: }
12723: // ]]>
12724: </script>
12725: 
12726: END
12727: }
12728: 
12729: sub upload_embedded {
12730:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
12731:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
12732:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
12733:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
12734:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
12735:         my $orig_uploaded_filename =
12736:             $env{'form.embedded_item_'.$i.'.filename'};
12737:         foreach my $type ('orig','ref','attrib','codebase') {
12738:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
12739:                 $env{'form.embedded_'.$type.'_'.$i} =
12740:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
12741:             }
12742:         }
12743:         my ($path,$fname) =
12744:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
12745:         # no path, whole string is fname
12746:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
12747:         $fname = &Apache::lonnet::clean_filename($fname);
12748:         # See if there is anything left
12749:         next if ($fname eq '');
12750: 
12751:         # Check if file already exists as a file or directory.
12752:         my ($state,$msg);
12753:         if ($context eq 'portfolio') {
12754:             my $port_path = $dirpath;
12755:             if ($group ne '') {
12756:                 $port_path = "groups/$group/$port_path";
12757:             }
12758:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
12759:                                               $fname,$group,'embedded_item_'.$i,
12760:                                               $dir_root,$port_path,$disk_quota,
12761:                                               $current_disk_usage,$uname,$udom);
12762:             if ($state eq 'will_exceed_quota'
12763:                 || $state eq 'file_locked') {
12764:                 $output .= $msg;
12765:                 next;
12766:             }
12767:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
12768:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
12769:             if ($state eq 'exists') {
12770:                 $output .= $msg;
12771:                 next;
12772:             }
12773:         }
12774:         # Check if extension is valid
12775:         if (($fname =~ /\.(\w+)$/) &&
12776:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
12777:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
12778:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
12779:             next;
12780:         } elsif (($fname =~ /\.(\w+)$/) &&
12781:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
12782:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
12783:             next;
12784:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
12785:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
12786:             next;
12787:         }
12788:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
12789:         my $subdir = $path;
12790:         $subdir =~ s{/+$}{};
12791:         if ($context eq 'portfolio') {
12792:             my $result;
12793:             if ($state eq 'existingfile') {
12794:                 $result=
12795:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
12796:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
12797:             } else {
12798:                 $result=
12799:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
12800:                                                     $dirpath.
12801:                                                     $env{'form.currentpath'}.$subdir);
12802:                 if ($result !~ m|^/uploaded/|) {
12803:                     $output .= '<span class="LC_error">'
12804:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
12805:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
12806:                                .'</span><br />';
12807:                     next;
12808:                 } else {
12809:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
12810:                                $path.$fname.'</span>').'<br />';     
12811:                 }
12812:             }
12813:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
12814:             my $extendedsubdir = $dirpath.'/'.$subdir;
12815:             $extendedsubdir =~ s{/+$}{};
12816:             my $result =
12817:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
12818:             if ($result !~ m|^/uploaded/|) {
12819:                 $output .= '<span class="LC_error">'
12820:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
12821:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
12822:                            .'</span><br />';
12823:                     next;
12824:             } else {
12825:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
12826:                            $path.$fname.'</span>').'<br />';
12827:                 if ($context eq 'syllabus') {
12828:                     &Apache::lonnet::make_public_indefinitely($result);
12829:                 }
12830:             }
12831:         } else {
12832: # Save the file
12833:             my $target = $env{'form.embedded_item_'.$i};
12834:             my $fullpath = $dir_root.$dirpath.'/'.$path;
12835:             my $dest = $fullpath.$fname;
12836:             my $url = $url_root.$dirpath.'/'.$path.$fname;
12837:             my @parts=split(/\//,"$dirpath/$path");
12838:             my $count;
12839:             my $filepath = $dir_root;
12840:             foreach my $subdir (@parts) {
12841:                 $filepath .= "/$subdir";
12842:                 if (!-e $filepath) {
12843:                     mkdir($filepath,0770);
12844:                 }
12845:             }
12846:             my $fh;
12847:             if (!open($fh,'>'.$dest)) {
12848:                 &Apache::lonnet::logthis('Failed to create '.$dest);
12849:                 $output .= '<span class="LC_error">'.
12850:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
12851:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
12852:                            '</span><br />';
12853:             } else {
12854:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
12855:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
12856:                     $output .= '<span class="LC_error">'.
12857:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
12858:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
12859:                               '</span><br />';
12860:                 } else {
12861:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
12862:                                $url.'</span>').'<br />';
12863:                     unless ($context eq 'testbank') {
12864:                         $footer .= &mt('View embedded file: [_1]',
12865:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
12866:                     }
12867:                 }
12868:                 close($fh);
12869:             }
12870:         }
12871:         if ($env{'form.embedded_ref_'.$i}) {
12872:             $pathchange{$i} = 1;
12873:         }
12874:     }
12875:     if ($output) {
12876:         $output = '<p>'.$output.'</p>';
12877:     }
12878:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
12879:     $returnflag = 'ok';
12880:     my $numpathchgs = scalar(keys(%pathchange));
12881:     if ($numpathchgs > 0) {
12882:         if ($context eq 'portfolio') {
12883:             $output .= '<p>'.&mt('or').'</p>';
12884:         } elsif ($context eq 'testbank') {
12885:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
12886:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
12887:             $returnflag = 'modify_orightml';
12888:         }
12889:     }
12890:     return ($output.$footer,$returnflag,$numpathchgs);
12891: }
12892: 
12893: sub modify_html_form {
12894:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
12895:     my $end = 0;
12896:     my $modifyform;
12897:     if ($context eq 'upload_embedded') {
12898:         return unless (ref($pathchange) eq 'HASH');
12899:         if ($env{'form.number_embedded_items'}) {
12900:             $end += $env{'form.number_embedded_items'};
12901:         }
12902:         if ($env{'form.number_pathchange_items'}) {
12903:             $end += $env{'form.number_pathchange_items'};
12904:         }
12905:         if ($end) {
12906:             for (my $i=0; $i<$end; $i++) {
12907:                 if ($i < $env{'form.number_embedded_items'}) {
12908:                     next unless($pathchange->{$i});
12909:                 }
12910:                 $modifyform .=
12911:                     &start_data_table_row().
12912:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
12913:                     'checked="checked" /></td>'.
12914:                     '<td>'.$env{'form.embedded_ref_'.$i}.
12915:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
12916:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
12917:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
12918:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
12919:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
12920:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
12921:                     '<td>'.$env{'form.embedded_orig_'.$i}.
12922:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
12923:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
12924:                     &end_data_table_row();
12925:             }
12926:         }
12927:     } else {
12928:         $modifyform = $pathchgtable;
12929:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12930:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
12931:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
12932:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
12933:         }
12934:     }
12935:     if ($modifyform) {
12936:         if ($actionurl eq '/adm/dependencies') {
12937:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
12938:         }
12939:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
12940:                '<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".
12941:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
12942:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
12943:                '</ol></p>'."\n".'<p>'.
12944:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
12945:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
12946:                &start_data_table()."\n".
12947:                &start_data_table_header_row().
12948:                '<th>'.&mt('Change?').'</th>'.
12949:                '<th>'.&mt('Current reference').'</th>'.
12950:                '<th>'.&mt('Required reference').'</th>'.
12951:                &end_data_table_header_row()."\n".
12952:                $modifyform.
12953:                &end_data_table().'<br />'."\n".$hiddenstate.
12954:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
12955:                '</form>'."\n";
12956:     }
12957:     return;
12958: }
12959: 
12960: sub modify_html_refs {
12961:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
12962:     my $container;
12963:     if ($context eq 'portfolio') {
12964:         $container = $env{'form.container'};
12965:     } elsif ($context eq 'coursedoc') {
12966:         $container = $env{'form.primaryurl'};
12967:     } elsif ($context eq 'manage_dependencies') {
12968:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
12969:         $container = "/$container";
12970:     } elsif ($context eq 'syllabus') {
12971:         $container = $url;
12972:     } else {
12973:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
12974:     }
12975:     my (%allfiles,%codebase,$output,$content);
12976:     my @changes = &get_env_multiple('form.namechange');
12977:     unless ((@changes > 0) || ($context eq 'syllabus')) {
12978:         if (wantarray) {
12979:             return ('',0,0); 
12980:         } else {
12981:             return;
12982:         }
12983:     }
12984:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
12985:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
12986:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
12987:             if (wantarray) {
12988:                 return ('',0,0);
12989:             } else {
12990:                 return;
12991:             }
12992:         } 
12993:         $content = &Apache::lonnet::getfile($container);
12994:         if ($content eq '-1') {
12995:             if (wantarray) {
12996:                 return ('',0,0);
12997:             } else {
12998:                 return;
12999:             }
13000:         }
13001:     } else {
13002:         unless ($container =~ /^\Q$dir_root\E/) {
13003:             if (wantarray) {
13004:                 return ('',0,0);
13005:             } else {
13006:                 return;
13007:             }
13008:         } 
13009:         if (open(my $fh,'<',$container)) {
13010:             $content = join('', <$fh>);
13011:             close($fh);
13012:         } else {
13013:             if (wantarray) {
13014:                 return ('',0,0);
13015:             } else {
13016:                 return;
13017:             }
13018:         }
13019:     }
13020:     my ($count,$codebasecount) = (0,0);
13021:     my $mm = new File::MMagic;
13022:     my $mime_type = $mm->checktype_contents($content);
13023:     if ($mime_type eq 'text/html') {
13024:         my $parse_result = 
13025:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
13026:                                                     \%codebase,\$content);
13027:         if ($parse_result eq 'ok') {
13028:             foreach my $i (@changes) {
13029:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
13030:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
13031:                 if ($allfiles{$ref}) {
13032:                     my $newname =  $orig;
13033:                     my ($attrib_regexp,$codebase);
13034:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
13035:                     if ($attrib_regexp =~ /:/) {
13036:                         $attrib_regexp =~ s/\:/|/g;
13037:                     }
13038:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
13039:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
13040:                         $count += $numchg;
13041:                         $allfiles{$newname} = $allfiles{$ref};
13042:                         delete($allfiles{$ref});
13043:                     }
13044:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
13045:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
13046:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
13047:                         $codebasecount ++;
13048:                     }
13049:                 }
13050:             }
13051:             my $skiprewrites;
13052:             if ($count || $codebasecount) {
13053:                 my $saveresult;
13054:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
13055:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
13056:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
13057:                     if ($url eq $container) {
13058:                         my ($fname) = ($container =~ m{/([^/]+)$});
13059:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
13060:                                             $count,'<span class="LC_filename">'.
13061:                                             $fname.'</span>').'</p>';
13062:                     } else {
13063:                          $output = '<p class="LC_error">'.
13064:                                    &mt('Error: update failed for: [_1].',
13065:                                    '<span class="LC_filename">'.
13066:                                    $container.'</span>').'</p>';
13067:                     }
13068:                     if ($context eq 'syllabus') {
13069:                         unless ($saveresult eq 'ok') {
13070:                             $skiprewrites = 1;
13071:                         }
13072:                     }
13073:                 } else {
13074:                     if (open(my $fh,'>',$container)) {
13075:                         print $fh $content;
13076:                         close($fh);
13077:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
13078:                                   $count,'<span class="LC_filename">'.
13079:                                   $container.'</span>').'</p>';
13080:                     } else {
13081:                          $output = '<p class="LC_error">'.
13082:                                    &mt('Error: could not update [_1].',
13083:                                    '<span class="LC_filename">'.
13084:                                    $container.'</span>').'</p>';
13085:                     }
13086:                 }
13087:             }
13088:             if (($context eq 'syllabus') && (!$skiprewrites)) {
13089:                 my ($actionurl,$state);
13090:                 $actionurl = "/public/$udom/$uname/syllabus";
13091:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
13092:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
13093:                                               \%codebase,
13094:                                               {'context' => 'rewrites',
13095:                                                'ignore_remote_references' => 1,});
13096:                 if (ref($mapping) eq 'HASH') {
13097:                     my $rewrites = 0;
13098:                     foreach my $key (keys(%{$mapping})) {
13099:                         next if ($key =~ m{^https?://});
13100:                         my $ref = $mapping->{$key};
13101:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
13102:                         my $attrib;
13103:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
13104:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
13105:                         }
13106:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
13107:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
13108:                             $rewrites += $numchg;
13109:                         }
13110:                     }
13111:                     if ($rewrites) {
13112:                         my $saveresult; 
13113:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
13114:                         if ($url eq $container) {
13115:                             my ($fname) = ($container =~ m{/([^/]+)$});
13116:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
13117:                                             $count,'<span class="LC_filename">'.
13118:                                             $fname.'</span>').'</p>';
13119:                         } else {
13120:                             $output .= '<p class="LC_error">'.
13121:                                        &mt('Error: could not update links in [_1].',
13122:                                        '<span class="LC_filename">'.
13123:                                        $container.'</span>').'</p>';
13124: 
13125:                         }
13126:                     }
13127:                 }
13128:             }
13129:         } else {
13130:             &logthis('Failed to parse '.$container.
13131:                      ' to modify references: '.$parse_result);
13132:         }
13133:     }
13134:     if (wantarray) {
13135:         return ($output,$count,$codebasecount);
13136:     } else {
13137:         return $output;
13138:     }
13139: }
13140: 
13141: sub check_for_existing {
13142:     my ($path,$fname,$element) = @_;
13143:     my ($state,$msg);
13144:     if (-d $path.'/'.$fname) {
13145:         $state = 'exists';
13146:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
13147:     } elsif (-e $path.'/'.$fname) {
13148:         $state = 'exists';
13149:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
13150:     }
13151:     if ($state eq 'exists') {
13152:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
13153:     }
13154:     return ($state,$msg);
13155: }
13156: 
13157: sub check_for_upload {
13158:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
13159:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
13160:     my $filesize = length($env{'form.'.$element});
13161:     if (!$filesize) {
13162:         my $msg = '<span class="LC_error">'.
13163:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
13164:                       '<span class="LC_filename">'.$fname.'</span>',
13165:                       $filesize).'<br />'.
13166:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
13167:                   '</span>';
13168:         return ('zero_bytes',$msg);
13169:     }
13170:     $filesize =  $filesize/1000; #express in k (1024?)
13171:     my $getpropath = 1;
13172:     my ($dirlistref,$listerror) =
13173:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
13174:     my $found_file = 0;
13175:     my $locked_file = 0;
13176:     my @lockers;
13177:     my $navmap;
13178:     if ($env{'request.course.id'}) {
13179:         $navmap = Apache::lonnavmaps::navmap->new();
13180:     }
13181:     if (ref($dirlistref) eq 'ARRAY') {
13182:         foreach my $line (@{$dirlistref}) {
13183:             my ($file_name,$rest)=split(/\&/,$line,2);
13184:             if ($file_name eq $fname){
13185:                 $file_name = $path.$file_name;
13186:                 if ($group ne '') {
13187:                     $file_name = $group.$file_name;
13188:                 }
13189:                 $found_file = 1;
13190:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
13191:                     foreach my $lock (@lockers) {
13192:                         if (ref($lock) eq 'ARRAY') {
13193:                             my ($symb,$crsid) = @{$lock};
13194:                             if ($crsid eq $env{'request.course.id'}) {
13195:                                 if (ref($navmap)) {
13196:                                     my $res = $navmap->getBySymb($symb);
13197:                                     foreach my $part (@{$res->parts()}) { 
13198:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
13199:                                         unless (($slot_status == $res->RESERVED) ||
13200:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
13201:                                             $locked_file = 1;
13202:                                         }
13203:                                     }
13204:                                 } else {
13205:                                     $locked_file = 1;
13206:                                 }
13207:                             } else {
13208:                                 $locked_file = 1;
13209:                             }
13210:                         }
13211:                    }
13212:                 } else {
13213:                     my @info = split(/\&/,$rest);
13214:                     my $currsize = $info[6]/1000;
13215:                     if ($currsize < $filesize) {
13216:                         my $extra = $filesize - $currsize;
13217:                         if (($current_disk_usage + $extra) > $disk_quota) {
13218:                             my $msg = '<p class="LC_warning">'.
13219:                                       &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.',
13220:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
13221:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
13222:                                                    $disk_quota,$current_disk_usage).'</p>';
13223:                             return ('will_exceed_quota',$msg);
13224:                         }
13225:                     }
13226:                 }
13227:             }
13228:         }
13229:     }
13230:     if (($current_disk_usage + $filesize) > $disk_quota){
13231:         my $msg = '<p class="LC_warning">'.
13232:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
13233:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
13234:         return ('will_exceed_quota',$msg);
13235:     } elsif ($found_file) {
13236:         if ($locked_file) {
13237:             my $msg = '<p class="LC_warning">';
13238:             $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>');
13239:             $msg .= '</p>';
13240:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
13241:             return ('file_locked',$msg);
13242:         } else {
13243:             my $msg = '<p class="LC_error">';
13244:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
13245:             $msg .= '</p>';
13246:             return ('existingfile',$msg);
13247:         }
13248:     }
13249: }
13250: 
13251: sub check_for_traversal {
13252:     my ($path,$url,$toplevel) = @_;
13253:     my @parts=split(/\//,$path);
13254:     my $cleanpath;
13255:     my $fullpath = $url;
13256:     for (my $i=0;$i<@parts;$i++) {
13257:         next if ($parts[$i] eq '.');
13258:         if ($parts[$i] eq '..') {
13259:             $fullpath =~ s{([^/]+/)$}{};
13260:         } else {
13261:             $fullpath .= $parts[$i].'/';
13262:         }
13263:     }
13264:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
13265:         $cleanpath = $1;
13266:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
13267:         my $curr_toprel = $1;
13268:         my @parts = split(/\//,$curr_toprel);
13269:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
13270:         my @urlparts = split(/\//,$url_toprel);
13271:         my $doubledots;
13272:         my $startdiff = -1;
13273:         for (my $i=0; $i<@urlparts; $i++) {
13274:             if ($startdiff == -1) {
13275:                 unless ($urlparts[$i] eq $parts[$i]) {
13276:                     $startdiff = $i;
13277:                     $doubledots .= '../';
13278:                 }
13279:             } else {
13280:                 $doubledots .= '../';
13281:             }
13282:         }
13283:         if ($startdiff > -1) {
13284:             $cleanpath = $doubledots;
13285:             for (my $i=$startdiff; $i<@parts; $i++) {
13286:                 $cleanpath .= $parts[$i].'/';
13287:             }
13288:         }
13289:     }
13290:     $cleanpath =~ s{(/)$}{};
13291:     return $cleanpath;
13292: }
13293: 
13294: sub is_archive_file {
13295:     my ($mimetype) = @_;
13296:     if (($mimetype eq 'application/octet-stream') ||
13297:         ($mimetype eq 'application/x-stuffit') ||
13298:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
13299:         return 1;
13300:     }
13301:     return;
13302: }
13303: 
13304: sub decompress_form {
13305:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
13306:     my %lt = &Apache::lonlocal::texthash (
13307:         this => 'This file is an archive file.',
13308:         camt => 'This file is a Camtasia archive file.',
13309:         itsc => 'Its contents are as follows:',
13310:         youm => 'You may wish to extract its contents.',
13311:         extr => 'Extract contents',
13312:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
13313:         proa => 'Process automatically?',
13314:         yes  => 'Yes',
13315:         no   => 'No',
13316:         fold => 'Title for folder containing movie',
13317:         movi => 'Title for page containing embedded movie', 
13318:     );
13319:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
13320:     my ($is_camtasia,$topdir,%toplevel,@paths);
13321:     my $info = &list_archive_contents($fileloc,\@paths);
13322:     if (@paths) {
13323:         foreach my $path (@paths) {
13324:             $path =~ s{^/}{};
13325:             if ($path =~ m{^([^/]+)/$}) {
13326:                 $topdir = $1;
13327:             }
13328:             if ($path =~ m{^([^/]+)/}) {
13329:                 $toplevel{$1} = $path;
13330:             } else {
13331:                 $toplevel{$path} = $path;
13332:             }
13333:         }
13334:     }
13335:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
13336:         my @camtasia6 = ("$topdir/","$topdir/index.html",
13337:                         "$topdir/media/",
13338:                         "$topdir/media/$topdir.mp4",
13339:                         "$topdir/media/FirstFrame.png",
13340:                         "$topdir/media/player.swf",
13341:                         "$topdir/media/swfobject.js",
13342:                         "$topdir/media/expressInstall.swf");
13343:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
13344:                          "$topdir/$topdir.mp4",
13345:                          "$topdir/$topdir\_config.xml",
13346:                          "$topdir/$topdir\_controller.swf",
13347:                          "$topdir/$topdir\_embed.css",
13348:                          "$topdir/$topdir\_First_Frame.png",
13349:                          "$topdir/$topdir\_player.html",
13350:                          "$topdir/$topdir\_Thumbnails.png",
13351:                          "$topdir/playerProductInstall.swf",
13352:                          "$topdir/scripts/",
13353:                          "$topdir/scripts/config_xml.js",
13354:                          "$topdir/scripts/handlebars.js",
13355:                          "$topdir/scripts/jquery-1.7.1.min.js",
13356:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
13357:                          "$topdir/scripts/modernizr.js",
13358:                          "$topdir/scripts/player-min.js",
13359:                          "$topdir/scripts/swfobject.js",
13360:                          "$topdir/skins/",
13361:                          "$topdir/skins/configuration_express.xml",
13362:                          "$topdir/skins/express_show/",
13363:                          "$topdir/skins/express_show/player-min.css",
13364:                          "$topdir/skins/express_show/spritesheet.png");
13365:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
13366:                          "$topdir/$topdir.mp4",
13367:                          "$topdir/$topdir\_config.xml",
13368:                          "$topdir/$topdir\_controller.swf",
13369:                          "$topdir/$topdir\_embed.css",
13370:                          "$topdir/$topdir\_First_Frame.png",
13371:                          "$topdir/$topdir\_player.html",
13372:                          "$topdir/$topdir\_Thumbnails.png",
13373:                          "$topdir/playerProductInstall.swf",
13374:                          "$topdir/scripts/",
13375:                          "$topdir/scripts/config_xml.js",
13376:                          "$topdir/scripts/techsmith-smart-player.min.js",
13377:                          "$topdir/skins/",
13378:                          "$topdir/skins/configuration_express.xml",
13379:                          "$topdir/skins/express_show/",
13380:                          "$topdir/skins/express_show/spritesheet.min.css",
13381:                          "$topdir/skins/express_show/spritesheet.png",
13382:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
13383:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
13384:         if (@diffs == 0) {
13385:             $is_camtasia = 6;
13386:         } else {
13387:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
13388:             if (@diffs == 0) {
13389:                 $is_camtasia = 8;
13390:             } else {
13391:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
13392:                 if (@diffs == 0) {
13393:                     $is_camtasia = 8;
13394:                 }
13395:             }
13396:         }
13397:     }
13398:     my $output;
13399:     if ($is_camtasia) {
13400:         $output = <<"ENDCAM";
13401: <script type="text/javascript" language="Javascript">
13402: // <![CDATA[
13403: 
13404: function camtasiaToggle() {
13405:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
13406:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
13407:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
13408:                 document.getElementById('camtasia_titles').style.display='block';
13409:             } else {
13410:                 document.getElementById('camtasia_titles').style.display='none';
13411:             }
13412:         }
13413:     }
13414:     return;
13415: }
13416: 
13417: // ]]>
13418: </script>
13419: <p>$lt{'camt'}</p>
13420: ENDCAM
13421:     } else {
13422:         $output = '<p>'.$lt{'this'};
13423:         if ($info eq '') {
13424:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
13425:         } else {
13426:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
13427:                        '<div><pre>'.$info.'</pre></div>';
13428:         }
13429:     }
13430:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
13431:     my $duplicates;
13432:     my $num = 0;
13433:     if (ref($dirlist) eq 'ARRAY') {
13434:         foreach my $item (@{$dirlist}) {
13435:             if (ref($item) eq 'ARRAY') {
13436:                 if (exists($toplevel{$item->[0]})) {
13437:                     $duplicates .= 
13438:                         &start_data_table_row().
13439:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
13440:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
13441:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
13442:                         'value="1" />'.&mt('Yes').'</label>'.
13443:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
13444:                         '<td>'.$item->[0].'</td>';
13445:                     if ($item->[2]) {
13446:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
13447:                     } else {
13448:                         $duplicates .= '<td>'.&mt('File').'</td>';
13449:                     }
13450:                     $duplicates .= '<td>'.$item->[3].'</td>'.
13451:                                    '<td>'.
13452:                                    &Apache::lonlocal::locallocaltime($item->[4]).
13453:                                    '</td>'.
13454:                                    &end_data_table_row();
13455:                     $num ++;
13456:                 }
13457:             }
13458:         }
13459:     }
13460:     my $itemcount;
13461:     if (@paths > 0) {
13462:         $itemcount = scalar(@paths);
13463:     } else {
13464:         $itemcount = 1;
13465:     }
13466:     if ($is_camtasia) {
13467:         $output .= $lt{'auto'}.'<br />'.
13468:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
13469:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
13470:                    $lt{'yes'}.'</label>&nbsp;<label>'.
13471:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
13472:                    $lt{'no'}.'</label></span><br />'.
13473:                    '<div id="camtasia_titles" style="display:block">'.
13474:                    &Apache::lonhtmlcommon::start_pick_box().
13475:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
13476:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
13477:                    &Apache::lonhtmlcommon::row_closure().
13478:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
13479:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
13480:                    &Apache::lonhtmlcommon::row_closure(1).
13481:                    &Apache::lonhtmlcommon::end_pick_box().
13482:                    '</div>';
13483:     }
13484:     $output .= 
13485:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
13486:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
13487:         "\n";
13488:     if ($duplicates ne '') {
13489:         $output .= '<p><span class="LC_warning">'.
13490:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
13491:                    &start_data_table().
13492:                    &start_data_table_header_row().
13493:                    '<th>'.&mt('Overwrite?').'</th>'.
13494:                    '<th>'.&mt('Name').'</th>'.
13495:                    '<th>'.&mt('Type').'</th>'.
13496:                    '<th>'.&mt('Size').'</th>'.
13497:                    '<th>'.&mt('Last modified').'</th>'.
13498:                    &end_data_table_header_row().
13499:                    $duplicates.
13500:                    &end_data_table().
13501:                    '</p>';
13502:     }
13503:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
13504:     if (ref($hiddenelements) eq 'HASH') {
13505:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
13506:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
13507:         }
13508:     }
13509:     $output .= <<"END";
13510: <br />
13511: <input type="submit" name="decompress" value="$lt{'extr'}" />
13512: </form>
13513: $noextract
13514: END
13515:     return $output;
13516: }
13517: 
13518: sub decompression_utility {
13519:     my ($program) = @_;
13520:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
13521:     my $location;
13522:     if (grep(/^\Q$program\E$/,@utilities)) { 
13523:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
13524:                          '/usr/sbin/') {
13525:             if (-x $dir.$program) {
13526:                 $location = $dir.$program;
13527:                 last;
13528:             }
13529:         }
13530:     }
13531:     return $location;
13532: }
13533: 
13534: sub list_archive_contents {
13535:     my ($file,$pathsref) = @_;
13536:     my (@cmd,$output);
13537:     my $needsregexp;
13538:     if ($file =~ /\.zip$/) {
13539:         @cmd = (&decompression_utility('unzip'),"-l");
13540:         $needsregexp = 1;
13541:     } elsif (($file =~ m/\.tar\.gz$/) ||
13542:              ($file =~ /\.tgz$/)) {
13543:         @cmd = (&decompression_utility('tar'),"-ztf");
13544:     } elsif ($file =~ /\.tar\.bz2$/) {
13545:         @cmd = (&decompression_utility('tar'),"-jtf");
13546:     } elsif ($file =~ m|\.tar$|) {
13547:         @cmd = (&decompression_utility('tar'),"-tf");
13548:     }
13549:     if (@cmd) {
13550:         undef($!);
13551:         undef($@);
13552:         if (open(my $fh,"-|", @cmd, $file)) {
13553:             while (my $line = <$fh>) {
13554:                 $output .= $line;
13555:                 chomp($line);
13556:                 my $item;
13557:                 if ($needsregexp) {
13558:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
13559:                 } else {
13560:                     $item = $line;
13561:                 }
13562:                 if ($item ne '') {
13563:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
13564:                         push(@{$pathsref},$item);
13565:                     } 
13566:                 }
13567:             }
13568:             close($fh);
13569:         }
13570:     }
13571:     return $output;
13572: }
13573: 
13574: sub decompress_uploaded_file {
13575:     my ($file,$dir) = @_;
13576:     &Apache::lonnet::appenv({'cgi.file' => $file});
13577:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
13578:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
13579:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
13580:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
13581:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
13582:     my $decompressed = $env{'cgi.decompressed'};
13583:     &Apache::lonnet::delenv('cgi.file');
13584:     &Apache::lonnet::delenv('cgi.dir');
13585:     &Apache::lonnet::delenv('cgi.decompressed');
13586:     return ($decompressed,$result);
13587: }
13588: 
13589: sub process_decompression {
13590:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
13591:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
13592:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13593:                &mt('Unexpected file path.').'</p>'."\n";
13594:     }
13595:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
13596:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13597:                &mt('Unexpected course context.').'</p>'."\n";
13598:     }
13599:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
13600:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13601:                &mt('Filename contained unexpected characters.').'</p>'."\n";
13602:     }
13603:     my ($dir,$error,$warning,$output);
13604:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
13605:         $error = &mt('Filename not a supported archive file type.').
13606:                  '<br />'.&mt('Filename should end with one of: [_1].',
13607:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
13608:     } else {
13609:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
13610:         if ($docuhome eq 'no_host') {
13611:             $error = &mt('Could not determine home server for course.');
13612:         } else {
13613:             my @ids=&Apache::lonnet::current_machine_ids();
13614:             my $currdir = "$dir_root/$destination";
13615:             if (grep(/^\Q$docuhome\E$/,@ids)) {
13616:                 $dir = &LONCAPA::propath($docudom,$docuname).
13617:                        "$dir_root/$destination";
13618:             } else {
13619:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
13620:                        "$dir_root/$docudom/$docuname/$destination";
13621:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
13622:                     $error = &mt('Archive file not found.');
13623:                 }
13624:             }
13625:             my (@to_overwrite,@to_skip);
13626:             if ($env{'form.archive_overwrite_total'} > 0) {
13627:                 my $total = $env{'form.archive_overwrite_total'};
13628:                 for (my $i=0; $i<$total; $i++) {
13629:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
13630:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
13631:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
13632:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
13633:                     }
13634:                 }
13635:             }
13636:             my $numskip = scalar(@to_skip);
13637:             my $numoverwrite = scalar(@to_overwrite);
13638:             if (($numskip) && (!$numoverwrite)) { 
13639:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
13640:             } elsif ($dir eq '') {
13641:                 $error = &mt('Directory containing archive file unavailable.');
13642:             } elsif (!$error) {
13643:                 my ($decompressed,$display);
13644:                 if (($numskip) || ($numoverwrite)) {
13645:                     my $tempdir = time.'_'.$$.int(rand(10000));
13646:                     mkdir("$dir/$tempdir",0755);
13647:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
13648:                         ($decompressed,$display) = 
13649:                             &decompress_uploaded_file($file,"$dir/$tempdir");
13650:                         foreach my $item (@to_skip) {
13651:                             if (($item ne '') && ($item !~ /\.\./)) {
13652:                                 if (-f "$dir/$tempdir/$item") { 
13653:                                     unlink("$dir/$tempdir/$item");
13654:                                 } elsif (-d "$dir/$tempdir/$item") {
13655:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
13656:                                 }
13657:                             }
13658:                         }
13659:                         foreach my $item (@to_overwrite) {
13660:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
13661:                                 if (($item ne '') && ($item !~ /\.\./)) {
13662:                                     if (-f "$dir/$item") {
13663:                                         unlink("$dir/$item");
13664:                                     } elsif (-d "$dir/$item") {
13665:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
13666:                                     }
13667:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
13668:                                 }
13669:                             }
13670:                         }
13671:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
13672:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
13673:                         }
13674:                     }
13675:                 } else {
13676:                     ($decompressed,$display) = 
13677:                         &decompress_uploaded_file($file,$dir);
13678:                 }
13679:                 if ($decompressed eq 'ok') {
13680:                     $output = '<p class="LC_info">'.
13681:                               &mt('Files extracted successfully from archive.').
13682:                               '</p>'."\n";
13683:                     my ($warning,$result,@contents);
13684:                     my ($newdirlistref,$newlisterror) =
13685:                         &Apache::lonnet::dirlist($currdir,$docudom,
13686:                                                  $docuname,1);
13687:                     my (%is_dir,%changes,@newitems);
13688:                     my $dirptr = 16384;
13689:                     if (ref($newdirlistref) eq 'ARRAY') {
13690:                         foreach my $dir_line (@{$newdirlistref}) {
13691:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
13692:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
13693:                                 push(@newitems,$item);
13694:                                 if ($dirptr&$testdir) {
13695:                                     $is_dir{$item} = 1;
13696:                                 }
13697:                                 $changes{$item} = 1;
13698:                             }
13699:                         }
13700:                     }
13701:                     if (keys(%changes) > 0) {
13702:                         foreach my $item (sort(@newitems)) {
13703:                             if ($changes{$item}) {
13704:                                 push(@contents,$item);
13705:                             }
13706:                         }
13707:                     }
13708:                     if (@contents > 0) {
13709:                         my $wantform;
13710:                         unless ($env{'form.autoextract_camtasia'}) {
13711:                             $wantform = 1;
13712:                         }
13713:                         my (%children,%parent,%dirorder,%titles);
13714:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
13715:                                                                 $currdir,\%is_dir,
13716:                                                                 \%children,\%parent,
13717:                                                                 \@contents,\%dirorder,
13718:                                                                 \%titles,$wantform);
13719:                         if ($datatable ne '') {
13720:                             $output .= &archive_options_form('decompressed',$datatable,
13721:                                                              $count,$hiddenelem);
13722:                             my $startcount = 6;
13723:                             $output .= &archive_javascript($startcount,$count,
13724:                                                            \%titles,\%children);
13725:                         }
13726:                         if ($env{'form.autoextract_camtasia'}) {
13727:                             my $version = $env{'form.autoextract_camtasia'};
13728:                             my %displayed;
13729:                             my $total = 1;
13730:                             $env{'form.archive_directory'} = [];
13731:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
13732:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
13733:                                 $path =~ s{/$}{};
13734:                                 my $item;
13735:                                 if ($path ne '') {
13736:                                     $item = "$path/$titles{$i}";
13737:                                 } else {
13738:                                     $item = $titles{$i};
13739:                                 }
13740:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
13741:                                 if ($item eq $contents[0]) {
13742:                                     push(@{$env{'form.archive_directory'}},$i);
13743:                                     $env{'form.archive_'.$i} = 'display';
13744:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
13745:                                     $displayed{'folder'} = $i;
13746:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
13747:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
13748:                                     $env{'form.archive_'.$i} = 'display';
13749:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
13750:                                     $displayed{'web'} = $i;
13751:                                 } else {
13752:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
13753:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
13754:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
13755:                                         push(@{$env{'form.archive_directory'}},$i);
13756:                                     }
13757:                                     $env{'form.archive_'.$i} = 'dependency';
13758:                                 }
13759:                                 $total ++;
13760:                             }
13761:                             for (my $i=1; $i<$total; $i++) {
13762:                                 next if ($i == $displayed{'web'});
13763:                                 next if ($i == $displayed{'folder'});
13764:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
13765:                             }
13766:                             $env{'form.phase'} = 'decompress_cleanup';
13767:                             $env{'form.archivedelete'} = 1;
13768:                             $env{'form.archive_count'} = $total-1;
13769:                             $output .=
13770:                                 &process_extracted_files('coursedocs',$docudom,
13771:                                                          $docuname,$destination,
13772:                                                          $dir_root,$hiddenelem);
13773:                         }
13774:                     } else {
13775:                         $warning = &mt('No new items extracted from archive file.');
13776:                     }
13777:                 } else {
13778:                     $output = $display;
13779:                     $error = &mt('An error occurred during extraction from the archive file.');
13780:                 }
13781:             }
13782:         }
13783:     }
13784:     if ($error) {
13785:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13786:                    $error.'</p>'."\n";
13787:     }
13788:     if ($warning) {
13789:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
13790:     }
13791:     return $output;
13792: }
13793: 
13794: sub get_extracted {
13795:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
13796:         $titles,$wantform) = @_;
13797:     my $count = 0;
13798:     my $depth = 0;
13799:     my $datatable;
13800:     my @hierarchy;
13801:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
13802:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
13803:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
13804:     foreach my $item (@{$contents}) {
13805:         $count ++;
13806:         @{$dirorder->{$count}} = @hierarchy;
13807:         $titles->{$count} = $item;
13808:         &archive_hierarchy($depth,$count,$parent,$children);
13809:         if ($wantform) {
13810:             $datatable .= &archive_row($is_dir->{$item},$item,
13811:                                        $currdir,$depth,$count);
13812:         }
13813:         if ($is_dir->{$item}) {
13814:             $depth ++;
13815:             push(@hierarchy,$count);
13816:             $parent->{$depth} = $count;
13817:             $datatable .=
13818:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
13819:                                            \$depth,\$count,\@hierarchy,$dirorder,
13820:                                            $children,$parent,$titles,$wantform);
13821:             $depth --;
13822:             pop(@hierarchy);
13823:         }
13824:     }
13825:     return ($count,$datatable);
13826: }
13827: 
13828: sub recurse_extracted_archive {
13829:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
13830:         $children,$parent,$titles,$wantform) = @_;
13831:     my $result='';
13832:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
13833:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
13834:             (ref($dirorder) eq 'HASH')) {
13835:         return $result;
13836:     }
13837:     my $dirptr = 16384;
13838:     my ($newdirlistref,$newlisterror) =
13839:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
13840:     if (ref($newdirlistref) eq 'ARRAY') {
13841:         foreach my $dir_line (@{$newdirlistref}) {
13842:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
13843:             unless ($item =~ /^\.+$/) {
13844:                 $$count ++;
13845:                 @{$dirorder->{$$count}} = @{$hierarchy};
13846:                 $titles->{$$count} = $item;
13847:                 &archive_hierarchy($$depth,$$count,$parent,$children);
13848: 
13849:                 my $is_dir;
13850:                 if ($dirptr&$testdir) {
13851:                     $is_dir = 1;
13852:                 }
13853:                 if ($wantform) {
13854:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
13855:                 }
13856:                 if ($is_dir) {
13857:                     $$depth ++;
13858:                     push(@{$hierarchy},$$count);
13859:                     $parent->{$$depth} = $$count;
13860:                     $result .=
13861:                         &recurse_extracted_archive("$currdir/$item",$docudom,
13862:                                                    $docuname,$depth,$count,
13863:                                                    $hierarchy,$dirorder,$children,
13864:                                                    $parent,$titles,$wantform);
13865:                     $$depth --;
13866:                     pop(@{$hierarchy});
13867:                 }
13868:             }
13869:         }
13870:     }
13871:     return $result;
13872: }
13873: 
13874: sub archive_hierarchy {
13875:     my ($depth,$count,$parent,$children) =@_;
13876:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
13877:         if (exists($parent->{$depth})) {
13878:              $children->{$parent->{$depth}} .= $count.':';
13879:         }
13880:     }
13881:     return;
13882: }
13883: 
13884: sub archive_row {
13885:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
13886:     my ($name) = ($item =~ m{([^/]+)$});
13887:     my %choices = &Apache::lonlocal::texthash (
13888:                                        'display'    => 'Add as file',
13889:                                        'dependency' => 'Include as dependency',
13890:                                        'discard'    => 'Discard',
13891:                                       );
13892:     if ($is_dir) {
13893:         $choices{'display'} = &mt('Add as folder'); 
13894:     }
13895:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
13896:     my $offset = 0;
13897:     foreach my $action ('display','dependency','discard') {
13898:         $offset ++;
13899:         if ($action ne 'display') {
13900:             $offset ++;
13901:         }  
13902:         $output .= '<td><span class="LC_nobreak">'.
13903:                    '<label><input type="radio" name="archive_'.$count.
13904:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
13905:         my $text = $choices{$action};
13906:         if ($is_dir) {
13907:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
13908:             if ($action eq 'display') {
13909:                 $text = &mt('Add as folder');
13910:             }
13911:         } else {
13912:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
13913: 
13914:         }
13915:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
13916:         if ($action eq 'dependency') {
13917:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
13918:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
13919:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
13920:                        '<option value=""></option>'."\n".
13921:                        '</select>'."\n".
13922:                        '</div>';
13923:         } elsif ($action eq 'display') {
13924:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
13925:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
13926:                        '</div>';
13927:         }
13928:         $output .= '</td>';
13929:     }
13930:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
13931:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
13932:     for (my $i=0; $i<$depth; $i++) {
13933:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
13934:     }
13935:     if ($is_dir) {
13936:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
13937:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
13938:     } else {
13939:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
13940:     }
13941:     $output .= '&nbsp;'.$name.'</td>'."\n".
13942:                &end_data_table_row();
13943:     return $output;
13944: }
13945: 
13946: sub archive_options_form {
13947:     my ($form,$display,$count,$hiddenelem) = @_;
13948:     my %lt = &Apache::lonlocal::texthash(
13949:                perm => 'Permanently remove archive file?',
13950:                hows => 'How should each extracted item be incorporated in the course?',
13951:                cont => 'Content actions for all',
13952:                addf => 'Add as folder/file',
13953:                incd => 'Include as dependency for a displayed file',
13954:                disc => 'Discard',
13955:                no   => 'No',
13956:                yes  => 'Yes',
13957:                save => 'Save',
13958:     );
13959:     my $output = <<"END";
13960: <form name="$form" method="post" action="">
13961: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
13962: <label>
13963:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
13964: </label>
13965: &nbsp;
13966: <label>
13967:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
13968: </span>
13969: </p>
13970: <input type="hidden" name="phase" value="decompress_cleanup" />
13971: <br />$lt{'hows'}
13972: <div class="LC_columnSection">
13973:   <fieldset>
13974:     <legend>$lt{'cont'}</legend>
13975:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
13976:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
13977:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
13978:   </fieldset>
13979: </div>
13980: END
13981:     return $output.
13982:            &start_data_table()."\n".
13983:            $display."\n".
13984:            &end_data_table()."\n".
13985:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
13986:            $hiddenelem.
13987:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
13988:            '</form>';
13989: }
13990: 
13991: sub archive_javascript {
13992:     my ($startcount,$numitems,$titles,$children) = @_;
13993:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
13994:     my $maintitle = $env{'form.comment'};
13995:     my $scripttag = <<START;
13996: <script type="text/javascript">
13997: // <![CDATA[
13998: 
13999: function checkAll(form,prefix) {
14000:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
14001:     for (var i=0; i < form.elements.length; i++) {
14002:         var id = form.elements[i].id;
14003:         if ((id != '') && (id != undefined)) {
14004:             if (idstr.test(id)) {
14005:                 if (form.elements[i].type == 'radio') {
14006:                     form.elements[i].checked = true;
14007:                     var nostart = i-$startcount;
14008:                     var offset = nostart%7;
14009:                     var count = (nostart-offset)/7;    
14010:                     dependencyCheck(form,count,offset);
14011:                 }
14012:             }
14013:         }
14014:     }
14015: }
14016: 
14017: function propagateCheck(form,count) {
14018:     if (count > 0) {
14019:         var startelement = $startcount + ((count-1) * 7);
14020:         for (var j=1; j<6; j++) {
14021:             if ((j != 2) && (j != 4)) {
14022:                 var item = startelement + j; 
14023:                 if (form.elements[item].type == 'radio') {
14024:                     if (form.elements[item].checked) {
14025:                         containerCheck(form,count,j);
14026:                         break;
14027:                     }
14028:                 }
14029:             }
14030:         }
14031:     }
14032: }
14033: 
14034: numitems = $numitems
14035: var titles = new Array(numitems);
14036: var parents = new Array(numitems);
14037: for (var i=0; i<numitems; i++) {
14038:     parents[i] = new Array;
14039: }
14040: var maintitle = '$maintitle';
14041: 
14042: START
14043: 
14044:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
14045:         my @contents = split(/:/,$children->{$container});
14046:         for (my $i=0; $i<@contents; $i ++) {
14047:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
14048:         }
14049:     }
14050: 
14051:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
14052:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
14053:     }
14054: 
14055:     $scripttag .= <<END;
14056: 
14057: function containerCheck(form,count,offset) {
14058:     if (count > 0) {
14059:         dependencyCheck(form,count,offset);
14060:         var item = (offset+$startcount)+7*(count-1);
14061:         form.elements[item].checked = true;
14062:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
14063:             if (parents[count].length > 0) {
14064:                 for (var j=0; j<parents[count].length; j++) {
14065:                     containerCheck(form,parents[count][j],offset);
14066:                 }
14067:             }
14068:         }
14069:     }
14070: }
14071: 
14072: function dependencyCheck(form,count,offset) {
14073:     if (count > 0) {
14074:         var chosen = (offset+$startcount)+7*(count-1);
14075:         var depitem = $startcount + ((count-1) * 7) + 4;
14076:         var currtype = form.elements[depitem].type;
14077:         if (form.elements[chosen].value == 'dependency') {
14078:             document.getElementById('arc_depon_'+count).style.display='block'; 
14079:             form.elements[depitem].options.length = 0;
14080:             form.elements[depitem].options[0] = new Option('Select','',true,true);
14081:             for (var i=1; i<=numitems; i++) {
14082:                 if (i == count) {
14083:                     continue;
14084:                 }
14085:                 var startelement = $startcount + (i-1) * 7;
14086:                 for (var j=1; j<6; j++) {
14087:                     if ((j != 2) && (j!= 4)) {
14088:                         var item = startelement + j;
14089:                         if (form.elements[item].type == 'radio') {
14090:                             if (form.elements[item].checked) {
14091:                                 if (form.elements[item].value == 'display') {
14092:                                     var n = form.elements[depitem].options.length;
14093:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
14094:                                 }
14095:                             }
14096:                         }
14097:                     }
14098:                 }
14099:             }
14100:         } else {
14101:             document.getElementById('arc_depon_'+count).style.display='none';
14102:             form.elements[depitem].options.length = 0;
14103:             form.elements[depitem].options[0] = new Option('Select','',true,true);
14104:         }
14105:         titleCheck(form,count,offset);
14106:     }
14107: }
14108: 
14109: function propagateSelect(form,count,offset) {
14110:     if (count > 0) {
14111:         var item = (1+offset+$startcount)+7*(count-1);
14112:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
14113:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
14114:             if (parents[count].length > 0) {
14115:                 for (var j=0; j<parents[count].length; j++) {
14116:                     containerSelect(form,parents[count][j],offset,picked);
14117:                 }
14118:             }
14119:         }
14120:     }
14121: }
14122: 
14123: function containerSelect(form,count,offset,picked) {
14124:     if (count > 0) {
14125:         var item = (offset+$startcount)+7*(count-1);
14126:         if (form.elements[item].type == 'radio') {
14127:             if (form.elements[item].value == 'dependency') {
14128:                 if (form.elements[item+1].type == 'select-one') {
14129:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
14130:                         if (form.elements[item+1].options[i].value == picked) {
14131:                             form.elements[item+1].selectedIndex = i;
14132:                             break;
14133:                         }
14134:                     }
14135:                 }
14136:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
14137:                     if (parents[count].length > 0) {
14138:                         for (var j=0; j<parents[count].length; j++) {
14139:                             containerSelect(form,parents[count][j],offset,picked);
14140:                         }
14141:                     }
14142:                 }
14143:             }
14144:         }
14145:     }
14146: }
14147: 
14148: function titleCheck(form,count,offset) {
14149:     if (count > 0) {
14150:         var chosen = (offset+$startcount)+7*(count-1);
14151:         var depitem = $startcount + ((count-1) * 7) + 2;
14152:         var currtype = form.elements[depitem].type;
14153:         if (form.elements[chosen].value == 'display') {
14154:             document.getElementById('arc_title_'+count).style.display='block';
14155:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
14156:                 document.getElementById('archive_title_'+count).value=maintitle;
14157:             }
14158:         } else {
14159:             document.getElementById('arc_title_'+count).style.display='none';
14160:             if (currtype == 'text') { 
14161:                 document.getElementById('archive_title_'+count).value='';
14162:             }
14163:         }
14164:     }
14165:     return;
14166: }
14167: 
14168: // ]]>
14169: </script>
14170: END
14171:     return $scripttag;
14172: }
14173: 
14174: sub process_extracted_files {
14175:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
14176:     my $numitems = $env{'form.archive_count'};
14177:     return if ((!$numitems) || ($numitems =~ /\D/));
14178:     my @ids=&Apache::lonnet::current_machine_ids();
14179:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
14180:         %folders,%containers,%mapinner,%prompttofetch);
14181:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
14182:     if (grep(/^\Q$docuhome\E$/,@ids)) {
14183:         $prefix = &LONCAPA::propath($docudom,$docuname);
14184:         $pathtocheck = "$dir_root/$destination";
14185:         $dir = $dir_root;
14186:         $ishome = 1;
14187:     } else {
14188:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
14189:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
14190:         $dir = "$dir_root/$docudom/$docuname";
14191:     }
14192:     my $currdir = "$dir_root/$destination";
14193:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
14194:     if ($env{'form.folderpath'}) {
14195:         my @items = split('&',$env{'form.folderpath'});
14196:         $folders{'0'} = $items[-2];
14197:         if ($env{'form.folderpath'} =~ /\:1$/) {
14198:             $containers{'0'}='page';
14199:         } else {  
14200:             $containers{'0'}='sequence';
14201:         }
14202:     }
14203:     my @archdirs = &get_env_multiple('form.archive_directory');
14204:     if ($numitems) {
14205:         for (my $i=1; $i<=$numitems; $i++) {
14206:             my $path = $env{'form.archive_content_'.$i};
14207:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
14208:                 my $item = $1;
14209:                 $toplevelitems{$item} = $i;
14210:                 if (grep(/^\Q$i\E$/,@archdirs)) {
14211:                     $is_dir{$item} = 1;
14212:                 }
14213:             }
14214:         }
14215:     }
14216:     my ($output,%children,%parent,%titles,%dirorder,$result);
14217:     if (keys(%toplevelitems) > 0) {
14218:         my @contents = sort(keys(%toplevelitems));
14219:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
14220:                                            \%parent,\@contents,\%dirorder,\%titles);
14221:     }
14222:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
14223:     if ($numitems) {
14224:         for (my $i=1; $i<=$numitems; $i++) {
14225:             next if ($env{'form.archive_'.$i} eq 'dependency');
14226:             my $path = $env{'form.archive_content_'.$i};
14227:             if ($path =~ /^\Q$pathtocheck\E/) {
14228:                 if ($env{'form.archive_'.$i} eq 'discard') {
14229:                     if ($prefix ne '' && $path ne '') {
14230:                         if (-e $prefix.$path) {
14231:                             if ((@archdirs > 0) && 
14232:                                 (grep(/^\Q$i\E$/,@archdirs))) {
14233:                                 $todeletedir{$prefix.$path} = 1;
14234:                             } else {
14235:                                 $todelete{$prefix.$path} = 1;
14236:                             }
14237:                         }
14238:                     }
14239:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
14240:                     my ($docstitle,$title,$url,$outer);
14241:                     ($title) = ($path =~ m{/([^/]+)$});
14242:                     $docstitle = $env{'form.archive_title_'.$i};
14243:                     if ($docstitle eq '') {
14244:                         $docstitle = $title;
14245:                     }
14246:                     $outer = 0;
14247:                     if (ref($dirorder{$i}) eq 'ARRAY') {
14248:                         if (@{$dirorder{$i}} > 0) {
14249:                             foreach my $item (reverse(@{$dirorder{$i}})) {
14250:                                 if ($env{'form.archive_'.$item} eq 'display') {
14251:                                     $outer = $item;
14252:                                     last;
14253:                                 }
14254:                             }
14255:                         }
14256:                     }
14257:                     my ($errtext,$fatal) = 
14258:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
14259:                                                '/'.$folders{$outer}.'.'.
14260:                                                $containers{$outer});
14261:                     next if ($fatal);
14262:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
14263:                         if ($context eq 'coursedocs') {
14264:                             $mapinner{$i} = time;
14265:                             $folders{$i} = 'default_'.$mapinner{$i};
14266:                             $containers{$i} = 'sequence';
14267:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
14268:                                       $folders{$i}.'.'.$containers{$i};
14269:                             my $newidx = &LONCAPA::map::getresidx();
14270:                             $LONCAPA::map::resources[$newidx]=
14271:                                 $docstitle.':'.$url.':false:normal:res';
14272:                             push(@LONCAPA::map::order,$newidx);
14273:                             my ($outtext,$errtext) =
14274:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
14275:                                                         $docuname.'/'.$folders{$outer}.
14276:                                                         '.'.$containers{$outer},1,1);
14277:                             $newseqid{$i} = $newidx;
14278:                             unless ($errtext) {
14279:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
14280:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
14281:                                             '</li>'."\n";
14282:                             }
14283:                         }
14284:                     } else {
14285:                         if ($context eq 'coursedocs') {
14286:                             my $newidx=&LONCAPA::map::getresidx();
14287:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
14288:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
14289:                                       $title;
14290:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
14291:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
14292:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
14293:                                 }
14294:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
14295:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
14296:                                 }
14297:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
14298:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
14299:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
14300:                                         unless ($ishome) {
14301:                                             my $fetch = "$newdest{$i}/$title";
14302:                                             $fetch =~ s/^\Q$prefix$dir\E//;
14303:                                             $prompttofetch{$fetch} = 1;
14304:                                         }
14305:                                     }
14306:                                 }
14307:                                 $LONCAPA::map::resources[$newidx]=
14308:                                     $docstitle.':'.$url.':false:normal:res';
14309:                                 push(@LONCAPA::map::order, $newidx);
14310:                                 my ($outtext,$errtext)=
14311:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
14312:                                                             $docuname.'/'.$folders{$outer}.
14313:                                                             '.'.$containers{$outer},1,1);
14314:                                 unless ($errtext) {
14315:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
14316:                                         $result .= '<li>'.&mt('File: [_1] added to course',
14317:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
14318:                                                    '</li>'."\n";
14319:                                     }
14320:                                 }
14321:                             } else {
14322:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
14323:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
14324:                             }
14325:                         }
14326:                     }
14327:                 }
14328:             } else {
14329:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
14330:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
14331:             }
14332:         }
14333:         for (my $i=1; $i<=$numitems; $i++) {
14334:             next unless ($env{'form.archive_'.$i} eq 'dependency');
14335:             my $path = $env{'form.archive_content_'.$i};
14336:             if ($path =~ /^\Q$pathtocheck\E/) {
14337:                 my ($title) = ($path =~ m{/([^/]+)$});
14338:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
14339:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
14340:                     if (ref($dirorder{$i}) eq 'ARRAY') {
14341:                         my ($itemidx,$fullpath,$relpath);
14342:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
14343:                             my $container = $dirorder{$referrer{$i}}->[-1];
14344:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
14345:                                 if ($dirorder{$i}->[$j] eq $container) {
14346:                                     $itemidx = $j;
14347:                                 }
14348:                             }
14349:                         }
14350:                         if ($itemidx eq '') {
14351:                             $itemidx =  0;
14352:                         } 
14353:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
14354:                             if ($mapinner{$referrer{$i}}) {
14355:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
14356:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
14357:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
14358:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
14359:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
14360:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
14361:                                             if (!-e $fullpath) {
14362:                                                 mkdir($fullpath,0755);
14363:                                             }
14364:                                         }
14365:                                     } else {
14366:                                         last;
14367:                                     }
14368:                                 }
14369:                             }
14370:                         } elsif ($newdest{$referrer{$i}}) {
14371:                             $fullpath = $newdest{$referrer{$i}};
14372:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
14373:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
14374:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
14375:                                     last;
14376:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
14377:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
14378:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
14379:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
14380:                                         if (!-e $fullpath) {
14381:                                             mkdir($fullpath,0755);
14382:                                         }
14383:                                     }
14384:                                 } else {
14385:                                     last;
14386:                                 }
14387:                             }
14388:                         }
14389:                         if ($fullpath ne '') {
14390:                             if (-e "$prefix$path") {
14391:                                 unless (rename("$prefix$path","$fullpath/$title")) {
14392:                                      $warning .= &mt('Failed to rename dependency').'<br />';
14393:                                 }
14394:                             }
14395:                             if (-e "$fullpath/$title") {
14396:                                 my $showpath;
14397:                                 if ($relpath ne '') {
14398:                                     $showpath = "$relpath/$title";
14399:                                 } else {
14400:                                     $showpath = "/$title";
14401:                                 } 
14402:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
14403:                                                       &HTML::Entities::encode($showpath,'<>&"')).
14404:                                            '</li>'."\n";
14405:                                 unless ($ishome) {
14406:                                     my $fetch = "$fullpath/$title";
14407:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
14408:                                     $prompttofetch{$fetch} = 1;
14409:                                 }
14410:                             }
14411:                         }
14412:                     }
14413:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
14414:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
14415:                                     &HTML::Entities::encode($path,'<>&"'),
14416:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
14417:                                 '<br />';
14418:                 }
14419:             } else {
14420:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
14421:                                 &HTML::Entities::encode($path)).'<br />';
14422:             }
14423:         }
14424:         if (keys(%todelete)) {
14425:             foreach my $key (keys(%todelete)) {
14426:                 unlink($key);
14427:             }
14428:         }
14429:         if (keys(%todeletedir)) {
14430:             foreach my $key (keys(%todeletedir)) {
14431:                 rmdir($key);
14432:             }
14433:         }
14434:         foreach my $dir (sort(keys(%is_dir))) {
14435:             if (($pathtocheck ne '') && ($dir ne ''))  {
14436:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
14437:             }
14438:         }
14439:         if ($result ne '') {
14440:             $output .= '<ul>'."\n".
14441:                        $result."\n".
14442:                        '</ul>';
14443:         }
14444:         unless ($ishome) {
14445:             my $replicationfail;
14446:             foreach my $item (keys(%prompttofetch)) {
14447:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
14448:                 unless ($fetchresult eq 'ok') {
14449:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
14450:                 }
14451:             }
14452:             if ($replicationfail) {
14453:                 $output .= '<p class="LC_error">'.
14454:                            &mt('Course home server failed to retrieve:').'<ul>'.
14455:                            $replicationfail.
14456:                            '</ul></p>';
14457:             }
14458:         }
14459:     } else {
14460:         $warning = &mt('No items found in archive.');
14461:     }
14462:     if ($error) {
14463:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
14464:                    $error.'</p>'."\n";
14465:     }
14466:     if ($warning) {
14467:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
14468:     }
14469:     return $output;
14470: }
14471: 
14472: sub cleanup_empty_dirs {
14473:     my ($path) = @_;
14474:     if (($path ne '') && (-d $path)) {
14475:         if (opendir(my $dirh,$path)) {
14476:             my @dircontents = grep(!/^\./,readdir($dirh));
14477:             my $numitems = 0;
14478:             foreach my $item (@dircontents) {
14479:                 if (-d "$path/$item") {
14480:                     &cleanup_empty_dirs("$path/$item");
14481:                     if (-e "$path/$item") {
14482:                         $numitems ++;
14483:                     }
14484:                 } else {
14485:                     $numitems ++;
14486:                 }
14487:             }
14488:             if ($numitems == 0) {
14489:                 rmdir($path);
14490:             }
14491:             closedir($dirh);
14492:         }
14493:     }
14494:     return;
14495: }
14496: 
14497: =pod
14498: 
14499: =item * &get_folder_hierarchy()
14500: 
14501: Provides hierarchy of names of folders/sub-folders containing the current
14502: item,
14503: 
14504: Inputs: 3
14505:      - $navmap - navmaps object
14506: 
14507:      - $map - url for map (either the trigger itself, or map containing
14508:                            the resource, which is the trigger).
14509: 
14510:      - $showitem - 1 => show title for map itself; 0 => do not show.
14511: 
14512: Outputs: 1 @pathitems - array of folder/subfolder names.
14513: 
14514: =cut
14515: 
14516: sub get_folder_hierarchy {
14517:     my ($navmap,$map,$showitem) = @_;
14518:     my @pathitems;
14519:     if (ref($navmap)) {
14520:         my $mapres = $navmap->getResourceByUrl($map);
14521:         if (ref($mapres)) {
14522:             my $pcslist = $mapres->map_hierarchy();
14523:             if ($pcslist ne '') {
14524:                 my @pcs = split(/,/,$pcslist);
14525:                 foreach my $pc (@pcs) {
14526:                     if ($pc == 1) {
14527:                         push(@pathitems,&mt('Main Content'));
14528:                     } else {
14529:                         my $res = $navmap->getByMapPc($pc);
14530:                         if (ref($res)) {
14531:                             my $title = $res->compTitle();
14532:                             $title =~ s/\W+/_/g;
14533:                             if ($title ne '') {
14534:                                 push(@pathitems,$title);
14535:                             }
14536:                         }
14537:                     }
14538:                 }
14539:             }
14540:             if ($showitem) {
14541:                 if ($mapres->{ID} eq '0.0') {
14542:                     push(@pathitems,&mt('Main Content'));
14543:                 } else {
14544:                     my $maptitle = $mapres->compTitle();
14545:                     $maptitle =~ s/\W+/_/g;
14546:                     if ($maptitle ne '') {
14547:                         push(@pathitems,$maptitle);
14548:                     }
14549:                 }
14550:             }
14551:         }
14552:     }
14553:     return @pathitems;
14554: }
14555: 
14556: =pod
14557: 
14558: =item * &get_turnedin_filepath()
14559: 
14560: Determines path in a user's portfolio file for storage of files uploaded
14561: to a specific essayresponse or dropbox item.
14562: 
14563: Inputs: 3 required + 1 optional.
14564: $symb is symb for resource, $uname and $udom are for current user (required).
14565: $caller is optional (can be "submission", if routine is called when storing
14566: an upoaded file when "Submit Answer" button was pressed).
14567: 
14568: Returns array containing $path and $multiresp. 
14569: $path is path in portfolio.  $multiresp is 1 if this resource contains more
14570: than one file upload item.  Callers of routine should append partid as a 
14571: subdirectory to $path in cases where $multiresp is 1.
14572: 
14573: Called by: homework/essayresponse.pm and homework/structuretags.pm
14574: 
14575: =cut
14576: 
14577: sub get_turnedin_filepath {
14578:     my ($symb,$uname,$udom,$caller) = @_;
14579:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
14580:     my $turnindir;
14581:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
14582:     $turnindir = $userhash{'turnindir'};
14583:     my ($path,$multiresp);
14584:     if ($turnindir eq '') {
14585:         if ($caller eq 'submission') {
14586:             $turnindir = &mt('turned in');
14587:             $turnindir =~ s/\W+/_/g;
14588:             my %newhash = (
14589:                             'turnindir' => $turnindir,
14590:                           );
14591:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
14592:         }
14593:     }
14594:     if ($turnindir ne '') {
14595:         $path = '/'.$turnindir.'/';
14596:         my ($multipart,$turnin,@pathitems);
14597:         my $navmap = Apache::lonnavmaps::navmap->new();
14598:         if (defined($navmap)) {
14599:             my $mapres = $navmap->getResourceByUrl($map);
14600:             if (ref($mapres)) {
14601:                 my $pcslist = $mapres->map_hierarchy();
14602:                 if ($pcslist ne '') {
14603:                     foreach my $pc (split(/,/,$pcslist)) {
14604:                         my $res = $navmap->getByMapPc($pc);
14605:                         if (ref($res)) {
14606:                             my $title = $res->compTitle();
14607:                             $title =~ s/\W+/_/g;
14608:                             if ($title ne '') {
14609:                                 if (($pc > 1) && (length($title) > 12)) {
14610:                                     $title = substr($title,0,12);
14611:                                 }
14612:                                 push(@pathitems,$title);
14613:                             }
14614:                         }
14615:                     }
14616:                 }
14617:                 my $maptitle = $mapres->compTitle();
14618:                 $maptitle =~ s/\W+/_/g;
14619:                 if ($maptitle ne '') {
14620:                     if (length($maptitle) > 12) {
14621:                         $maptitle = substr($maptitle,0,12);
14622:                     }
14623:                     push(@pathitems,$maptitle);
14624:                 }
14625:                 unless ($env{'request.state'} eq 'construct') {
14626:                     my $res = $navmap->getBySymb($symb);
14627:                     if (ref($res)) {
14628:                         my $partlist = $res->parts();
14629:                         my $totaluploads = 0;
14630:                         if (ref($partlist) eq 'ARRAY') {
14631:                             foreach my $part (@{$partlist}) {
14632:                                 my @types = $res->responseType($part);
14633:                                 my @ids = $res->responseIds($part);
14634:                                 for (my $i=0; $i < scalar(@ids); $i++) {
14635:                                     if ($types[$i] eq 'essay') {
14636:                                         my $partid = $part.'_'.$ids[$i];
14637:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
14638:                                             $totaluploads ++;
14639:                                         }
14640:                                     }
14641:                                 }
14642:                             }
14643:                             if ($totaluploads > 1) {
14644:                                 $multiresp = 1;
14645:                             }
14646:                         }
14647:                     }
14648:                 }
14649:             } else {
14650:                 return;
14651:             }
14652:         } else {
14653:             return;
14654:         }
14655:         my $restitle=&Apache::lonnet::gettitle($symb);
14656:         $restitle =~ s/\W+/_/g;
14657:         if ($restitle eq '') {
14658:             $restitle = ($resurl =~ m{/[^/]+$});
14659:             if ($restitle eq '') {
14660:                 $restitle = time;
14661:             }
14662:         }
14663:         if (length($restitle) > 12) {
14664:             $restitle = substr($restitle,0,12);
14665:         }
14666:         push(@pathitems,$restitle);
14667:         $path .= join('/',@pathitems);
14668:     }
14669:     return ($path,$multiresp);
14670: }
14671: 
14672: =pod
14673: 
14674: =back
14675: 
14676: =head1 CSV Upload/Handling functions
14677: 
14678: =over 4
14679: 
14680: =item * &upfile_store($r)
14681: 
14682: Store uploaded file, $r should be the HTTP Request object,
14683: needs $env{'form.upfile'}
14684: returns $datatoken to be put into hidden field
14685: 
14686: =cut
14687: 
14688: sub upfile_store {
14689:     my $r=shift;
14690:     $env{'form.upfile'}=~s/\r/\n/gs;
14691:     $env{'form.upfile'}=~s/\f/\n/gs;
14692:     $env{'form.upfile'}=~s/\n+/\n/gs;
14693:     $env{'form.upfile'}=~s/\n+$//gs;
14694: 
14695:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
14696:                                      '_enroll_'.$env{'request.course.id'}.'_'.
14697:                                      time.'_'.$$);
14698:     return if ($datatoken eq '');
14699: 
14700:     {
14701:         my $datafile = $r->dir_config('lonDaemons').
14702:                            '/tmp/'.$datatoken.'.tmp';
14703:         if ( open(my $fh,'>',$datafile) ) {
14704:             print $fh $env{'form.upfile'};
14705:             close($fh);
14706:         }
14707:     }
14708:     return $datatoken;
14709: }
14710: 
14711: =pod
14712: 
14713: =item * &load_tmp_file($r,$datatoken)
14714: 
14715: Load uploaded file from tmp, $r should be the HTTP Request object,
14716: $datatoken is the name to assign to the temporary file.
14717: sets $env{'form.upfile'} to the contents of the file
14718: 
14719: =cut
14720: 
14721: sub load_tmp_file {
14722:     my ($r,$datatoken) = @_;
14723:     return if ($datatoken eq '');
14724:     my @studentdata=();
14725:     {
14726:         my $studentfile = $r->dir_config('lonDaemons').
14727:                               '/tmp/'.$datatoken.'.tmp';
14728:         if ( open(my $fh,'<',$studentfile) ) {
14729:             @studentdata=<$fh>;
14730:             close($fh);
14731:         }
14732:     }
14733:     $env{'form.upfile'}=join('',@studentdata);
14734: }
14735: 
14736: sub valid_datatoken {
14737:     my ($datatoken) = @_;
14738:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
14739:         return $datatoken;
14740:     }
14741:     return;
14742: }
14743: 
14744: =pod
14745: 
14746: =item * &upfile_record_sep()
14747: 
14748: Separate uploaded file into records
14749: returns array of records,
14750: needs $env{'form.upfile'} and $env{'form.upfiletype'}
14751: 
14752: =cut
14753: 
14754: sub upfile_record_sep {
14755:     if ($env{'form.upfiletype'} eq 'xml') {
14756:     } else {
14757: 	my @records;
14758: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
14759: 	    if ($line=~/^\s*$/) { next; }
14760: 	    push(@records,$line);
14761: 	}
14762: 	return @records;
14763:     }
14764: }
14765: 
14766: =pod
14767: 
14768: =item * &record_sep($record)
14769: 
14770: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
14771: 
14772: =cut
14773: 
14774: sub takeleft {
14775:     my $index=shift;
14776:     return substr('0000'.$index,-4,4);
14777: }
14778: 
14779: sub record_sep {
14780:     my $record=shift;
14781:     my %components=();
14782:     if ($env{'form.upfiletype'} eq 'xml') {
14783:     } elsif ($env{'form.upfiletype'} eq 'space') {
14784:         my $i=0;
14785:         foreach my $field (split(/\s+/,$record)) {
14786:             $field=~s/^(\"|\')//;
14787:             $field=~s/(\"|\')$//;
14788:             $components{&takeleft($i)}=$field;
14789:             $i++;
14790:         }
14791:     } elsif ($env{'form.upfiletype'} eq 'tab') {
14792:         my $i=0;
14793:         foreach my $field (split(/\t/,$record)) {
14794:             $field=~s/^(\"|\')//;
14795:             $field=~s/(\"|\')$//;
14796:             $components{&takeleft($i)}=$field;
14797:             $i++;
14798:         }
14799:     } else {
14800:         my $separator=',';
14801:         if ($env{'form.upfiletype'} eq 'semisv') {
14802:             $separator=';';
14803:         }
14804:         my $i=0;
14805: # the character we are looking for to indicate the end of a quote or a record 
14806:         my $looking_for=$separator;
14807: # do not add the characters to the fields
14808:         my $ignore=0;
14809: # we just encountered a separator (or the beginning of the record)
14810:         my $just_found_separator=1;
14811: # store the field we are working on here
14812:         my $field='';
14813: # work our way through all characters in record
14814:         foreach my $character ($record=~/(.)/g) {
14815:             if ($character eq $looking_for) {
14816:                if ($character ne $separator) {
14817: # Found the end of a quote, again looking for separator
14818:                   $looking_for=$separator;
14819:                   $ignore=1;
14820:                } else {
14821: # Found a separator, store away what we got
14822:                   $components{&takeleft($i)}=$field;
14823: 	          $i++;
14824:                   $just_found_separator=1;
14825:                   $ignore=0;
14826:                   $field='';
14827:                }
14828:                next;
14829:             }
14830: # single or double quotation marks after a separator indicate beginning of a quote
14831: # we are now looking for the end of the quote and need to ignore separators
14832:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
14833:                $looking_for=$character;
14834:                next;
14835:             }
14836: # ignore would be true after we reached the end of a quote
14837:             if ($ignore) { next; }
14838:             if (($just_found_separator) && ($character=~/\s/)) { next; }
14839:             $field.=$character;
14840:             $just_found_separator=0; 
14841:         }
14842: # catch the very last entry, since we never encountered the separator
14843:         $components{&takeleft($i)}=$field;
14844:     }
14845:     return %components;
14846: }
14847: 
14848: ######################################################
14849: ######################################################
14850: 
14851: =pod
14852: 
14853: =item * &upfile_select_html()
14854: 
14855: Return HTML code to select a file from the users machine and specify 
14856: the file type.
14857: 
14858: =cut
14859: 
14860: ######################################################
14861: ######################################################
14862: sub upfile_select_html {
14863:     my %Types = (
14864:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
14865:                  semisv => &mt('Semicolon separated values'),
14866:                  space => &mt('Space separated'),
14867:                  tab   => &mt('Tabulator separated'),
14868: #                 xml   => &mt('HTML/XML'),
14869:                  );
14870:     my $Str = '<input type="file" name="upfile" size="50" />'.
14871:         '<br />'.&mt('Type').': <select name="upfiletype">';
14872:     foreach my $type (sort(keys(%Types))) {
14873:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
14874:     }
14875:     $Str .= "</select>\n";
14876:     return $Str;
14877: }
14878: 
14879: sub get_samples {
14880:     my ($records,$toget) = @_;
14881:     my @samples=({});
14882:     my $got=0;
14883:     foreach my $rec (@$records) {
14884: 	my %temp = &record_sep($rec);
14885: 	if (! grep(/\S/, values(%temp))) { next; }
14886: 	if (%temp) {
14887: 	    $samples[$got]=\%temp;
14888: 	    $got++;
14889: 	    if ($got == $toget) { last; }
14890: 	}
14891:     }
14892:     return \@samples;
14893: }
14894: 
14895: ######################################################
14896: ######################################################
14897: 
14898: =pod
14899: 
14900: =item * &csv_print_samples($r,$records)
14901: 
14902: Prints a table of sample values from each column uploaded $r is an
14903: Apache Request ref, $records is an arrayref from
14904: &Apache::loncommon::upfile_record_sep
14905: 
14906: =cut
14907: 
14908: ######################################################
14909: ######################################################
14910: sub csv_print_samples {
14911:     my ($r,$records) = @_;
14912:     my $samples = &get_samples($records,5);
14913: 
14914:     $r->print(&mt('Samples').'<br />'.&start_data_table().
14915:               &start_data_table_header_row());
14916:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
14917:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
14918:     $r->print(&end_data_table_header_row());
14919:     foreach my $hash (@$samples) {
14920: 	$r->print(&start_data_table_row());
14921: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
14922: 	    $r->print('<td>');
14923: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
14924: 	    $r->print('</td>');
14925: 	}
14926: 	$r->print(&end_data_table_row());
14927:     }
14928:     $r->print(&end_data_table().'<br />'."\n");
14929: }
14930: 
14931: ######################################################
14932: ######################################################
14933: 
14934: =pod
14935: 
14936: =item * &csv_print_select_table($r,$records,$d)
14937: 
14938: Prints a table to create associations between values and table columns.
14939: 
14940: $r is an Apache Request ref,
14941: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
14942: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
14943: 
14944: =cut
14945: 
14946: ######################################################
14947: ######################################################
14948: sub csv_print_select_table {
14949:     my ($r,$records,$d) = @_;
14950:     my $i=0;
14951:     my $samples = &get_samples($records,1);
14952:     $r->print(&mt('Associate columns with student attributes.')."\n".
14953: 	      &start_data_table().&start_data_table_header_row().
14954:               '<th>'.&mt('Attribute').'</th>'.
14955:               '<th>'.&mt('Column').'</th>'.
14956:               &end_data_table_header_row()."\n");
14957:     foreach my $array_ref (@$d) {
14958: 	my ($value,$display,$defaultcol)=@{ $array_ref };
14959: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
14960: 
14961: 	$r->print('<td><select name="f'.$i.'"'.
14962: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
14963: 	$r->print('<option value="none"></option>');
14964: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
14965: 	    $r->print('<option value="'.$sample.'"'.
14966:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
14967:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
14968: 	}
14969: 	$r->print('</select></td>'.&end_data_table_row()."\n");
14970: 	$i++;
14971:     }
14972:     $r->print(&end_data_table());
14973:     $i--;
14974:     return $i;
14975: }
14976: 
14977: ######################################################
14978: ######################################################
14979: 
14980: =pod
14981: 
14982: =item * &csv_samples_select_table($r,$records,$d)
14983: 
14984: Prints a table of sample values from the upload and can make associate samples to internal names.
14985: 
14986: $r is an Apache Request ref,
14987: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
14988: $d is an array of 2 element arrays (internal name, displayed name)
14989: 
14990: =cut
14991: 
14992: ######################################################
14993: ######################################################
14994: sub csv_samples_select_table {
14995:     my ($r,$records,$d) = @_;
14996:     my $i=0;
14997:     #
14998:     my $max_samples = 5;
14999:     my $samples = &get_samples($records,$max_samples);
15000:     $r->print(&start_data_table().
15001:               &start_data_table_header_row().'<th>'.
15002:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
15003:               &end_data_table_header_row());
15004: 
15005:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
15006: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
15007: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
15008: 	foreach my $option (@$d) {
15009: 	    my ($value,$display,$defaultcol)=@{ $option };
15010: 	    $r->print('<option value="'.$value.'"'.
15011:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
15012:                       $display.'</option>');
15013: 	}
15014: 	$r->print('</select></td><td>');
15015: 	foreach my $line (0..($max_samples-1)) {
15016: 	    if (defined($samples->[$line]{$key})) { 
15017: 		$r->print($samples->[$line]{$key}."<br />\n"); 
15018: 	    }
15019: 	}
15020: 	$r->print('</td>'.&end_data_table_row());
15021: 	$i++;
15022:     }
15023:     $r->print(&end_data_table());
15024:     $i--;
15025:     return($i);
15026: }
15027: 
15028: ######################################################
15029: ######################################################
15030: 
15031: =pod
15032: 
15033: =item * &clean_excel_name($name)
15034: 
15035: Returns a replacement for $name which does not contain any illegal characters.
15036: 
15037: =cut
15038: 
15039: ######################################################
15040: ######################################################
15041: sub clean_excel_name {
15042:     my ($name) = @_;
15043:     $name =~ s/[:\*\?\/\\]//g;
15044:     if (length($name) > 31) {
15045:         $name = substr($name,0,31);
15046:     }
15047:     return $name;
15048: }
15049: 
15050: =pod
15051: 
15052: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
15053: 
15054: Returns either 1 or undef
15055: 
15056: 1 if the part is to be hidden, undef if it is to be shown
15057: 
15058: Arguments are:
15059: 
15060: $id the id of the part to be checked
15061: $symb, optional the symb of the resource to check
15062: $udom, optional the domain of the user to check for
15063: $uname, optional the username of the user to check for
15064: 
15065: =cut
15066: 
15067: sub check_if_partid_hidden {
15068:     my ($id,$symb,$udom,$uname) = @_;
15069:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
15070: 					 $symb,$udom,$uname);
15071:     my $truth=1;
15072:     #if the string starts with !, then the list is the list to show not hide
15073:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
15074:     my @hiddenlist=split(/,/,$hiddenparts);
15075:     foreach my $checkid (@hiddenlist) {
15076: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
15077:     }
15078:     return !$truth;
15079: }
15080: 
15081: 
15082: ############################################################
15083: ############################################################
15084: 
15085: =pod
15086: 
15087: =back 
15088: 
15089: =head1 cgi-bin script and graphing routines
15090: 
15091: =over 4
15092: 
15093: =item * &get_cgi_id()
15094: 
15095: Inputs: none
15096: 
15097: Returns an id which can be used to pass environment variables
15098: to various cgi-bin scripts.  These environment variables will
15099: be removed from the users environment after a given time by
15100: the routine &Apache::lonnet::transfer_profile_to_env.
15101: 
15102: =cut
15103: 
15104: ############################################################
15105: ############################################################
15106: my $uniq=0;
15107: sub get_cgi_id {
15108:     $uniq=($uniq+1)%100000;
15109:     return (time.'_'.$$.'_'.$uniq);
15110: }
15111: 
15112: ############################################################
15113: ############################################################
15114: 
15115: =pod
15116: 
15117: =item * &DrawBarGraph()
15118: 
15119: Facilitates the plotting of data in a (stacked) bar graph.
15120: Puts plot definition data into the users environment in order for 
15121: graph.png to plot it.  Returns an <img> tag for the plot.
15122: The bars on the plot are labeled '1','2',...,'n'.
15123: 
15124: Inputs:
15125: 
15126: =over 4
15127: 
15128: =item $Title: string, the title of the plot
15129: 
15130: =item $xlabel: string, text describing the X-axis of the plot
15131: 
15132: =item $ylabel: string, text describing the Y-axis of the plot
15133: 
15134: =item $Max: scalar, the maximum Y value to use in the plot
15135: If $Max is < any data point, the graph will not be rendered.
15136: 
15137: =item $colors: array ref holding the colors to be used for the data sets when
15138: they are plotted.  If undefined, default values will be used.
15139: 
15140: =item $labels: array ref holding the labels to use on the x-axis for the bars.
15141: 
15142: =item @Values: An array of array references.  Each array reference holds data
15143: to be plotted in a stacked bar chart.
15144: 
15145: =item If the final element of @Values is a hash reference the key/value
15146: pairs will be added to the graph definition.
15147: 
15148: =back
15149: 
15150: Returns:
15151: 
15152: An <img> tag which references graph.png and the appropriate identifying
15153: information for the plot.
15154: 
15155: =cut
15156: 
15157: ############################################################
15158: ############################################################
15159: sub DrawBarGraph {
15160:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
15161:     #
15162:     if (! defined($colors)) {
15163:         $colors = ['#33ff00', 
15164:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
15165:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
15166:                   ]; 
15167:     }
15168:     my $extra_settings = {};
15169:     if (ref($Values[-1]) eq 'HASH') {
15170:         $extra_settings = pop(@Values);
15171:     }
15172:     #
15173:     my $identifier = &get_cgi_id();
15174:     my $id = 'cgi.'.$identifier;        
15175:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
15176:         return '';
15177:     }
15178:     #
15179:     my @Labels;
15180:     if (defined($labels)) {
15181:         @Labels = @$labels;
15182:     } else {
15183:         for (my $i=0;$i<@{$Values[0]};$i++) {
15184:             push(@Labels,$i+1);
15185:         }
15186:     }
15187:     #
15188:     my $NumBars = scalar(@{$Values[0]});
15189:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
15190:     my %ValuesHash;
15191:     my $NumSets=1;
15192:     foreach my $array (@Values) {
15193:         next if (! ref($array));
15194:         $ValuesHash{$id.'.data.'.$NumSets++} = 
15195:             join(',',@$array);
15196:     }
15197:     #
15198:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
15199:     if ($NumBars < 3) {
15200:         $width = 120+$NumBars*32;
15201:         $xskip = 1;
15202:         $bar_width = 30;
15203:     } elsif ($NumBars < 5) {
15204:         $width = 120+$NumBars*20;
15205:         $xskip = 1;
15206:         $bar_width = 20;
15207:     } elsif ($NumBars < 10) {
15208:         $width = 120+$NumBars*15;
15209:         $xskip = 1;
15210:         $bar_width = 15;
15211:     } elsif ($NumBars <= 25) {
15212:         $width = 120+$NumBars*11;
15213:         $xskip = 5;
15214:         $bar_width = 8;
15215:     } elsif ($NumBars <= 50) {
15216:         $width = 120+$NumBars*8;
15217:         $xskip = 5;
15218:         $bar_width = 4;
15219:     } else {
15220:         $width = 120+$NumBars*8;
15221:         $xskip = 5;
15222:         $bar_width = 4;
15223:     }
15224:     #
15225:     $Max = 1 if ($Max < 1);
15226:     if ( int($Max) < $Max ) {
15227:         $Max++;
15228:         $Max = int($Max);
15229:     }
15230:     $Title  = '' if (! defined($Title));
15231:     $xlabel = '' if (! defined($xlabel));
15232:     $ylabel = '' if (! defined($ylabel));
15233:     $ValuesHash{$id.'.title'}    = &escape($Title);
15234:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
15235:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
15236:     $ValuesHash{$id.'.y_max_value'} = $Max;
15237:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
15238:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
15239:     $ValuesHash{$id.'.PlotType'} = 'bar';
15240:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
15241:     $ValuesHash{$id.'.height'}   = $height;
15242:     $ValuesHash{$id.'.width'}    = $width;
15243:     $ValuesHash{$id.'.xskip'}    = $xskip;
15244:     $ValuesHash{$id.'.bar_width'} = $bar_width;
15245:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
15246:     #
15247:     # Deal with other parameters
15248:     while (my ($key,$value) = each(%$extra_settings)) {
15249:         $ValuesHash{$id.'.'.$key} = $value;
15250:     }
15251:     #
15252:     &Apache::lonnet::appenv(\%ValuesHash);
15253:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15254: }
15255: 
15256: ############################################################
15257: ############################################################
15258: 
15259: =pod
15260: 
15261: =item * &DrawXYGraph()
15262: 
15263: Facilitates the plotting of data in an XY graph.
15264: Puts plot definition data into the users environment in order for 
15265: graph.png to plot it.  Returns an <img> tag for the plot.
15266: 
15267: Inputs:
15268: 
15269: =over 4
15270: 
15271: =item $Title: string, the title of the plot
15272: 
15273: =item $xlabel: string, text describing the X-axis of the plot
15274: 
15275: =item $ylabel: string, text describing the Y-axis of the plot
15276: 
15277: =item $Max: scalar, the maximum Y value to use in the plot
15278: If $Max is < any data point, the graph will not be rendered.
15279: 
15280: =item $colors: Array ref containing the hex color codes for the data to be 
15281: plotted in.  If undefined, default values will be used.
15282: 
15283: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
15284: 
15285: =item $Ydata: Array ref containing Array refs.  
15286: Each of the contained arrays will be plotted as a separate curve.
15287: 
15288: =item %Values: hash indicating or overriding any default values which are 
15289: passed to graph.png.  
15290: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
15291: 
15292: =back
15293: 
15294: Returns:
15295: 
15296: An <img> tag which references graph.png and the appropriate identifying
15297: information for the plot.
15298: 
15299: =cut
15300: 
15301: ############################################################
15302: ############################################################
15303: sub DrawXYGraph {
15304:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
15305:     #
15306:     # Create the identifier for the graph
15307:     my $identifier = &get_cgi_id();
15308:     my $id = 'cgi.'.$identifier;
15309:     #
15310:     $Title  = '' if (! defined($Title));
15311:     $xlabel = '' if (! defined($xlabel));
15312:     $ylabel = '' if (! defined($ylabel));
15313:     my %ValuesHash = 
15314:         (
15315:          $id.'.title'  => &escape($Title),
15316:          $id.'.xlabel' => &escape($xlabel),
15317:          $id.'.ylabel' => &escape($ylabel),
15318:          $id.'.y_max_value'=> $Max,
15319:          $id.'.labels'     => join(',',@$Xlabels),
15320:          $id.'.PlotType'   => 'XY',
15321:          );
15322:     #
15323:     if (defined($colors) && ref($colors) eq 'ARRAY') {
15324:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
15325:     }
15326:     #
15327:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
15328:         return '';
15329:     }
15330:     my $NumSets=1;
15331:     foreach my $array (@{$Ydata}){
15332:         next if (! ref($array));
15333:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
15334:     }
15335:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
15336:     #
15337:     # Deal with other parameters
15338:     while (my ($key,$value) = each(%Values)) {
15339:         $ValuesHash{$id.'.'.$key} = $value;
15340:     }
15341:     #
15342:     &Apache::lonnet::appenv(\%ValuesHash);
15343:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15344: }
15345: 
15346: ############################################################
15347: ############################################################
15348: 
15349: =pod
15350: 
15351: =item * &DrawXYYGraph()
15352: 
15353: Facilitates the plotting of data in an XY graph with two Y axes.
15354: Puts plot definition data into the users environment in order for 
15355: graph.png to plot it.  Returns an <img> tag for the plot.
15356: 
15357: Inputs:
15358: 
15359: =over 4
15360: 
15361: =item $Title: string, the title of the plot
15362: 
15363: =item $xlabel: string, text describing the X-axis of the plot
15364: 
15365: =item $ylabel: string, text describing the Y-axis of the plot
15366: 
15367: =item $colors: Array ref containing the hex color codes for the data to be 
15368: plotted in.  If undefined, default values will be used.
15369: 
15370: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
15371: 
15372: =item $Ydata1: The first data set
15373: 
15374: =item $Min1: The minimum value of the left Y-axis
15375: 
15376: =item $Max1: The maximum value of the left Y-axis
15377: 
15378: =item $Ydata2: The second data set
15379: 
15380: =item $Min2: The minimum value of the right Y-axis
15381: 
15382: =item $Max2: The maximum value of the left Y-axis
15383: 
15384: =item %Values: hash indicating or overriding any default values which are 
15385: passed to graph.png.  
15386: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
15387: 
15388: =back
15389: 
15390: Returns:
15391: 
15392: An <img> tag which references graph.png and the appropriate identifying
15393: information for the plot.
15394: 
15395: =cut
15396: 
15397: ############################################################
15398: ############################################################
15399: sub DrawXYYGraph {
15400:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
15401:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
15402:     #
15403:     # Create the identifier for the graph
15404:     my $identifier = &get_cgi_id();
15405:     my $id = 'cgi.'.$identifier;
15406:     #
15407:     $Title  = '' if (! defined($Title));
15408:     $xlabel = '' if (! defined($xlabel));
15409:     $ylabel = '' if (! defined($ylabel));
15410:     my %ValuesHash = 
15411:         (
15412:          $id.'.title'  => &escape($Title),
15413:          $id.'.xlabel' => &escape($xlabel),
15414:          $id.'.ylabel' => &escape($ylabel),
15415:          $id.'.labels' => join(',',@$Xlabels),
15416:          $id.'.PlotType' => 'XY',
15417:          $id.'.NumSets' => 2,
15418:          $id.'.two_axes' => 1,
15419:          $id.'.y1_max_value' => $Max1,
15420:          $id.'.y1_min_value' => $Min1,
15421:          $id.'.y2_max_value' => $Max2,
15422:          $id.'.y2_min_value' => $Min2,
15423:          );
15424:     #
15425:     if (defined($colors) && ref($colors) eq 'ARRAY') {
15426:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
15427:     }
15428:     #
15429:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
15430:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
15431:         return '';
15432:     }
15433:     my $NumSets=1;
15434:     foreach my $array ($Ydata1,$Ydata2){
15435:         next if (! ref($array));
15436:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
15437:     }
15438:     #
15439:     # Deal with other parameters
15440:     while (my ($key,$value) = each(%Values)) {
15441:         $ValuesHash{$id.'.'.$key} = $value;
15442:     }
15443:     #
15444:     &Apache::lonnet::appenv(\%ValuesHash);
15445:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15446: }
15447: 
15448: ############################################################
15449: ############################################################
15450: 
15451: =pod
15452: 
15453: =back 
15454: 
15455: =head1 Statistics helper routines?  
15456: 
15457: Bad place for them but what the hell.
15458: 
15459: =over 4
15460: 
15461: =item * &chartlink()
15462: 
15463: Returns a link to the chart for a specific student.  
15464: 
15465: Inputs:
15466: 
15467: =over 4
15468: 
15469: =item $linktext: The text of the link
15470: 
15471: =item $sname: The students username
15472: 
15473: =item $sdomain: The students domain
15474: 
15475: =back
15476: 
15477: =back
15478: 
15479: =cut
15480: 
15481: ############################################################
15482: ############################################################
15483: sub chartlink {
15484:     my ($linktext, $sname, $sdomain) = @_;
15485:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
15486:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
15487:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
15488:        '">'.$linktext.'</a>';
15489: }
15490: 
15491: #######################################################
15492: #######################################################
15493: 
15494: =pod
15495: 
15496: =head1 Course Environment Routines
15497: 
15498: =over 4
15499: 
15500: =item * &restore_course_settings()
15501: 
15502: =item * &store_course_settings()
15503: 
15504: Restores/Store indicated form parameters from the course environment.
15505: Will not overwrite existing values of the form parameters.
15506: 
15507: Inputs: 
15508: a scalar describing the data (e.g. 'chart', 'problem_analysis')
15509: 
15510: a hash ref describing the data to be stored.  For example:
15511:    
15512: %Save_Parameters = ('Status' => 'scalar',
15513:     'chartoutputmode' => 'scalar',
15514:     'chartoutputdata' => 'scalar',
15515:     'Section' => 'array',
15516:     'Group' => 'array',
15517:     'StudentData' => 'array',
15518:     'Maps' => 'array');
15519: 
15520: Returns: both routines return nothing
15521: 
15522: =back
15523: 
15524: =cut
15525: 
15526: #######################################################
15527: #######################################################
15528: sub store_course_settings {
15529:     return &store_settings($env{'request.course.id'},@_);
15530: }
15531: 
15532: sub store_settings {
15533:     # save to the environment
15534:     # appenv the same items, just to be safe
15535:     my $udom  = $env{'user.domain'};
15536:     my $uname = $env{'user.name'};
15537:     my ($context,$prefix,$Settings) = @_;
15538:     my %SaveHash;
15539:     my %AppHash;
15540:     while (my ($setting,$type) = each(%$Settings)) {
15541:         my $basename = join('.','internal',$context,$prefix,$setting);
15542:         my $envname = 'environment.'.$basename;
15543:         if (exists($env{'form.'.$setting})) {
15544:             # Save this value away
15545:             if ($type eq 'scalar' &&
15546:                 (! exists($env{$envname}) || 
15547:                  $env{$envname} ne $env{'form.'.$setting})) {
15548:                 $SaveHash{$basename} = $env{'form.'.$setting};
15549:                 $AppHash{$envname}   = $env{'form.'.$setting};
15550:             } elsif ($type eq 'array') {
15551:                 my $stored_form;
15552:                 if (ref($env{'form.'.$setting})) {
15553:                     $stored_form = join(',',
15554:                                         map {
15555:                                             &escape($_);
15556:                                         } sort(@{$env{'form.'.$setting}}));
15557:                 } else {
15558:                     $stored_form = 
15559:                         &escape($env{'form.'.$setting});
15560:                 }
15561:                 # Determine if the array contents are the same.
15562:                 if ($stored_form ne $env{$envname}) {
15563:                     $SaveHash{$basename} = $stored_form;
15564:                     $AppHash{$envname}   = $stored_form;
15565:                 }
15566:             }
15567:         }
15568:     }
15569:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
15570:                                           $udom,$uname);
15571:     if ($put_result !~ /^(ok|delayed)/) {
15572:         &Apache::lonnet::logthis('unable to save form parameters, '.
15573:                                  'got error:'.$put_result);
15574:     }
15575:     # Make sure these settings stick around in this session, too
15576:     &Apache::lonnet::appenv(\%AppHash);
15577:     return;
15578: }
15579: 
15580: sub restore_course_settings {
15581:     return &restore_settings($env{'request.course.id'},@_);
15582: }
15583: 
15584: sub restore_settings {
15585:     my ($context,$prefix,$Settings) = @_;
15586:     while (my ($setting,$type) = each(%$Settings)) {
15587:         next if (exists($env{'form.'.$setting}));
15588:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
15589:             '.'.$setting;
15590:         if (exists($env{$envname})) {
15591:             if ($type eq 'scalar') {
15592:                 $env{'form.'.$setting} = $env{$envname};
15593:             } elsif ($type eq 'array') {
15594:                 $env{'form.'.$setting} = [ 
15595:                                            map { 
15596:                                                &unescape($_); 
15597:                                            } split(',',$env{$envname})
15598:                                            ];
15599:             }
15600:         }
15601:     }
15602: }
15603: 
15604: #######################################################
15605: #######################################################
15606: 
15607: =pod
15608: 
15609: =head1 Domain E-mail Routines  
15610: 
15611: =over 4
15612: 
15613: =item * &build_recipient_list()
15614: 
15615: Build recipient lists for following types of e-mail:
15616: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
15617: (d) Help requests, (e) Course requests needing approval, (f) loncapa
15618: module change checking, student/employee ID conflict checks, as
15619: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
15620: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
15621: 
15622: Inputs:
15623: defmail (scalar - email address of default recipient), 
15624: mailing type (scalar: errormail, packagesmail, helpdeskmail,
15625: requestsmail, updatesmail, or idconflictsmail).
15626: 
15627: defdom (domain for which to retrieve configuration settings),
15628: 
15629: origmail (scalar - email address of recipient from loncapa.conf, 
15630: i.e., predates configuration by DC via domainprefs.pm
15631: 
15632: $requname username of requester (if mailing type is helpdeskmail)
15633: 
15634: $requdom domain of requester (if mailing type is helpdeskmail)
15635: 
15636: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
15637: 
15638: 
15639: Returns: comma separated list of addresses to which to send e-mail.
15640: 
15641: =back
15642: 
15643: =cut
15644: 
15645: ############################################################
15646: ############################################################
15647: sub build_recipient_list {
15648:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
15649:     my @recipients;
15650:     my ($otheremails,$lastresort,$allbcc,$addtext);
15651:     my %domconfig =
15652:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
15653:     if (ref($domconfig{'contacts'}) eq 'HASH') {
15654:         if (exists($domconfig{'contacts'}{$mailing})) {
15655:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
15656:                 my @contacts = ('adminemail','supportemail');
15657:                 foreach my $item (@contacts) {
15658:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
15659:                         my $addr = $domconfig{'contacts'}{$item}; 
15660:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
15661:                             push(@recipients,$addr);
15662:                         }
15663:                     }
15664:                 }
15665:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
15666:                 if ($mailing eq 'helpdeskmail') {
15667:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
15668:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
15669:                         my @ok_bccs;
15670:                         foreach my $bcc (@bccs) {
15671:                             $bcc =~ s/^\s+//g;
15672:                             $bcc =~ s/\s+$//g;
15673:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15674:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15675:                                     push(@ok_bccs,$bcc);
15676:                                 }
15677:                             }
15678:                         }
15679:                         if (@ok_bccs > 0) {
15680:                             $allbcc = join(', ',@ok_bccs);
15681:                         }
15682:                     }
15683:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
15684:                 }
15685:             }
15686:         } elsif ($origmail ne '') {
15687:             $lastresort = $origmail;
15688:         }
15689:         if ($mailing eq 'helpdeskmail') {
15690:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
15691:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
15692:                 my ($inststatus,$inststatus_checked);
15693:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
15694:                     ($env{'user.domain'} ne 'public')) {
15695:                     $inststatus_checked = 1;
15696:                     $inststatus = $env{'environment.inststatus'};
15697:                 }
15698:                 unless ($inststatus_checked) {
15699:                     if (($requname ne '') && ($requdom ne '')) {
15700:                         if (($requname =~ /^$match_username$/) &&
15701:                             ($requdom =~ /^$match_domain$/) &&
15702:                             (&Apache::lonnet::domain($requdom))) {
15703:                             my $requhome = &Apache::lonnet::homeserver($requname,
15704:                                                                       $requdom);
15705:                             unless ($requhome eq 'no_host') {
15706:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
15707:                                 $inststatus = $userenv{'inststatus'};
15708:                                 $inststatus_checked = 1;
15709:                             }
15710:                         }
15711:                     }
15712:                 }
15713:                 unless ($inststatus_checked) {
15714:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
15715:                         my %srch = (srchby     => 'email',
15716:                                     srchdomain => $defdom,
15717:                                     srchterm   => $reqemail,
15718:                                     srchtype   => 'exact');
15719:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
15720:                         foreach my $uname (keys(%srch_results)) {
15721:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
15722:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
15723:                                 $inststatus_checked = 1;
15724:                                 last;
15725:                             }
15726:                         }
15727:                         unless ($inststatus_checked) {
15728:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
15729:                             if ($dirsrchres eq 'ok') {
15730:                                 foreach my $uname (keys(%srch_results)) {
15731:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
15732:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
15733:                                         $inststatus_checked = 1;
15734:                                         last;
15735:                                     }
15736:                                 }
15737:                             }
15738:                         }
15739:                     }
15740:                 }
15741:                 if ($inststatus ne '') {
15742:                     foreach my $status (split(/\:/,$inststatus)) {
15743:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
15744:                             my @contacts = ('adminemail','supportemail');
15745:                             foreach my $item (@contacts) {
15746:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
15747:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
15748:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
15749:                                         push(@recipients,$addr);
15750:                                     }
15751:                                 }
15752:                             }
15753:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
15754:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
15755:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
15756:                                 my @ok_bccs;
15757:                                 foreach my $bcc (@bccs) {
15758:                                     $bcc =~ s/^\s+//g;
15759:                                     $bcc =~ s/\s+$//g;
15760:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15761:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15762:                                             push(@ok_bccs,$bcc);
15763:                                         }
15764:                                     }
15765:                                 }
15766:                                 if (@ok_bccs > 0) {
15767:                                     $allbcc = join(', ',@ok_bccs);
15768:                                 }
15769:                             }
15770:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
15771:                             last;
15772:                         }
15773:                     }
15774:                 }
15775:             }
15776:         }
15777:     } elsif ($origmail ne '') {
15778:         $lastresort = $origmail;
15779:     }
15780:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
15781:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
15782:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
15783:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
15784:             my %what = (
15785:                           perlvar => 1,
15786:                        );
15787:             my $primary = &Apache::lonnet::domain($defdom,'primary');
15788:             if ($primary) {
15789:                 my $gotaddr;
15790:                 my ($result,$returnhash) =
15791:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
15792:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
15793:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
15794:                         $lastresort = $returnhash->{'lonSupportEMail'};
15795:                         $gotaddr = 1;
15796:                     }
15797:                 }
15798:                 unless ($gotaddr) {
15799:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
15800:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
15801:                     unless ($uintdom eq $intdom) {
15802:                         my %domconfig =
15803:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
15804:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
15805:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
15806:                                 my @contacts = ('adminemail','supportemail');
15807:                                 foreach my $item (@contacts) {
15808:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
15809:                                         my $addr = $domconfig{'contacts'}{$item};
15810:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
15811:                                             push(@recipients,$addr);
15812:                                         }
15813:                                     }
15814:                                 }
15815:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
15816:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
15817:                                 }
15818:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
15819:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
15820:                                     my @ok_bccs;
15821:                                     foreach my $bcc (@bccs) {
15822:                                         $bcc =~ s/^\s+//g;
15823:                                         $bcc =~ s/\s+$//g;
15824:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15825:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15826:                                                 push(@ok_bccs,$bcc);
15827:                                             }
15828:                                         }
15829:                                     }
15830:                                     if (@ok_bccs > 0) {
15831:                                         $allbcc = join(', ',@ok_bccs);
15832:                                     }
15833:                                 }
15834:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
15835:                             }
15836:                         }
15837:                     }
15838:                 }
15839:             }
15840:         }
15841:     }
15842:     if (defined($defmail)) {
15843:         if ($defmail ne '') {
15844:             push(@recipients,$defmail);
15845:         }
15846:     }
15847:     if ($otheremails) {
15848:         my @others;
15849:         if ($otheremails =~ /,/) {
15850:             @others = split(/,/,$otheremails);
15851:         } else {
15852:             push(@others,$otheremails);
15853:         }
15854:         foreach my $addr (@others) {
15855:             if (!grep(/^\Q$addr\E$/,@recipients)) {
15856:                 push(@recipients,$addr);
15857:             }
15858:         }
15859:     }
15860:     if ($mailing eq 'helpdeskmail') {
15861:         if ((!@recipients) && ($lastresort ne '')) {
15862:             push(@recipients,$lastresort);
15863:         }
15864:     } elsif ($lastresort ne '') {
15865:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
15866:             push(@recipients,$lastresort);
15867:         }
15868:     }
15869:     my $recipientlist = join(',',@recipients);
15870:     if (wantarray) {
15871:         return ($recipientlist,$allbcc,$addtext);
15872:     } else {
15873:         return $recipientlist;
15874:     }
15875: }
15876: 
15877: ############################################################
15878: ############################################################
15879: 
15880: =pod
15881: 
15882: =over 4
15883: 
15884: =item * &mime_email()
15885: 
15886: Sends an email with a possible attachment
15887: 
15888: Inputs:
15889: 
15890: =over 4
15891: 
15892: from -              Sender's email address
15893: 
15894: replyto -           Reply-To email address
15895: 
15896: to -                Email address of recipient
15897: 
15898: subject -           Subject of email
15899: 
15900: body -              Body of email
15901: 
15902: cc_string -         Carbon copy email address
15903: 
15904: bcc -               Blind carbon copy email address
15905: 
15906: attachment_path -   Path of file to be attached
15907: 
15908: file_name -         Name of file to be attached
15909: 
15910: attachment_text -   The body of an attachment of type "TEXT"
15911: 
15912: =back
15913: 
15914: =back
15915: 
15916: =cut
15917: 
15918: ############################################################
15919: ############################################################
15920: 
15921: sub mime_email {
15922:     my ($from,$replyto,$to,$subject,$body,$cc_string,$bcc,$attachment_path, 
15923:         $file_name,$attachment_text) = @_;
15924:  
15925:     my $msg = MIME::Lite->new(
15926:              From    => $from,
15927:              To      => $to,
15928:              Subject => $subject,
15929:              Type    =>'TEXT',
15930:              Data    => $body,
15931:              );
15932:     if ($replyto ne '') {
15933:         $msg->add("Reply-To" => $replyto);
15934:     }
15935:     if ($cc_string ne '') {
15936:         $msg->add("Cc" => $cc_string);
15937:     }
15938:     if ($bcc ne '') {
15939:         $msg->add("Bcc" => $bcc);
15940:     }
15941:     $msg->attr("content-type"         => "text/plain");
15942:     $msg->attr("content-type.charset" => "UTF-8");
15943:     # Attach file if given
15944:     if ($attachment_path) {
15945:         unless ($file_name) {
15946:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
15947:         }
15948:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
15949:         $msg->attach(Type     => $type,
15950:                      Path     => $attachment_path,
15951:                      Filename => $file_name
15952:                      );
15953:     # Otherwise attach text if given
15954:     } elsif ($attachment_text) {
15955:         $msg->attach(Type => 'TEXT',
15956:                      Data => $attachment_text);
15957:     }
15958:     # Send it
15959:     $msg->send('sendmail');
15960: }
15961: 
15962: ############################################################
15963: ############################################################
15964: 
15965: =pod
15966: 
15967: =head1 Course Catalog Routines
15968: 
15969: =over 4
15970: 
15971: =item * &gather_categories()
15972: 
15973: Converts category definitions - keys of categories hash stored in  
15974: coursecategories in configuration.db on the primary library server in a 
15975: domain - to an array.  Also generates javascript and idx hash used to 
15976: generate Domain Coordinator interface for editing Course Categories.
15977: 
15978: Inputs:
15979: 
15980: categories (reference to hash of category definitions).
15981: 
15982: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15983:       categories and subcategories).
15984: 
15985: idx (reference to hash of counters used in Domain Coordinator interface for 
15986:       editing Course Categories).
15987: 
15988: jsarray (reference to array of categories used to create Javascript arrays for
15989:          Domain Coordinator interface for editing Course Categories).
15990: 
15991: Returns: nothing
15992: 
15993: Side effects: populates cats, idx and jsarray. 
15994: 
15995: =cut
15996: 
15997: sub gather_categories {
15998:     my ($categories,$cats,$idx,$jsarray) = @_;
15999:     my %counters;
16000:     my $num = 0;
16001:     foreach my $item (keys(%{$categories})) {
16002:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
16003:         if ($container eq '' && $depth == 0) {
16004:             $cats->[$depth][$categories->{$item}] = $cat;
16005:         } else {
16006:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
16007:         }
16008:         my ($escitem,$tail) = split(/:/,$item,2);
16009:         if ($counters{$tail} eq '') {
16010:             $counters{$tail} = $num;
16011:             $num ++;
16012:         }
16013:         if (ref($idx) eq 'HASH') {
16014:             $idx->{$item} = $counters{$tail};
16015:         }
16016:         if (ref($jsarray) eq 'ARRAY') {
16017:             push(@{$jsarray->[$counters{$tail}]},$item);
16018:         }
16019:     }
16020:     return;
16021: }
16022: 
16023: =pod
16024: 
16025: =item * &extract_categories()
16026: 
16027: Used to generate breadcrumb trails for course categories.
16028: 
16029: Inputs:
16030: 
16031: categories (reference to hash of category definitions).
16032: 
16033: cats (reference to array of arrays/hashes which encapsulates hierarchy of
16034:       categories and subcategories).
16035: 
16036: trails (reference to array of breacrumb trails for each category).
16037: 
16038: allitems (reference to hash - key is category key 
16039:          (format: escaped(name):escaped(parent category):depth in hierarchy).
16040: 
16041: idx (reference to hash of counters used in Domain Coordinator interface for
16042:       editing Course Categories).
16043: 
16044: jsarray (reference to array of categories used to create Javascript arrays for
16045:          Domain Coordinator interface for editing Course Categories).
16046: 
16047: subcats (reference to hash of arrays containing all subcategories within each 
16048:          category, -recursive)
16049: 
16050: maxd (reference to hash used to hold max depth for all top-level categories).
16051: 
16052: Returns: nothing
16053: 
16054: Side effects: populates trails and allitems hash references.
16055: 
16056: =cut
16057: 
16058: sub extract_categories {
16059:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
16060:     if (ref($categories) eq 'HASH') {
16061:         &gather_categories($categories,$cats,$idx,$jsarray);
16062:         if (ref($cats->[0]) eq 'ARRAY') {
16063:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
16064:                 my $name = $cats->[0][$i];
16065:                 my $item = &escape($name).'::0';
16066:                 my $trailstr;
16067:                 if ($name eq 'instcode') {
16068:                     $trailstr = &mt('Official courses (with institutional codes)');
16069:                 } elsif ($name eq 'communities') {
16070:                     $trailstr = &mt('Communities');
16071:                 } elsif ($name eq 'placement') {
16072:                     $trailstr = &mt('Placement Tests');
16073:                 } else {
16074:                     $trailstr = $name;
16075:                 }
16076:                 if ($allitems->{$item} eq '') {
16077:                     push(@{$trails},$trailstr);
16078:                     $allitems->{$item} = scalar(@{$trails})-1;
16079:                 }
16080:                 my @parents = ($name);
16081:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
16082:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
16083:                         my $category = $cats->[1]{$name}[$j];
16084:                         if (ref($subcats) eq 'HASH') {
16085:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
16086:                         }
16087:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
16088:                     }
16089:                 } else {
16090:                     if (ref($subcats) eq 'HASH') {
16091:                         $subcats->{$item} = [];
16092:                     }
16093:                     if (ref($maxd) eq 'HASH') {
16094:                         $maxd->{$name} = 1;
16095:                     }
16096:                 }
16097:             }
16098:         }
16099:     }
16100:     return;
16101: }
16102: 
16103: =pod
16104: 
16105: =item * &recurse_categories()
16106: 
16107: Recursively used to generate breadcrumb trails for course categories.
16108: 
16109: Inputs:
16110: 
16111: cats (reference to array of arrays/hashes which encapsulates hierarchy of
16112:       categories and subcategories).
16113: 
16114: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
16115: 
16116: category (current course category, for which breadcrumb trail is being generated).
16117: 
16118: trails (reference to array of breadcrumb trails for each category).
16119: 
16120: allitems (reference to hash - key is category key
16121:          (format: escaped(name):escaped(parent category):depth in hierarchy).
16122: 
16123: parents (array containing containers directories for current category, 
16124:          back to top level). 
16125: 
16126: Returns: nothing
16127: 
16128: Side effects: populates trails and allitems hash references
16129: 
16130: =cut
16131: 
16132: sub recurse_categories {
16133:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
16134:     my $shallower = $depth - 1;
16135:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
16136:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
16137:             my $name = $cats->[$depth]{$category}[$k];
16138:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
16139:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
16140:             if ($allitems->{$item} eq '') {
16141:                 push(@{$trails},$trailstr);
16142:                 $allitems->{$item} = scalar(@{$trails})-1;
16143:             }
16144:             my $deeper = $depth+1;
16145:             push(@{$parents},$category);
16146:             if (ref($subcats) eq 'HASH') {
16147:                 my $subcat = &escape($name).':'.$category.':'.$depth;
16148:                 for (my $j=@{$parents}; $j>=0; $j--) {
16149:                     my $higher;
16150:                     if ($j > 0) {
16151:                         $higher = &escape($parents->[$j]).':'.
16152:                                   &escape($parents->[$j-1]).':'.$j;
16153:                     } else {
16154:                         $higher = &escape($parents->[$j]).'::'.$j;
16155:                     }
16156:                     push(@{$subcats->{$higher}},$subcat);
16157:                 }
16158:             }
16159:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
16160:                                 $subcats,$maxd);
16161:             pop(@{$parents});
16162:         }
16163:     } else {
16164:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
16165:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
16166:         if ($allitems->{$item} eq '') {
16167:             push(@{$trails},$trailstr);
16168:             $allitems->{$item} = scalar(@{$trails})-1;
16169:         }
16170:         if (ref($maxd) eq 'HASH') {
16171:             if ($depth > $maxd->{$parents->[0]}) {
16172:                 $maxd->{$parents->[0]} = $depth;
16173:             }
16174:         }
16175:     }
16176:     return;
16177: }
16178: 
16179: =pod
16180: 
16181: =item * &assign_categories_table()
16182: 
16183: Create a datatable for display of hierarchical categories in a domain,
16184: with checkboxes to allow a course to be categorized. 
16185: 
16186: Inputs:
16187: 
16188: cathash - reference to hash of categories defined for the domain (from
16189:           configuration.db)
16190: 
16191: currcat - scalar with an & separated list of categories assigned to a course. 
16192: 
16193: type    - scalar contains course type (Course or Community).
16194: 
16195: disabled - scalar (optional) contains disabled="disabled" if input elements are
16196:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
16197: 
16198: Returns: $output (markup to be displayed) 
16199: 
16200: =cut
16201: 
16202: sub assign_categories_table {
16203:     my ($cathash,$currcat,$type,$disabled) = @_;
16204:     my $output;
16205:     if (ref($cathash) eq 'HASH') {
16206:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
16207:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
16208:         $maxdepth = scalar(@cats);
16209:         if (@cats > 0) {
16210:             my $itemcount = 0;
16211:             if (ref($cats[0]) eq 'ARRAY') {
16212:                 my @currcategories;
16213:                 if ($currcat ne '') {
16214:                     @currcategories = split('&',$currcat);
16215:                 }
16216:                 my $table;
16217:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
16218:                     my $parent = $cats[0][$i];
16219:                     next if ($parent eq 'instcode');
16220:                     if ($type eq 'Community') {
16221:                         next unless ($parent eq 'communities');
16222:                     } elsif ($type eq 'Placement') {
16223:                         next unless ($parent eq 'placement');
16224:                     } else {
16225:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
16226:                     }
16227:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
16228:                     my $item = &escape($parent).'::0';
16229:                     my $checked = '';
16230:                     if (@currcategories > 0) {
16231:                         if (grep(/^\Q$item\E$/,@currcategories)) {
16232:                             $checked = ' checked="checked"';
16233:                         }
16234:                     }
16235:                     my $parent_title = $parent;
16236:                     if ($parent eq 'communities') {
16237:                         $parent_title = &mt('Communities');
16238:                     } elsif ($parent eq 'placement') {
16239:                         $parent_title = &mt('Placement Tests');
16240:                     }
16241:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
16242:                               '<input type="checkbox" name="usecategory" value="'.
16243:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
16244:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
16245:                     my $depth = 1;
16246:                     push(@path,$parent);
16247:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
16248:                     pop(@path);
16249:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
16250:                     $itemcount ++;
16251:                 }
16252:                 if ($itemcount) {
16253:                     $output = &Apache::loncommon::start_data_table().
16254:                               $table.
16255:                               &Apache::loncommon::end_data_table();
16256:                 }
16257:             }
16258:         }
16259:     }
16260:     return $output;
16261: }
16262: 
16263: =pod
16264: 
16265: =item * &assign_category_rows()
16266: 
16267: Create a datatable row for display of nested categories in a domain,
16268: with checkboxes to allow a course to be categorized,called recursively.
16269: 
16270: Inputs:
16271: 
16272: itemcount - track row number for alternating colors
16273: 
16274: cats - reference to array of arrays/hashes which encapsulates hierarchy of
16275:       categories and subcategories.
16276: 
16277: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
16278: 
16279: parent - parent of current category item
16280: 
16281: path - Array containing all categories back up through the hierarchy from the
16282:        current category to the top level.
16283: 
16284: currcategories - reference to array of current categories assigned to the course
16285: 
16286: disabled - scalar (optional) contains disabled="disabled" if input elements are
16287:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
16288: 
16289: Returns: $output (markup to be displayed).
16290: 
16291: =cut
16292: 
16293: sub assign_category_rows {
16294:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
16295:     my ($text,$name,$item,$chgstr);
16296:     if (ref($cats) eq 'ARRAY') {
16297:         my $maxdepth = scalar(@{$cats});
16298:         if (ref($cats->[$depth]) eq 'HASH') {
16299:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
16300:                 my $numchildren = @{$cats->[$depth]{$parent}};
16301:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
16302:                 $text .= '<td><table class="LC_data_table">';
16303:                 for (my $j=0; $j<$numchildren; $j++) {
16304:                     $name = $cats->[$depth]{$parent}[$j];
16305:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
16306:                     my $deeper = $depth+1;
16307:                     my $checked = '';
16308:                     if (ref($currcategories) eq 'ARRAY') {
16309:                         if (@{$currcategories} > 0) {
16310:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
16311:                                 $checked = ' checked="checked"';
16312:                             }
16313:                         }
16314:                     }
16315:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
16316:                              '<input type="checkbox" name="usecategory" value="'.
16317:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
16318:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
16319:                              '</td><td>';
16320:                     if (ref($path) eq 'ARRAY') {
16321:                         push(@{$path},$name);
16322:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
16323:                         pop(@{$path});
16324:                     }
16325:                     $text .= '</td></tr>';
16326:                 }
16327:                 $text .= '</table></td>';
16328:             }
16329:         }
16330:     }
16331:     return $text;
16332: }
16333: 
16334: =pod
16335: 
16336: =back
16337: 
16338: =cut
16339: 
16340: ############################################################
16341: ############################################################
16342: 
16343: 
16344: sub commit_customrole {
16345:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
16346:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
16347:                          ($start?', '.&mt('starting').' '.localtime($start):'').
16348:                          ($end?', ending '.localtime($end):'').': <b>'.
16349:               &Apache::lonnet::assigncustomrole(
16350:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
16351:                  '</b><br />';
16352:     return $output;
16353: }
16354: 
16355: sub commit_standardrole {
16356:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
16357:     my ($output,$logmsg,$linefeed);
16358:     if ($context eq 'auto') {
16359:         $linefeed = "\n";
16360:     } else {
16361:         $linefeed = "<br />\n";
16362:     }  
16363:     if ($three eq 'st') {
16364:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
16365:                                          $one,$two,$sec,$context,$credits);
16366:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
16367:             ($result eq 'unknown_course') || ($result eq 'refused')) {
16368:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
16369:         } else {
16370:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
16371:                ($start?', '.&mt('starting').' '.localtime($start):'').
16372:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
16373:             if ($context eq 'auto') {
16374:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
16375:             } else {
16376:                $output .= '<b>'.$result.'</b>'.$linefeed.
16377:                &mt('Add to classlist').': <b>ok</b>';
16378:             }
16379:             $output .= $linefeed;
16380:         }
16381:     } else {
16382:         $output = &mt('Assigning').' '.$three.' in '.$url.
16383:                ($start?', '.&mt('starting').' '.localtime($start):'').
16384:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
16385:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
16386:         if ($context eq 'auto') {
16387:             $output .= $result.$linefeed;
16388:         } else {
16389:             $output .= '<b>'.$result.'</b>'.$linefeed;
16390:         }
16391:     }
16392:     return $output;
16393: }
16394: 
16395: sub commit_studentrole {
16396:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
16397:         $credits) = @_;
16398:     my ($result,$linefeed,$oldsecurl,$newsecurl);
16399:     if ($context eq 'auto') {
16400:         $linefeed = "\n";
16401:     } else {
16402:         $linefeed = '<br />'."\n";
16403:     }
16404:     if (defined($one) && defined($two)) {
16405:         my $cid=$one.'_'.$two;
16406:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
16407:         my $secchange = 0;
16408:         my $expire_role_result;
16409:         my $modify_section_result;
16410:         if ($oldsec ne '-1') { 
16411:             if ($oldsec ne $sec) {
16412:                 $secchange = 1;
16413:                 my $now = time;
16414:                 my $uurl='/'.$cid;
16415:                 $uurl=~s/\_/\//g;
16416:                 if ($oldsec) {
16417:                     $uurl.='/'.$oldsec;
16418:                 }
16419:                 $oldsecurl = $uurl;
16420:                 $expire_role_result = 
16421:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
16422:                 if ($env{'request.course.sec'} ne '') { 
16423:                     if ($expire_role_result eq 'refused') {
16424:                         my @roles = ('st');
16425:                         my @statuses = ('previous');
16426:                         my @roledoms = ($one);
16427:                         my $withsec = 1;
16428:                         my %roleshash = 
16429:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
16430:                                               \@statuses,\@roles,\@roledoms,$withsec);
16431:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
16432:                             my ($oldstart,$oldend) = 
16433:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
16434:                             if ($oldend > 0 && $oldend <= $now) {
16435:                                 $expire_role_result = 'ok';
16436:                             }
16437:                         }
16438:                     }
16439:                 }
16440:                 $result = $expire_role_result;
16441:             }
16442:         }
16443:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
16444:             $modify_section_result = 
16445:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
16446:                                                            undef,undef,undef,$sec,
16447:                                                            $end,$start,'','',$cid,
16448:                                                            '',$context,$credits);
16449:             if ($modify_section_result =~ /^ok/) {
16450:                 if ($secchange == 1) {
16451:                     if ($sec eq '') {
16452:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
16453:                     } else {
16454:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
16455:                     }
16456:                 } elsif ($oldsec eq '-1') {
16457:                     if ($sec eq '') {
16458:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
16459:                     } else {
16460:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
16461:                     }
16462:                 } else {
16463:                     if ($sec eq '') {
16464:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
16465:                     } else {
16466:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
16467:                     }
16468:                 }
16469:             } else {
16470:                 if ($secchange) { 
16471:                     $$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;
16472:                 } else {
16473:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
16474:                 }
16475:             }
16476:             $result = $modify_section_result;
16477:         } elsif ($secchange == 1) {
16478:             if ($oldsec eq '') {
16479:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
16480:             } else {
16481:                 $$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;
16482:             }
16483:             if ($expire_role_result eq 'refused') {
16484:                 my $newsecurl = '/'.$cid;
16485:                 $newsecurl =~ s/\_/\//g;
16486:                 if ($sec ne '') {
16487:                     $newsecurl.='/'.$sec;
16488:                 }
16489:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
16490:                     if ($sec eq '') {
16491:                         $$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;
16492:                     } else {
16493:                         $$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;
16494:                     }
16495:                 }
16496:             }
16497:         }
16498:     } else {
16499:         $$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;
16500:         $result = "error: incomplete course id\n";
16501:     }
16502:     return $result;
16503: }
16504: 
16505: sub show_role_extent {
16506:     my ($scope,$context,$role) = @_;
16507:     $scope =~ s{^/}{};
16508:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
16509:     push(@courseroles,'co');
16510:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
16511:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
16512:         $scope =~ s{/}{_};
16513:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
16514:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
16515:         my ($audom,$auname) = split(/\//,$scope);
16516:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
16517:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
16518:     } else {
16519:         $scope =~ s{/$}{};
16520:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
16521:                    &Apache::lonnet::domain($scope,'description').'</span>');
16522:     }
16523: }
16524: 
16525: ############################################################
16526: ############################################################
16527: 
16528: sub check_clone {
16529:     my ($args,$linefeed) = @_;
16530:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
16531:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
16532:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
16533:     my $clonetitle;
16534:     my @clonemsg;
16535:     my $can_clone = 0;
16536:     my $lctype = lc($args->{'crstype'});
16537:     if ($lctype ne 'community') {
16538:         $lctype = 'course';
16539:     }
16540:     if ($clonehome eq 'no_host') {
16541:         if ($args->{'crstype'} eq 'Community') {
16542:             push(@clonemsg,({
16543:                               mt => 'No new community created.',
16544:                               args => [],
16545:                             },
16546:                             {
16547:                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
16548:                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
16549:                             }));
16550:         } else {
16551:             push(@clonemsg,({
16552:                               mt => 'No new course created.',
16553:                               args => [],
16554:                             },
16555:                             {
16556:                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
16557:                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
16558:                             }));
16559:         }
16560:     } else {
16561: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
16562:         $clonetitle = $clonedesc{'description'};
16563:         if ($args->{'crstype'} eq 'Community') {
16564:             if ($clonedesc{'type'} ne 'Community') {
16565:                 push(@clonemsg,({
16566:                                   mt => 'No new community created.',
16567:                                   args => [],
16568:                                 },
16569:                                 {
16570:                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
16571:                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
16572:                                 }));
16573:                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
16574:             }
16575:         }
16576: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
16577:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
16578: 	    $can_clone = 1;
16579: 	} else {
16580: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
16581: 						 $args->{'clonedomain'},$args->{'clonecourse'});
16582:             if ($clonehash{'cloners'} eq '') {
16583:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
16584:                 if ($domdefs{'canclone'}) {
16585:                     unless ($domdefs{'canclone'} eq 'none') {
16586:                         if ($domdefs{'canclone'} eq 'domain') {
16587:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
16588:                                 $can_clone = 1;
16589:                             }
16590:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
16591:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
16592:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
16593:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
16594:                                 $can_clone = 1;
16595:                             }
16596:                         }
16597:                     }
16598:                 }
16599:             } else {
16600: 	        my @cloners = split(/,/,$clonehash{'cloners'});
16601:                 if (grep(/^\*$/,@cloners)) {
16602:                     $can_clone = 1;
16603:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
16604:                     $can_clone = 1;
16605:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
16606:                     $can_clone = 1;
16607:                 }
16608:                 unless ($can_clone) {
16609:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
16610:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
16611:                         my (%gotdomdefaults,%gotcodedefaults);
16612:                         foreach my $cloner (@cloners) {
16613:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
16614:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
16615:                                 my (%codedefaults,@code_order);
16616:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
16617:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
16618:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
16619:                                     }
16620:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
16621:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
16622:                                     }
16623:                                 } else {
16624:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
16625:                                                                             \%codedefaults,
16626:                                                                             \@code_order);
16627:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
16628:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
16629:                                 }
16630:                                 if (@code_order > 0) {
16631:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
16632:                                                                                 $cloner,$clonehash{'internal.coursecode'},
16633:                                                                                 $args->{'crscode'})) {
16634:                                         $can_clone = 1;
16635:                                         last;
16636:                                     }
16637:                                 }
16638:                             }
16639:                         }
16640:                     }
16641:                 }
16642:             }
16643:             unless ($can_clone) {
16644:                 my $ccrole = 'cc';
16645:                 if ($args->{'crstype'} eq 'Community') {
16646:                     $ccrole = 'co';
16647:                 }
16648: 	        my %roleshash =
16649: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
16650: 					          $args->{'ccdomain'},
16651:                                                   'userroles',['active'],[$ccrole],
16652: 					          [$args->{'clonedomain'}]);
16653: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
16654:                     $can_clone = 1;
16655:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
16656:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
16657:                     $can_clone = 1;
16658:                 }
16659:             }
16660:             unless ($can_clone) {
16661:                 if ($args->{'crstype'} eq 'Community') {
16662:                     push(@clonemsg,({
16663:                                       mt => 'No new community created.',
16664:                                       args => [],
16665:                                     },
16666:                                     {
16667:                                       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]).',
16668:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
16669:                                     }));
16670:                 } else {
16671:                     push(@clonemsg,({
16672:                                       mt => 'No new course created.',
16673:                                       args => [],
16674:                                     },
16675:                                     {
16676:                                       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]).',
16677:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
16678:                                     }));
16679:                 }
16680: 	    }
16681:         }
16682:     }
16683:     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
16684: }
16685: 
16686: sub construct_course {
16687:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
16688:         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
16689:     my ($outcome,$msgref,$clonemsgref);
16690:     my $linefeed =  '<br />'."\n";
16691:     if ($context eq 'auto') {
16692:         $linefeed = "\n";
16693:     }
16694: 
16695: #
16696: # Are we cloning?
16697: #
16698:     my ($can_clone,$cloneid,$clonehome,$clonetitle);
16699:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
16700: 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
16701:         if (!$can_clone) {
16702: 	    return (0,$outcome,$clonemsgref);
16703: 	}
16704:     }
16705: 
16706: #
16707: # Open course
16708: #
16709:     my $showncrstype;
16710:     if ($args->{'crstype'} eq 'Placement') {
16711:         $showncrstype = 'placement test'; 
16712:     } else {  
16713:         $showncrstype = lc($args->{'crstype'});
16714:     }
16715:     my %cenv=();
16716:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
16717:                                              $args->{'cdescr'},
16718:                                              $args->{'curl'},
16719:                                              $args->{'course_home'},
16720:                                              $args->{'nonstandard'},
16721:                                              $args->{'crscode'},
16722:                                              $args->{'ccuname'}.':'.
16723:                                              $args->{'ccdomain'},
16724:                                              $args->{'crstype'},
16725:                                              $cnum,$context,$category,
16726:                                              $callercontext);
16727: 
16728:     # Note: The testing routines depend on this being output; see 
16729:     # Utils::Course. This needs to at least be output as a comment
16730:     # if anyone ever decides to not show this, and Utils::Course::new
16731:     # will need to be suitably modified.
16732:     if (($callercontext eq 'auto') && ($user_lh ne '')) {
16733:         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
16734:     } else {
16735:         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
16736:     }
16737:     if ($$courseid =~ /^error:/) {
16738:         return (0,$outcome,$clonemsgref);
16739:     }
16740: 
16741: #
16742: # Check if created correctly
16743: #
16744:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
16745:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
16746:     if ($crsuhome eq 'no_host') {
16747:         if (($callercontext eq 'auto') && ($user_lh ne '')) {
16748:             $outcome .= &mt_user($user_lh,
16749:                             'Course creation failed, unrecognized course home server.');
16750:         } else {
16751:             $outcome .= &mt('Course creation failed, unrecognized course home server.');
16752:         }
16753:         $outcome .= $linefeed;
16754:         return (0,$outcome,$clonemsgref);
16755:     }
16756:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
16757: 
16758: #
16759: # Do the cloning
16760: #   
16761:     my @clonemsg;
16762:     if ($can_clone && $cloneid) {
16763:         push(@clonemsg,
16764:                       {
16765:                           mt => 'Created [_1] by cloning from [_2]',
16766:                           args => [$showncrstype,$clonetitle],
16767:                       });
16768: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
16769: # Copy all files
16770:         my @info =
16771: 	    &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
16772: 	                                             $args->{'dateshift'},$args->{'crscode'},
16773:                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
16774:                                                      $args->{'tinyurls'});
16775:         if (@info) {
16776:             push(@clonemsg,@info);
16777:         }
16778: # Restore URL
16779: 	$cenv{'url'}=$oldcenv{'url'};
16780: # Restore title
16781: 	$cenv{'description'}=$oldcenv{'description'};
16782: # Restore creation date, creator and creation context.
16783:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
16784:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
16785:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
16786: # Mark as cloned
16787: 	$cenv{'clonedfrom'}=$cloneid;
16788: # Need to clone grading mode
16789:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
16790:         $cenv{'grading'}=$newenv{'grading'};
16791: # Do not clone these environment entries
16792:         &Apache::lonnet::del('environment',
16793:                   ['default_enrollment_start_date',
16794:                    'default_enrollment_end_date',
16795:                    'question.email',
16796:                    'policy.email',
16797:                    'comment.email',
16798:                    'pch.users.denied',
16799:                    'plc.users.denied',
16800:                    'hidefromcat',
16801:                    'checkforpriv',
16802:                    'categories'],
16803:                    $$crsudom,$$crsunum);
16804:         if ($args->{'textbook'}) {
16805:             $cenv{'internal.textbook'} = $args->{'textbook'};
16806:         }
16807:     }
16808: 
16809: #
16810: # Set environment (will override cloned, if existing)
16811: #
16812:     my @sections = ();
16813:     my @xlists = ();
16814:     if ($args->{'crstype'}) {
16815:         $cenv{'type'}=$args->{'crstype'};
16816:     }
16817:     if ($args->{'lti'}) {
16818:         $cenv{'internal.lti'}=$args->{'lti'};
16819:     }
16820:     if ($args->{'crsid'}) {
16821:         $cenv{'courseid'}=$args->{'crsid'};
16822:     }
16823:     if ($args->{'crscode'}) {
16824:         $cenv{'internal.coursecode'}=$args->{'crscode'};
16825:     }
16826:     if ($args->{'crsquota'} ne '') {
16827:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
16828:     } else {
16829:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
16830:     }
16831:     if ($args->{'ccuname'}) {
16832:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
16833:                                         ':'.$args->{'ccdomain'};
16834:     } else {
16835:         $cenv{'internal.courseowner'} = $args->{'curruser'};
16836:     }
16837:     if ($args->{'defaultcredits'}) {
16838:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
16839:     }
16840:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
16841:     if ($args->{'crssections'}) {
16842:         $cenv{'internal.sectionnums'} = '';
16843:         if ($args->{'crssections'} =~ m/,/) {
16844:             @sections = split/,/,$args->{'crssections'};
16845:         } else {
16846:             $sections[0] = $args->{'crssections'};
16847:         }
16848:         if (@sections > 0) {
16849:             foreach my $item (@sections) {
16850:                 my ($sec,$gp) = split/:/,$item;
16851:                 my $class = $args->{'crscode'}.$sec;
16852:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
16853:                 $cenv{'internal.sectionnums'} .= $item.',';
16854:                 unless ($addcheck eq 'ok') {
16855:                     push(@badclasses,$class);
16856:                 }
16857:             }
16858:             $cenv{'internal.sectionnums'} =~ s/,$//;
16859:         }
16860:     }
16861: # do not hide course coordinator from staff listing, 
16862: # even if privileged
16863:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16864: # add course coordinator's domain to domains to check for privileged users
16865: # if different to course domain
16866:     if ($$crsudom ne $args->{'ccdomain'}) {
16867:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
16868:     }
16869: # add crosslistings
16870:     if ($args->{'crsxlist'}) {
16871:         $cenv{'internal.crosslistings'}='';
16872:         if ($args->{'crsxlist'} =~ m/,/) {
16873:             @xlists = split/,/,$args->{'crsxlist'};
16874:         } else {
16875:             $xlists[0] = $args->{'crsxlist'};
16876:         }
16877:         if (@xlists > 0) {
16878:             foreach my $item (@xlists) {
16879:                 my ($xl,$gp) = split/:/,$item;
16880:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
16881:                 $cenv{'internal.crosslistings'} .= $item.',';
16882:                 unless ($addcheck eq 'ok') {
16883:                     push(@badclasses,$xl);
16884:                 }
16885:             }
16886:             $cenv{'internal.crosslistings'} =~ s/,$//;
16887:         }
16888:     }
16889:     if ($args->{'autoadds'}) {
16890:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
16891:     }
16892:     if ($args->{'autodrops'}) {
16893:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
16894:     }
16895: # check for notification of enrollment changes
16896:     my @notified = ();
16897:     if ($args->{'notify_owner'}) {
16898:         if ($args->{'ccuname'} ne '') {
16899:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
16900:         }
16901:     }
16902:     if ($args->{'notify_dc'}) {
16903:         if ($uname ne '') { 
16904:             push(@notified,$uname.':'.$udom);
16905:         }
16906:     }
16907:     if (@notified > 0) {
16908:         my $notifylist;
16909:         if (@notified > 1) {
16910:             $notifylist = join(',',@notified);
16911:         } else {
16912:             $notifylist = $notified[0];
16913:         }
16914:         $cenv{'internal.notifylist'} = $notifylist;
16915:     }
16916:     if (@badclasses > 0) {
16917:         my %lt=&Apache::lonlocal::texthash(
16918:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
16919:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
16920:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
16921:         );
16922:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
16923:                            &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'};
16924:         if ($context eq 'auto') {
16925:             $outcome .= $badclass_msg.$linefeed;
16926:         } else {
16927:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
16928:         }
16929:         foreach my $item (@badclasses) {
16930:             if ($context eq 'auto') {
16931:                 $outcome .= " - $item\n";
16932:             } else {
16933:                 $outcome .= "<li>$item</li>\n";
16934:             }
16935:         }
16936:         if ($context eq 'auto') {
16937:             $outcome .= $linefeed;
16938:         } else {
16939:             $outcome .= "</ul><br /><br /></div>\n";
16940:         } 
16941:     }
16942:     if ($args->{'no_end_date'}) {
16943:         $args->{'endaccess'} = 0;
16944:     }
16945:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
16946:     $cenv{'internal.autoend'}=$args->{'enrollend'};
16947:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
16948:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
16949:     if ($args->{'showphotos'}) {
16950:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
16951:     }
16952:     $cenv{'internal.authtype'} = $args->{'authtype'};
16953:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
16954:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
16955:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
16956:             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'); 
16957:             if ($context eq 'auto') {
16958:                 $outcome .= $krb_msg;
16959:             } else {
16960:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
16961:             }
16962:             $outcome .= $linefeed;
16963:         }
16964:     }
16965:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
16966:        if ($args->{'setpolicy'}) {
16967:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16968:        }
16969:        if ($args->{'setcontent'}) {
16970:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16971:        }
16972:        if ($args->{'setcomment'}) {
16973:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16974:        }
16975:     }
16976:     if ($args->{'reshome'}) {
16977: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
16978: 	$cenv{'reshome'}=~s/\/+$/\//;
16979:     }
16980: #
16981: # course has keyed access
16982: #
16983:     if ($args->{'setkeys'}) {
16984:        $cenv{'keyaccess'}='yes';
16985:     }
16986: # if specified, key authority is not course, but user
16987: # only active if keyaccess is yes
16988:     if ($args->{'keyauth'}) {
16989: 	my ($user,$domain) = split(':',$args->{'keyauth'});
16990: 	$user = &LONCAPA::clean_username($user);
16991: 	$domain = &LONCAPA::clean_username($domain);
16992: 	if ($user ne '' && $domain ne '') {
16993: 	    $cenv{'keyauth'}=$user.':'.$domain;
16994: 	}
16995:     }
16996: 
16997: #
16998: #  generate and store uniquecode (available to course requester), if course should have one.
16999: #
17000:     if ($args->{'uniquecode'}) {
17001:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
17002:         if ($code) {
17003:             $cenv{'internal.uniquecode'} = $code;
17004:             my %crsinfo =
17005:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
17006:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
17007:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
17008:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
17009:             } 
17010:             if (ref($coderef)) {
17011:                 $$coderef = $code;
17012:             }
17013:         }
17014:     }
17015: 
17016:     if ($args->{'disresdis'}) {
17017:         $cenv{'pch.roles.denied'}='st';
17018:     }
17019:     if ($args->{'disablechat'}) {
17020:         $cenv{'plc.roles.denied'}='st';
17021:     }
17022: 
17023:     # Record we've not yet viewed the Course Initialization Helper for this 
17024:     # course
17025:     $cenv{'course.helper.not.run'} = 1;
17026:     #
17027:     # Use new Randomseed
17028:     #
17029:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
17030:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
17031:     #
17032:     # The encryption code and receipt prefix for this course
17033:     #
17034:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
17035:     $cenv{'internal.encpref'}=100+int(9*rand(99));
17036:     #
17037:     # By default, use standard grading
17038:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
17039: 
17040:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
17041:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
17042: #
17043: # Open all assignments
17044: #
17045:     if ($args->{'openall'}) {
17046:        my $opendate = time;
17047:        if ($args->{'openallfrom'} =~ /^\d+$/) {
17048:            $opendate = $args->{'openallfrom'};
17049:        }
17050:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
17051:        my %storecontent = ($storeunder         => $opendate,
17052:                            $storeunder.'.type' => 'date_start');
17053:        $outcome .= &mt('All assignments open starting [_1]',
17054:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
17055:                    &Apache::lonnet::cput
17056:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
17057:    }
17058: #
17059: # Set first page
17060: #
17061:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
17062: 	    || ($cloneid)) {
17063: 	use LONCAPA::map;
17064: 	$outcome .= &mt('Setting first resource').': ';
17065: 
17066: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
17067:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
17068: 
17069:         $outcome .= ($fatal?$errtext:'read ok').' - ';
17070:         my $title; my $url;
17071:         if ($args->{'firstres'} eq 'syl') {
17072: 	    $title=&mt('Syllabus');
17073:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
17074:         } else {
17075:             $title=&mt('Table of Contents');
17076:             $url='/adm/navmaps';
17077:         }
17078: 
17079:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
17080: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
17081: 
17082: 	if ($errtext) { $fatal=2; }
17083:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
17084:     }
17085: 
17086: # 
17087: # Set params for Placement Tests
17088: #
17089:     if ($args->{'crstype'} eq 'Placement') {
17090:        my %storecontent; 
17091:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
17092:        my %defaults = (
17093:                         buttonshide   => { value => 'yes',
17094:                                            type => 'string_yesno',},
17095:                         type          => { value => 'randomizetry',
17096:                                            type  => 'string_questiontype',},
17097:                         maxtries      => { value => 1,
17098:                                            type => 'int_pos',},
17099:                         problemstatus => { value => 'no',
17100:                                            type  => 'string_problemstatus',},
17101:                       );
17102:        foreach my $key (keys(%defaults)) {
17103:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
17104:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
17105:        }
17106:        &Apache::lonnet::cput
17107:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
17108:     }
17109: 
17110:     return (1,$outcome,\@clonemsg);
17111: }
17112: 
17113: sub make_unique_code {
17114:     my ($cdom,$cnum) = @_;
17115:     # get lock on uniquecodes db
17116:     my $lockhash = {
17117:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
17118:                                                   ':'.$env{'user.domain'},
17119:                    };
17120:     my $tries = 0;
17121:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
17122:     my ($code,$error);
17123:   
17124:     while (($gotlock ne 'ok') && ($tries<3)) {
17125:         $tries ++;
17126:         sleep 1;
17127:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
17128:     }
17129:     if ($gotlock eq 'ok') {
17130:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
17131:         my $gotcode;
17132:         my $attempts = 0;
17133:         while ((!$gotcode) && ($attempts < 100)) {
17134:             $code = &generate_code();
17135:             if (!exists($currcodes{$code})) {
17136:                 $gotcode = 1;
17137:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
17138:                     $error = 'nostore';
17139:                 }
17140:             }
17141:             $attempts ++;
17142:         }
17143:         my @del_lock = ($cnum."\0".'uniquecodes');
17144:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
17145:     } else {
17146:         $error = 'nolock';
17147:     }
17148:     return ($code,$error);
17149: }
17150: 
17151: sub generate_code {
17152:     my $code;
17153:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
17154:     for (my $i=0; $i<6; $i++) {
17155:         my $lettnum = int (rand 2);
17156:         my $item = '';
17157:         if ($lettnum) {
17158:             $item = $letts[int( rand(18) )];
17159:         } else {
17160:             $item = 1+int( rand(8) );
17161:         }
17162:         $code .= $item;
17163:     }
17164:     return $code;
17165: }
17166: 
17167: ############################################################
17168: ############################################################
17169: 
17170: # Community, Course and Placement Test
17171: sub course_type {
17172:     my ($cid) = @_;
17173:     if (!defined($cid)) {
17174:         $cid = $env{'request.course.id'};
17175:     }
17176:     if (defined($env{'course.'.$cid.'.type'})) {
17177:         return $env{'course.'.$cid.'.type'};
17178:     } else {
17179:         return 'Course';
17180:     }
17181: }
17182: 
17183: sub group_term {
17184:     my $crstype = &course_type();
17185:     my %names = (
17186:                   'Course' => 'group',
17187:                   'Community' => 'group',
17188:                   'Placement' => 'group',
17189:                 );
17190:     return $names{$crstype};
17191: }
17192: 
17193: sub course_types {
17194:     my @types = ('official','unofficial','community','textbook','placement','lti');
17195:     my %typename = (
17196:                          official   => 'Official course',
17197:                          unofficial => 'Unofficial course',
17198:                          community  => 'Community',
17199:                          textbook   => 'Textbook course',
17200:                          placement  => 'Placement test',
17201:                          lti        => 'LTI provider',
17202:                    );
17203:     return (\@types,\%typename);
17204: }
17205: 
17206: sub icon {
17207:     my ($file)=@_;
17208:     my $curfext = lc((split(/\./,$file))[-1]);
17209:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
17210:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
17211:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
17212: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
17213: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
17214: 	            $curfext.".gif") {
17215: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
17216: 		$curfext.".gif";
17217: 	}
17218:     }
17219:     return &lonhttpdurl($iconname);
17220: } 
17221: 
17222: sub lonhttpdurl {
17223: #
17224: # Had been used for "small fry" static images on separate port 8080.
17225: # Modify here if lightweight http functionality desired again.
17226: # Currently eliminated due to increasing firewall issues.
17227: #
17228:     my ($url)=@_;
17229:     return $url;
17230: }
17231: 
17232: sub connection_aborted {
17233:     my ($r)=@_;
17234:     $r->print(" ");$r->rflush();
17235:     my $c = $r->connection;
17236:     return $c->aborted();
17237: }
17238: 
17239: #    Escapes strings that may have embedded 's that will be put into
17240: #    strings as 'strings'.
17241: sub escape_single {
17242:     my ($input) = @_;
17243:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
17244:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
17245:     return $input;
17246: }
17247: 
17248: #  Same as escape_single, but escape's "'s  This 
17249: #  can be used for  "strings"
17250: sub escape_double {
17251:     my ($input) = @_;
17252:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
17253:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
17254:     return $input;
17255: }
17256:  
17257: #   Escapes the last element of a full URL.
17258: sub escape_url {
17259:     my ($url)   = @_;
17260:     my @urlslices = split(/\//, $url,-1);
17261:     my $lastitem = &escape(pop(@urlslices));
17262:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
17263: }
17264: 
17265: sub compare_arrays {
17266:     my ($arrayref1,$arrayref2) = @_;
17267:     my (@difference,%count);
17268:     @difference = ();
17269:     %count = ();
17270:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
17271:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
17272:         foreach my $element (keys(%count)) {
17273:             if ($count{$element} == 1) {
17274:                 push(@difference,$element);
17275:             }
17276:         }
17277:     }
17278:     return @difference;
17279: }
17280: 
17281: sub lon_status_items {
17282:     my %defaults = (
17283:                      E         => 100,
17284:                      W         => 4,
17285:                      N         => 1,
17286:                      U         => 5,
17287:                      threshold => 200,
17288:                      sysmail   => 2500,
17289:                    );
17290:     my %names = (
17291:                    E => 'Errors',
17292:                    W => 'Warnings',
17293:                    N => 'Notices',
17294:                    U => 'Unsent',
17295:                 );
17296:     return (\%defaults,\%names);
17297: }
17298: 
17299: # -------------------------------------------------------- Initialize user login
17300: sub init_user_environment {
17301:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
17302:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
17303: 
17304:     my $public=($username eq 'public' && $domain eq 'public');
17305: 
17306:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
17307:     my $now=time;
17308: 
17309:     if ($public) {
17310: 	my $max_public=100;
17311: 	my $oldest;
17312: 	my $oldest_time=0;
17313: 	for(my $next=1;$next<=$max_public;$next++) {
17314: 	    if (-e $lonids."/publicuser_$next.id") {
17315: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
17316: 		if ($mtime<$oldest_time || !$oldest_time) {
17317: 		    $oldest_time=$mtime;
17318: 		    $oldest=$next;
17319: 		}
17320: 	    } else {
17321: 		$cookie="publicuser_$next";
17322: 		last;
17323: 	    }
17324: 	}
17325: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
17326:     } else {
17327: 	# See if old ID present, if so, remove if this isn't a robot,
17328: 	# killing any existing non-robot sessions
17329: 	if (!$args->{'robot'}) {
17330: 	    opendir(DIR,$lonids);
17331: 	    while ($filename=readdir(DIR)) {
17332: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
17333:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
17334:                             &GDBM_READER(),0640)) {
17335:                         my $linkedfile;
17336:                         if (exists($oldenv{'user.linkedenv'})) {
17337:                             $linkedfile = $oldenv{'user.linkedenv'};
17338:                         }
17339:                         untie(%oldenv);
17340:                         if (unlink("$lonids/$filename")) {
17341:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
17342:                                 if (-l "$lonids/$linkedfile.id") {
17343:                                     unlink("$lonids/$linkedfile.id");
17344:                                 }
17345:                             }
17346:                         }
17347:                     } else {
17348:                         unlink($lonids.'/'.$filename);
17349:                     }
17350: 		}
17351: 	    }
17352: 	    closedir(DIR);
17353: # If there is a undeleted lockfile for the user's paste buffer remove it.
17354:             my $namespace = 'nohist_courseeditor';
17355:             my $lockingkey = 'paste'."\0".'locked_num';
17356:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
17357:                                                 $domain,$username);
17358:             if (exists($lockhash{$lockingkey})) {
17359:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
17360:                 unless ($delresult eq 'ok') {
17361:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
17362:                 }
17363:             }
17364: 	}
17365: # Give them a new cookie
17366: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
17367: 		                   : $now.$$.int(rand(10000)));
17368: 	$cookie="$username\_$id\_$domain\_$authhost";
17369:     
17370: # Initialize roles
17371: 
17372: 	($userroles,$firstaccenv,$timerintenv) = 
17373:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
17374:     }
17375: # ------------------------------------ Check browser type and MathML capability
17376: 
17377:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
17378:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
17379: 
17380: # ------------------------------------------------------------- Get environment
17381: 
17382:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
17383:     my ($tmp) = keys(%userenv);
17384:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
17385: 	undef(%userenv);
17386:     }
17387:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
17388: 	$form->{'interface'}=$userenv{'interface'};
17389:     }
17390:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
17391: 
17392: # --------------- Do not trust query string to be put directly into environment
17393:     foreach my $option ('interface','localpath','localres') {
17394:         $form->{$option}=~s/[\n\r\=]//gs;
17395:     }
17396: # --------------------------------------------------------- Write first profile
17397: 
17398:     {
17399:         my $ip = &Apache::lonnet::get_requestor_ip($r);
17400: 	my %initial_env = 
17401: 	    ("user.name"          => $username,
17402: 	     "user.domain"        => $domain,
17403: 	     "user.home"          => $authhost,
17404: 	     "browser.type"       => $clientbrowser,
17405: 	     "browser.version"    => $clientversion,
17406: 	     "browser.mathml"     => $clientmathml,
17407: 	     "browser.unicode"    => $clientunicode,
17408: 	     "browser.os"         => $clientos,
17409:              "browser.mobile"     => $clientmobile,
17410:              "browser.info"       => $clientinfo,
17411:              "browser.osversion"  => $clientosversion,
17412: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
17413: 	     "request.course.fn"  => '',
17414: 	     "request.course.uri" => '',
17415: 	     "request.course.sec" => '',
17416: 	     "request.role"       => 'cm',
17417: 	     "request.role.adv"   => $env{'user.adv'},
17418: 	     "request.host"       => $ip,);
17419: 
17420:         if ($form->{'localpath'}) {
17421: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
17422: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
17423:         }
17424: 	
17425: 	if ($form->{'interface'}) {
17426: 	    $form->{'interface'}=~s/\W//gs;
17427: 	    $initial_env{"browser.interface"} = $form->{'interface'};
17428: 	    $env{'browser.interface'}=$form->{'interface'};
17429: 	}
17430: 
17431:         if ($form->{'iptoken'}) {
17432:             my $lonhost = $r->dir_config('lonHostID');
17433:             $initial_env{"user.noloadbalance"} = $lonhost;
17434:             $env{'user.noloadbalance'} = $lonhost;
17435:         }
17436: 
17437:         if ($form->{'noloadbalance'}) {
17438:             my @hosts = &Apache::lonnet::current_machine_ids();
17439:             my $hosthere = $form->{'noloadbalance'};
17440:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
17441:                 $initial_env{"user.noloadbalance"} = $hosthere;
17442:                 $env{'user.noloadbalance'} = $hosthere;
17443:             }
17444:         }
17445: 
17446:         unless ($domain eq 'public') {
17447:             my %is_adv = ( is_adv => $env{'user.adv'} );
17448:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
17449: 
17450:             foreach my $tool ('aboutme','blog','webdav','portfolio','timezone') {
17451:                 $userenv{'availabletools.'.$tool} = 
17452:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
17453:                                                       undef,\%userenv,\%domdef,\%is_adv);
17454:             }
17455: 
17456:             foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
17457:                 $userenv{'canrequest.'.$crstype} =
17458:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
17459:                                                       'reload','requestcourses',
17460:                                                       \%userenv,\%domdef,\%is_adv);
17461:             }
17462: 
17463:             $userenv{'canrequest.author'} =
17464:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
17465:                                                   'reload','requestauthor',
17466:                                                   \%userenv,\%domdef,\%is_adv);
17467:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
17468:                                                  $domain,$username);
17469:             my $reqstatus = $reqauthor{'author_status'};
17470:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
17471:                 if (ref($reqauthor{'author'}) eq 'HASH') {
17472:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
17473:                                                       $reqauthor{'author'}{'timestamp'};
17474:                 }
17475:             }
17476:             my ($types,$typename) = &course_types();
17477:             if (ref($types) eq 'ARRAY') {
17478:                 my @options = ('approval','validate','autolimit');
17479:                 my $optregex = join('|',@options);
17480:                 my (%willtrust,%trustchecked);
17481:                 foreach my $type (@{$types}) {
17482:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
17483:                     if ($dom_str ne '') {
17484:                         my $updatedstr = '';
17485:                         my @possdomains = split(',',$dom_str);
17486:                         foreach my $entry (@possdomains) {
17487:                             my ($extdom,$extopt) = split(':',$entry);
17488:                             unless ($trustchecked{$extdom}) {
17489:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
17490:                                 $trustchecked{$extdom} = 1;
17491:                             }
17492:                             if ($willtrust{$extdom}) {
17493:                                 $updatedstr .= $entry.',';
17494:                             }
17495:                         }
17496:                         $updatedstr =~ s/,$//;
17497:                         if ($updatedstr) {
17498:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
17499:                         } else {
17500:                             delete($userenv{'reqcrsotherdom.'.$type});
17501:                         }
17502:                     }
17503:                 }
17504:             }
17505:         }
17506: 	$env{'user.environment'} = "$lonids/$cookie.id";
17507: 
17508: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
17509: 		 &GDBM_WRCREAT(),0640)) {
17510: 	    &_add_to_env(\%disk_env,\%initial_env);
17511: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
17512: 	    &_add_to_env(\%disk_env,$userroles);
17513:             if (ref($firstaccenv) eq 'HASH') {
17514:                 &_add_to_env(\%disk_env,$firstaccenv);
17515:             }
17516:             if (ref($timerintenv) eq 'HASH') {
17517:                 &_add_to_env(\%disk_env,$timerintenv);
17518:             }
17519: 	    if (ref($args->{'extra_env'})) {
17520: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
17521: 	    }
17522: 	    untie(%disk_env);
17523: 	} else {
17524: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
17525: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
17526: 	    return 'error: '.$!;
17527: 	}
17528:     }
17529:     $env{'request.role'}='cm';
17530:     $env{'request.role.adv'}=$env{'user.adv'};
17531:     $env{'browser.type'}=$clientbrowser;
17532: 
17533:     return $cookie;
17534: 
17535: }
17536: 
17537: sub _add_to_env {
17538:     my ($idf,$env_data,$prefix) = @_;
17539:     if (ref($env_data) eq 'HASH') {
17540:         while (my ($key,$value) = each(%$env_data)) {
17541: 	    $idf->{$prefix.$key} = $value;
17542: 	    $env{$prefix.$key}   = $value;
17543:         }
17544:     }
17545: }
17546: 
17547: # --- Get the symbolic name of a problem and the url
17548: sub get_symb {
17549:     my ($request,$silent) = @_;
17550:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
17551:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
17552:     if ($symb eq '') {
17553:         if (!$silent) {
17554:             if (ref($request)) { 
17555:                 $request->print("Unable to handle ambiguous references:$url:.");
17556:             }
17557:             return ();
17558:         }
17559:     }
17560:     &Apache::lonenc::check_decrypt(\$symb);
17561:     return ($symb);
17562: }
17563: 
17564: # --------------------------------------------------------------Get annotation
17565: 
17566: sub get_annotation {
17567:     my ($symb,$enc) = @_;
17568: 
17569:     my $key = $symb;
17570:     if (!$enc) {
17571:         $key =
17572:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
17573:     }
17574:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
17575:     return $annotation{$key};
17576: }
17577: 
17578: sub clean_symb {
17579:     my ($symb,$delete_enc) = @_;
17580: 
17581:     &Apache::lonenc::check_decrypt(\$symb);
17582:     my $enc = $env{'request.enc'};
17583:     if ($delete_enc) {
17584:         delete($env{'request.enc'});
17585:     }
17586: 
17587:     return ($symb,$enc);
17588: }
17589: 
17590: ############################################################
17591: ############################################################
17592: 
17593: =pod
17594: 
17595: =head1 Routines for building display used to search for courses
17596: 
17597: 
17598: =over 4
17599: 
17600: =item * &build_filters()
17601: 
17602: Create markup for a table used to set filters to use when selecting
17603: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
17604: and quotacheck.pl
17605: 
17606: 
17607: Inputs:
17608: 
17609: filterlist - anonymous array of fields to include as potential filters 
17610: 
17611: crstype - course type
17612: 
17613: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
17614:               to pop-open a course selector (will contain "extra element"). 
17615: 
17616: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
17617: 
17618: filter - anonymous hash of criteria and their values
17619: 
17620: action - form action
17621: 
17622: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
17623: 
17624: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
17625: 
17626: cloneruname - username of owner of new course who wants to clone
17627: 
17628: clonerudom - domain of owner of new course who wants to clone
17629: 
17630: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
17631: 
17632: codetitlesref - reference to array of titles of components in institutional codes (official courses)
17633: 
17634: codedom - domain
17635: 
17636: formname - value of form element named "form". 
17637: 
17638: fixeddom - domain, if fixed.
17639: 
17640: prevphase - value to assign to form element named "phase" when going back to the previous screen  
17641: 
17642: cnameelement - name of form element in form on opener page which will receive title of selected course 
17643: 
17644: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
17645: 
17646: cdomelement - name of form element in form on opener page which will receive domain of selected course
17647: 
17648: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
17649: 
17650: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
17651: 
17652: clonewarning - warning message about missing information for intended course owner when DC creates a course
17653: 
17654: 
17655: Returns: $output - HTML for display of search criteria, and hidden form elements.
17656: 
17657: 
17658: Side Effects: None
17659: 
17660: =cut
17661: 
17662: # ---------------------------------------------- search for courses based on last activity etc.
17663: 
17664: sub build_filters {
17665:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
17666:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
17667:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
17668:         $cnameelement,$cnumelement,$cdomelement,$setroles,
17669:         $clonetext,$clonewarning) = @_;
17670:     my ($list,$jscript);
17671:     my $onchange = 'javascript:updateFilters(this)';
17672:     my ($domainselectform,$sincefilterform,$createdfilterform,
17673:         $ownerdomselectform,$persondomselectform,$instcodeform,
17674:         $typeselectform,$instcodetitle);
17675:     if ($formname eq '') {
17676:         $formname = $caller;
17677:     }
17678:     foreach my $item (@{$filterlist}) {
17679:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
17680:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
17681:             if ($item eq 'domainfilter') {
17682:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
17683:             } elsif ($item eq 'coursefilter') {
17684:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
17685:             } elsif ($item eq 'ownerfilter') {
17686:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
17687:             } elsif ($item eq 'ownerdomfilter') {
17688:                 $filter->{'ownerdomfilter'} =
17689:                     &LONCAPA::clean_domain($filter->{$item});
17690:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
17691:                                                        'ownerdomfilter',1);
17692:             } elsif ($item eq 'personfilter') {
17693:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
17694:             } elsif ($item eq 'persondomfilter') {
17695:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
17696:                                                         'persondomfilter',1);
17697:             } else {
17698:                 $filter->{$item} =~ s/\W//g;
17699:             }
17700:             if (!$filter->{$item}) {
17701:                 $filter->{$item} = '';
17702:             }
17703:         }
17704:         if ($item eq 'domainfilter') {
17705:             my $allow_blank = 1;
17706:             if ($formname eq 'portform') {
17707:                 $allow_blank=0;
17708:             } elsif ($formname eq 'studentform') {
17709:                 $allow_blank=0;
17710:             }
17711:             if ($fixeddom) {
17712:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
17713:                                     ' value="'.$codedom.'" />'.
17714:                                     &Apache::lonnet::domain($codedom,'description');
17715:             } else {
17716:                 $domainselectform = &select_dom_form($filter->{$item},
17717:                                                      'domainfilter',
17718:                                                       $allow_blank,'',$onchange);
17719:             }
17720:         } else {
17721:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
17722:         }
17723:     }
17724: 
17725:     # last course activity filter and selection
17726:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
17727: 
17728:     # course created filter and selection
17729:     if (exists($filter->{'createdfilter'})) {
17730:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
17731:     }
17732: 
17733:     my $prefix = $crstype;
17734:     if ($crstype eq 'Placement') {
17735:         $prefix = 'Placement Test'
17736:     }
17737:     my %lt = &Apache::lonlocal::texthash(
17738:                 'cac' => "$prefix Activity",
17739:                 'ccr' => "$prefix Created",
17740:                 'cde' => "$prefix Title",
17741:                 'cdo' => "$prefix Domain",
17742:                 'ins' => 'Institutional Code',
17743:                 'inc' => 'Institutional Categorization',
17744:                 'cow' => "$prefix Owner/Co-owner",
17745:                 'cop' => "$prefix Personnel Includes",
17746:                 'cog' => 'Type',
17747:              );
17748: 
17749:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
17750:         my $typeval = 'Course';
17751:         if ($crstype eq 'Community') {
17752:             $typeval = 'Community';
17753:         } elsif ($crstype eq 'Placement') {
17754:             $typeval = 'Placement';
17755:         }
17756:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
17757:     } else {
17758:         $typeselectform =  '<select name="type" size="1"';
17759:         if ($onchange) {
17760:             $typeselectform .= ' onchange="'.$onchange.'"';
17761:         }
17762:         $typeselectform .= '>'."\n";
17763:         foreach my $posstype ('Course','Community','Placement') {
17764:             my $shown;
17765:             if ($posstype eq 'Placement') {
17766:                 $shown = &mt('Placement Test');
17767:             } else {
17768:                 $shown = &mt($posstype);
17769:             }
17770:             $typeselectform.='<option value="'.$posstype.'"'.
17771:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
17772:         }
17773:         $typeselectform.="</select>";
17774:     }
17775: 
17776:     my ($cloneableonlyform,$cloneabletitle);
17777:     if (exists($filter->{'cloneableonly'})) {
17778:         my $cloneableon = '';
17779:         my $cloneableoff = ' checked="checked"';
17780:         if ($filter->{'cloneableonly'}) {
17781:             $cloneableon = $cloneableoff;
17782:             $cloneableoff = '';
17783:         }
17784:         $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>';
17785:         if ($formname eq 'ccrs') {
17786:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
17787:         } else {
17788:             $cloneabletitle = &mt('Cloneable by you');
17789:         }
17790:     }
17791:     my $officialjs;
17792:     if ($crstype eq 'Course') {
17793:         if (exists($filter->{'instcodefilter'})) {
17794: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
17795: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
17796:             if ($codedom) { 
17797:                 $officialjs = 1;
17798:                 ($instcodeform,$jscript,$$numtitlesref) =
17799:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
17800:                                                                   $officialjs,$codetitlesref);
17801:                 if ($jscript) {
17802:                     $jscript = '<script type="text/javascript">'."\n".
17803:                                '// <![CDATA['."\n".
17804:                                $jscript."\n".
17805:                                '// ]]>'."\n".
17806:                                '</script>'."\n";
17807:                 }
17808:             }
17809:             if ($instcodeform eq '') {
17810:                 $instcodeform =
17811:                     '<input type="text" name="instcodefilter" size="10" value="'.
17812:                     $list->{'instcodefilter'}.'" />';
17813:                 $instcodetitle = $lt{'ins'};
17814:             } else {
17815:                 $instcodetitle = $lt{'inc'};
17816:             }
17817:             if ($fixeddom) {
17818:                 $instcodetitle .= '<br />('.$codedom.')';
17819:             }
17820:         }
17821:     }
17822:     my $output = qq|
17823: <form method="post" name="filterpicker" action="$action">
17824: <input type="hidden" name="form" value="$formname" />
17825: |;
17826:     if ($formname eq 'modifycourse') {
17827:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
17828:                    '<input type="hidden" name="prevphase" value="'.
17829:                    $prevphase.'" />'."\n";
17830:     } elsif ($formname eq 'quotacheck') {
17831:         $output .= qq|
17832: <input type="hidden" name="sortby" value="" />
17833: <input type="hidden" name="sortorder" value="" />
17834: |;
17835:     } else {
17836:         my $name_input;
17837:         if ($cnameelement ne '') {
17838:             $name_input = '<input type="hidden" name="cnameelement" value="'.
17839:                           $cnameelement.'" />';
17840:         }
17841:         $output .= qq|
17842: <input type="hidden" name="cnumelement" value="$cnumelement" />
17843: <input type="hidden" name="cdomelement" value="$cdomelement" />
17844: $name_input
17845: $roleelement
17846: $multelement
17847: $typeelement
17848: |;
17849:         if ($formname eq 'portform') {
17850:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
17851:         }
17852:     }
17853:     if ($fixeddom) {
17854:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
17855:     }
17856:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
17857:     if ($sincefilterform) {
17858:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
17859:                   .$sincefilterform
17860:                   .&Apache::lonhtmlcommon::row_closure();
17861:     }
17862:     if ($createdfilterform) {
17863:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
17864:                   .$createdfilterform
17865:                   .&Apache::lonhtmlcommon::row_closure();
17866:     }
17867:     if ($domainselectform) {
17868:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
17869:                   .$domainselectform
17870:                   .&Apache::lonhtmlcommon::row_closure();
17871:     }
17872:     if ($typeselectform) {
17873:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
17874:             $output .= $typeselectform;
17875:         } else {
17876:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
17877:                       .$typeselectform
17878:                       .&Apache::lonhtmlcommon::row_closure();
17879:         }
17880:     }
17881:     if ($instcodeform) {
17882:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
17883:                   .$instcodeform
17884:                   .&Apache::lonhtmlcommon::row_closure();
17885:     }
17886:     if (exists($filter->{'ownerfilter'})) {
17887:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
17888:                    '<table><tr><td>'.&mt('Username').'<br />'.
17889:                    '<input type="text" name="ownerfilter" size="20" value="'.
17890:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
17891:                    $ownerdomselectform.'</td></tr></table>'.
17892:                    &Apache::lonhtmlcommon::row_closure();
17893:     }
17894:     if (exists($filter->{'personfilter'})) {
17895:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
17896:                    '<table><tr><td>'.&mt('Username').'<br />'.
17897:                    '<input type="text" name="personfilter" size="20" value="'.
17898:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
17899:                    $persondomselectform.'</td></tr></table>'.
17900:                    &Apache::lonhtmlcommon::row_closure();
17901:     }
17902:     if (exists($filter->{'coursefilter'})) {
17903:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
17904:                   .'<input type="text" name="coursefilter" size="25" value="'
17905:                   .$list->{'coursefilter'}.'" />'
17906:                   .&Apache::lonhtmlcommon::row_closure();
17907:     }
17908:     if ($cloneableonlyform) {
17909:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
17910:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
17911:     }
17912:     if (exists($filter->{'descriptfilter'})) {
17913:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
17914:                   .'<input type="text" name="descriptfilter" size="40" value="'
17915:                   .$list->{'descriptfilter'}.'" />'
17916:                   .&Apache::lonhtmlcommon::row_closure(1);
17917:     }
17918:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
17919:                '<input type="hidden" name="updater" value="" />'."\n".
17920:                '<input type="submit" name="gosearch" value="'.
17921:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
17922:     return $jscript.$clonewarning.$output;
17923: }
17924: 
17925: =pod 
17926: 
17927: =item * &timebased_select_form()
17928: 
17929: Create markup for a dropdown list used to select a time-based
17930: filter e.g., Course Activity, Course Created, when searching for courses
17931: or communities
17932: 
17933: Inputs:
17934: 
17935: item - name of form element (sincefilter or createdfilter)
17936: 
17937: filter - anonymous hash of criteria and their values
17938: 
17939: Returns: HTML for a select box contained a blank, then six time selections,
17940:          with value set in incoming form variables currently selected. 
17941: 
17942: Side Effects: None
17943: 
17944: =cut
17945: 
17946: sub timebased_select_form {
17947:     my ($item,$filter) = @_;
17948:     if (ref($filter) eq 'HASH') {
17949:         $filter->{$item} =~ s/[^\d-]//g;
17950:         if (!$filter->{$item}) { $filter->{$item}=-1; }
17951:         return &select_form(
17952:                             $filter->{$item},
17953:                             $item,
17954:                             {      '-1' => '',
17955:                                 '86400' => &mt('today'),
17956:                                '604800' => &mt('last week'),
17957:                               '2592000' => &mt('last month'),
17958:                               '7776000' => &mt('last three months'),
17959:                              '15552000' => &mt('last six months'),
17960:                              '31104000' => &mt('last year'),
17961:                     'select_form_order' =>
17962:                            ['-1','86400','604800','2592000','7776000',
17963:                             '15552000','31104000']});
17964:     }
17965: }
17966: 
17967: =pod
17968: 
17969: =item * &js_changer()
17970: 
17971: Create script tag containing Javascript used to submit course search form
17972: when course type or domain is changed, and also to hide 'Searching ...' on
17973: page load completion for page showing search result.
17974: 
17975: Inputs: None
17976: 
17977: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
17978: 
17979: Side Effects: None
17980: 
17981: =cut
17982: 
17983: sub js_changer {
17984:     return <<ENDJS;
17985: <script type="text/javascript">
17986: // <![CDATA[
17987: function updateFilters(caller) {
17988:     if (typeof(caller) != "undefined") {
17989:         document.filterpicker.updater.value = caller.name;
17990:     }
17991:     document.filterpicker.submit();
17992: }
17993: 
17994: function hideSearching() {
17995:     if (document.getElementById('searching')) {
17996:         document.getElementById('searching').style.display = 'none';
17997:     }
17998:     return;
17999: }
18000: 
18001: // ]]>
18002: </script>
18003: 
18004: ENDJS
18005: }
18006: 
18007: =pod
18008: 
18009: =item * &search_courses()
18010: 
18011: Process selected filters form course search form and pass to lonnet::courseiddump
18012: to retrieve a hash for which keys are courseIDs which match the selected filters.
18013: 
18014: Inputs:
18015: 
18016: dom - domain being searched 
18017: 
18018: type - course type ('Course' or 'Community' or '.' if any).
18019: 
18020: filter - anonymous hash of criteria and their values
18021: 
18022: numtitles - for institutional codes - number of categories
18023: 
18024: cloneruname - optional username of new course owner
18025: 
18026: clonerudom - optional domain of new course owner
18027: 
18028: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
18029:             (used when DC is using course creation form)
18030: 
18031: codetitles - reference to array of titles of components in institutional codes (official courses).
18032: 
18033: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
18034:            (and so can clone automatically)
18035: 
18036: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
18037: 
18038: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
18039:               courses to clone 
18040: 
18041: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
18042: 
18043: 
18044: Side Effects: None
18045: 
18046: =cut
18047: 
18048: 
18049: sub search_courses {
18050:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
18051:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
18052:     my (%courses,%showcourses,$cloner);
18053:     if (($filter->{'ownerfilter'} ne '') ||
18054:         ($filter->{'ownerdomfilter'} ne '')) {
18055:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
18056:                                        $filter->{'ownerdomfilter'};
18057:     }
18058:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
18059:         if (!$filter->{$item}) {
18060:             $filter->{$item}='.';
18061:         }
18062:     }
18063:     my $now = time;
18064:     my $timefilter =
18065:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
18066:     my ($createdbefore,$createdafter);
18067:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
18068:         $createdbefore = $now;
18069:         $createdafter = $now-$filter->{'createdfilter'};
18070:     }
18071:     my ($instcodefilter,$regexpok);
18072:     if ($numtitles) {
18073:         if ($env{'form.official'} eq 'on') {
18074:             $instcodefilter =
18075:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
18076:             $regexpok = 1;
18077:         } elsif ($env{'form.official'} eq 'off') {
18078:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
18079:             unless ($instcodefilter eq '') {
18080:                 $regexpok = -1;
18081:             }
18082:         }
18083:     } else {
18084:         $instcodefilter = $filter->{'instcodefilter'};
18085:     }
18086:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
18087:     if ($type eq '') { $type = '.'; }
18088: 
18089:     if (($clonerudom ne '') && ($cloneruname ne '')) {
18090:         $cloner = $cloneruname.':'.$clonerudom;
18091:     }
18092:     %courses = &Apache::lonnet::courseiddump($dom,
18093:                                              $filter->{'descriptfilter'},
18094:                                              $timefilter,
18095:                                              $instcodefilter,
18096:                                              $filter->{'combownerfilter'},
18097:                                              $filter->{'coursefilter'},
18098:                                              undef,undef,$type,$regexpok,undef,undef,
18099:                                              undef,undef,$cloner,$cc_clone,
18100:                                              $filter->{'cloneableonly'},
18101:                                              $createdbefore,$createdafter,undef,
18102:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
18103:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
18104:         my $ccrole;
18105:         if ($type eq 'Community') {
18106:             $ccrole = 'co';
18107:         } else {
18108:             $ccrole = 'cc';
18109:         }
18110:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
18111:                                                      $filter->{'persondomfilter'},
18112:                                                      'userroles',undef,
18113:                                                      [$ccrole,'in','ad','ep','ta','cr'],
18114:                                                      $dom);
18115:         foreach my $role (keys(%rolehash)) {
18116:             my ($cnum,$cdom,$courserole) = split(':',$role);
18117:             my $cid = $cdom.'_'.$cnum;
18118:             if (exists($courses{$cid})) {
18119:                 if (ref($courses{$cid}) eq 'HASH') {
18120:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
18121:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
18122:                             push(@{$courses{$cid}{roles}},$courserole);
18123:                         }
18124:                     } else {
18125:                         $courses{$cid}{roles} = [$courserole];
18126:                     }
18127:                     $showcourses{$cid} = $courses{$cid};
18128:                 }
18129:             }
18130:         }
18131:         %courses = %showcourses;
18132:     }
18133:     return %courses;
18134: }
18135: 
18136: =pod
18137: 
18138: =back
18139: 
18140: =head1 Routines for version requirements for current course.
18141: 
18142: =over 4
18143: 
18144: =item * &check_release_required()
18145: 
18146: Compares required LON-CAPA version with version on server, and
18147: if required version is newer looks for a server with the required version.
18148: 
18149: Looks first at servers in user's owen domain; if none suitable, looks at
18150: servers in course's domain are permitted to host sessions for user's domain.
18151: 
18152: Inputs:
18153: 
18154: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
18155: 
18156: $courseid - Course ID of current course
18157: 
18158: $rolecode - User's current role in course (for switchserver query string).
18159: 
18160: $required - LON-CAPA version needed by course (format: Major.Minor).
18161: 
18162: 
18163: Returns:
18164: 
18165: $switchserver - query string tp append to /adm/switchserver call (if 
18166:                 current server's LON-CAPA version is too old. 
18167: 
18168: $warning - Message is displayed if no suitable server could be found.
18169: 
18170: =cut
18171: 
18172: sub check_release_required {
18173:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
18174:     my ($switchserver,$warning);
18175:     if ($required ne '') {
18176:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
18177:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
18178:         if ($reqdmajor ne '' && $reqdminor ne '') {
18179:             my $otherserver;
18180:             if (($major eq '' && $minor eq '') ||
18181:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
18182:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
18183:                 my $switchlcrev =
18184:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
18185:                                                            $userdomserver);
18186:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
18187:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
18188:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
18189:                     my $cdom = $env{'course.'.$courseid.'.domain'};
18190:                     if ($cdom ne $env{'user.domain'}) {
18191:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
18192:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
18193:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
18194:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
18195:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
18196:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
18197:                         my $canhost =
18198:                             &Apache::lonnet::can_host_session($env{'user.domain'},
18199:                                                               $coursedomserver,
18200:                                                               $remoterev,
18201:                                                               $udomdefaults{'remotesessions'},
18202:                                                               $defdomdefaults{'hostedsessions'});
18203: 
18204:                         if ($canhost) {
18205:                             $otherserver = $coursedomserver;
18206:                         } else {
18207:                             $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.");
18208:                         }
18209:                     } else {
18210:                         $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).");
18211:                     }
18212:                 } else {
18213:                     $otherserver = $userdomserver;
18214:                 }
18215:             }
18216:             if ($otherserver ne '') {
18217:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
18218:             }
18219:         }
18220:     }
18221:     return ($switchserver,$warning);
18222: }
18223: 
18224: =pod
18225: 
18226: =item * &check_release_result()
18227: 
18228: Inputs:
18229: 
18230: $switchwarning - Warning message if no suitable server found to host session.
18231: 
18232: $switchserver - query string to append to /adm/switchserver containing lonHostID
18233:                 and current role.
18234: 
18235: Returns: HTML to display with information about requirement to switch server.
18236:          Either displaying warning with link to Roles/Courses screen or
18237:          display link to switchserver.
18238: 
18239: =cut
18240: 
18241: sub check_release_result {
18242:     my ($switchwarning,$switchserver) = @_;
18243:     my $output = &start_page('Selected course unavailable on this server').
18244:                  '<p class="LC_warning">';
18245:     if ($switchwarning) {
18246:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
18247:         if (&show_course()) {
18248:             $output .= &mt('Display courses');
18249:         } else {
18250:             $output .= &mt('Display roles');
18251:         }
18252:         $output .= '</a>';
18253:     } elsif ($switchserver) {
18254:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
18255:                    '<br />'.
18256:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
18257:                    &mt('Switch Server').
18258:                    '</a>';
18259:     }
18260:     $output .= '</p>'.&end_page();
18261:     return $output;
18262: }
18263: 
18264: =pod
18265: 
18266: =item * &needs_coursereinit()
18267: 
18268: Determine if course contents stored for user's session needs to be
18269: refreshed, because content has changed since "Big Hash" last tied.
18270: 
18271: Check for change is made if time last checked is more than 10 minutes ago
18272: (by default).
18273: 
18274: Inputs:
18275: 
18276: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
18277: 
18278: $interval (optional) - Time which may elapse (in s) between last check for content
18279:                        change in current course. (default: 600 s).  
18280: 
18281: Returns: an array; first element is:
18282: 
18283: =over 4
18284: 
18285: 'switch' - if content updates mean user's session
18286:            needs to be switched to a server running a newer LON-CAPA version
18287:  
18288: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
18289:            on current server hosting user's session                
18290: 
18291: ''       - if no action required.
18292: 
18293: =back
18294: 
18295: If first item element is 'switch':
18296: 
18297: second item is $switchwarning - Warning message if no suitable server found to host session. 
18298: 
18299: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
18300:                               and current role. 
18301: 
18302: otherwise: no other elements returned.
18303: 
18304: =back
18305: 
18306: =cut
18307: 
18308: sub needs_coursereinit {
18309:     my ($loncaparev,$interval) = @_;
18310:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
18311:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
18312:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
18313:     my $now = time;
18314:     if ($interval eq '') {
18315:         $interval = 600;
18316:     }
18317:     if (($now-$env{'request.course.timechecked'})>$interval) {
18318:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
18319:         my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
18320:         if ($blocked) {
18321:             return ();
18322:         }
18323:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
18324:         if ($lastchange > $env{'request.course.tied'}) {
18325:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
18326:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
18327:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
18328:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
18329:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
18330:                                              $curr_reqd_hash{'internal.releaserequired'}});
18331:                     my ($switchserver,$switchwarning) =
18332:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
18333:                                                 $curr_reqd_hash{'internal.releaserequired'});
18334:                     if ($switchwarning ne '' || $switchserver ne '') {
18335:                         return ('switch',$switchwarning,$switchserver);
18336:                     }
18337:                 }
18338:             }
18339:             return ('update');
18340:         }
18341:     }
18342:     return ();
18343: }
18344: 
18345: sub update_content_constraints {
18346:     my ($cdom,$cnum,$chome,$cid,$keeporder) = @_;
18347:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
18348:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
18349:     my (%checkresponsetypes,%checkcrsrestypes);
18350:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
18351:         my ($item,$name,$value) = split(/:/,$key);
18352:         if ($item eq 'resourcetag') {
18353:             if ($name eq 'responsetype') {
18354:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
18355:             }
18356:         } elsif ($item eq 'course') {
18357:             if ($name eq 'courserestype') {
18358:                 $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
18359:             }
18360:         }
18361:     }
18362:     my $navmap = Apache::lonnavmaps::navmap->new();
18363:     if (defined($navmap)) {
18364:         my (%allresponses,%allcrsrestypes);
18365:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
18366:             if ($res->is_tool()) {
18367:                 if ($allcrsrestypes{'exttool'}) {
18368:                     $allcrsrestypes{'exttool'} ++;
18369:                 } else {
18370:                     $allcrsrestypes{'exttool'} = 1;
18371:                 }
18372:                 next;
18373:             }
18374:             my %responses = $res->responseTypes();
18375:             foreach my $key (keys(%responses)) {
18376:                 next unless(exists($checkresponsetypes{$key}));
18377:                 $allresponses{$key} += $responses{$key};
18378:             }
18379:         }
18380:         foreach my $key (keys(%allresponses)) {
18381:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
18382:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
18383:                 ($reqdmajor,$reqdminor) = ($major,$minor);
18384:             }
18385:         }
18386:         foreach my $key (keys(%allcrsrestypes)) {
18387:             my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
18388:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
18389:                 ($reqdmajor,$reqdminor) = ($major,$minor);
18390:             }
18391:         }
18392:         undef($navmap);
18393:     }
18394:     my (@resources,@order,@resparms,@zombies);
18395:     if ($keeporder) {
18396:         use LONCAPA::map;
18397:         @resources = @LONCAPA::map::resources;
18398:         @order = @LONCAPA::map::order;
18399:         @resparms = @LONCAPA::map::resparms;
18400:         @zombies = @LONCAPA::map::zombies;
18401:     }
18402:     my $suppmap = 'supplemental.sequence';
18403:     my ($suppcount,$supptools,$errors) = (0,0,0);
18404:     ($suppcount,$supptools,$errors) = &recurse_supplemental($cnum,$cdom,$suppmap,
18405:                                                             $suppcount,$supptools,$errors);
18406:     if ($keeporder) {
18407:         @LONCAPA::map::resources = @resources;
18408:         @LONCAPA::map::order = @order;
18409:         @LONCAPA::map::resparms = @resparms;
18410:         @LONCAPA::map::zombies = @zombies;
18411:     }
18412:     if ($supptools) {
18413:         my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
18414:         if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
18415:             ($reqdmajor,$reqdminor) = ($major,$minor);
18416:         }
18417:     }
18418:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
18419:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
18420:     }
18421:     return;
18422: }
18423: 
18424: sub allmaps_incourse {
18425:     my ($cdom,$cnum,$chome,$cid) = @_;
18426:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
18427:         $cid = $env{'request.course.id'};
18428:         $cdom = $env{'course.'.$cid.'.domain'};
18429:         $cnum = $env{'course.'.$cid.'.num'};
18430:         $chome = $env{'course.'.$cid.'.home'};
18431:     }
18432:     my %allmaps = ();
18433:     my $lastchange =
18434:         &Apache::lonnet::get_coursechange($cdom,$cnum);
18435:     if ($lastchange > $env{'request.course.tied'}) {
18436:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
18437:         unless ($ferr) {
18438:             &update_content_constraints($cdom,$cnum,$chome,$cid,1);
18439:         }
18440:     }
18441:     my $navmap = Apache::lonnavmaps::navmap->new();
18442:     if (defined($navmap)) {
18443:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
18444:             $allmaps{$res->src()} = 1;
18445:         }
18446:     }
18447:     return \%allmaps;
18448: }
18449: 
18450: sub parse_supplemental_title {
18451:     my ($title) = @_;
18452: 
18453:     my ($foldertitle,$renametitle);
18454:     if ($title =~ /&amp;&amp;&amp;/) {
18455:         $title = &HTML::Entites::decode($title);
18456:     }
18457:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
18458:         $renametitle=$4;
18459:         my ($time,$uname,$udom) = ($1,$2,$3);
18460:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
18461:         my $name =  &plainname($uname,$udom);
18462:         $name = &HTML::Entities::encode($name,'"<>&\'');
18463:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
18464:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
18465:             $name.': <br />'.$foldertitle;
18466:     }
18467:     if (wantarray) {
18468:         return ($title,$foldertitle,$renametitle);
18469:     }
18470:     return $title;
18471: }
18472: 
18473: sub recurse_supplemental {
18474:     my ($cnum,$cdom,$suppmap,$numfiles,$numexttools,$errors) = @_;
18475:     if ($suppmap) {
18476:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
18477:         if ($fatal) {
18478:             $errors ++;
18479:         } else {
18480:             my @order = @LONCAPA::map::order;
18481:             if (@order > 0) {
18482:                 my @resources = @LONCAPA::map::resources;
18483:                 foreach my $idx (@order) {
18484:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$resources[$idx]);
18485:                     if (($src ne '') && ($status eq 'res')) {
18486:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
18487:                             ($numfiles,$numexttools,$errors) = &recurse_supplemental($cnum,$cdom,$1,
18488:                                                                    $numfiles,$numexttools,$errors);
18489:                         } else {
18490:                             if ($src =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
18491:                                 $numexttools ++;
18492:                             }
18493:                             $numfiles ++;
18494:                         }
18495:                     }
18496:                 }
18497:             }
18498:         }
18499:     }
18500:     return ($numfiles,$numexttools,$errors);
18501: }
18502: 
18503: sub symb_to_docspath {
18504:     my ($symb,$navmapref) = @_;
18505:     return unless ($symb && ref($navmapref));
18506:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
18507:     if ($resurl=~/\.(sequence|page)$/) {
18508:         $mapurl=$resurl;
18509:     } elsif ($resurl eq 'adm/navmaps') {
18510:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
18511:     }
18512:     my $mapresobj;
18513:     unless (ref($$navmapref)) {
18514:         $$navmapref = Apache::lonnavmaps::navmap->new();
18515:     }
18516:     if (ref($$navmapref)) {
18517:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
18518:     }
18519:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
18520:     my $type=$2;
18521:     my $path;
18522:     if (ref($mapresobj)) {
18523:         my $pcslist = $mapresobj->map_hierarchy();
18524:         if ($pcslist ne '') {
18525:             foreach my $pc (split(/,/,$pcslist)) {
18526:                 next if ($pc <= 1);
18527:                 my $res = $$navmapref->getByMapPc($pc);
18528:                 if (ref($res)) {
18529:                     my $thisurl = $res->src();
18530:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
18531:                     my $thistitle = $res->title();
18532:                     $path .= '&'.
18533:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
18534:                              &escape($thistitle).
18535:                              ':'.$res->randompick().
18536:                              ':'.$res->randomout().
18537:                              ':'.$res->encrypted().
18538:                              ':'.$res->randomorder().
18539:                              ':'.$res->is_page();
18540:                 }
18541:             }
18542:         }
18543:         $path =~ s/^\&//;
18544:         my $maptitle = $mapresobj->title();
18545:         if ($mapurl eq 'default') {
18546:             $maptitle = 'Main Content';
18547:         }
18548:         $path .= (($path ne '')? '&' : '').
18549:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
18550:                  &escape($maptitle).
18551:                  ':'.$mapresobj->randompick().
18552:                  ':'.$mapresobj->randomout().
18553:                  ':'.$mapresobj->encrypted().
18554:                  ':'.$mapresobj->randomorder().
18555:                  ':'.$mapresobj->is_page();
18556:     } else {
18557:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
18558:         my $ispage = (($type eq 'page')? 1 : '');
18559:         if ($mapurl eq 'default') {
18560:             $maptitle = 'Main Content';
18561:         }
18562:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
18563:                 &escape($maptitle).':::::'.$ispage;
18564:     }
18565:     unless ($mapurl eq 'default') {
18566:         $path = 'default&'.
18567:                 &escape('Main Content').
18568:                 ':::::&'.$path;
18569:     }
18570:     return $path;
18571: }
18572: 
18573: sub captcha_display {
18574:     my ($context,$lonhost,$defdom) = @_;
18575:     my ($output,$error);
18576:     my ($captcha,$pubkey,$privkey,$version) = 
18577:         &get_captcha_config($context,$lonhost,$defdom);
18578:     if ($captcha eq 'original') {
18579:         $output = &create_captcha();
18580:         unless ($output) {
18581:             $error = 'captcha';
18582:         }
18583:     } elsif ($captcha eq 'recaptcha') {
18584:         $output = &create_recaptcha($pubkey,$version);
18585:         unless ($output) {
18586:             $error = 'recaptcha';
18587:         }
18588:     }
18589:     return ($output,$error,$captcha,$version);
18590: }
18591: 
18592: sub captcha_response {
18593:     my ($context,$lonhost,$defdom) = @_;
18594:     my ($captcha_chk,$captcha_error);
18595:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
18596:     if ($captcha eq 'original') {
18597:         ($captcha_chk,$captcha_error) = &check_captcha();
18598:     } elsif ($captcha eq 'recaptcha') {
18599:         $captcha_chk = &check_recaptcha($privkey,$version);
18600:     } else {
18601:         $captcha_chk = 1;
18602:     }
18603:     return ($captcha_chk,$captcha_error);
18604: }
18605: 
18606: sub get_captcha_config {
18607:     my ($context,$lonhost,$dom_in_effect) = @_;
18608:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
18609:     my $hostname = &Apache::lonnet::hostname($lonhost);
18610:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
18611:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
18612:     if ($context eq 'usercreation') {
18613:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
18614:         if (ref($domconfig{$context}) eq 'HASH') {
18615:             $hashtocheck = $domconfig{$context}{'cancreate'};
18616:             if (ref($hashtocheck) eq 'HASH') {
18617:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
18618:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
18619:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
18620:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
18621:                     }
18622:                     if ($privkey && $pubkey) {
18623:                         $captcha = 'recaptcha';
18624:                         $version = $hashtocheck->{'recaptchaversion'};
18625:                         if ($version ne '2') {
18626:                             $version = 1;
18627:                         }
18628:                     } else {
18629:                         $captcha = 'original';
18630:                     }
18631:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
18632:                     $captcha = 'original';
18633:                 }
18634:             }
18635:         } else {
18636:             $captcha = 'captcha';
18637:         }
18638:     } elsif ($context eq 'login') {
18639:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
18640:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
18641:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
18642:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
18643:             if ($privkey && $pubkey) {
18644:                 $captcha = 'recaptcha';
18645:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
18646:                 if ($version ne '2') {
18647:                     $version = 1; 
18648:                 }
18649:             } else {
18650:                 $captcha = 'original';
18651:             }
18652:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
18653:             $captcha = 'original';
18654:         }
18655:     } elsif ($context eq 'passwords') {
18656:         if ($dom_in_effect) {
18657:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
18658:             if ($passwdconf{'captcha'} eq 'recaptcha') {
18659:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
18660:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
18661:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
18662:                 }
18663:                 if ($privkey && $pubkey) {
18664:                     $captcha = 'recaptcha';
18665:                     $version = $passwdconf{'recaptchaversion'};
18666:                     if ($version ne '2') {
18667:                         $version = 1;
18668:                     }
18669:                 } else {
18670:                     $captcha = 'original';
18671:                 }
18672:             } elsif ($passwdconf{'captcha'} ne 'notused') {
18673:                 $captcha = 'original';
18674:             }
18675:         }
18676:     } 
18677:     return ($captcha,$pubkey,$privkey,$version);
18678: }
18679: 
18680: sub create_captcha {
18681:     my %captcha_params = &captcha_settings();
18682:     my ($output,$maxtries,$tries) = ('',10,0);
18683:     while ($tries < $maxtries) {
18684:         $tries ++;
18685:         my $captcha = Authen::Captcha->new (
18686:                                            output_folder => $captcha_params{'output_dir'},
18687:                                            data_folder   => $captcha_params{'db_dir'},
18688:                                           );
18689:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
18690: 
18691:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
18692:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
18693:                       '<span class="LC_nobreak">'.
18694:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
18695:                       '<input type="text" size="5" name="code" value="" autocomplete="new-password" />'.
18696:                       '</span><br />'.
18697:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
18698:             last;
18699:         }
18700:     }
18701:     if ($output eq '') {
18702:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
18703:     }
18704:     return $output;
18705: }
18706: 
18707: sub captcha_settings {
18708:     my %captcha_params = (
18709:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
18710:                            www_output_dir => "/captchaspool",
18711:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
18712:                            numchars       => '5',
18713:                          );
18714:     return %captcha_params;
18715: }
18716: 
18717: sub check_captcha {
18718:     my ($captcha_chk,$captcha_error);
18719:     my $code = $env{'form.code'};
18720:     my $md5sum = $env{'form.crypt'};
18721:     my %captcha_params = &captcha_settings();
18722:     my $captcha = Authen::Captcha->new(
18723:                       output_folder => $captcha_params{'output_dir'},
18724:                       data_folder   => $captcha_params{'db_dir'},
18725:                   );
18726:     $captcha_chk = $captcha->check_code($code,$md5sum);
18727:     my %captcha_hash = (
18728:                         0       => 'Code not checked (file error)',
18729:                        -1      => 'Failed: code expired',
18730:                        -2      => 'Failed: invalid code (not in database)',
18731:                        -3      => 'Failed: invalid code (code does not match crypt)',
18732:     );
18733:     if ($captcha_chk != 1) {
18734:         $captcha_error = $captcha_hash{$captcha_chk}
18735:     }
18736:     return ($captcha_chk,$captcha_error);
18737: }
18738: 
18739: sub create_recaptcha {
18740:     my ($pubkey,$version) = @_;
18741:     if ($version >= 2) {
18742:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
18743:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
18744:     } else {
18745:         my $use_ssl;
18746:         if ($ENV{'SERVER_PORT'} == 443) {
18747:             $use_ssl = 1;
18748:         }
18749:         my $captcha = Captcha::reCAPTCHA->new;
18750:         return $captcha->get_options_setter({theme => 'white'})."\n".
18751:                $captcha->get_html($pubkey,undef,$use_ssl).
18752:                &mt('If the text is hard to read, [_1] will replace them.',
18753:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
18754:                '<br /><br />';
18755:     }
18756: }
18757: 
18758: sub check_recaptcha {
18759:     my ($privkey,$version) = @_;
18760:     my $captcha_chk;
18761:     my $ip = &Apache::lonnet::get_requestor_ip();
18762:     if ($version >= 2) {
18763:         my %info = (
18764:                      secret   => $privkey, 
18765:                      response => $env{'form.g-recaptcha-response'},
18766:                      remoteip => $ip,
18767:                    );
18768:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
18769:         $request->content(join('&',map {
18770:                          my $name = escape($_);
18771:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
18772:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
18773:                          : &escape($info{$_}) );
18774:         } keys(%info)));
18775:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
18776:         if ($response->is_success)  {
18777:             my $data = JSON::DWIW->from_json($response->decoded_content);
18778:             if (ref($data) eq 'HASH') {
18779:                 if ($data->{'success'}) {
18780:                     $captcha_chk = 1;
18781:                 }
18782:             }
18783:         }
18784:     } else {
18785:         my $captcha = Captcha::reCAPTCHA->new;
18786:         my $captcha_result =
18787:             $captcha->check_answer(
18788:                                     $privkey,
18789:                                     $ip,
18790:                                     $env{'form.recaptcha_challenge_field'},
18791:                                     $env{'form.recaptcha_response_field'},
18792:                                   );
18793:         if ($captcha_result->{is_valid}) {
18794:             $captcha_chk = 1;
18795:         }
18796:     }
18797:     return $captcha_chk;
18798: }
18799: 
18800: sub emailusername_info {
18801:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
18802:     my %titles = &Apache::lonlocal::texthash (
18803:                      lastname      => 'Last Name',
18804:                      firstname     => 'First Name',
18805:                      institution   => 'School/college/university',
18806:                      location      => "School's city, state/province, country",
18807:                      web           => "School's web address",
18808:                      officialemail => 'E-mail address at institution (if different)',
18809:                      id            => 'Student/Employee ID',
18810:                  );
18811:     return (\@fields,\%titles);
18812: }
18813: 
18814: sub cleanup_html {
18815:     my ($incoming) = @_;
18816:     my $outgoing;
18817:     if ($incoming ne '') {
18818:         $outgoing = $incoming;
18819:         $outgoing =~ s/;/&#059;/g;
18820:         $outgoing =~ s/\#/&#035;/g;
18821:         $outgoing =~ s/\&/&#038;/g;
18822:         $outgoing =~ s/</&#060;/g;
18823:         $outgoing =~ s/>/&#062;/g;
18824:         $outgoing =~ s/\(/&#040/g;
18825:         $outgoing =~ s/\)/&#041;/g;
18826:         $outgoing =~ s/"/&#034;/g;
18827:         $outgoing =~ s/'/&#039;/g;
18828:         $outgoing =~ s/\$/&#036;/g;
18829:         $outgoing =~ s{/}{&#047;}g;
18830:         $outgoing =~ s/=/&#061;/g;
18831:         $outgoing =~ s/\\/&#092;/g
18832:     }
18833:     return $outgoing;
18834: }
18835: 
18836: # Checks for critical messages and returns a redirect url if one exists.
18837: # $interval indicates how often to check for messages.
18838: # $context is the calling context -- roles, grades, contents, menu or flip. 
18839: sub critical_redirect {
18840:     my ($interval,$context) = @_;
18841:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
18842:         return ();
18843:     }
18844:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
18845:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
18846:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
18847:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
18848:             my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
18849:             if ($blocked) {
18850:                 my $checkrole = "cm./$cdom/$cnum";
18851:                 if ($env{'request.course.sec'} ne '') {
18852:                     $checkrole .= "/$env{'request.course.sec'}";
18853:                 }
18854:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
18855:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
18856:                     return;
18857:                 }
18858:             }
18859:         }
18860:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
18861:                                         $env{'user.name'});
18862:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
18863:         my $redirecturl;
18864:         if ($what[0]) {
18865: 	    if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
18866: 	        $redirecturl='/adm/email?critical=display';
18867: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
18868:                 return (1, $url);
18869:             }
18870:         }
18871:     } 
18872:     return ();
18873: }
18874: 
18875: # Use:
18876: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
18877: #
18878: ##################################################
18879: #          password associated functions         #
18880: ##################################################
18881: sub des_keys {
18882:     # Make a new key for DES encryption.
18883:     # Each key has two parts which are returned separately.
18884:     # Please note:  Each key must be passed through the &hex function
18885:     # before it is output to the web browser.  The hex versions cannot
18886:     # be used to decrypt.
18887:     my @hexstr=('0','1','2','3','4','5','6','7',
18888:                 '8','9','a','b','c','d','e','f');
18889:     my $lkey='';
18890:     for (0..7) {
18891:         $lkey.=$hexstr[rand(15)];
18892:     }
18893:     my $ukey='';
18894:     for (0..7) {
18895:         $ukey.=$hexstr[rand(15)];
18896:     }
18897:     return ($lkey,$ukey);
18898: }
18899: 
18900: sub des_decrypt {
18901:     my ($key,$cyphertext) = @_;
18902:     my $keybin=pack("H16",$key);
18903:     my $cypher;
18904:     if ($Crypt::DES::VERSION>=2.03) {
18905:         $cypher=new Crypt::DES $keybin;
18906:     } else {
18907:         $cypher=new DES $keybin;
18908:     }
18909:     my $plaintext='';
18910:     my $cypherlength = length($cyphertext);
18911:     my $numchunks = int($cypherlength/32);
18912:     for (my $j=0; $j<$numchunks; $j++) {
18913:         my $start = $j*32;
18914:         my $cypherblock = substr($cyphertext,$start,32);
18915:         my $chunk =
18916:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
18917:         $chunk .=
18918:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
18919:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
18920:         $plaintext .= $chunk;
18921:     }
18922:     return $plaintext;
18923: }
18924: 
18925: sub get_requested_shorturls {
18926:     my ($cdom,$cnum,$navmap) = @_;
18927:     return unless (ref($navmap));
18928:     my ($numnew,$errors);
18929:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
18930:     if (@toshorten) {
18931:         my (%maps,%resources,%titles);
18932:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
18933:                                                                'shorturls',$cdom,$cnum);
18934:         if (keys(%resources)) {
18935:             my %tocreate;
18936:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
18937:                 my $symb = $resources{$item};
18938:                 if ($symb) {
18939:                     $tocreate{$cnum.'&'.$symb} = 1;
18940:                 }
18941:             }
18942:             if (keys(%tocreate)) {
18943:                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
18944:                                                       \%tocreate);
18945:             }
18946:         }
18947:     }
18948:     return ($numnew,$errors);
18949: }
18950: 
18951: sub make_short_symbs {
18952:     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
18953:     my ($numnew,@errors);
18954:     if (ref($tocreateref) eq 'HASH') {
18955:         my %tocreate = %{$tocreateref};
18956:         if (keys(%tocreate)) {
18957:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
18958:             my $su = Short::URL->new(no_vowels => 1);
18959:             my $init = '';
18960:             my (%newunique,%addcourse,%courseonly,%failed);
18961:             # get lock on tiny db
18962:             my $now = time;
18963:             if ($lockuser eq '') {
18964:                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
18965:             }
18966:             my $lockhash = {
18967:                                 "lock\0$now" => $lockuser,
18968:                             };
18969:             my $tries = 0;
18970:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
18971:             my ($code,$error);
18972:             while (($gotlock ne 'ok') && ($tries<3)) {
18973:                 $tries ++;
18974:                 sleep 1;
18975:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
18976:             }
18977:             if ($gotlock eq 'ok') {
18978:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
18979:                                        \%addcourse,\%courseonly,\%failed);
18980:                 if (keys(%failed)) {
18981:                     my $numfailed = scalar(keys(%failed));
18982:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
18983:                 }
18984:                 if (keys(%newunique)) {
18985:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
18986:                     if ($putres eq 'ok') {
18987:                         $numnew = scalar(keys(%newunique));
18988:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
18989:                         unless ($newputres eq 'ok') {
18990:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
18991:                         }
18992:                     } else {
18993:                         push(@errors,&mt('error: could not store unique six character URLs'));
18994:                     }
18995:                 }
18996:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
18997:                 unless ($dellockres eq 'ok') {
18998:                     push(@errors,&mt('error: could not release lockfile'));
18999:                 }
19000:             } else {
19001:                 push(@errors,&mt('error: could not obtain lockfile'));
19002:             }
19003:             if (keys(%courseonly)) {
19004:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
19005:                 if ($result ne 'ok') {
19006:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
19007:                 }
19008:             }
19009:         }
19010:     }
19011:     return ($numnew,\@errors);
19012: }
19013: 
19014: sub shorten_symbs {
19015:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
19016:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
19017:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
19018:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
19019:     my (%possibles,%collisions);
19020:     foreach my $key (keys(%{$tocreate})) {
19021:         my $num = String::CRC32::crc32($key);
19022:         my $tiny = $su->encode($num,$init);
19023:         if ($tiny) {
19024:             $possibles{$tiny} = $key;
19025:         }
19026:     }
19027:     if (!$init) {
19028:         $init = 1;
19029:     } else {
19030:         $init ++;
19031:     }
19032:     if (keys(%possibles)) {
19033:         my @posstiny = keys(%possibles);
19034:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
19035:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
19036:         if (keys(%currtiny)) {
19037:             foreach my $key (keys(%currtiny)) {
19038:                 next if ($currtiny{$key} eq '');
19039:                 if ($currtiny{$key} eq $possibles{$key}) {
19040:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
19041:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
19042:                         $courseonly->{$tsymb} = $key;
19043:                     }
19044:                 } else {
19045:                     $collisions{$possibles{$key}} = 1;
19046:                 }
19047:                 delete($possibles{$key});
19048:             }
19049:         }
19050:         foreach my $key (keys(%possibles)) {
19051:             $newunique->{$key} = $possibles{$key};
19052:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
19053:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
19054:                 $addcourse->{$tsymb} = $key;
19055:             }
19056:         }
19057:     }
19058:     if (keys(%collisions)) {
19059:         if ($init <5) {
19060:             if (!$init) {
19061:                 $init = 1;
19062:             } else {
19063:                 $init ++;
19064:             }
19065:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
19066:                                    $newunique,$addcourse,$courseonly,$failed);
19067:         } else {
19068:             foreach my $key (keys(%collisions)) {
19069:                 $failed->{$key} = 1;
19070:             }
19071:         }
19072:     }
19073:     return $init;
19074: }
19075: 
19076: sub is_nonframeable {
19077:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
19078:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
19079:     return if (($remprotocol eq '') || ($remhost eq ''));
19080: 
19081:     $remprotocol = lc($remprotocol);
19082:     $remhost = lc($remhost);
19083:     my $remport = 80;
19084:     if ($remprotocol eq 'https') {
19085:         $remport = 443;
19086:     }
19087:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
19088:     if ($cached) {
19089:         unless ($nocache) {
19090:             if ($result) {
19091:                 return 1;
19092:             } else {
19093:                 return 0;
19094:             }
19095:         }
19096:     }
19097:     my $uselink;
19098:     my $request = new HTTP::Request('HEAD',$url);
19099:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
19100:     if ($response->is_success()) {
19101:         my $secpolicy = lc($response->header('content-security-policy'));
19102:         my $xframeop = lc($response->header('x-frame-options'));
19103:         $secpolicy =~ s/^\s+|\s+$//g;
19104:         $xframeop =~ s/^\s+|\s+$//g;
19105:         if (($secpolicy ne '') || ($xframeop ne '')) {
19106:             my $remotehost = $remprotocol.'://'.$remhost;
19107:             my ($origin,$protocol,$port);
19108:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
19109:                 $port = $ENV{'SERVER_PORT'};
19110:             } else {
19111:                 $port = 80;
19112:             }
19113:             if ($absolute eq '') {
19114:                 $protocol = 'http:';
19115:                 if ($port == 443) {
19116:                     $protocol = 'https:';
19117:                 }
19118:                 $origin = $protocol.'//'.lc($hostname);
19119:             } else {
19120:                 $origin = lc($absolute);
19121:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
19122:             }
19123:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
19124:                 my $framepolicy = $1;
19125:                 $framepolicy =~ s/^\s+|\s+$//g;
19126:                 my @policies = split(/\s+/,$framepolicy);
19127:                 if (@policies) {
19128:                     if (grep(/^\Q'none'\E$/,@policies)) {
19129:                         $uselink = 1;
19130:                     } else {
19131:                         $uselink = 1;
19132:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
19133:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
19134:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
19135:                             undef($uselink);
19136:                         }
19137:                         if ($uselink) {
19138:                             if (grep(/^\Q'self'\E$/,@policies)) {
19139:                                 if (($origin ne '') && ($remotehost eq $origin)) {
19140:                                     undef($uselink);
19141:                                 }
19142:                             }
19143:                         }
19144:                         if ($uselink) {
19145:                             my @possok;
19146:                             if ($ip ne '') {
19147:                                 push(@possok,$ip);
19148:                             }
19149:                             my $hoststr = '';
19150:                             foreach my $part (reverse(split(/\./,$hostname))) {
19151:                                 if ($hoststr eq '') {
19152:                                     $hoststr = $part;
19153:                                 } else {
19154:                                     $hoststr = "$part.$hoststr";
19155:                                 }
19156:                                 if ($hoststr eq $hostname) {
19157:                                     push(@possok,$hostname);
19158:                                 } else {
19159:                                     push(@possok,"*.$hoststr");
19160:                                 }
19161:                             }
19162:                             if (@possok) {
19163:                                 foreach my $poss (@possok) {
19164:                                     last if (!$uselink);
19165:                                     foreach my $policy (@policies) {
19166:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
19167:                                             undef($uselink);
19168:                                             last;
19169:                                         }
19170:                                     }
19171:                                 }
19172:                             }
19173:                         }
19174:                     }
19175:                 }
19176:             } elsif ($xframeop ne '') {
19177:                 $uselink = 1;
19178:                 my @policies = split(/\s*,\s*/,$xframeop);
19179:                 if (@policies) {
19180:                     unless (grep(/^deny$/,@policies)) {
19181:                         if ($origin ne '') {
19182:                             if (grep(/^sameorigin$/,@policies)) {
19183:                                 if ($remotehost eq $origin) {
19184:                                     undef($uselink);
19185:                                 }
19186:                             }
19187:                             if ($uselink) {
19188:                                 foreach my $policy (@policies) {
19189:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
19190:                                         my $allowfrom = $1;
19191:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
19192:                                             undef($uselink);
19193:                                             last;
19194:                                         }
19195:                                     }
19196:                                 }
19197:                             }
19198:                         }
19199:                     }
19200:                 }
19201:             }
19202:         }
19203:     }
19204:     if ($nocache) {
19205:         if ($cached) {
19206:             my $devalidate;
19207:             if ($uselink && !$result) {
19208:                 $devalidate = 1;
19209:             } elsif (!$uselink && $result) {
19210:                 $devalidate = 1;
19211:             }
19212:             if ($devalidate) {
19213:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
19214:             }
19215:         }
19216:     } else {
19217:         if ($uselink) {
19218:             $result = 1;
19219:         } else {
19220:             $result = 0;
19221:         }
19222:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
19223:     }
19224:     return $uselink;
19225: }
19226: 
19227: sub page_menu {
19228:     my ($menucolls,$menunum) = @_;
19229:     my %menu;
19230:     foreach my $item (split(/;/,$menucolls)) {
19231:         my ($num,$value) = split(/\%/,$item);
19232:         if ($num eq $menunum) {
19233:             my @entries = split(/\&/,$value);
19234:             foreach my $entry (@entries) {
19235:                 my ($name,$fields) = split(/=/,$entry);
19236:                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
19237:                     $menu{$name} = $fields;
19238:                 } else {
19239:                     my @shown;
19240:                     if ($fields =~ /,/) {
19241:                         @shown = split(/,/,$fields);
19242:                     } else {
19243:                         @shown = ($fields);
19244:                     }
19245:                     if (@shown) {
19246:                         foreach my $field (@shown) {
19247:                             next if ($field eq '');
19248:                             $menu{$field} = 1;
19249:                         }
19250:                     }
19251:                 }
19252:             }
19253:         }
19254:     }
19255:     return %menu;
19256: }
19257: 
19258: 1;
19259: __END__;
19260: 

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