File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1075.2.161.2.11: download - view: text, annotated - select for diffs
Wed Nov 16 14:50:04 2022 UTC (18 months, 2 weeks ago) by raeburn
Branches: version_2_11_4_msu
- For 2.11.4 (modified)
  Include changes in rev. 1.1396

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1075.2.161.2.11 2022/11/16 14:50:04 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 HTTP::Request;
   75: use DateTime::TimeZone;
   76: use DateTime::Locale;
   77: use Encode();
   78: use Authen::Captcha;
   79: use Captcha::reCAPTCHA;
   80: use JSON::DWIW;
   81: use LWP::UserAgent;
   82: use Crypt::DES;
   83: use DynaLoader; # for Crypt::DES version
   84: use File::Copy();
   85: use File::Path();
   86: use String::CRC32();
   87: use Short::URL();
   88: 
   89: # ---------------------------------------------- Designs
   90: use vars qw(%defaultdesign);
   91: 
   92: my $readit;
   93: 
   94: 
   95: ##
   96: ## Global Variables
   97: ##
   98: 
   99: 
  100: # ----------------------------------------------- SSI with retries:
  101: #
  102: 
  103: =pod
  104: 
  105: =head1 Server Side include with retries:
  106: 
  107: =over 4
  108: 
  109: =item * &ssi_with_retries(resource,retries form)
  110: 
  111: Performs an ssi with some number of retries.  Retries continue either
  112: until the result is ok or until the retry count supplied by the
  113: caller is exhausted.  
  114: 
  115: Inputs:
  116: 
  117: =over 4
  118: 
  119: resource   - Identifies the resource to insert.
  120: 
  121: retries    - Count of the number of retries allowed.
  122: 
  123: form       - Hash that identifies the rendering options.
  124: 
  125: =back
  126: 
  127: Returns:
  128: 
  129: =over 4
  130: 
  131: content    - The content of the response.  If retries were exhausted this is empty.
  132: 
  133: response   - The response from the last attempt (which may or may not have been successful.
  134: 
  135: =back
  136: 
  137: =back
  138: 
  139: =cut
  140: 
  141: sub ssi_with_retries {
  142:     my ($resource, $retries, %form) = @_;
  143: 
  144: 
  145:     my $ok = 0;			# True if we got a good response.
  146:     my $content;
  147:     my $response;
  148: 
  149:     # Try to get the ssi done. within the retries count:
  150: 
  151:     do {
  152: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  153: 	$ok      = $response->is_success;
  154:         if (!$ok) {
  155:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  156:         }
  157: 	$retries--;
  158:     } while (!$ok && ($retries > 0));
  159: 
  160:     if (!$ok) {
  161: 	$content = '';		# On error return an empty content.
  162:     }
  163:     return ($content, $response);
  164: 
  165: }
  166: 
  167: 
  168: 
  169: # ----------------------------------------------- Filetypes/Languages/Copyright
  170: my %language;
  171: my %supported_language;
  172: my %latex_language;		# For choosing hyphenation in <transl..>
  173: my %latex_language_bykey;	# for choosing hyphenation from metadata
  174: my %cprtag;
  175: my %scprtag;
  176: my %fe; my %fd; my %fm;
  177: my %category_extensions;
  178: 
  179: # ---------------------------------------------- Thesaurus variables
  180: #
  181: # %Keywords:
  182: #      A hash used by &keyword to determine if a word is considered a keyword.
  183: # $thesaurus_db_file 
  184: #      Scalar containing the full path to the thesaurus database.
  185: 
  186: my %Keywords;
  187: my $thesaurus_db_file;
  188: 
  189: #
  190: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  191: # thesaurus.tab, and filecategories.tab.
  192: #
  193: BEGIN {
  194:     # Variable initialization
  195:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  196:     #
  197:     unless ($readit) {
  198: # ------------------------------------------------------------------- languages
  199:     {
  200:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  201:                                    '/language.tab';
  202:         if ( open(my $fh,'<',$langtabfile) ) {
  203:             while (my $line = <$fh>) {
  204:                 next if ($line=~/^\#/);
  205:                 chomp($line);
  206:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  207:                 $language{$key}=$val.' - '.$enc;
  208:                 if ($sup) {
  209:                     $supported_language{$key}=$sup;
  210:                 }
  211: 		if ($latex) {
  212: 		    $latex_language_bykey{$key} = $latex;
  213: 		    $latex_language{$two} = $latex;
  214: 		}
  215:             }
  216:             close($fh);
  217:         }
  218:     }
  219: # ------------------------------------------------------------------ copyrights
  220:     {
  221:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  222:                                   '/copyright.tab';
  223:         if ( open (my $fh,'<',$copyrightfile) ) {
  224:             while (my $line = <$fh>) {
  225:                 next if ($line=~/^\#/);
  226:                 chomp($line);
  227:                 my ($key,$val)=(split(/\s+/,$line,2));
  228:                 $cprtag{$key}=$val;
  229:             }
  230:             close($fh);
  231:         }
  232:     }
  233: # ----------------------------------------------------------- source copyrights
  234:     {
  235:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  236:                                   '/source_copyright.tab';
  237:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
  238:             while (my $line = <$fh>) {
  239:                 next if ($line =~ /^\#/);
  240:                 chomp($line);
  241:                 my ($key,$val)=(split(/\s+/,$line,2));
  242:                 $scprtag{$key}=$val;
  243:             }
  244:             close($fh);
  245:         }
  246:     }
  247: 
  248: # -------------------------------------------------------------- default domain designs
  249:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  250:     my $designfile = $designdir.'/default.tab';
  251:     if ( open (my $fh,'<',$designfile) ) {
  252:         while (my $line = <$fh>) {
  253:             next if ($line =~ /^\#/);
  254:             chomp($line);
  255:             my ($key,$val)=(split(/\=/,$line));
  256:             if ($val) { $defaultdesign{$key}=$val; }
  257:         }
  258:         close($fh);
  259:     }
  260: 
  261: # ------------------------------------------------------------- file categories
  262:     {
  263:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  264:                                   '/filecategories.tab';
  265:         if ( open (my $fh,'<',$categoryfile) ) {
  266: 	    while (my $line = <$fh>) {
  267: 		next if ($line =~ /^\#/);
  268: 		chomp($line);
  269:                 my ($extension,$category)=(split(/\s+/,$line,2));
  270:                 push(@{$category_extensions{lc($category)}},$extension);
  271:             }
  272:             close($fh);
  273:         }
  274: 
  275:     }
  276: # ------------------------------------------------------------------ file types
  277:     {
  278:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  279:                '/filetypes.tab';
  280:         if ( open (my $fh,'<',$typesfile) ) {
  281:             while (my $line = <$fh>) {
  282: 		next if ($line =~ /^\#/);
  283: 		chomp($line);
  284:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  285:                 if ($descr ne '') {
  286:                     $fe{$ending}=lc($emb);
  287:                     $fd{$ending}=$descr;
  288:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  289:                 }
  290:             }
  291:             close($fh);
  292:         }
  293:     }
  294:     &Apache::lonnet::logthis(
  295:              "<span style='color:yellow;'>INFO: Read file types</span>");
  296:     $readit=1;
  297:     }  # end of unless($readit) 
  298:     
  299: }
  300: 
  301: ###############################################################
  302: ##           HTML and Javascript Helper Functions            ##
  303: ###############################################################
  304: 
  305: =pod 
  306: 
  307: =head1 HTML and Javascript Functions
  308: 
  309: =over 4
  310: 
  311: =item * &browser_and_searcher_javascript()
  312: 
  313: X<browsing, javascript>X<searching, javascript>Returns a string
  314: containing javascript with two functions, C<openbrowser> and
  315: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  316: tags.
  317: 
  318: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  319: 
  320: inputs: formname, elementname, only, omit
  321: 
  322: formname and elementname indicate the name of the html form and name of
  323: the element that the results of the browsing selection are to be placed in. 
  324: 
  325: Specifying 'only' will restrict the browser to displaying only files
  326: with the given extension.  Can be a comma separated list.
  327: 
  328: Specifying 'omit' will restrict the browser to NOT displaying files
  329: with the given extension.  Can be a comma separated list.
  330: 
  331: =item * &opensearcher(formname,elementname) [javascript]
  332: 
  333: Inputs: formname, elementname
  334: 
  335: formname and elementname specify the name of the html form and the name
  336: of the element the selection from the search results will be placed in.
  337: 
  338: =cut
  339: 
  340: sub browser_and_searcher_javascript {
  341:     my ($mode)=@_;
  342:     if (!defined($mode)) { $mode='edit'; }
  343:     my $resurl=&escape_single(&lastresurl());
  344:     return <<END;
  345: // <!-- BEGIN LON-CAPA Internal
  346:     var editbrowser = null;
  347:     function openbrowser(formname,elementname,only,omit,titleelement) {
  348:         var url = '$resurl/?';
  349:         if (editbrowser == null) {
  350:             url += 'launch=1&';
  351:         }
  352:         url += 'catalogmode=interactive&';
  353:         url += 'mode=$mode&';
  354:         url += 'inhibitmenu=yes&';
  355:         url += 'form=' + formname + '&';
  356:         if (only != null) {
  357:             url += 'only=' + only + '&';
  358:         } else {
  359:             url += 'only=&';
  360: 	}
  361:         if (omit != null) {
  362:             url += 'omit=' + omit + '&';
  363:         } else {
  364:             url += 'omit=&';
  365: 	}
  366:         if (titleelement != null) {
  367:             url += 'titleelement=' + titleelement + '&';
  368:         } else {
  369: 	    url += 'titleelement=&';
  370: 	}
  371:         url += 'element=' + elementname + '';
  372:         var title = 'Browser';
  373:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  374:         options += ',width=700,height=600';
  375:         editbrowser = open(url,title,options,'1');
  376:         editbrowser.focus();
  377:     }
  378:     var editsearcher;
  379:     function opensearcher(formname,elementname,titleelement) {
  380:         var url = '/adm/searchcat?';
  381:         if (editsearcher == null) {
  382:             url += 'launch=1&';
  383:         }
  384:         url += 'catalogmode=interactive&';
  385:         url += 'mode=$mode&';
  386:         url += 'form=' + formname + '&';
  387:         if (titleelement != null) {
  388:             url += 'titleelement=' + titleelement + '&';
  389:         } else {
  390: 	    url += 'titleelement=&';
  391: 	}
  392:         url += 'element=' + elementname + '';
  393:         var title = 'Search';
  394:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  395:         options += ',width=700,height=600';
  396:         editsearcher = open(url,title,options,'1');
  397:         editsearcher.focus();
  398:     }
  399: // END LON-CAPA Internal -->
  400: END
  401: }
  402: 
  403: sub lastresurl {
  404:     if ($env{'environment.lastresurl'}) {
  405: 	return $env{'environment.lastresurl'}
  406:     } else {
  407: 	return '/res';
  408:     }
  409: }
  410: 
  411: sub storeresurl {
  412:     my $resurl=&Apache::lonnet::clutter(shift);
  413:     unless ($resurl=~/^\/res/) { return 0; }
  414:     $resurl=~s/\/$//;
  415:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  416:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  417:     return 1;
  418: }
  419: 
  420: sub studentbrowser_javascript {
  421:    unless (
  422:             (($env{'request.course.id'}) && 
  423:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  424: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  425: 					  '/'.$env{'request.course.sec'})
  426: 	      ))
  427:          || ($env{'request.role'}=~/^(au|dc|su)/)
  428:           ) { return ''; }  
  429:    return (<<'ENDSTDBRW');
  430: <script type="text/javascript" language="Javascript">
  431: // <![CDATA[
  432:     var stdeditbrowser;
  433:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv) {
  434:         var url = '/adm/pickstudent?';
  435:         var filter;
  436: 	if (!ignorefilter) {
  437: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  438: 	}
  439:         if (filter != null) {
  440:            if (filter != '') {
  441:                url += 'filter='+filter+'&';
  442: 	   }
  443:         }
  444:         url += 'form=' + formname + '&unameelement='+uname+
  445:                                     '&udomelement='+udom+
  446:                                     '&clicker='+clicker;
  447: 	if (roleflag) { url+="&roles=1"; }
  448:         if (courseadv == 'condition') {
  449:             if (document.getElementById('courseadv')) {
  450:                 courseadv = document.getElementById('courseadv').value;
  451:             }
  452:         }
  453:         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
  454:         var title = 'Student_Browser';
  455:         var options = 'scrollbars=1,resizable=1,menubar=0';
  456:         options += ',width=700,height=600';
  457:         stdeditbrowser = open(url,title,options,'1');
  458:         stdeditbrowser.focus();
  459:     }
  460: // ]]>
  461: </script>
  462: ENDSTDBRW
  463: }
  464: 
  465: sub resourcebrowser_javascript {
  466:    unless ($env{'request.course.id'}) { return ''; }
  467:    return (<<'ENDRESBRW');
  468: <script type="text/javascript" language="Javascript">
  469: // <![CDATA[
  470:     var reseditbrowser;
  471:     function openresbrowser(formname,reslink) {
  472:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  473:         var title = 'Resource_Browser';
  474:         var options = 'scrollbars=1,resizable=1,menubar=0';
  475:         options += ',width=700,height=500';
  476:         reseditbrowser = open(url,title,options,'1');
  477:         reseditbrowser.focus();
  478:     }
  479: // ]]>
  480: </script>
  481: ENDRESBRW
  482: }
  483: 
  484: sub selectstudent_link {
  485:    my ($form,$unameele,$udomele,$courseadv,$clickerid)=@_;
  486:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  487:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  488:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  489:    if ($env{'request.course.id'}) {  
  490:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  491: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  492: 					'/'.$env{'request.course.sec'})) {
  493: 	   return '';
  494:        }
  495:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  496:        if ($courseadv eq 'only') {
  497:            $callargs .= ",'',1,'$courseadv'";
  498:        } elsif ($courseadv eq 'none') {
  499:            $callargs .= ",'','','$courseadv'";
  500:        } elsif ($courseadv eq 'condition') {
  501:            $callargs .= ",'','','$courseadv'";
  502:        }
  503:        return '<span class="LC_nobreak">'.
  504:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  505:               &mt('Select User').'</a></span>';
  506:    }
  507:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  508:        $callargs .= ",'',1"; 
  509:        return '<span class="LC_nobreak">'.
  510:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  511:               &mt('Select User').'</a></span>';
  512:    }
  513:    return '';
  514: }
  515: 
  516: sub selectresource_link {
  517:    my ($form,$reslink,$arg)=@_;
  518:    
  519:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  520:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  521:    unless ($env{'request.course.id'}) { return $arg; }
  522:    return '<span class="LC_nobreak">'.
  523:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  524:               $arg.'</a></span>';
  525: }
  526: 
  527: 
  528: 
  529: sub authorbrowser_javascript {
  530:     return <<"ENDAUTHORBRW";
  531: <script type="text/javascript" language="JavaScript">
  532: // <![CDATA[
  533: var stdeditbrowser;
  534: 
  535: function openauthorbrowser(formname,udom) {
  536:     var url = '/adm/pickauthor?';
  537:     url += 'form='+formname+'&roledom='+udom;
  538:     var title = 'Author_Browser';
  539:     var options = 'scrollbars=1,resizable=1,menubar=0';
  540:     options += ',width=700,height=600';
  541:     stdeditbrowser = open(url,title,options,'1');
  542:     stdeditbrowser.focus();
  543: }
  544: 
  545: // ]]>
  546: </script>
  547: ENDAUTHORBRW
  548: }
  549: 
  550: sub coursebrowser_javascript {
  551:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
  552:         $credits_element,$instcode) = @_;
  553:     my $wintitle = 'Course_Browser';
  554:     if ($crstype eq 'Community') {
  555:         $wintitle = 'Community_Browser';
  556:     }
  557:     my $id_functions = &javascript_index_functions();
  558:     my $output = '
  559: <script type="text/javascript" language="JavaScript">
  560: // <![CDATA[
  561:     var stdeditbrowser;'."\n";
  562: 
  563:     $output .= <<"ENDSTDBRW";
  564:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  565:         var url = '/adm/pickcourse?';
  566:         var formid = getFormIdByName(formname);
  567:         var domainfilter = getDomainFromSelectbox(formname,udom);
  568:         if (domainfilter != null) {
  569:            if (domainfilter != '') {
  570:                url += 'domainfilter='+domainfilter+'&';
  571: 	   }
  572:         }
  573:         url += 'form=' + formname + '&cnumelement='+uname+
  574: 	                            '&cdomelement='+udom+
  575:                                     '&cnameelement='+desc;
  576:         if (extra_element !=null && extra_element != '') {
  577:             if (formname == 'rolechoice' || formname == 'studentform') {
  578:                 url += '&roleelement='+extra_element;
  579:                 if (domainfilter == null || domainfilter == '') {
  580:                     url += '&domainfilter='+extra_element;
  581:                 }
  582:             }
  583:             else {
  584:                 if (formname == 'portform') {
  585:                     url += '&setroles='+extra_element;
  586:                 } else {
  587:                     if (formname == 'rules') {
  588:                         url += '&fixeddom='+extra_element; 
  589:                     }
  590:                 }
  591:             }     
  592:         }
  593:         if (type != null && type != '') {
  594:             url += '&type='+type;
  595:         }
  596:         if (type_elem != null && type_elem != '') {
  597:             url += '&typeelement='+type_elem;
  598:         }
  599:         if (formname == 'ccrs') {
  600:             var ownername = document.forms[formid].ccuname.value;
  601:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  602:             url += '&cloner='+ownername+':'+ownerdom;
  603:             if (type == 'Course') {
  604:                 url += '&crscode='+document.forms[formid].crscode.value;
  605:             }
  606:         }
  607:         if (formname == 'requestcrs') {
  608:             url += '&crsdom=$domainfilter&crscode=$instcode';
  609:         }
  610:         if (multflag !=null && multflag != '') {
  611:             url += '&multiple='+multflag;
  612:         }
  613:         var title = '$wintitle';
  614:         var options = 'scrollbars=1,resizable=1,menubar=0';
  615:         options += ',width=700,height=600';
  616:         stdeditbrowser = open(url,title,options,'1');
  617:         stdeditbrowser.focus();
  618:     }
  619: $id_functions
  620: ENDSTDBRW
  621:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
  622:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
  623:                                       $credits_element);
  624:     }
  625:     $output .= '
  626: // ]]>
  627: </script>';
  628:     return $output;
  629: }
  630: 
  631: sub javascript_index_functions {
  632:     return <<"ENDJS";
  633: 
  634: function getFormIdByName(formname) {
  635:     for (var i=0;i<document.forms.length;i++) {
  636:         if (document.forms[i].name == formname) {
  637:             return i;
  638:         }
  639:     }
  640:     return -1;
  641: }
  642: 
  643: function getIndexByName(formid,item) {
  644:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  645:         if (document.forms[formid].elements[i].name == item) {
  646:             return i;
  647:         }
  648:     }
  649:     return -1;
  650: }
  651: 
  652: function getDomainFromSelectbox(formname,udom) {
  653:     var userdom;
  654:     var formid = getFormIdByName(formname);
  655:     if (formid > -1) {
  656:         var domid = getIndexByName(formid,udom);
  657:         if (domid > -1) {
  658:             if (document.forms[formid].elements[domid].type == 'select-one') {
  659:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  660:             }
  661:             if (document.forms[formid].elements[domid].type == 'hidden') {
  662:                 userdom=document.forms[formid].elements[domid].value;
  663:             }
  664:         }
  665:     }
  666:     return userdom;
  667: }
  668: 
  669: ENDJS
  670: 
  671: }
  672: 
  673: sub javascript_array_indexof {
  674:     return <<ENDJS;
  675: <script type="text/javascript" language="JavaScript">
  676: // <![CDATA[
  677: 
  678: if (!Array.prototype.indexOf) {
  679:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  680:         "use strict";
  681:         if (this === void 0 || this === null) {
  682:             throw new TypeError();
  683:         }
  684:         var t = Object(this);
  685:         var len = t.length >>> 0;
  686:         if (len === 0) {
  687:             return -1;
  688:         }
  689:         var n = 0;
  690:         if (arguments.length > 0) {
  691:             n = Number(arguments[1]);
  692:             if (n !== n) { // shortcut for verifying if it's NaN
  693:                 n = 0;
  694:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  695:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  696:             }
  697:         }
  698:         if (n >= len) {
  699:             return -1;
  700:         }
  701:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  702:         for (; k < len; k++) {
  703:             if (k in t && t[k] === searchElement) {
  704:                 return k;
  705:             }
  706:         }
  707:         return -1;
  708:     }
  709: }
  710: 
  711: // ]]>
  712: </script>
  713: 
  714: ENDJS
  715: 
  716: }
  717: 
  718: sub userbrowser_javascript {
  719:     my $id_functions = &javascript_index_functions();
  720:     return <<"ENDUSERBRW";
  721: 
  722: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  723:     var url = '/adm/pickuser?';
  724:     var userdom = getDomainFromSelectbox(formname,udom);
  725:     if (userdom != null) {
  726:        if (userdom != '') {
  727:            url += 'srchdom='+userdom+'&';
  728:        }
  729:     }
  730:     url += 'form=' + formname + '&unameelement='+uname+
  731:                                 '&udomelement='+udom+
  732:                                 '&ulastelement='+ulast+
  733:                                 '&ufirstelement='+ufirst+
  734:                                 '&uemailelement='+uemail+
  735:                                 '&hideudomelement='+hideudom+
  736:                                 '&coursedom='+crsdom;
  737:     if ((caller != null) && (caller != undefined)) {
  738:         url += '&caller='+caller;
  739:     }
  740:     var title = 'User_Browser';
  741:     var options = 'scrollbars=1,resizable=1,menubar=0';
  742:     options += ',width=700,height=600';
  743:     var stdeditbrowser = open(url,title,options,'1');
  744:     stdeditbrowser.focus();
  745: }
  746: 
  747: function fix_domain (formname,udom,origdom,uname) {
  748:     var formid = getFormIdByName(formname);
  749:     if (formid > -1) {
  750:         var unameid = getIndexByName(formid,uname);
  751:         var domid = getIndexByName(formid,udom);
  752:         var hidedomid = getIndexByName(formid,origdom);
  753:         if (hidedomid > -1) {
  754:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  755:             var unameval = document.forms[formid].elements[unameid].value;
  756:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  757:                 if (domid > -1) {
  758:                     var slct = document.forms[formid].elements[domid];
  759:                     if (slct.type == 'select-one') {
  760:                         var i;
  761:                         for (i=0;i<slct.length;i++) {
  762:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  763:                         }
  764:                     }
  765:                     if (slct.type == 'hidden') {
  766:                         slct.value = fixeddom;
  767:                     }
  768:                 }
  769:             }
  770:         }
  771:     }
  772:     return;
  773: }
  774: 
  775: $id_functions
  776: ENDUSERBRW
  777: }
  778: 
  779: sub setsec_javascript {
  780:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
  781:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  782:         $communityrolestr);
  783:     if ($role_element ne '') {
  784:         my @allroles = ('st','ta','ep','in','ad');
  785:         foreach my $crstype ('Course','Community') {
  786:             if ($crstype eq 'Community') {
  787:                 foreach my $role (@allroles) {
  788:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  789:                 }
  790:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  791:             } else {
  792:                 foreach my $role (@allroles) {
  793:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  794:                 }
  795:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  796:             }
  797:         }
  798:         $rolestr = '"'.join('","',@allroles).'"';
  799:         $courserolestr = '"'.join('","',@courserolenames).'"';
  800:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  801:     }
  802:     my $setsections = qq|
  803: function setSect(sectionlist) {
  804:     var sectionsArray = new Array();
  805:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  806:         sectionsArray = sectionlist.split(",");
  807:     }
  808:     var numSections = sectionsArray.length;
  809:     document.$formname.$sec_element.length = 0;
  810:     if (numSections == 0) {
  811:         document.$formname.$sec_element.multiple=false;
  812:         document.$formname.$sec_element.size=1;
  813:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  814:     } else {
  815:         if (numSections == 1) {
  816:             document.$formname.$sec_element.multiple=false;
  817:             document.$formname.$sec_element.size=1;
  818:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  819:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  820:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  821:         } else {
  822:             for (var i=0; i<numSections; i++) {
  823:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  824:             }
  825:             document.$formname.$sec_element.multiple=true
  826:             if (numSections < 3) {
  827:                 document.$formname.$sec_element.size=numSections;
  828:             } else {
  829:                 document.$formname.$sec_element.size=3;
  830:             }
  831:             document.$formname.$sec_element.options[0].selected = false
  832:         }
  833:     }
  834: }
  835: 
  836: function setRole(crstype) {
  837: |;
  838:     if ($role_element eq '') {
  839:         $setsections .= '    return;
  840: }
  841: ';
  842:     } else {
  843:         $setsections .= qq|
  844:     var elementLength = document.$formname.$role_element.length;
  845:     var allroles = Array($rolestr);
  846:     var courserolenames = Array($courserolestr);
  847:     var communityrolenames = Array($communityrolestr);
  848:     if (elementLength != undefined) {
  849:         if (document.$formname.$role_element.options[5].value == 'cc') {
  850:             if (crstype == 'Course') {
  851:                 return;
  852:             } else {
  853:                 allroles[5] = 'co';
  854:                 for (var i=0; i<6; i++) {
  855:                     document.$formname.$role_element.options[i].value = allroles[i];
  856:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  857:                 }
  858:             }
  859:         } else {
  860:             if (crstype == 'Community') {
  861:                 return;
  862:             } else {
  863:                 allroles[5] = 'cc';
  864:                 for (var i=0; i<6; i++) {
  865:                     document.$formname.$role_element.options[i].value = allroles[i];
  866:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  867:                 }
  868:             }
  869:         }
  870:     }
  871:     return;
  872: }
  873: |;
  874:     }
  875:     if ($credits_element) {
  876:         $setsections .= qq|
  877: function setCredits(defaultcredits) {
  878:     document.$formname.$credits_element.value = defaultcredits;
  879:     return;
  880: }
  881: |;
  882:     }
  883:     return $setsections;
  884: }
  885: 
  886: sub selectcourse_link {
  887:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  888:        $typeelement) = @_;
  889:    my $type = $selecttype;
  890:    my $linktext = &mt('Select Course');
  891:    if ($selecttype eq 'Community') {
  892:        $linktext = &mt('Select Community');
  893:    } elsif ($selecttype eq 'Course/Community') {
  894:        $linktext = &mt('Select Course/Community');
  895:        $type = '';
  896:    } elsif ($selecttype eq 'Select') {
  897:        $linktext = &mt('Select');
  898:        $type = '';
  899:    }
  900:    return '<span class="LC_nobreak">'
  901:          ."<a href='"
  902:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  903:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  904:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  905:          ."'>".$linktext.'</a>'
  906:          .'</span>';
  907: }
  908: 
  909: sub selectauthor_link {
  910:    my ($form,$udom)=@_;
  911:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  912:           &mt('Select Author').'</a>';
  913: }
  914: 
  915: sub selectuser_link {
  916:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  917:         $coursedom,$linktext,$caller) = @_;
  918:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  919:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  920:            ');">'.$linktext.'</a>';
  921: }
  922: 
  923: sub check_uncheck_jscript {
  924:     my $jscript = <<"ENDSCRT";
  925: function checkAll(field) {
  926:     if (field.length > 0) {
  927:         for (i = 0; i < field.length; i++) {
  928:             if (!field[i].disabled) {
  929:                 field[i].checked = true;
  930:             }
  931:         }
  932:     } else {
  933:         if (!field.disabled) {
  934:             field.checked = true;
  935:         }
  936:     }
  937: }
  938:  
  939: function uncheckAll(field) {
  940:     if (field.length > 0) {
  941:         for (i = 0; i < field.length; i++) {
  942:             field[i].checked = false ;
  943:         }
  944:     } else {
  945:         field.checked = false ;
  946:     }
  947: }
  948: ENDSCRT
  949:     return $jscript;
  950: }
  951: 
  952: sub select_timezone {
  953:    my ($name,$selected,$onchange,$includeempty,$id,$disabled)=@_;
  954:    my $output='<select name="'.$name.'" '.$id.$onchange.$disabled.'>'."\n";
  955:    if ($includeempty) {
  956:        $output .= '<option value=""';
  957:        if (($selected eq '') || ($selected eq 'local')) {
  958:            $output .= ' selected="selected" ';
  959:        }
  960:        $output .= '> </option>';
  961:    }
  962:    my @timezones = DateTime::TimeZone->all_names;
  963:    foreach my $tzone (@timezones) {
  964:        $output.= '<option value="'.$tzone.'"';
  965:        if ($tzone eq $selected) {
  966:            $output.=' selected="selected"';
  967:        }
  968:        $output.=">$tzone</option>\n";
  969:    }
  970:    $output.="</select>";
  971:    return $output;
  972: }
  973: 
  974: sub select_datelocale {
  975:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  976:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  977:     if ($includeempty) {
  978:         $output .= '<option value=""';
  979:         if ($selected eq '') {
  980:             $output .= ' selected="selected" ';
  981:         }
  982:         $output .= '> </option>';
  983:     }
  984:     my @languages = &Apache::lonlocal::preferred_languages();
  985:     my (@possibles,%locale_names);
  986:     my @locales = DateTime::Locale->ids();
  987:     foreach my $id (@locales) {
  988:         if ($id ne '') {
  989:             my ($en_terr,$native_terr);
  990:             my $loc = DateTime::Locale->load($id);
  991:             if (ref($loc)) {
  992:                 $en_terr = $loc->name();
  993:                 $native_terr = $loc->native_name();
  994:                 if (grep(/^en$/,@languages) || !@languages) {
  995:                     if ($en_terr ne '') {
  996:                         $locale_names{$id} = '('.$en_terr.')';
  997:                     } elsif ($native_terr ne '') {
  998:                         $locale_names{$id} = $native_terr;
  999:                     }
 1000:                 } else {
 1001:                     if ($native_terr ne '') {
 1002:                         $locale_names{$id} = $native_terr.' ';
 1003:                     } elsif ($en_terr ne '') {
 1004:                         $locale_names{$id} = '('.$en_terr.')';
 1005:                     }
 1006:                 }
 1007:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
 1008:                 push(@possibles,$id);
 1009:             }
 1010:         }
 1011:     }
 1012:     foreach my $item (sort(@possibles)) {
 1013:         $output.= '<option value="'.$item.'"';
 1014:         if ($item eq $selected) {
 1015:             $output.=' selected="selected"';
 1016:         }
 1017:         $output.=">$item";
 1018:         if ($locale_names{$item} ne '') {
 1019:             $output.='  '.$locale_names{$item};
 1020:         }
 1021:         $output.="</option>\n";
 1022:     }
 1023:     $output.="</select>";
 1024:     return $output;
 1025: }
 1026: 
 1027: sub select_language {
 1028:     my ($name,$selected,$includeempty,$noedit) = @_;
 1029:     my %langchoices;
 1030:     if ($includeempty) {
 1031:         %langchoices = ('' => 'No language preference');
 1032:     }
 1033:     foreach my $id (&languageids()) {
 1034:         my $code = &supportedlanguagecode($id);
 1035:         if ($code) {
 1036:             $langchoices{$code} = &plainlanguagedescription($id);
 1037:         }
 1038:     }
 1039:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
 1040:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
 1041: }
 1042: 
 1043: =pod
 1044: 
 1045: =item * &linked_select_forms(...)
 1046: 
 1047: linked_select_forms returns a string containing a <script></script> block
 1048: and html for two <select> menus.  The select menus will be linked in that
 1049: changing the value of the first menu will result in new values being placed
 1050: in the second menu.  The values in the select menu will appear in alphabetical
 1051: order unless a defined order is provided.
 1052: 
 1053: linked_select_forms takes the following ordered inputs:
 1054: 
 1055: =over 4
 1056: 
 1057: =item * $formname, the name of the <form> tag
 1058: 
 1059: =item * $middletext, the text which appears between the <select> tags
 1060: 
 1061: =item * $firstdefault, the default value for the first menu
 1062: 
 1063: =item * $firstselectname, the name of the first <select> tag
 1064: 
 1065: =item * $secondselectname, the name of the second <select> tag
 1066: 
 1067: =item * $hashref, a reference to a hash containing the data for the menus.
 1068: 
 1069: =item * $menuorder, the order of values in the first menu
 1070: 
 1071: =item * $onchangefirst, additional javascript call to execute for an onchange
 1072:         event for the first <select> tag
 1073: 
 1074: =item * $onchangesecond, additional javascript call to execute for an onchange
 1075:         event for the second <select> tag
 1076: 
 1077: =back 
 1078: 
 1079: Below is an example of such a hash.  Only the 'text', 'default', and 
 1080: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1081: values for the first select menu.  The text that coincides with the 
 1082: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1083: and text for the second menu are given in the hash pointed to by 
 1084: $menu{$choice1}->{'select2'}.  
 1085: 
 1086:  my %menu = ( A1 => { text =>"Choice A1" ,
 1087:                        default => "B3",
 1088:                        select2 => { 
 1089:                            B1 => "Choice B1",
 1090:                            B2 => "Choice B2",
 1091:                            B3 => "Choice B3",
 1092:                            B4 => "Choice B4"
 1093:                            },
 1094:                        order => ['B4','B3','B1','B2'],
 1095:                    },
 1096:                A2 => { text =>"Choice A2" ,
 1097:                        default => "C2",
 1098:                        select2 => { 
 1099:                            C1 => "Choice C1",
 1100:                            C2 => "Choice C2",
 1101:                            C3 => "Choice C3"
 1102:                            },
 1103:                        order => ['C2','C1','C3'],
 1104:                    },
 1105:                A3 => { text =>"Choice A3" ,
 1106:                        default => "D6",
 1107:                        select2 => { 
 1108:                            D1 => "Choice D1",
 1109:                            D2 => "Choice D2",
 1110:                            D3 => "Choice D3",
 1111:                            D4 => "Choice D4",
 1112:                            D5 => "Choice D5",
 1113:                            D6 => "Choice D6",
 1114:                            D7 => "Choice D7"
 1115:                            },
 1116:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1117:                    }
 1118:                );
 1119: 
 1120: =cut
 1121: 
 1122: sub linked_select_forms {
 1123:     my ($formname,
 1124:         $middletext,
 1125:         $firstdefault,
 1126:         $firstselectname,
 1127:         $secondselectname, 
 1128:         $hashref,
 1129:         $menuorder,
 1130:         $onchangefirst,
 1131:         $onchangesecond
 1132:         ) = @_;
 1133:     my $second = "document.$formname.$secondselectname";
 1134:     my $first = "document.$formname.$firstselectname";
 1135:     # output the javascript to do the changing
 1136:     my $result = '';
 1137:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1138:     $result.="// <![CDATA[\n";
 1139:     $result.="var select2data = new Object();\n";
 1140:     $" = '","';
 1141:     my $debug = '';
 1142:     foreach my $s1 (sort(keys(%$hashref))) {
 1143:         $result.="select2data.d_$s1 = new Object();\n";        
 1144:         $result.="select2data.d_$s1.def = new String('".
 1145:             $hashref->{$s1}->{'default'}."');\n";
 1146:         $result.="select2data.d_$s1.values = new Array(";
 1147:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1148:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1149:             @s2values = @{$hashref->{$s1}->{'order'}};
 1150:         }
 1151:         $result.="\"@s2values\");\n";
 1152:         $result.="select2data.d_$s1.texts = new Array(";        
 1153:         my @s2texts;
 1154:         foreach my $value (@s2values) {
 1155:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
 1156:         }
 1157:         $result.="\"@s2texts\");\n";
 1158:     }
 1159:     $"=' ';
 1160:     $result.= <<"END";
 1161: 
 1162: function select1_changed() {
 1163:     // Determine new choice
 1164:     var newvalue = "d_" + $first.value;
 1165:     // update select2
 1166:     var values     = select2data[newvalue].values;
 1167:     var texts      = select2data[newvalue].texts;
 1168:     var select2def = select2data[newvalue].def;
 1169:     var i;
 1170:     // out with the old
 1171:     for (i = 0; i < $second.options.length; i++) {
 1172:         $second.options[i] = null;
 1173:     }
 1174:     // in with the nuclear
 1175:     for (i=0;i<values.length; i++) {
 1176:         $second.options[i] = new Option(values[i]);
 1177:         $second.options[i].value = values[i];
 1178:         $second.options[i].text = texts[i];
 1179:         if (values[i] == select2def) {
 1180:             $second.options[i].selected = true;
 1181:         }
 1182:     }
 1183: }
 1184: // ]]>
 1185: </script>
 1186: END
 1187:     # output the initial values for the selection lists
 1188:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
 1189:     my @order = sort(keys(%{$hashref}));
 1190:     if (ref($menuorder) eq 'ARRAY') {
 1191:         @order = @{$menuorder};
 1192:     }
 1193:     foreach my $value (@order) {
 1194:         $result.="    <option value=\"$value\" ";
 1195:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1196:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1197:     }
 1198:     $result .= "</select>\n";
 1199:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1200:     $result .= $middletext;
 1201:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
 1202:     if ($onchangesecond) {
 1203:         $result .= ' onchange="'.$onchangesecond.'"';
 1204:     }
 1205:     $result .= ">\n";
 1206:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1207:     
 1208:     my @secondorder = sort(keys(%select2));
 1209:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1210:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1211:     }
 1212:     foreach my $value (@secondorder) {
 1213:         $result.="    <option value=\"$value\" ";        
 1214:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1215:         $result.=">".&mt($select2{$value})."</option>\n";
 1216:     }
 1217:     $result .= "</select>\n";
 1218:     #    return $debug;
 1219:     return $result;
 1220: }   #  end of sub linked_select_forms {
 1221: 
 1222: =pod
 1223: 
 1224: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid,$links_target)
 1225: 
 1226: Returns a string corresponding to an HTML link to the given help
 1227: $topic, where $topic corresponds to the name of a .tex file in
 1228: /home/httpd/html/adm/help/tex, with underscores replaced by
 1229: spaces. 
 1230: 
 1231: $text will optionally be linked to the same topic, allowing you to
 1232: link text in addition to the graphic. If you do not want to link
 1233: text, but wish to specify one of the later parameters, pass an
 1234: empty string. 
 1235: 
 1236: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1237: the link will not open a new window. If false, the link will open
 1238: a new window using Javascript. (Default is false.) 
 1239: 
 1240: $width and $height are optional numerical parameters that will
 1241: override the width and height of the popped up window, which may
 1242: be useful for certain help topics with big pictures included.
 1243: 
 1244: $imgid is the id of the img tag used for the help icon. This may be
 1245: used in a javascript call to switch the image src.  See 
 1246: lonhtmlcommon::htmlareaselectactive() for an example.
 1247: 
 1248: $links_target will optionally be set to a target (_top, _parent or _self).
 1249: 
 1250: =cut
 1251: 
 1252: sub help_open_topic {
 1253:     my ($topic, $text, $stayOnPage, $width, $height, $imgid, $links_target) = @_;
 1254:     $text = "" if (not defined $text);
 1255:     $stayOnPage = 0 if (not defined $stayOnPage);
 1256:     $width = 500 if (not defined $width);
 1257:     $height = 400 if (not defined $height);
 1258:     my $filename = $topic;
 1259:     $filename =~ s/ /_/g;
 1260: 
 1261:     my $template = "";
 1262:     my $link;
 1263:     
 1264:     $topic=~s/\W/\_/g;
 1265: 
 1266:     if (!$stayOnPage) {
 1267:         if ($env{'browser.mobile'}) {
 1268: 	    $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1269:         } else {
 1270:             $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1271:         }
 1272:     } elsif ($stayOnPage eq 'popup') {
 1273:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1274:     } else {
 1275: 	$link = "/adm/help/${filename}.hlp";
 1276:     }
 1277: 
 1278:     # Add the text
 1279:     my $target = ' target="_top"';
 1280:     if ($links_target) {
 1281:         $target = ' target="'.$links_target.'"';
 1282:     } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self')) {
 1283:         $target = '';
 1284:     }
 1285:     if ($text ne "") {	
 1286: 	$template.='<span class="LC_help_open_topic">'
 1287:                   .'<a'.$target.' href="'.$link.'">'
 1288:                   .$text.'</a>';
 1289:     }
 1290: 
 1291:     # (Always) Add the graphic
 1292:     my $title = &mt('Online Help');
 1293:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1294:     if ($imgid ne '') {
 1295:         $imgid = ' id="'.$imgid.'"';
 1296:     }
 1297:     $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
 1298:               .'<img src="'.$helpicon.'" border="0"'
 1299:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1300:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1301:               .' /></a>';
 1302:     if ($text ne "") {	
 1303:         $template.='</span>';
 1304:     }
 1305:     return $template;
 1306: 
 1307: }
 1308: 
 1309: # This is a quicky function for Latex cheatsheet editing, since it 
 1310: # appears in at least four places
 1311: sub helpLatexCheatsheet {
 1312:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1313:     my $out;
 1314:     my $addOther = '';
 1315:     if ($topic) {
 1316: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1317:     }
 1318:     $out = '<span>' # Start cheatsheet
 1319: 	  .$addOther
 1320:           .'<span>'
 1321: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1322: 	  .'</span> <span>'
 1323: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1324: 	  .'</span>';
 1325:     unless ($not_author) {
 1326:         $out .= ' <span>'
 1327: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1328: 	       .'</span> <span>'
 1329:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
 1330:                .'</span>';
 1331:     }
 1332:     $out .= '</span>'; # End cheatsheet
 1333:     return $out;
 1334: }
 1335: 
 1336: sub general_help {
 1337:     my $helptopic='Student_Intro';
 1338:     if ($env{'request.role'}=~/^(ca|au)/) {
 1339: 	$helptopic='Authoring_Intro';
 1340:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1341: 	$helptopic='Course_Coordination_Intro';
 1342:     } elsif ($env{'request.role'}=~/^dc/) {
 1343:         $helptopic='Domain_Coordination_Intro';
 1344:     }
 1345:     return $helptopic;
 1346: }
 1347: 
 1348: sub update_help_link {
 1349:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1350:     my $origurl = $ENV{'REQUEST_URI'};
 1351:     $origurl=~s|^/~|/priv/|;
 1352:     my $timestamp = time;
 1353:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1354:         $$datum = &escape($$datum);
 1355:     }
 1356: 
 1357:     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";
 1358:     my $output .= <<"ENDOUTPUT";
 1359: <script type="text/javascript">
 1360: // <![CDATA[
 1361: banner_link = '$banner_link';
 1362: // ]]>
 1363: </script>
 1364: ENDOUTPUT
 1365:     return $output;
 1366: }
 1367: 
 1368: # now just updates the help link and generates a blue icon
 1369: sub help_open_menu {
 1370:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text,$links_target) 
 1371: 	= @_;    
 1372:     $stayOnPage = 1;
 1373:     my $output;
 1374:     if ($component_help) {
 1375: 	if (!$text) {
 1376: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1377: 				       $width,$height,'',$links_target);
 1378: 	} else {
 1379: 	    my $help_text;
 1380: 	    $help_text=&unescape($topic);
 1381: 	    $output='<table><tr><td>'.
 1382: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1383: 				 $width,$height,'',$links_target).'</td></tr></table>';
 1384: 	}
 1385:     }
 1386:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1387:     return $output.$banner_link;
 1388: }
 1389: 
 1390: sub top_nav_help {
 1391:     my ($text,$linkattr) = @_;
 1392:     $text = &mt($text);
 1393:     my $stay_on_page;
 1394:     unless ($env{'environment.remote'} eq 'on') {
 1395:         $stay_on_page = 1;
 1396:     }
 1397:     my ($link,$banner_link);
 1398:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
 1399:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1400: 	                         : "javascript:helpMenu('open')";
 1401:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1402:     }
 1403:     my $title = &mt('Get help');
 1404:     if ($link) {
 1405:         return <<"END";
 1406: $banner_link
 1407: <a href="$link" title="$title" $linkattr>$text</a>
 1408: END
 1409:     } else {
 1410:         return '&nbsp;'.$text.'&nbsp;';
 1411:     }
 1412: }
 1413: 
 1414: sub help_menu_js {
 1415:     my ($httphost) = @_;
 1416:     my $stayOnPage = 1;
 1417:     my $width = 620;
 1418:     my $height = 600;
 1419:     my $helptopic=&general_help();
 1420:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
 1421:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1422:     my $start_page =
 1423:         &Apache::loncommon::start_page('Help Menu', undef,
 1424: 				       {'frameset'    => 1,
 1425: 					'js_ready'    => 1,
 1426:                                         'use_absolute' => $httphost,
 1427: 					'add_entries' => {
 1428: 					    'border' => '0',
 1429: 					    'rows'   => "110,*",},});
 1430:     my $end_page =
 1431:         &Apache::loncommon::end_page({'frameset' => 1,
 1432: 				      'js_ready' => 1,});
 1433: 
 1434:     my $template .= <<"ENDTEMPLATE";
 1435: <script type="text/javascript">
 1436: // <![CDATA[
 1437: // <!-- BEGIN LON-CAPA Internal
 1438: var banner_link = '';
 1439: function helpMenu(target) {
 1440:     var caller = this;
 1441:     if (target == 'open') {
 1442:         var newWindow = null;
 1443:         try {
 1444:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1445:         }
 1446:         catch(error) {
 1447:             writeHelp(caller);
 1448:             return;
 1449:         }
 1450:         if (newWindow) {
 1451:             caller = newWindow;
 1452:         }
 1453:     }
 1454:     writeHelp(caller);
 1455:     return;
 1456: }
 1457: function writeHelp(caller) {
 1458:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
 1459:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
 1460:     caller.document.close();
 1461:     caller.focus();
 1462: }
 1463: // END LON-CAPA Internal -->
 1464: // ]]>
 1465: </script>
 1466: ENDTEMPLATE
 1467:     return $template;
 1468: }
 1469: 
 1470: sub help_open_bug {
 1471:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1472:     unless ($env{'user.adv'}) { return ''; }
 1473:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1474:     $text = "" if (not defined $text);
 1475: 	$stayOnPage=1;
 1476:     $width = 600 if (not defined $width);
 1477:     $height = 600 if (not defined $height);
 1478: 
 1479:     $topic=~s/\W+/\+/g;
 1480:     my $link='';
 1481:     my $template='';
 1482:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1483: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1484:     if (!$stayOnPage)
 1485:     {
 1486: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1487:     }
 1488:     else
 1489:     {
 1490: 	$link = $url;
 1491:     }
 1492: 
 1493:     my $target = '_top';
 1494:     if ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
 1495:         (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
 1496:         $target = '_blank';
 1497:     }
 1498: 
 1499:     # Add the text
 1500:     if ($text ne "")
 1501:     {
 1502: 	$template .= 
 1503:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1504:   "<td bgcolor='#FF5555'><a target=\"$target\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1505:     }
 1506: 
 1507:     # Add the graphic
 1508:     my $title = &mt('Report a Bug');
 1509:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1510:     $template .= <<"ENDTEMPLATE";
 1511:  <a target="$target" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1512: ENDTEMPLATE
 1513:     if ($text ne '') { $template.='</td></tr></table>' };
 1514:     return $template;
 1515: 
 1516: }
 1517: 
 1518: sub help_open_faq {
 1519:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1520:     unless ($env{'user.adv'}) { return ''; }
 1521:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1522:     $text = "" if (not defined $text);
 1523: 	$stayOnPage=1;
 1524:     $width = 350 if (not defined $width);
 1525:     $height = 400 if (not defined $height);
 1526: 
 1527:     $topic=~s/\W+/\+/g;
 1528:     my $link='';
 1529:     my $template='';
 1530:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1531:     if (!$stayOnPage)
 1532:     {
 1533: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1534:     }
 1535:     else
 1536:     {
 1537: 	$link = $url;
 1538:     }
 1539: 
 1540:     # Add the text
 1541:     if ($text ne "")
 1542:     {
 1543: 	$template .= 
 1544:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1545:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1546:     }
 1547: 
 1548:     # Add the graphic
 1549:     my $title = &mt('View the FAQ');
 1550:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1551:     $template .= <<"ENDTEMPLATE";
 1552:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1553: ENDTEMPLATE
 1554:     if ($text ne '') { $template.='</td></tr></table>' };
 1555:     return $template;
 1556: 
 1557: }
 1558: 
 1559: ###############################################################
 1560: ###############################################################
 1561: 
 1562: =pod
 1563: 
 1564: =item * &change_content_javascript():
 1565: 
 1566: This and the next function allow you to create small sections of an
 1567: otherwise static HTML page that you can update on the fly with
 1568: Javascript, even in Netscape 4.
 1569: 
 1570: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1571: must be written to the HTML page once. It will prove the Javascript
 1572: function "change(name, content)". Calling the change function with the
 1573: name of the section 
 1574: you want to update, matching the name passed to C<changable_area>, and
 1575: the new content you want to put in there, will put the content into
 1576: that area.
 1577: 
 1578: B<Note>: Netscape 4 only reserves enough space for the changable area
 1579: to contain room for the original contents. You need to "make space"
 1580: for whatever changes you wish to make, and be B<sure> to check your
 1581: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1582: it's adequate for updating a one-line status display, but little more.
 1583: This script will set the space to 100% width, so you only need to
 1584: worry about height in Netscape 4.
 1585: 
 1586: Modern browsers are much less limiting, and if you can commit to the
 1587: user not using Netscape 4, this feature may be used freely with
 1588: pretty much any HTML.
 1589: 
 1590: =cut
 1591: 
 1592: sub change_content_javascript {
 1593:     # If we're on Netscape 4, we need to use Layer-based code
 1594:     if ($env{'browser.type'} eq 'netscape' &&
 1595: 	$env{'browser.version'} =~ /^4\./) {
 1596: 	return (<<NETSCAPE4);
 1597: 	function change(name, content) {
 1598: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1599: 	    doc.open();
 1600: 	    doc.write(content);
 1601: 	    doc.close();
 1602: 	}
 1603: NETSCAPE4
 1604:     } else {
 1605: 	# Otherwise, we need to use semi-standards-compliant code
 1606: 	# (technically, "innerHTML" isn't standard but the equivalent
 1607: 	# is really scary, and every useful browser supports it
 1608: 	return (<<DOMBASED);
 1609: 	function change(name, content) {
 1610: 	    element = document.getElementById(name);
 1611: 	    element.innerHTML = content;
 1612: 	}
 1613: DOMBASED
 1614:     }
 1615: }
 1616: 
 1617: =pod
 1618: 
 1619: =item * &changable_area($name,$origContent):
 1620: 
 1621: This provides a "changable area" that can be modified on the fly via
 1622: the Javascript code provided in C<change_content_javascript>. $name is
 1623: the name you will use to reference the area later; do not repeat the
 1624: same name on a given HTML page more then once. $origContent is what
 1625: the area will originally contain, which can be left blank.
 1626: 
 1627: =cut
 1628: 
 1629: sub changable_area {
 1630:     my ($name, $origContent) = @_;
 1631: 
 1632:     if ($env{'browser.type'} eq 'netscape' &&
 1633: 	$env{'browser.version'} =~ /^4\./) {
 1634: 	# If this is netscape 4, we need to use the Layer tag
 1635: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1636:     } else {
 1637: 	return "<span id='$name'>$origContent</span>";
 1638:     }
 1639: }
 1640: 
 1641: =pod
 1642: 
 1643: =item * &viewport_geometry_js 
 1644: 
 1645: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1646: 
 1647: =cut
 1648: 
 1649: 
 1650: sub viewport_geometry_js { 
 1651:     return <<"GEOMETRY";
 1652: var Geometry = {};
 1653: function init_geometry() {
 1654:     if (Geometry.init) { return };
 1655:     Geometry.init=1;
 1656:     if (window.innerHeight) {
 1657:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1658:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1659:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1660:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1661:     }
 1662:     else if (document.documentElement && document.documentElement.clientHeight) {
 1663:         Geometry.getViewportHeight =
 1664:             function() { return document.documentElement.clientHeight; };
 1665:         Geometry.getViewportWidth =
 1666:             function() { return document.documentElement.clientWidth; };
 1667: 
 1668:         Geometry.getHorizontalScroll =
 1669:             function() { return document.documentElement.scrollLeft; };
 1670:         Geometry.getVerticalScroll =
 1671:             function() { return document.documentElement.scrollTop; };
 1672:     }
 1673:     else if (document.body.clientHeight) {
 1674:         Geometry.getViewportHeight =
 1675:             function() { return document.body.clientHeight; };
 1676:         Geometry.getViewportWidth =
 1677:             function() { return document.body.clientWidth; };
 1678:         Geometry.getHorizontalScroll =
 1679:             function() { return document.body.scrollLeft; };
 1680:         Geometry.getVerticalScroll =
 1681:             function() { return document.body.scrollTop; };
 1682:     }
 1683: }
 1684: 
 1685: GEOMETRY
 1686: }
 1687: 
 1688: =pod
 1689: 
 1690: =item * &viewport_size_js()
 1691: 
 1692: 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. 
 1693: 
 1694: =cut
 1695: 
 1696: sub viewport_size_js {
 1697:     my $geometry = &viewport_geometry_js();
 1698:     return <<"DIMS";
 1699: 
 1700: $geometry
 1701: 
 1702: function getViewportDims(width,height) {
 1703:     init_geometry();
 1704:     width.value = Geometry.getViewportWidth();
 1705:     height.value = Geometry.getViewportHeight();
 1706:     return;
 1707: }
 1708: 
 1709: DIMS
 1710: }
 1711: 
 1712: =pod
 1713: 
 1714: =item * &resize_textarea_js()
 1715: 
 1716: emits the needed javascript to resize a textarea to be as big as possible
 1717: 
 1718: creates a function resize_textrea that takes two IDs first should be
 1719: the id of the element to resize, second should be the id of a div that
 1720: surrounds everything that comes after the textarea, this routine needs
 1721: to be attached to the <body> for the onload and onresize events.
 1722: 
 1723: =back
 1724: 
 1725: =cut
 1726: 
 1727: sub resize_textarea_js {
 1728:     my $geometry = &viewport_geometry_js();
 1729:     return <<"RESIZE";
 1730:     <script type="text/javascript">
 1731: // <![CDATA[
 1732: $geometry
 1733: 
 1734: function getX(element) {
 1735:     var x = 0;
 1736:     while (element) {
 1737: 	x += element.offsetLeft;
 1738: 	element = element.offsetParent;
 1739:     }
 1740:     return x;
 1741: }
 1742: function getY(element) {
 1743:     var y = 0;
 1744:     while (element) {
 1745: 	y += element.offsetTop;
 1746: 	element = element.offsetParent;
 1747:     }
 1748:     return y;
 1749: }
 1750: 
 1751: 
 1752: function resize_textarea(textarea_id,bottom_id) {
 1753:     init_geometry();
 1754:     var textarea        = document.getElementById(textarea_id);
 1755:     //alert(textarea);
 1756: 
 1757:     var textarea_top    = getY(textarea);
 1758:     var textarea_height = textarea.offsetHeight;
 1759:     var bottom          = document.getElementById(bottom_id);
 1760:     var bottom_top      = getY(bottom);
 1761:     var bottom_height   = bottom.offsetHeight;
 1762:     var window_height   = Geometry.getViewportHeight();
 1763:     var fudge           = 23;
 1764:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1765:     if (new_height < 300) {
 1766: 	new_height = 300;
 1767:     }
 1768:     textarea.style.height=new_height+'px';
 1769: }
 1770: // ]]>
 1771: </script>
 1772: RESIZE
 1773: 
 1774: }
 1775: 
 1776: sub colorfuleditor_js {
 1777:     return <<"COLORFULEDIT"
 1778: <script type="text/javascript">
 1779: // <![CDATA[>
 1780:     function fold_box(curDepth, lastresource){
 1781: 
 1782:     // we need a list because there can be several blocks you need to fold in one tag
 1783:         var block = document.getElementsByName('foldblock_'+curDepth);
 1784:     // but there is only one folding button per tag
 1785:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
 1786: 
 1787:         if(block.item(0).style.display == 'none'){
 1788: 
 1789:             foldbutton.value = '@{[&mt("Hide")]}';
 1790:             for (i = 0; i < block.length; i++){
 1791:                 block.item(i).style.display = '';
 1792:             }
 1793:         }else{
 1794: 
 1795:             foldbutton.value = '@{[&mt("Show")]}';
 1796:             for (i = 0; i < block.length; i++){
 1797:                 // block.item(i).style.visibility = 'collapse';
 1798:                 block.item(i).style.display = 'none';
 1799:             }
 1800:         };
 1801:         saveState(lastresource);
 1802:     }
 1803: 
 1804:     function saveState (lastresource) {
 1805: 
 1806:         var tag_list = getTagList();
 1807:         if(tag_list != null){
 1808:             var timestamp = new Date().getTime();
 1809:             var key = lastresource;
 1810: 
 1811:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
 1812:             // starting with timestamp
 1813:             var value = timestamp+';';
 1814: 
 1815:             // building the list of key-value pairs
 1816:             for(var i = 0; i < tag_list.length; i++){
 1817:                 value += tag_list[i]+',';
 1818:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
 1819:             }
 1820: 
 1821:             // only iterate whole storage if nothing to override
 1822:             if(localStorage.getItem(key) == null){
 1823: 
 1824:                 // prevent storage from growing large
 1825:                 if(localStorage.length > 50){
 1826:                     var regex_getTimestamp = /^(?:\d)+;/;
 1827:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
 1828:                     var oldest_key;
 1829: 
 1830:                     for(var i = 1; i < localStorage.length; i++){
 1831:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
 1832:                             oldest_key = localStorage.key(i);
 1833:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
 1834:                         }
 1835:                     }
 1836:                     localStorage.removeItem(oldest_key);
 1837:                 }
 1838:             }
 1839:             localStorage.setItem(key,value);
 1840:         }
 1841:     }
 1842: 
 1843:     // restore folding status of blocks (on page load)
 1844:     function restoreState (lastresource) {
 1845:         if(localStorage.getItem(lastresource) != null){
 1846:             var key = lastresource;
 1847:             var value = localStorage.getItem(key);
 1848:             var regex_delTimestamp = /^\d+;/;
 1849: 
 1850:             value.replace(regex_delTimestamp, '');
 1851: 
 1852:             var valueArr = value.split(';');
 1853:             var pairs;
 1854:             var elements;
 1855:             for (var i = 0; i < valueArr.length; i++){
 1856:                 pairs = valueArr[i].split(',');
 1857:                 elements = document.getElementsByName(pairs[0]);
 1858: 
 1859:                 for (var j = 0; j < elements.length; j++){
 1860:                     elements[j].style.display = pairs[1];
 1861:                     if (pairs[1] == "none"){
 1862:                         var regex_id = /([_\\d]+)\$/;
 1863:                         regex_id.exec(pairs[0]);
 1864:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
 1865:                     }
 1866:                 }
 1867:             }
 1868:         }
 1869:     }
 1870: 
 1871:     function getTagList () {
 1872: 
 1873:         var stringToSearch = document.lonhomework.innerHTML;
 1874: 
 1875:         var ret = new Array();
 1876:         var regex_findBlock = /(foldblock_.*?)"/g;
 1877:         var tag_list = stringToSearch.match(regex_findBlock);
 1878: 
 1879:         if(tag_list != null){
 1880:             for(var i = 0; i < tag_list.length; i++){
 1881:                 ret.push(tag_list[i].replace(/"/, ''));
 1882:             }
 1883:         }
 1884:         return ret;
 1885:     }
 1886: 
 1887:     function saveScrollPosition (resource) {
 1888:         var tag_list = getTagList();
 1889: 
 1890:         // we dont always want to jump to the first block
 1891:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
 1892:         if(\$(window).scrollTop() > 170){
 1893:             if(tag_list != null){
 1894:                 var result;
 1895:                 for(var i = 0; i < tag_list.length; i++){
 1896:                     if(isElementInViewport(tag_list[i])){
 1897:                         result += tag_list[i]+';';
 1898:                     }
 1899:                 }
 1900:                 sessionStorage.setItem('anchor_'+resource, result);
 1901:             }
 1902:         } else {
 1903:             // we dont need to save zero, just delete the item to leave everything tidy
 1904:             sessionStorage.removeItem('anchor_'+resource);
 1905:         }
 1906:     }
 1907: 
 1908:     function restoreScrollPosition(resource){
 1909: 
 1910:         var elem = sessionStorage.getItem('anchor_'+resource);
 1911:         if(elem != null){
 1912:             var tag_list = elem.split(';');
 1913:             var elem_list;
 1914: 
 1915:             for(var i = 0; i < tag_list.length; i++){
 1916:                 elem_list = document.getElementsByName(tag_list[i]);
 1917: 
 1918:                 if(elem_list.length > 0){
 1919:                     elem = elem_list[0];
 1920:                     break;
 1921:                 }
 1922:             }
 1923:             elem.scrollIntoView();
 1924:         }
 1925:     }
 1926: 
 1927:     function isElementInViewport(el) {
 1928: 
 1929:         // change to last element instead of first
 1930:         var elem = document.getElementsByName(el);
 1931:         var rect = elem[0].getBoundingClientRect();
 1932: 
 1933:         return (
 1934:             rect.top >= 0 &&
 1935:             rect.left >= 0 &&
 1936:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
 1937:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
 1938:         );
 1939:     }
 1940: 
 1941:     function autosize(depth){
 1942:         var cmInst = window['cm'+depth];
 1943:         var fitsizeButton = document.getElementById('fitsize'+depth);
 1944: 
 1945:         // is fixed size, switching to dynamic
 1946:         if (sessionStorage.getItem("autosized_"+depth) == null) {
 1947:             cmInst.setSize("","auto");
 1948:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
 1949:             sessionStorage.setItem("autosized_"+depth, "yes");
 1950: 
 1951:         // is dynamic size, switching to fixed
 1952:         } else {
 1953:             cmInst.setSize("","300px");
 1954:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
 1955:             sessionStorage.removeItem("autosized_"+depth);
 1956:         }
 1957:     }
 1958: 
 1959: 
 1960: 
 1961: // ]]>
 1962: </script>
 1963: COLORFULEDIT
 1964: }
 1965: 
 1966: sub xmleditor_js {
 1967:     return <<XMLEDIT
 1968: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
 1969: <script type="text/javascript">
 1970: // <![CDATA[>
 1971: 
 1972:     function saveScrollPosition (resource) {
 1973: 
 1974:         var scrollPos = \$(window).scrollTop();
 1975:         sessionStorage.setItem(resource,scrollPos);
 1976:     }
 1977: 
 1978:     function restoreScrollPosition(resource){
 1979: 
 1980:         var scrollPos = sessionStorage.getItem(resource);
 1981:         \$(window).scrollTop(scrollPos);
 1982:     }
 1983: 
 1984:     // unless internet explorer
 1985:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
 1986: 
 1987:         \$(document).ready(function() {
 1988:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
 1989:         });
 1990:     }
 1991: 
 1992:     // inserts text at cursor position into codemirror (xml editor only)
 1993:     function insertText(text){
 1994:         cm.focus();
 1995:         var curPos = cm.getCursor();
 1996:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
 1997:     }
 1998: // ]]>
 1999: </script>
 2000: XMLEDIT
 2001: }
 2002: 
 2003: sub insert_folding_button {
 2004:     my $curDepth = $Apache::lonxml::curdepth;
 2005:     my $lastresource = $env{'request.ambiguous'};
 2006: 
 2007:     return "<input type=\"button\" id=\"folding_btn_$curDepth\"
 2008:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
 2009: }
 2010: 
 2011: 
 2012: =pod
 2013: 
 2014: =head1 Excel and CSV file utility routines
 2015: 
 2016: =cut
 2017: 
 2018: ###############################################################
 2019: ###############################################################
 2020: 
 2021: =pod
 2022: 
 2023: =over 4
 2024: 
 2025: =item * &csv_translate($text) 
 2026: 
 2027: Translate $text to allow it to be output as a 'comma separated values' 
 2028: format.
 2029: 
 2030: =cut
 2031: 
 2032: ###############################################################
 2033: ###############################################################
 2034: sub csv_translate {
 2035:     my $text = shift;
 2036:     $text =~ s/\"/\"\"/g;
 2037:     $text =~ s/\n/ /g;
 2038:     return $text;
 2039: }
 2040: 
 2041: ###############################################################
 2042: ###############################################################
 2043: 
 2044: =pod
 2045: 
 2046: =item * &define_excel_formats()
 2047: 
 2048: Define some commonly used Excel cell formats.
 2049: 
 2050: Currently supported formats:
 2051: 
 2052: =over 4
 2053: 
 2054: =item header
 2055: 
 2056: =item bold
 2057: 
 2058: =item h1
 2059: 
 2060: =item h2
 2061: 
 2062: =item h3
 2063: 
 2064: =item h4
 2065: 
 2066: =item i
 2067: 
 2068: =item date
 2069: 
 2070: =back
 2071: 
 2072: Inputs: $workbook
 2073: 
 2074: Returns: $format, a hash reference.
 2075: 
 2076: 
 2077: =cut
 2078: 
 2079: ###############################################################
 2080: ###############################################################
 2081: sub define_excel_formats {
 2082:     my ($workbook) = @_;
 2083:     my $format;
 2084:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 2085:                                                 bottom    => 1,
 2086:                                                 align     => 'center');
 2087:     $format->{'bold'} = $workbook->add_format(bold=>1);
 2088:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 2089:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 2090:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 2091:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 2092:     $format->{'i'}    = $workbook->add_format(italic=>1);
 2093:     $format->{'date'} = $workbook->add_format(num_format=>
 2094:                                             'mm/dd/yyyy hh:mm:ss');
 2095:     return $format;
 2096: }
 2097: 
 2098: ###############################################################
 2099: ###############################################################
 2100: 
 2101: =pod
 2102: 
 2103: =item * &create_workbook()
 2104: 
 2105: Create an Excel worksheet.  If it fails, output message on the
 2106: request object and return undefs.
 2107: 
 2108: Inputs: Apache request object
 2109: 
 2110: Returns (undef) on failure, 
 2111:     Excel worksheet object, scalar with filename, and formats 
 2112:     from &Apache::loncommon::define_excel_formats on success
 2113: 
 2114: =cut
 2115: 
 2116: ###############################################################
 2117: ###############################################################
 2118: sub create_workbook {
 2119:     my ($r) = @_;
 2120:         #
 2121:     # Create the excel spreadsheet
 2122:     my $filename = '/prtspool/'.
 2123:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2124:         time.'_'.rand(1000000000).'.xls';
 2125:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 2126:     if (! defined($workbook)) {
 2127:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 2128:         $r->print(
 2129:             '<p class="LC_error">'
 2130:            .&mt('Problems occurred in creating the new Excel file.')
 2131:            .' '.&mt('This error has been logged.')
 2132:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2133:            .'</p>'
 2134:         );
 2135:         return (undef);
 2136:     }
 2137:     #
 2138:     $workbook->set_tempdir(LONCAPA::tempdir());
 2139:     #
 2140:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 2141:     return ($workbook,$filename,$format);
 2142: }
 2143: 
 2144: ###############################################################
 2145: ###############################################################
 2146: 
 2147: =pod
 2148: 
 2149: =item * &create_text_file()
 2150: 
 2151: Create a file to write to and eventually make available to the user.
 2152: If file creation fails, outputs an error message on the request object and 
 2153: return undefs.
 2154: 
 2155: Inputs: Apache request object, and file suffix
 2156: 
 2157: Returns (undef) on failure, 
 2158:     Filehandle and filename on success.
 2159: 
 2160: =cut
 2161: 
 2162: ###############################################################
 2163: ###############################################################
 2164: sub create_text_file {
 2165:     my ($r,$suffix) = @_;
 2166:     if (! defined($suffix)) { $suffix = 'txt'; };
 2167:     my $fh;
 2168:     my $filename = '/prtspool/'.
 2169:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2170:         time.'_'.rand(1000000000).'.'.$suffix;
 2171:     $fh = Apache::File->new('>/home/httpd'.$filename);
 2172:     if (! defined($fh)) {
 2173:         $r->log_error("Couldn't open $filename for output $!");
 2174:         $r->print(
 2175:             '<p class="LC_error">'
 2176:            .&mt('Problems occurred in creating the output file.')
 2177:            .' '.&mt('This error has been logged.')
 2178:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2179:            .'</p>'
 2180:         );
 2181:     }
 2182:     return ($fh,$filename)
 2183: }
 2184: 
 2185: 
 2186: =pod 
 2187: 
 2188: =back
 2189: 
 2190: =cut
 2191: 
 2192: ###############################################################
 2193: ##        Home server <option> list generating code          ##
 2194: ###############################################################
 2195: 
 2196: # ------------------------------------------
 2197: 
 2198: sub domain_select {
 2199:     my ($name,$value,$multiple)=@_;
 2200:     my %domains=map { 
 2201: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 2202:     } &Apache::lonnet::all_domains();
 2203:     if ($multiple) {
 2204: 	$domains{''}=&mt('Any domain');
 2205: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2206: 	return &multiple_select_form($name,$value,4,\%domains);
 2207:     } else {
 2208: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2209: 	return &select_form($name,$value,\%domains);
 2210:     }
 2211: }
 2212: 
 2213: #-------------------------------------------
 2214: 
 2215: =pod
 2216: 
 2217: =head1 Routines for form select boxes
 2218: 
 2219: =over 4
 2220: 
 2221: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 2222: 
 2223: Returns a string containing a <select> element int multiple mode
 2224: 
 2225: 
 2226: Args:
 2227:   $name - name of the <select> element
 2228:   $value - scalar or array ref of values that should already be selected
 2229:   $size - number of rows long the select element is
 2230:   $hash - the elements should be 'option' => 'shown text'
 2231:           (shown text should already have been &mt())
 2232:   $order - (optional) array ref of the order to show the elements in
 2233: 
 2234: =cut
 2235: 
 2236: #-------------------------------------------
 2237: sub multiple_select_form {
 2238:     my ($name,$value,$size,$hash,$order)=@_;
 2239:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 2240:     my $output='';
 2241:     if (! defined($size)) {
 2242:         $size = 4;
 2243:         if (scalar(keys(%$hash))<4) {
 2244:             $size = scalar(keys(%$hash));
 2245:         }
 2246:     }
 2247:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 2248:     my @order;
 2249:     if (ref($order) eq 'ARRAY')  {
 2250:         @order = @{$order};
 2251:     } else {
 2252:         @order = sort(keys(%$hash));
 2253:     }
 2254:     if (exists($$hash{'select_form_order'})) {
 2255:         @order = @{$$hash{'select_form_order'}};
 2256:     }
 2257:         
 2258:     foreach my $key (@order) {
 2259:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 2260:         $output.='selected="selected" ' if ($selected{$key});
 2261:         $output.='>'.$hash->{$key}."</option>\n";
 2262:     }
 2263:     $output.="</select>\n";
 2264:     return $output;
 2265: }
 2266: 
 2267: #-------------------------------------------
 2268: 
 2269: =pod
 2270: 
 2271: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
 2272: 
 2273: Returns a string containing a <select name='$name' size='1'> form to 
 2274: allow a user to select options from a ref to a hash containing:
 2275: option_name => displayed text. An optional $onchange can include
 2276: a javascript onchange item, e.g., onchange="this.form.submit();".
 2277: An optional arg -- $readonly -- if true will cause the select form
 2278: to be disabled, e.g., for the case where an instructor has a section-
 2279: specific role, and is viewing/modifying parameters.  
 2280: 
 2281: See lonrights.pm for an example invocation and use.
 2282: 
 2283: =cut
 2284: 
 2285: #-------------------------------------------
 2286: sub select_form {
 2287:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
 2288:     return unless (ref($hashref) eq 'HASH');
 2289:     if ($onchange) {
 2290:         $onchange = ' onchange="'.$onchange.'"';
 2291:     }
 2292:     my $disabled;
 2293:     if ($readonly) {
 2294:         $disabled = ' disabled="disabled"';
 2295:     }
 2296:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2297:     my @keys;
 2298:     if (exists($hashref->{'select_form_order'})) {
 2299: 	@keys=@{$hashref->{'select_form_order'}};
 2300:     } else {
 2301: 	@keys=sort(keys(%{$hashref}));
 2302:     }
 2303:     foreach my $key (@keys) {
 2304:         $selectform.=
 2305: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2306:             ($key eq $def ? 'selected="selected" ' : '').
 2307:                 ">".$hashref->{$key}."</option>\n";
 2308:     }
 2309:     $selectform.="</select>";
 2310:     return $selectform;
 2311: }
 2312: 
 2313: # For display filters
 2314: 
 2315: sub display_filter {
 2316:     my ($context) = @_;
 2317:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2318:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2319:     my $phraseinput = 'hidden';
 2320:     my $includeinput = 'hidden';
 2321:     my ($checked,$includetypestext);
 2322:     if ($env{'form.displayfilter'} eq 'containing') {
 2323:         $phraseinput = 'text'; 
 2324:         if ($context eq 'parmslog') {
 2325:             $includeinput = 'checkbox';
 2326:             if ($env{'form.includetypes'}) {
 2327:                 $checked = ' checked="checked"';
 2328:             }
 2329:             $includetypestext = &mt('Include parameter types');
 2330:         }
 2331:     } else {
 2332:         $includetypestext = '&nbsp;';
 2333:     }
 2334:     my ($additional,$secondid,$thirdid);
 2335:     if ($context eq 'parmslog') {
 2336:         $additional = 
 2337:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2338:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2339:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2340:             '</label>';
 2341:         $secondid = 'includetypes';
 2342:         $thirdid = 'includetypestext';
 2343:     }
 2344:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2345:                                                     '$secondid','$thirdid')";
 2346:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2347: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 2348: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2349: 	   '</label></span> <span class="LC_nobreak">'.
 2350:            &mt('Filter: [_1]',
 2351: 	   &select_form($env{'form.displayfilter'},
 2352: 			'displayfilter',
 2353: 			{'currentfolder' => 'Current folder/page',
 2354: 			 'containing' => 'Containing phrase',
 2355: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2356: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2357:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2358:                          '" />'.$additional;
 2359: }
 2360: 
 2361: sub display_filter_js {
 2362:     my $includetext = &mt('Include parameter types');
 2363:     return <<"ENDJS";
 2364:   
 2365: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2366:     var firstType = 'hidden';
 2367:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2368:         firstType = 'text';
 2369:     }
 2370:     firstObject = document.getElementById(firstid);
 2371:     if (typeof(firstObject) == 'object') {
 2372:         if (firstObject.type != firstType) {
 2373:             changeInputType(firstObject,firstType);
 2374:         }
 2375:     }
 2376:     if (context == 'parmslog') {
 2377:         var secondType = 'hidden';
 2378:         if (firstType == 'text') {
 2379:             secondType = 'checkbox';
 2380:         }
 2381:         secondObject = document.getElementById(secondid);  
 2382:         if (typeof(secondObject) == 'object') {
 2383:             if (secondObject.type != secondType) {
 2384:                 changeInputType(secondObject,secondType);
 2385:             }
 2386:         }
 2387:         var textItem = document.getElementById(thirdid);
 2388:         var currtext = textItem.innerHTML;
 2389:         var newtext;
 2390:         if (firstType == 'text') {
 2391:             newtext = '$includetext';
 2392:         } else {
 2393:             newtext = '&nbsp;';
 2394:         }
 2395:         if (currtext != newtext) {
 2396:             textItem.innerHTML = newtext;
 2397:         }
 2398:     }
 2399:     return;
 2400: }
 2401: 
 2402: function changeInputType(oldObject,newType) {
 2403:     var newObject = document.createElement('input');
 2404:     newObject.type = newType;
 2405:     if (oldObject.size) {
 2406:         newObject.size = oldObject.size;
 2407:     }
 2408:     if (oldObject.value) {
 2409:         newObject.value = oldObject.value;
 2410:     }
 2411:     if (oldObject.name) {
 2412:         newObject.name = oldObject.name;
 2413:     }
 2414:     if (oldObject.id) {
 2415:         newObject.id = oldObject.id;
 2416:     }
 2417:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2418:     return;
 2419: }
 2420: 
 2421: ENDJS
 2422: }
 2423: 
 2424: sub gradeleveldescription {
 2425:     my $gradelevel=shift;
 2426:     my %gradelevels=(0 => 'Not specified',
 2427: 		     1 => 'Grade 1',
 2428: 		     2 => 'Grade 2',
 2429: 		     3 => 'Grade 3',
 2430: 		     4 => 'Grade 4',
 2431: 		     5 => 'Grade 5',
 2432: 		     6 => 'Grade 6',
 2433: 		     7 => 'Grade 7',
 2434: 		     8 => 'Grade 8',
 2435: 		     9 => 'Grade 9',
 2436: 		     10 => 'Grade 10',
 2437: 		     11 => 'Grade 11',
 2438: 		     12 => 'Grade 12',
 2439: 		     13 => 'Grade 13',
 2440: 		     14 => '100 Level',
 2441: 		     15 => '200 Level',
 2442: 		     16 => '300 Level',
 2443: 		     17 => '400 Level',
 2444: 		     18 => 'Graduate Level');
 2445:     return &mt($gradelevels{$gradelevel});
 2446: }
 2447: 
 2448: sub select_level_form {
 2449:     my ($deflevel,$name)=@_;
 2450:     unless ($deflevel) { $deflevel=0; }
 2451:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2452:     for (my $i=0; $i<=18; $i++) {
 2453:         $selectform.="<option value=\"$i\" ".
 2454:             ($i==$deflevel ? 'selected="selected" ' : '').
 2455:                 ">".&gradeleveldescription($i)."</option>\n";
 2456:     }
 2457:     $selectform.="</select>";
 2458:     return $selectform;
 2459: }
 2460: 
 2461: #-------------------------------------------
 2462: 
 2463: =pod
 2464: 
 2465: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
 2466: 
 2467: Returns a string containing a <select name='$name' size='1'> form to 
 2468: allow a user to select the domain to preform an operation in.  
 2469: See loncreateuser.pm for an example invocation and use.
 2470: 
 2471: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2472: selected");
 2473: 
 2474: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2475: 
 2476: 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.
 2477: 
 2478: The optional $incdoms is a reference to an array of domains which will be the only available options.
 2479: 
 2480: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
 2481: 
 2482: The optional $disabled argument, if true, adds the disabled attribute to the select tag. 
 2483: 
 2484: =cut
 2485: 
 2486: #-------------------------------------------
 2487: sub select_dom_form {
 2488:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
 2489:     if ($onchange) {
 2490:         $onchange = ' onchange="'.$onchange.'"';
 2491:     }
 2492:     if ($disabled) {
 2493:         $disabled = ' disabled="disabled"';
 2494:     }
 2495:     my (@domains,%exclude);
 2496:     if (ref($incdoms) eq 'ARRAY') {
 2497:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2498:     } else {
 2499:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2500:     }
 2501:     if ($includeempty) { @domains=('',@domains); }
 2502:     if (ref($excdoms) eq 'ARRAY') {
 2503:         map { $exclude{$_} = 1; } @{$excdoms};
 2504:     }
 2505:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2506:     foreach my $dom (@domains) {
 2507:         next if ($exclude{$dom});
 2508:         $selectdomain.="<option value=\"$dom\" ".
 2509:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2510:         if ($showdomdesc) {
 2511:             if ($dom ne '') {
 2512:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2513:                 if ($domdesc ne '') {
 2514:                     $selectdomain .= ' ('.$domdesc.')';
 2515:                 }
 2516:             } 
 2517:         }
 2518:         $selectdomain .= "</option>\n";
 2519:     }
 2520:     $selectdomain.="</select>";
 2521:     return $selectdomain;
 2522: }
 2523: 
 2524: #-------------------------------------------
 2525: 
 2526: =pod
 2527: 
 2528: =item * &home_server_form_item($domain,$name,$defaultflag)
 2529: 
 2530: input: 4 arguments (two required, two optional) - 
 2531:     $domain - domain of new user
 2532:     $name - name of form element
 2533:     $default - Value of 'default' causes a default item to be first 
 2534:                             option, and selected by default. 
 2535:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2536:                             if 1 server found, or default, if 0 found.
 2537: output: returns 2 items: 
 2538: (a) form element which contains either:
 2539:    (i) <select name="$name">
 2540:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2541:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2542:        </select>
 2543:        form item if there are multiple library servers in $domain, or
 2544:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2545:        if there is only one library server in $domain.
 2546: 
 2547: (b) number of library servers found.
 2548: 
 2549: See loncreateuser.pm for example of use.
 2550: 
 2551: =cut
 2552: 
 2553: #-------------------------------------------
 2554: sub home_server_form_item {
 2555:     my ($domain,$name,$default,$hide) = @_;
 2556:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2557:     my $result;
 2558:     my $numlib = keys(%servers);
 2559:     if ($numlib > 1) {
 2560:         $result .= '<select name="'.$name.'" />'."\n";
 2561:         if ($default) {
 2562:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2563:                        '</option>'."\n";
 2564:         }
 2565:         foreach my $hostid (sort(keys(%servers))) {
 2566:             $result.= '<option value="'.$hostid.'">'.
 2567: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2568:         }
 2569:         $result .= '</select>'."\n";
 2570:     } elsif ($numlib == 1) {
 2571:         my $hostid;
 2572:         foreach my $item (keys(%servers)) {
 2573:             $hostid = $item;
 2574:         }
 2575:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2576:                    $hostid.'" />';
 2577:                    if (!$hide) {
 2578:                        $result .= $hostid.' '.$servers{$hostid};
 2579:                    }
 2580:                    $result .= "\n";
 2581:     } elsif ($default) {
 2582:         $result .= '<input type="hidden" name="'.$name.
 2583:                    '" value="default" />';
 2584:                    if (!$hide) {
 2585:                        $result .= &mt('default');
 2586:                    }
 2587:                    $result .= "\n";
 2588:     }
 2589:     return ($result,$numlib);
 2590: }
 2591: 
 2592: =pod
 2593: 
 2594: =back 
 2595: 
 2596: =cut
 2597: 
 2598: ###############################################################
 2599: ##                  Decoding User Agent                      ##
 2600: ###############################################################
 2601: 
 2602: =pod
 2603: 
 2604: =head1 Decoding the User Agent
 2605: 
 2606: =over 4
 2607: 
 2608: =item * &decode_user_agent()
 2609: 
 2610: Inputs: $r
 2611: 
 2612: Outputs:
 2613: 
 2614: =over 4
 2615: 
 2616: =item * $httpbrowser
 2617: 
 2618: =item * $clientbrowser
 2619: 
 2620: =item * $clientversion
 2621: 
 2622: =item * $clientmathml
 2623: 
 2624: =item * $clientunicode
 2625: 
 2626: =item * $clientos
 2627: 
 2628: =item * $clientmobile
 2629: 
 2630: =item * $clientinfo
 2631: 
 2632: =item * $clientosversion
 2633: 
 2634: =back
 2635: 
 2636: =back 
 2637: 
 2638: =cut
 2639: 
 2640: ###############################################################
 2641: ###############################################################
 2642: sub decode_user_agent {
 2643:     my ($r)=@_;
 2644:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2645:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2646:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2647:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2648:     my $clientbrowser='unknown';
 2649:     my $clientversion='0';
 2650:     my $clientmathml='';
 2651:     my $clientunicode='0';
 2652:     my $clientmobile=0;
 2653:     my $clientosversion='';
 2654:     for (my $i=0;$i<=$#browsertype;$i++) {
 2655:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
 2656: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2657: 	    $clientbrowser=$bname;
 2658:             $httpbrowser=~/$vreg/i;
 2659: 	    $clientversion=$1;
 2660:             $clientmathml=($clientversion>=$minv);
 2661:             $clientunicode=($clientversion>=$univ);
 2662: 	}
 2663:     }
 2664:     my $clientos='unknown';
 2665:     my $clientinfo;
 2666:     if (($httpbrowser=~/linux/i) ||
 2667:         ($httpbrowser=~/unix/i) ||
 2668:         ($httpbrowser=~/ux/i) ||
 2669:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2670:     if (($httpbrowser=~/vax/i) ||
 2671:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2672:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2673:     if (($httpbrowser=~/mac/i) ||
 2674:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2675:     if ($httpbrowser=~/win/i) {
 2676:         $clientos='win';
 2677:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
 2678:             $clientosversion = $1;
 2679:         }
 2680:     }
 2681:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2682:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 2683:         $clientmobile=lc($1);
 2684:     }
 2685:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 2686:         $clientinfo = 'firefox-'.$1;
 2687:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 2688:         $clientinfo = 'chromeframe-'.$1;
 2689:     }
 2690:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2691:             $clientunicode,$clientos,$clientmobile,$clientinfo,
 2692:             $clientosversion);
 2693: }
 2694: 
 2695: ###############################################################
 2696: ##    Authentication changing form generation subroutines    ##
 2697: ###############################################################
 2698: ##
 2699: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2700: ## hash, and have reasonable default values.
 2701: ##
 2702: ##    formname = the name given in the <form> tag.
 2703: #-------------------------------------------
 2704: 
 2705: =pod
 2706: 
 2707: =head1 Authentication Routines
 2708: 
 2709: =over 4
 2710: 
 2711: =item * &authform_xxxxxx()
 2712: 
 2713: The authform_xxxxxx subroutines provide javascript and html forms which 
 2714: handle some of the conveniences required for authentication forms.  
 2715: This is not an optimal method, but it works.  
 2716: 
 2717: =over 4
 2718: 
 2719: =item * authform_header
 2720: 
 2721: =item * authform_authorwarning
 2722: 
 2723: =item * authform_nochange
 2724: 
 2725: =item * authform_kerberos
 2726: 
 2727: =item * authform_internal
 2728: 
 2729: =item * authform_filesystem
 2730: 
 2731: =back
 2732: 
 2733: See loncreateuser.pm for invocation and use examples.
 2734: 
 2735: =cut
 2736: 
 2737: #-------------------------------------------
 2738: sub authform_header{  
 2739:     my %in = (
 2740:         formname => 'cu',
 2741:         kerb_def_dom => '',
 2742:         @_,
 2743:     );
 2744:     $in{'formname'} = 'document.' . $in{'formname'};
 2745:     my $result='';
 2746: 
 2747: #---------------------------------------------- Code for upper case translation
 2748:     my $Javascript_toUpperCase;
 2749:     unless ($in{kerb_def_dom}) {
 2750:         $Javascript_toUpperCase =<<"END";
 2751:         switch (choice) {
 2752:            case 'krb': currentform.elements[choicearg].value =
 2753:                currentform.elements[choicearg].value.toUpperCase();
 2754:                break;
 2755:            default:
 2756:         }
 2757: END
 2758:     } else {
 2759:         $Javascript_toUpperCase = "";
 2760:     }
 2761: 
 2762:     my $radioval = "'nochange'";
 2763:     if (defined($in{'curr_authtype'})) {
 2764:         if ($in{'curr_authtype'} ne '') {
 2765:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2766:         }
 2767:     }
 2768:     my $argfield = 'null';
 2769:     if (defined($in{'mode'})) {
 2770:         if ($in{'mode'} eq 'modifycourse')  {
 2771:             if (defined($in{'curr_autharg'})) {
 2772:                 if ($in{'curr_autharg'} ne '') {
 2773:                     $argfield = "'$in{'curr_autharg'}'";
 2774:                 }
 2775:             }
 2776:         }
 2777:     }
 2778: 
 2779:     $result.=<<"END";
 2780: var current = new Object();
 2781: current.radiovalue = $radioval;
 2782: current.argfield = $argfield;
 2783: 
 2784: function changed_radio(choice,currentform) {
 2785:     var choicearg = choice + 'arg';
 2786:     // If a radio button in changed, we need to change the argfield
 2787:     if (current.radiovalue != choice) {
 2788:         current.radiovalue = choice;
 2789:         if (current.argfield != null) {
 2790:             currentform.elements[current.argfield].value = '';
 2791:         }
 2792:         if (choice == 'nochange') {
 2793:             current.argfield = null;
 2794:         } else {
 2795:             current.argfield = choicearg;
 2796:             switch(choice) {
 2797:                 case 'krb': 
 2798:                     currentform.elements[current.argfield].value = 
 2799:                         "$in{'kerb_def_dom'}";
 2800:                 break;
 2801:               default:
 2802:                 break;
 2803:             }
 2804:         }
 2805:     }
 2806:     return;
 2807: }
 2808: 
 2809: function changed_text(choice,currentform) {
 2810:     var choicearg = choice + 'arg';
 2811:     if (currentform.elements[choicearg].value !='') {
 2812:         $Javascript_toUpperCase
 2813:         // clear old field
 2814:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2815:             currentform.elements[current.argfield].value = '';
 2816:         }
 2817:         current.argfield = choicearg;
 2818:     }
 2819:     set_auth_radio_buttons(choice,currentform);
 2820:     return;
 2821: }
 2822: 
 2823: function set_auth_radio_buttons(newvalue,currentform) {
 2824:     var numauthchoices = currentform.login.length;
 2825:     if (typeof numauthchoices  == "undefined") {
 2826:         return;
 2827:     } 
 2828:     var i=0;
 2829:     while (i < numauthchoices) {
 2830:         if (currentform.login[i].value == newvalue) { break; }
 2831:         i++;
 2832:     }
 2833:     if (i == numauthchoices) {
 2834:         return;
 2835:     }
 2836:     current.radiovalue = newvalue;
 2837:     currentform.login[i].checked = true;
 2838:     return;
 2839: }
 2840: END
 2841:     return $result;
 2842: }
 2843: 
 2844: sub authform_authorwarning {
 2845:     my $result='';
 2846:     $result='<i>'.
 2847:         &mt('As a general rule, only authors or co-authors should be '.
 2848:             'filesystem authenticated '.
 2849:             '(which allows access to the server filesystem).')."</i>\n";
 2850:     return $result;
 2851: }
 2852: 
 2853: sub authform_nochange {
 2854:     my %in = (
 2855:               formname => 'document.cu',
 2856:               kerb_def_dom => 'MSU.EDU',
 2857:               @_,
 2858:           );
 2859:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
 2860:     my $result;
 2861:     if (!$authnum) {
 2862:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 2863:     } else {
 2864:         $result = '<label>'.&mt('[_1] Do not change login data',
 2865:                   '<input type="radio" name="login" value="nochange" '.
 2866:                   'checked="checked" onclick="'.
 2867:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2868: 	    '</label>';
 2869:     }
 2870:     return $result;
 2871: }
 2872: 
 2873: sub authform_kerberos {
 2874:     my %in = (
 2875:               formname => 'document.cu',
 2876:               kerb_def_dom => 'MSU.EDU',
 2877:               kerb_def_auth => 'krb4',
 2878:               @_,
 2879:               );
 2880:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2881:         $autharg,$jscall,$disabled);
 2882:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2883:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2884:        $check5 = ' checked="checked"';
 2885:     } else {
 2886:        $check4 = ' checked="checked"';
 2887:     }
 2888:     if ($in{'readonly'}) {
 2889:         $disabled = ' disabled="disabled"';
 2890:     }
 2891:     $krbarg = $in{'kerb_def_dom'};
 2892:     if (defined($in{'curr_authtype'})) {
 2893:         if ($in{'curr_authtype'} eq 'krb') {
 2894:             $krbcheck = ' checked="checked"';
 2895:             if (defined($in{'mode'})) {
 2896:                 if ($in{'mode'} eq 'modifyuser') {
 2897:                     $krbcheck = '';
 2898:                 }
 2899:             }
 2900:             if (defined($in{'curr_kerb_ver'})) {
 2901:                 if ($in{'curr_krb_ver'} eq '5') {
 2902:                     $check5 = ' checked="checked"';
 2903:                     $check4 = '';
 2904:                 } else {
 2905:                     $check4 = ' checked="checked"';
 2906:                     $check5 = '';
 2907:                 }
 2908:             }
 2909:             if (defined($in{'curr_autharg'})) {
 2910:                 $krbarg = $in{'curr_autharg'};
 2911:             }
 2912:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2913:                 if (defined($in{'curr_autharg'})) {
 2914:                     $result = 
 2915:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2916:         $in{'curr_autharg'},$krbver);
 2917:                 } else {
 2918:                     $result =
 2919:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2920:                 }
 2921:                 return $result; 
 2922:             }
 2923:         }
 2924:     } else {
 2925:         if ($authnum == 1) {
 2926:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2927:         }
 2928:     }
 2929:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2930:         return;
 2931:     } elsif ($authtype eq '') {
 2932:         if (defined($in{'mode'})) {
 2933:             if ($in{'mode'} eq 'modifycourse') {
 2934:                 if ($authnum == 1) {
 2935:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
 2936:                 }
 2937:             }
 2938:         }
 2939:     }
 2940:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2941:     if ($authtype eq '') {
 2942:         $authtype = '<input type="radio" name="login" value="krb" '.
 2943:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2944:                     $krbcheck.$disabled.' />';
 2945:     }
 2946:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2947:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 2948:          $in{'curr_authtype'} eq 'krb5') ||
 2949:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 2950:          $in{'curr_authtype'} eq 'krb4')) {
 2951:         $result .= &mt
 2952:         ('[_1] Kerberos authenticated with domain [_2] '.
 2953:          '[_3] Version 4 [_4] Version 5 [_5]',
 2954:          '<label>'.$authtype,
 2955:          '</label><input type="text" size="10" name="krbarg" '.
 2956:              'value="'.$krbarg.'" '.
 2957:              'onchange="'.$jscall.'"'.$disabled.' />',
 2958:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
 2959:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
 2960: 	 '</label>');
 2961:     } elsif ($can_assign{'krb4'}) {
 2962:         $result .= &mt
 2963:         ('[_1] Kerberos authenticated with domain [_2] '.
 2964:          '[_3] Version 4 [_4]',
 2965:          '<label>'.$authtype,
 2966:          '</label><input type="text" size="10" name="krbarg" '.
 2967:              'value="'.$krbarg.'" '.
 2968:              'onchange="'.$jscall.'"'.$disabled.' />',
 2969:          '<label><input type="hidden" name="krbver" value="4" />',
 2970:          '</label>');
 2971:     } elsif ($can_assign{'krb5'}) {
 2972:         $result .= &mt
 2973:         ('[_1] Kerberos authenticated with domain [_2] '.
 2974:          '[_3] Version 5 [_4]',
 2975:          '<label>'.$authtype,
 2976:          '</label><input type="text" size="10" name="krbarg" '.
 2977:              'value="'.$krbarg.'" '.
 2978:              'onchange="'.$jscall.'"'.$disabled.' />',
 2979:          '<label><input type="hidden" name="krbver" value="5" />',
 2980:          '</label>');
 2981:     }
 2982:     return $result;
 2983: }
 2984: 
 2985: sub authform_internal {
 2986:     my %in = (
 2987:                 formname => 'document.cu',
 2988:                 kerb_def_dom => 'MSU.EDU',
 2989:                 @_,
 2990:                 );
 2991:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
 2992:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2993:     if ($in{'readonly'}) {
 2994:         $disabled = ' disabled="disabled"';
 2995:     }
 2996:     if (defined($in{'curr_authtype'})) {
 2997:         if ($in{'curr_authtype'} eq 'int') {
 2998:             if ($can_assign{'int'}) {
 2999:                 $intcheck = 'checked="checked" ';
 3000:                 if (defined($in{'mode'})) {
 3001:                     if ($in{'mode'} eq 'modifyuser') {
 3002:                         $intcheck = '';
 3003:                     }
 3004:                 }
 3005:                 if (defined($in{'curr_autharg'})) {
 3006:                     $intarg = $in{'curr_autharg'};
 3007:                 }
 3008:             } else {
 3009:                 $result = &mt('Currently internally authenticated.');
 3010:                 return $result;
 3011:             }
 3012:         }
 3013:     } else {
 3014:         if ($authnum == 1) {
 3015:             $authtype = '<input type="hidden" name="login" value="int" />';
 3016:         }
 3017:     }
 3018:     if (!$can_assign{'int'}) {
 3019:         return;
 3020:     } elsif ($authtype eq '') {
 3021:         if (defined($in{'mode'})) {
 3022:             if ($in{'mode'} eq 'modifycourse') {
 3023:                 if ($authnum == 1) {
 3024:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
 3025:                 }
 3026:             }
 3027:         }
 3028:     }
 3029:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 3030:     if ($authtype eq '') {
 3031:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 3032:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
 3033:     }
 3034:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 3035:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3036:     $result = &mt
 3037:         ('[_1] Internally authenticated (with initial password [_2])',
 3038:          '<label>'.$authtype,'</label>'.$autharg);
 3039:     $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>';
 3040:     return $result;
 3041: }
 3042: 
 3043: sub authform_local {
 3044:     my %in = (
 3045:               formname => 'document.cu',
 3046:               kerb_def_dom => 'MSU.EDU',
 3047:               @_,
 3048:               );
 3049:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
 3050:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3051:     if ($in{'readonly'}) {
 3052:         $disabled = ' disabled="disabled"';
 3053:     }
 3054:     if (defined($in{'curr_authtype'})) {
 3055:         if ($in{'curr_authtype'} eq 'loc') {
 3056:             if ($can_assign{'loc'}) {
 3057:                 $loccheck = 'checked="checked" ';
 3058:                 if (defined($in{'mode'})) {
 3059:                     if ($in{'mode'} eq 'modifyuser') {
 3060:                         $loccheck = '';
 3061:                     }
 3062:                 }
 3063:                 if (defined($in{'curr_autharg'})) {
 3064:                     $locarg = $in{'curr_autharg'};
 3065:                 }
 3066:             } else {
 3067:                 $result = &mt('Currently using local (institutional) authentication.');
 3068:                 return $result;
 3069:             }
 3070:         }
 3071:     } else {
 3072:         if ($authnum == 1) {
 3073:             $authtype = '<input type="hidden" name="login" value="loc" />';
 3074:         }
 3075:     }
 3076:     if (!$can_assign{'loc'}) {
 3077:         return;
 3078:     } elsif ($authtype eq '') {
 3079:         if (defined($in{'mode'})) {
 3080:             if ($in{'mode'} eq 'modifycourse') {
 3081:                 if ($authnum == 1) {
 3082:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
 3083:                 }
 3084:             }
 3085:         }
 3086:     }
 3087:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 3088:     if ($authtype eq '') {
 3089:         $authtype = '<input type="radio" name="login" value="loc" '.
 3090:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 3091:                     $jscall.'"'.$disabled.' />';
 3092:     }
 3093:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 3094:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3095:     $result = &mt('[_1] Local Authentication with argument [_2]',
 3096:                   '<label>'.$authtype,'</label>'.$autharg);
 3097:     return $result;
 3098: }
 3099: 
 3100: sub authform_filesystem {
 3101:     my %in = (
 3102:               formname => 'document.cu',
 3103:               kerb_def_dom => 'MSU.EDU',
 3104:               @_,
 3105:               );
 3106:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
 3107:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3108:     if ($in{'readonly'}) {
 3109:         $disabled = ' disabled="disabled"';
 3110:     }
 3111:     if (defined($in{'curr_authtype'})) {
 3112:         if ($in{'curr_authtype'} eq 'fsys') {
 3113:             if ($can_assign{'fsys'}) {
 3114:                 $fsyscheck = 'checked="checked" ';
 3115:                 if (defined($in{'mode'})) {
 3116:                     if ($in{'mode'} eq 'modifyuser') {
 3117:                         $fsyscheck = '';
 3118:                     }
 3119:                 }
 3120:             } else {
 3121:                 $result = &mt('Currently Filesystem Authenticated.');
 3122:                 return $result;
 3123:             }           
 3124:         }
 3125:     } else {
 3126:         if ($authnum == 1) {
 3127:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 3128:         }
 3129:     }
 3130:     if (!$can_assign{'fsys'}) {
 3131:         return;
 3132:     } elsif ($authtype eq '') {
 3133:         if (defined($in{'mode'})) {
 3134:             if ($in{'mode'} eq 'modifycourse') {
 3135:                 if ($authnum == 1) {
 3136:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
 3137:                 }
 3138:             }
 3139:         }
 3140:     }
 3141:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 3142:     if ($authtype eq '') {
 3143:         $authtype = '<input type="radio" name="login" value="fsys" '.
 3144:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 3145:                     $jscall.'"'.$disabled.' />';
 3146:     }
 3147:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
 3148:                ' onchange="'.$jscall.'"'.$disabled.' />';
 3149:     $result = &mt
 3150:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 3151:          '<label>'.$authtype,'</label>'.$autharg);
 3152:     return $result;
 3153: }
 3154: 
 3155: sub get_assignable_auth {
 3156:     my ($dom) = @_;
 3157:     if ($dom eq '') {
 3158:         $dom = $env{'request.role.domain'};
 3159:     }
 3160:     my %can_assign = (
 3161:                           krb4 => 1,
 3162:                           krb5 => 1,
 3163:                           int  => 1,
 3164:                           loc  => 1,
 3165:                      );
 3166:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 3167:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 3168:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 3169:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 3170:             my $context;
 3171:             if ($env{'request.role'} =~ /^au/) {
 3172:                 $context = 'author';
 3173:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
 3174:                 $context = 'domain';
 3175:             } elsif ($env{'request.course.id'}) {
 3176:                 $context = 'course';
 3177:             }
 3178:             if ($context) {
 3179:                 if (ref($authhash->{$context}) eq 'HASH') {
 3180:                    %can_assign = %{$authhash->{$context}}; 
 3181:                 }
 3182:             }
 3183:         }
 3184:     }
 3185:     my $authnum = 0;
 3186:     foreach my $key (keys(%can_assign)) {
 3187:         if ($can_assign{$key}) {
 3188:             $authnum ++;
 3189:         }
 3190:     }
 3191:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 3192:         $authnum --;
 3193:     }
 3194:     return ($authnum,%can_assign);
 3195: }
 3196: 
 3197: sub check_passwd_rules {
 3198:     my ($domain,$plainpass) = @_;
 3199:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
 3200:     my ($min,$max,@chars,@brokerule,$warning);
 3201:     $min = $Apache::lonnet::passwdmin;
 3202:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
 3203:         if ($passwdconf{'min'} =~ /^\d+$/) {
 3204:             if ($passwdconf{'min'} > $min) {
 3205:                 $min = $passwdconf{'min'};
 3206:             }
 3207:         }
 3208:         if ($passwdconf{'max'} =~ /^\d+$/) {
 3209:             $max = $passwdconf{'max'};
 3210:         }
 3211:         @chars = @{$passwdconf{'chars'}};
 3212:     }
 3213:     if (($min) && (length($plainpass) < $min)) {
 3214:         push(@brokerule,'min');
 3215:     }
 3216:     if (($max) && (length($plainpass) > $max)) {
 3217:         push(@brokerule,'max');
 3218:     }
 3219:     if (@chars) {
 3220:         my %rules;
 3221:         map { $rules{$_} = 1; } @chars;
 3222:         if ($rules{'uc'}) {
 3223:             unless ($plainpass =~ /[A-Z]/) {
 3224:                 push(@brokerule,'uc');
 3225:             }
 3226:         }
 3227:         if ($rules{'lc'}) {
 3228:             unless ($plainpass =~ /[a-z]/) {
 3229:                 push(@brokerule,'lc');
 3230:             }
 3231:         }
 3232:         if ($rules{'num'}) {
 3233:             unless ($plainpass =~ /\d/) {
 3234:                 push(@brokerule,'num');
 3235:             }
 3236:         }
 3237:         if ($rules{'spec'}) {
 3238:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
 3239:                 push(@brokerule,'spec');
 3240:             }
 3241:         }
 3242:     }
 3243:     if (@brokerule) {
 3244:         my %rulenames = &Apache::lonlocal::texthash(
 3245:             uc   => 'At least one upper case letter',
 3246:             lc   => 'At least one lower case letter',
 3247:             num  => 'At least one number',
 3248:             spec => 'At least one non-alphanumeric',
 3249:         );
 3250:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
 3251:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
 3252:         $rulenames{'num'} .= ': 0123456789';
 3253:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
 3254:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
 3255:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
 3256:         $warning = &mt('Password did not satisfy the following:').'<ul>';
 3257:         foreach my $rule ('min','max','uc','lc','num','spec') {
 3258:             if (grep(/^$rule$/,@brokerule)) {
 3259:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
 3260:             }
 3261:         }
 3262:         $warning .= '</ul>';
 3263:     }
 3264:     if (wantarray) {
 3265:         return @brokerule;
 3266:     }
 3267:     return $warning;
 3268: }
 3269: 
 3270: sub passwd_validation_js {
 3271:     my ($currpasswdval,$domain,$context,$id) = @_;
 3272:     my (%passwdconf,$alertmsg);
 3273:     if ($context eq 'linkprot') {
 3274:         my %domconfig = &Apache::lonnet::get_dom('configuration',['ltisec'],$domain);
 3275:         if (ref($domconfig{'ltisec'}) eq 'HASH') {
 3276:             if (ref($domconfig{'ltisec'}{'rules'}) eq 'HASH') {
 3277:                 %passwdconf = %{$domconfig{'ltisec'}{'rules'}};
 3278:             }
 3279:         }
 3280:         if ($id eq 'add') {
 3281:             $alertmsg = &mt('Secret for added launcher did not satisfy requirement(s):').'\n\n';
 3282:         } elsif ($id =~ /^\d+$/) {
 3283:             my $pos = $id+1;
 3284:             $alertmsg = &mt('Secret for launcher [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
 3285:         } else {
 3286:             $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
 3287:         }
 3288:     } else {
 3289:         %passwdconf = &Apache::lonnet::get_passwdconf($domain);
 3290:         $alertmsg = &mt('Initial password did not satisfy requirement(s):').'\n\n';
 3291:     }
 3292:     my ($min,$max,@chars,$numrules,$intargjs,%alert);
 3293:     $numrules = 0;
 3294:     $min = $Apache::lonnet::passwdmin;
 3295:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
 3296:         if ($passwdconf{'min'} =~ /^\d+$/) {
 3297:             if ($passwdconf{'min'} > $min) {
 3298:                 $min = $passwdconf{'min'};
 3299:             }
 3300:         }
 3301:         if ($passwdconf{'max'} =~ /^\d+$/) {
 3302:             $max = $passwdconf{'max'};
 3303:             $numrules ++;
 3304:         }
 3305:         @chars = @{$passwdconf{'chars'}};
 3306:         if (@chars) {
 3307:             $numrules ++;
 3308:         }
 3309:     }
 3310:     if ($min > 0) {
 3311:         $numrules ++;
 3312:     }
 3313:     if (($min > 0) || ($max ne '') || (@chars > 0)) {
 3314:         if ($min) {
 3315:             $alert{'min'} = &mt('minimum [quant,_1,character]',$min).'\n';
 3316:         }
 3317:         if ($max) {
 3318:             $alert{'max'} = &mt('maximum [quant,_1,character]',$max).'\n';
 3319:         }
 3320:         my (@charalerts,@charrules);
 3321:         if (@chars) {
 3322:             if (grep(/^uc$/,@chars)) {
 3323:                 push(@charalerts,&mt('contain at least one upper case letter'));
 3324:                 push(@charrules,'uc');
 3325:             }
 3326:             if (grep(/^lc$/,@chars)) {
 3327:                 push(@charalerts,&mt('contain at least one lower case letter'));
 3328:                 push(@charrules,'lc');
 3329:             }
 3330:             if (grep(/^num$/,@chars)) {
 3331:                 push(@charalerts,&mt('contain at least one number'));
 3332:                 push(@charrules,'num');
 3333:             }
 3334:             if (grep(/^spec$/,@chars)) {
 3335:                 push(@charalerts,&mt('contain at least one non-alphanumeric'));
 3336:                 push(@charrules,'spec');
 3337:             }
 3338:         }
 3339:         $intargjs = qq|            var rulesmsg = '';\n|.
 3340:                     qq|            var currpwval = $currpasswdval;\n|;
 3341:             if ($min) {
 3342:                 $intargjs .= qq|
 3343:             if (currpwval.length < $min) {
 3344:                 rulesmsg += ' - $alert{min}';
 3345:             }
 3346: |;
 3347:             }
 3348:             if ($max) {
 3349:                 $intargjs .= qq|
 3350:             if (currpwval.length > $max) {
 3351:                 rulesmsg += ' - $alert{max}';
 3352:             }
 3353: |;
 3354:             }
 3355:             if (@chars > 0) {
 3356:                 my $charrulestr = '"'.join('","',@charrules).'"';
 3357:                 my $charalertstr = '"'.join('","',@charalerts).'"';
 3358:                 $intargjs .= qq|            var brokerules = new Array();\n|.
 3359:                              qq|            var charrules = new Array($charrulestr);\n|.
 3360:                              qq|            var charalerts = new Array($charalertstr);\n|;
 3361:                 my %rules;
 3362:                 map { $rules{$_} = 1; } @chars;
 3363:                 if ($rules{'uc'}) {
 3364:                     $intargjs .= qq|
 3365:             var ucRegExp = /[A-Z]/;
 3366:             if (!ucRegExp.test(currpwval)) {
 3367:                 brokerules.push('uc');
 3368:             }
 3369: |;
 3370:                 }
 3371:                 if ($rules{'lc'}) {
 3372:                     $intargjs .= qq|
 3373:             var lcRegExp = /[a-z]/;
 3374:             if (!lcRegExp.test(currpwval)) {
 3375:                 brokerules.push('lc');
 3376:             }
 3377: |;
 3378:                 }
 3379:                 if ($rules{'num'}) {
 3380:                      $intargjs .= qq|
 3381:             var numRegExp = /[0-9]/;
 3382:             if (!numRegExp.test(currpwval)) {
 3383:                 brokerules.push('num');
 3384:             }
 3385: |;
 3386:                 }
 3387:                 if ($rules{'spec'}) {
 3388:                      $intargjs .= q|
 3389:             var specRegExp = /[!"#$%&'()*+,\-.\/:;<=>?@[\\^\]_`{\|}~]/;
 3390:             if (!specRegExp.test(currpwval)) {
 3391:                 brokerules.push('spec');
 3392:             }
 3393: |;
 3394:                 }
 3395:                 $intargjs .= qq|
 3396:             if (brokerules.length > 0) {
 3397:                 for (var i=0; i<brokerules.length; i++) {
 3398:                     for (var j=0; j<charrules.length; j++) {
 3399:                         if (brokerules[i] == charrules[j]) {
 3400:                             rulesmsg += ' - '+charalerts[j]+'\\n';
 3401:                             break;
 3402:                         }
 3403:                     }
 3404:                 }
 3405:             }
 3406: |;
 3407:             }
 3408:             $intargjs .= qq|
 3409:             if (rulesmsg != '') {
 3410:                 rulesmsg = '$alertmsg'+rulesmsg;
 3411:                 alert(rulesmsg);
 3412:                 return false;
 3413:             }
 3414: |;
 3415:     }
 3416:     return ($numrules,$intargjs);
 3417: }
 3418: 
 3419: ###############################################################
 3420: ##    Get Kerberos Defaults for Domain                 ##
 3421: ###############################################################
 3422: ##
 3423: ## Returns default kerberos version and an associated argument
 3424: ## as listed in file domain.tab. If not listed, provides
 3425: ## appropriate default domain and kerberos version.
 3426: ##
 3427: #-------------------------------------------
 3428: 
 3429: =pod
 3430: 
 3431: =item * &get_kerberos_defaults()
 3432: 
 3433: get_kerberos_defaults($target_domain) returns the default kerberos
 3434: version and domain. If not found, it defaults to version 4 and the 
 3435: domain of the server.
 3436: 
 3437: =over 4
 3438: 
 3439: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 3440: 
 3441: =back
 3442: 
 3443: =back
 3444: 
 3445: =cut
 3446: 
 3447: #-------------------------------------------
 3448: sub get_kerberos_defaults {
 3449:     my $domain=shift;
 3450:     my ($krbdef,$krbdefdom);
 3451:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 3452:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 3453:         $krbdef = $domdefaults{'auth_def'};
 3454:         $krbdefdom = $domdefaults{'auth_arg_def'};
 3455:     } else {
 3456:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 3457:         my $krbdefdom=$1;
 3458:         $krbdefdom=~tr/a-z/A-Z/;
 3459:         $krbdef = "krb4";
 3460:     }
 3461:     return ($krbdef,$krbdefdom);
 3462: }
 3463: 
 3464: 
 3465: ###############################################################
 3466: ##                Thesaurus Functions                        ##
 3467: ###############################################################
 3468: 
 3469: =pod
 3470: 
 3471: =head1 Thesaurus Functions
 3472: 
 3473: =over 4
 3474: 
 3475: =item * &initialize_keywords()
 3476: 
 3477: Initializes the package variable %Keywords if it is empty.  Uses the
 3478: package variable $thesaurus_db_file.
 3479: 
 3480: =cut
 3481: 
 3482: ###################################################
 3483: 
 3484: sub initialize_keywords {
 3485:     return 1 if (scalar keys(%Keywords));
 3486:     # If we are here, %Keywords is empty, so fill it up
 3487:     #   Make sure the file we need exists...
 3488:     if (! -e $thesaurus_db_file) {
 3489:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 3490:                                  " failed because it does not exist");
 3491:         return 0;
 3492:     }
 3493:     #   Set up the hash as a database
 3494:     my %thesaurus_db;
 3495:     if (! tie(%thesaurus_db,'GDBM_File',
 3496:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3497:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 3498:                                  $thesaurus_db_file);
 3499:         return 0;
 3500:     } 
 3501:     #  Get the average number of appearances of a word.
 3502:     my $avecount = $thesaurus_db{'average.count'};
 3503:     #  Put keywords (those that appear > average) into %Keywords
 3504:     while (my ($word,$data)=each (%thesaurus_db)) {
 3505:         my ($count,undef) = split /:/,$data;
 3506:         $Keywords{$word}++ if ($count > $avecount);
 3507:     }
 3508:     untie %thesaurus_db;
 3509:     # Remove special values from %Keywords.
 3510:     foreach my $value ('total.count','average.count') {
 3511:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 3512:   }
 3513:     return 1;
 3514: }
 3515: 
 3516: ###################################################
 3517: 
 3518: =pod
 3519: 
 3520: =item * &keyword($word)
 3521: 
 3522: Returns true if $word is a keyword.  A keyword is a word that appears more 
 3523: than the average number of times in the thesaurus database.  Calls 
 3524: &initialize_keywords
 3525: 
 3526: =cut
 3527: 
 3528: ###################################################
 3529: 
 3530: sub keyword {
 3531:     return if (!&initialize_keywords());
 3532:     my $word=lc(shift());
 3533:     $word=~s/\W//g;
 3534:     return exists($Keywords{$word});
 3535: }
 3536: 
 3537: ###############################################################
 3538: 
 3539: =pod 
 3540: 
 3541: =item * &get_related_words()
 3542: 
 3543: Look up a word in the thesaurus.  Takes a scalar argument and returns
 3544: an array of words.  If the keyword is not in the thesaurus, an empty array
 3545: will be returned.  The order of the words returned is determined by the
 3546: database which holds them.
 3547: 
 3548: Uses global $thesaurus_db_file.
 3549: 
 3550: 
 3551: =cut
 3552: 
 3553: ###############################################################
 3554: sub get_related_words {
 3555:     my $keyword = shift;
 3556:     my %thesaurus_db;
 3557:     if (! -e $thesaurus_db_file) {
 3558:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 3559:                                  "failed because the file does not exist");
 3560:         return ();
 3561:     }
 3562:     if (! tie(%thesaurus_db,'GDBM_File',
 3563:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3564:         return ();
 3565:     } 
 3566:     my @Words=();
 3567:     my $count=0;
 3568:     if (exists($thesaurus_db{$keyword})) {
 3569: 	# The first element is the number of times
 3570: 	# the word appears.  We do not need it now.
 3571: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 3572: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 3573: 	my $threshold=$mostfrequentcount/10;
 3574:         foreach my $possibleword (@RelatedWords) {
 3575:             my ($word,$wordcount)=split(/\,/,$possibleword);
 3576:             if ($wordcount>$threshold) {
 3577: 		push(@Words,$word);
 3578:                 $count++;
 3579:                 if ($count>10) { last; }
 3580: 	    }
 3581:         }
 3582:     }
 3583:     untie %thesaurus_db;
 3584:     return @Words;
 3585: }
 3586: 
 3587: =pod
 3588: 
 3589: =back
 3590: 
 3591: =cut
 3592: 
 3593: # -------------------------------------------------------------- Plaintext name
 3594: =pod
 3595: 
 3596: =head1 User Name Functions
 3597: 
 3598: =over 4
 3599: 
 3600: =item * &plainname($uname,$udom,$first)
 3601: 
 3602: Takes a users logon name and returns it as a string in
 3603: "first middle last generation" form 
 3604: if $first is set to 'lastname' then it returns it as
 3605: 'lastname generation, firstname middlename' if their is a lastname
 3606: 
 3607: =cut
 3608: 
 3609: 
 3610: ###############################################################
 3611: sub plainname {
 3612:     my ($uname,$udom,$first)=@_;
 3613:     return if (!defined($uname) || !defined($udom));
 3614:     my %names=&getnames($uname,$udom);
 3615:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 3616: 					  $names{'middlename'},
 3617: 					  $names{'lastname'},
 3618: 					  $names{'generation'},$first);
 3619:     $name=~s/^\s+//;
 3620:     $name=~s/\s+$//;
 3621:     $name=~s/\s+/ /g;
 3622:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 3623:     return $name;
 3624: }
 3625: 
 3626: # -------------------------------------------------------------------- Nickname
 3627: =pod
 3628: 
 3629: =item * &nickname($uname,$udom)
 3630: 
 3631: Gets a users name and returns it as a string as
 3632: 
 3633: "&quot;nickname&quot;"
 3634: 
 3635: if the user has a nickname or
 3636: 
 3637: "first middle last generation"
 3638: 
 3639: if the user does not
 3640: 
 3641: =cut
 3642: 
 3643: sub nickname {
 3644:     my ($uname,$udom)=@_;
 3645:     return if (!defined($uname) || !defined($udom));
 3646:     my %names=&getnames($uname,$udom);
 3647:     my $name=$names{'nickname'};
 3648:     if ($name) {
 3649:        $name='&quot;'.$name.'&quot;'; 
 3650:     } else {
 3651:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 3652: 	     $names{'lastname'}.' '.$names{'generation'};
 3653:        $name=~s/\s+$//;
 3654:        $name=~s/\s+/ /g;
 3655:     }
 3656:     return $name;
 3657: }
 3658: 
 3659: sub getnames {
 3660:     my ($uname,$udom)=@_;
 3661:     return if (!defined($uname) || !defined($udom));
 3662:     if ($udom eq 'public' && $uname eq 'public') {
 3663: 	return ('lastname' => &mt('Public'));
 3664:     }
 3665:     my $id=$uname.':'.$udom;
 3666:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 3667:     if ($cached) {
 3668: 	return %{$names};
 3669:     } else {
 3670: 	my %loadnames=&Apache::lonnet::get('environment',
 3671:                     ['firstname','middlename','lastname','generation','nickname'],
 3672: 					 $udom,$uname);
 3673: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 3674: 	return %loadnames;
 3675:     }
 3676: }
 3677: 
 3678: # -------------------------------------------------------------------- getemails
 3679: 
 3680: =pod
 3681: 
 3682: =item * &getemails($uname,$udom)
 3683: 
 3684: Gets a user's email information and returns it as a hash with keys:
 3685: notification, critnotification, permanentemail
 3686: 
 3687: For notification and critnotification, values are comma-separated lists 
 3688: of e-mail addresses; for permanentemail, value is a single e-mail address.
 3689:  
 3690: 
 3691: =cut
 3692: 
 3693: 
 3694: sub getemails {
 3695:     my ($uname,$udom)=@_;
 3696:     if ($udom eq 'public' && $uname eq 'public') {
 3697: 	return;
 3698:     }
 3699:     if (!$udom) { $udom=$env{'user.domain'}; }
 3700:     if (!$uname) { $uname=$env{'user.name'}; }
 3701:     my $id=$uname.':'.$udom;
 3702:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 3703:     if ($cached) {
 3704: 	return %{$names};
 3705:     } else {
 3706: 	my %loadnames=&Apache::lonnet::get('environment',
 3707:                     			   ['notification','critnotification',
 3708: 					    'permanentemail'],
 3709: 					   $udom,$uname);
 3710: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 3711: 	return %loadnames;
 3712:     }
 3713: }
 3714: 
 3715: sub flush_email_cache {
 3716:     my ($uname,$udom)=@_;
 3717:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3718:     if (!$uname) { $uname=$env{'user.name'};   }
 3719:     return if ($udom eq 'public' && $uname eq 'public');
 3720:     my $id=$uname.':'.$udom;
 3721:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 3722: }
 3723: 
 3724: # -------------------------------------------------------------------- getlangs
 3725: 
 3726: =pod
 3727: 
 3728: =item * &getlangs($uname,$udom)
 3729: 
 3730: Gets a user's language preference and returns it as a hash with key:
 3731: language.
 3732: 
 3733: =cut
 3734: 
 3735: 
 3736: sub getlangs {
 3737:     my ($uname,$udom) = @_;
 3738:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3739:     if (!$uname) { $uname=$env{'user.name'};   }
 3740:     my $id=$uname.':'.$udom;
 3741:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 3742:     if ($cached) {
 3743:         return %{$langs};
 3744:     } else {
 3745:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 3746:                                            $udom,$uname);
 3747:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 3748:         return %loadlangs;
 3749:     }
 3750: }
 3751: 
 3752: sub flush_langs_cache {
 3753:     my ($uname,$udom)=@_;
 3754:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3755:     if (!$uname) { $uname=$env{'user.name'};   }
 3756:     return if ($udom eq 'public' && $uname eq 'public');
 3757:     my $id=$uname.':'.$udom;
 3758:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 3759: }
 3760: 
 3761: # ------------------------------------------------------------------ Screenname
 3762: 
 3763: =pod
 3764: 
 3765: =item * &screenname($uname,$udom)
 3766: 
 3767: Gets a users screenname and returns it as a string
 3768: 
 3769: =cut
 3770: 
 3771: sub screenname {
 3772:     my ($uname,$udom)=@_;
 3773:     if ($uname eq $env{'user.name'} &&
 3774: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 3775:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 3776:     return $names{'screenname'};
 3777: }
 3778: 
 3779: 
 3780: # ------------------------------------------------------------- Confirm Wrapper
 3781: =pod
 3782: 
 3783: =item * &confirmwrapper($message)
 3784: 
 3785: Wrap messages about completion of operation in box
 3786: 
 3787: =cut
 3788: 
 3789: sub confirmwrapper {
 3790:     my ($message)=@_;
 3791:     if ($message) {
 3792:         return "\n".'<div class="LC_confirm_box">'."\n"
 3793:                .$message."\n"
 3794:                .'</div>'."\n";
 3795:     } else {
 3796:         return $message;
 3797:     }
 3798: }
 3799: 
 3800: # ------------------------------------------------------------- Message Wrapper
 3801: 
 3802: sub messagewrapper {
 3803:     my ($link,$username,$domain,$subject,$text)=@_;
 3804:     return 
 3805:         '<a href="/adm/email?compose=individual&amp;'.
 3806:         'recname='.$username.'&amp;recdom='.$domain.
 3807: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3808:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3809: }
 3810: 
 3811: # --------------------------------------------------------------- Notes Wrapper
 3812: 
 3813: sub noteswrapper {
 3814:     my ($link,$un,$do)=@_;
 3815:     return 
 3816: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3817: }
 3818: 
 3819: # ------------------------------------------------------------- Aboutme Wrapper
 3820: 
 3821: sub aboutmewrapper {
 3822:     my ($link,$username,$domain,$target,$class)=@_;
 3823:     if (!defined($username)  && !defined($domain)) {
 3824:         return;
 3825:     }
 3826:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 3827: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3828: }
 3829: 
 3830: # ------------------------------------------------------------ Syllabus Wrapper
 3831: 
 3832: sub syllabuswrapper {
 3833:     my ($linktext,$coursedir,$domain)=@_;
 3834:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3835: }
 3836: 
 3837: sub aboutme_on {
 3838:     my ($uname,$udom)=@_;
 3839:     unless ($uname) { $uname=$env{'user.name'}; }
 3840:     unless ($udom)  { $udom=$env{'user.domain'}; }
 3841:     return if ($udom eq 'public' && $uname eq 'public');
 3842:     my $hashkey=$uname.':'.$udom;
 3843:     my ($aboutme,$cached)=&Apache::lonnet::is_cached_new('aboutme',$hashkey);
 3844:     if ($cached) {
 3845:         return $aboutme;
 3846:     }
 3847:     $aboutme = &Apache::lonnet::usertools_access($uname,$udom,'aboutme');
 3848:     &Apache::lonnet::do_cache_new('aboutme',$hashkey,$aboutme,3600);
 3849:     return $aboutme;
 3850: }
 3851: 
 3852: sub devalidate_aboutme_cache {
 3853:     my ($uname,$udom)=@_;
 3854:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3855:     if (!$uname) { $uname=$env{'user.name'};   }
 3856:     return if ($udom eq 'public' && $uname eq 'public');
 3857:     my $id=$uname.':'.$udom;
 3858:     &Apache::lonnet::devalidate_cache_new('aboutme',$id);
 3859: }
 3860: 
 3861: # -----------------------------------------------------------------------------
 3862: 
 3863: sub track_student_link {
 3864:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3865:     my $link ="/adm/trackstudent?";
 3866:     my $title = 'View recent activity';
 3867:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3868:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3869:         $link .= "selected_student=$sname:$sdom";
 3870:         $title .= ' of this student';
 3871:     } 
 3872:     if (defined($target) && $target !~ /^\s*$/) {
 3873:         $target = qq{target="$target"};
 3874:     } else {
 3875:         $target = '';
 3876:     }
 3877:     if ($start) { $link.='&amp;start='.$start; }
 3878:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3879:     $title = &mt($title);
 3880:     $linktext = &mt($linktext);
 3881:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3882: 	&help_open_topic('View_recent_activity');
 3883: }
 3884: 
 3885: sub slot_reservations_link {
 3886:     my ($linktext,$sname,$sdom,$target) = @_;
 3887:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3888:     my $title = 'View slot reservation history';
 3889:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3890:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3891:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3892:         $title .= ' of this student';
 3893:     }
 3894:     if (defined($target) && $target !~ /^\s*$/) {
 3895:         $target = qq{target="$target"};
 3896:     } else {
 3897:         $target = '';
 3898:     }
 3899:     $title = &mt($title);
 3900:     $linktext = &mt($linktext);
 3901:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3902: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3903: 
 3904: }
 3905: 
 3906: # ===================================================== Display a student photo
 3907: 
 3908: 
 3909: sub student_image_tag {
 3910:     my ($domain,$user)=@_;
 3911:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3912:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3913: 	return '<img src="'.$imgsrc.'" align="right" />';
 3914:     } else {
 3915: 	return '';
 3916:     }
 3917: }
 3918: 
 3919: =pod
 3920: 
 3921: =back
 3922: 
 3923: =head1 Access .tab File Data
 3924: 
 3925: =over 4
 3926: 
 3927: =item * &languageids() 
 3928: 
 3929: returns list of all language ids
 3930: 
 3931: =cut
 3932: 
 3933: sub languageids {
 3934:     return sort(keys(%language));
 3935: }
 3936: 
 3937: =pod
 3938: 
 3939: =item * &languagedescription() 
 3940: 
 3941: returns description of a specified language id
 3942: 
 3943: =cut
 3944: 
 3945: sub languagedescription {
 3946:     my $code=shift;
 3947:     return  ($supported_language{$code}?'* ':'').
 3948:             $language{$code}.
 3949: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 3950: }
 3951: 
 3952: =pod
 3953: 
 3954: =item * &plainlanguagedescription
 3955: 
 3956: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 3957: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 3958: 
 3959: =cut
 3960: 
 3961: sub plainlanguagedescription {
 3962:     my $code=shift;
 3963:     return $language{$code};
 3964: }
 3965: 
 3966: =pod
 3967: 
 3968: =item * &supportedlanguagecode
 3969: 
 3970: Returns the supported language code (e.g. sptutf maps to pt) given a language
 3971: code.
 3972: 
 3973: =cut
 3974: 
 3975: sub supportedlanguagecode {
 3976:     my $code=shift;
 3977:     return $supported_language{$code};
 3978: }
 3979: 
 3980: =pod
 3981: 
 3982: =item * &latexlanguage()
 3983: 
 3984: Given a language key code returns the correspondnig language to use
 3985: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 3986: is no supported hyphenation for the language code.
 3987: 
 3988: =cut
 3989: 
 3990: sub latexlanguage {
 3991:     my $code = shift;
 3992:     return $latex_language{$code};
 3993: }
 3994: 
 3995: =pod
 3996: 
 3997: =item * &latexhyphenation()
 3998: 
 3999: Same as above but what's supplied is the language as it might be stored
 4000: in the metadata.
 4001: 
 4002: =cut
 4003: 
 4004: sub latexhyphenation {
 4005:     my $key = shift;
 4006:     return $latex_language_bykey{$key};
 4007: }
 4008: 
 4009: =pod
 4010: 
 4011: =item * &copyrightids() 
 4012: 
 4013: returns list of all copyrights
 4014: 
 4015: =cut
 4016: 
 4017: sub copyrightids {
 4018:     return sort(keys(%cprtag));
 4019: }
 4020: 
 4021: =pod
 4022: 
 4023: =item * &copyrightdescription() 
 4024: 
 4025: returns description of a specified copyright id
 4026: 
 4027: =cut
 4028: 
 4029: sub copyrightdescription {
 4030:     return &mt($cprtag{shift(@_)});
 4031: }
 4032: 
 4033: =pod
 4034: 
 4035: =item * &source_copyrightids() 
 4036: 
 4037: returns list of all source copyrights
 4038: 
 4039: =cut
 4040: 
 4041: sub source_copyrightids {
 4042:     return sort(keys(%scprtag));
 4043: }
 4044: 
 4045: =pod
 4046: 
 4047: =item * &source_copyrightdescription() 
 4048: 
 4049: returns description of a specified source copyright id
 4050: 
 4051: =cut
 4052: 
 4053: sub source_copyrightdescription {
 4054:     return &mt($scprtag{shift(@_)});
 4055: }
 4056: 
 4057: =pod
 4058: 
 4059: =item * &filecategories() 
 4060: 
 4061: returns list of all file categories
 4062: 
 4063: =cut
 4064: 
 4065: sub filecategories {
 4066:     return sort(keys(%category_extensions));
 4067: }
 4068: 
 4069: =pod
 4070: 
 4071: =item * &filecategorytypes() 
 4072: 
 4073: returns list of file types belonging to a given file
 4074: category
 4075: 
 4076: =cut
 4077: 
 4078: sub filecategorytypes {
 4079:     my ($cat) = @_;
 4080:     return @{$category_extensions{lc($cat)}};
 4081: }
 4082: 
 4083: =pod
 4084: 
 4085: =item * &fileembstyle() 
 4086: 
 4087: returns embedding style for a specified file type
 4088: 
 4089: =cut
 4090: 
 4091: sub fileembstyle {
 4092:     return $fe{lc(shift(@_))};
 4093: }
 4094: 
 4095: sub filemimetype {
 4096:     return $fm{lc(shift(@_))};
 4097: }
 4098: 
 4099: 
 4100: sub filecategoryselect {
 4101:     my ($name,$value)=@_;
 4102:     return &select_form($value,$name,
 4103:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 4104: }
 4105: 
 4106: =pod
 4107: 
 4108: =item * &filedescription() 
 4109: 
 4110: returns description for a specified file type
 4111: 
 4112: =cut
 4113: 
 4114: sub filedescription {
 4115:     my $file_description = $fd{lc(shift())};
 4116:     $file_description =~ s:([\[\]]):~$1:g;
 4117:     return &mt($file_description);
 4118: }
 4119: 
 4120: =pod
 4121: 
 4122: =item * &filedescriptionex() 
 4123: 
 4124: returns description for a specified file type with
 4125: extra formatting
 4126: 
 4127: =cut
 4128: 
 4129: sub filedescriptionex {
 4130:     my $ex=shift;
 4131:     my $file_description = $fd{lc($ex)};
 4132:     $file_description =~ s:([\[\]]):~$1:g;
 4133:     return '.'.$ex.' '.&mt($file_description);
 4134: }
 4135: 
 4136: # End of .tab access
 4137: =pod
 4138: 
 4139: =back
 4140: 
 4141: =cut
 4142: 
 4143: # ------------------------------------------------------------------ File Types
 4144: sub fileextensions {
 4145:     return sort(keys(%fe));
 4146: }
 4147: 
 4148: # ----------------------------------------------------------- Display Languages
 4149: # returns a hash with all desired display languages
 4150: #
 4151: 
 4152: sub display_languages {
 4153:     my %languages=();
 4154:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 4155: 	$languages{$lang}=1;
 4156:     }
 4157:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 4158:     if ($env{'form.displaylanguage'}) {
 4159: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 4160: 	    $languages{$lang}=1;
 4161:         }
 4162:     }
 4163:     return %languages;
 4164: }
 4165: 
 4166: sub languages {
 4167:     my ($possible_langs) = @_;
 4168:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 4169:     if (!ref($possible_langs)) {
 4170: 	if( wantarray ) {
 4171: 	    return @preferred_langs;
 4172: 	} else {
 4173: 	    return $preferred_langs[0];
 4174: 	}
 4175:     }
 4176:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 4177:     my @preferred_possibilities;
 4178:     foreach my $preferred_lang (@preferred_langs) {
 4179: 	if (exists($possibilities{$preferred_lang})) {
 4180: 	    push(@preferred_possibilities, $preferred_lang);
 4181: 	}
 4182:     }
 4183:     if( wantarray ) {
 4184: 	return @preferred_possibilities;
 4185:     }
 4186:     return $preferred_possibilities[0];
 4187: }
 4188: 
 4189: sub user_lang {
 4190:     my ($touname,$toudom,$fromcid) = @_;
 4191:     my @userlangs;
 4192:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 4193:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 4194:                     $env{'course.'.$fromcid.'.languages'}));
 4195:     } else {
 4196:         my %langhash = &getlangs($touname,$toudom);
 4197:         if ($langhash{'languages'} ne '') {
 4198:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 4199:         } else {
 4200:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 4201:             if ($domdefs{'lang_def'} ne '') {
 4202:                 @userlangs = ($domdefs{'lang_def'});
 4203:             }
 4204:         }
 4205:     }
 4206:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 4207:     my $user_lh = Apache::localize->get_handle(@languages);
 4208:     return $user_lh;
 4209: }
 4210: 
 4211: 
 4212: ###############################################################
 4213: ##               Student Answer Attempts                     ##
 4214: ###############################################################
 4215: 
 4216: =pod
 4217: 
 4218: =head1 Alternate Problem Views
 4219: 
 4220: =over 4
 4221: 
 4222: =item * &get_previous_attempt($symb, $username, $domain, $course,
 4223:     $getattempt, $regexp, $gradesub, $usec, $identifier)
 4224: 
 4225: Return string with previous attempt on problem. Arguments:
 4226: 
 4227: =over 4
 4228: 
 4229: =item * $symb: Problem, including path
 4230: 
 4231: =item * $username: username of the desired student
 4232: 
 4233: =item * $domain: domain of the desired student
 4234: 
 4235: =item * $course: Course ID
 4236: 
 4237: =item * $getattempt: Leave blank for all attempts, otherwise put
 4238:     something
 4239: 
 4240: =item * $regexp: if string matches this regexp, the string will be
 4241:     sent to $gradesub
 4242: 
 4243: =item * $gradesub: routine that processes the string if it matches $regexp
 4244: 
 4245: =item * $usec: section of the desired student
 4246: 
 4247: =item * $identifier: counter for student (multiple students one problem) or
 4248:     problem (one student; whole sequence).
 4249: 
 4250: =back
 4251: 
 4252: The output string is a table containing all desired attempts, if any.
 4253: 
 4254: =cut
 4255: 
 4256: sub get_previous_attempt {
 4257:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
 4258:   my $prevattempts='';
 4259:   no strict 'refs';
 4260:   if ($symb) {
 4261:     my (%returnhash)=
 4262:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 4263:     if ($returnhash{'version'}) {
 4264:       my %lasthash=();
 4265:       my $version;
 4266:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 4267:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
 4268:             if ($key =~ /\.rawrndseed$/) {
 4269:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
 4270:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
 4271:             } else {
 4272:                 $lasthash{$key}=$returnhash{$version.':'.$key};
 4273:             }
 4274:         }
 4275:       }
 4276:       $prevattempts=&start_data_table().&start_data_table_header_row();
 4277:       $prevattempts.='<th>'.&mt('History').'</th>';
 4278:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
 4279:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 4280:       foreach my $key (sort(keys(%lasthash))) {
 4281: 	my ($ign,@parts) = split(/\./,$key);
 4282: 	if ($#parts > 0) {
 4283: 	  my $data=$parts[-1];
 4284:           next if ($data eq 'foilorder');
 4285: 	  pop(@parts);
 4286:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 4287:           if ($data eq 'type') {
 4288:               unless ($showsurv) {
 4289:                   my $id = join(',',@parts);
 4290:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 4291:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 4292:                       $lasthidden{$ign.'.'.$id} = 1;
 4293:                   }
 4294:               }
 4295:               if ($identifier ne '') {
 4296:                   my $id = join(',',@parts);
 4297:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
 4298:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
 4299:                       $hidestatus{$ign.'.'.$id} = 1;
 4300:                   }
 4301:               }
 4302:           } elsif ($data eq 'regrader') {
 4303:               if (($identifier ne '') && (@parts)) {
 4304:                   my $id = join(',',@parts);
 4305:                   $regraded{$ign.'.'.$id} = 1;
 4306:               }
 4307:           } 
 4308: 	} else {
 4309: 	  if ($#parts == 0) {
 4310: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 4311: 	  } else {
 4312: 	    $prevattempts.='<th>'.$ign.'</th>';
 4313: 	  }
 4314: 	}
 4315:       }
 4316:       $prevattempts.=&end_data_table_header_row();
 4317:       if ($getattempt eq '') {
 4318:         my (%solved,%resets,%probstatus);
 4319:         if (($identifier ne '') && (keys(%regraded) > 0)) {
 4320:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 4321:                 foreach my $id (keys(%regraded)) {
 4322:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
 4323:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
 4324:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
 4325:                         push(@{$resets{$id}},$version);
 4326:                     }
 4327:                 }
 4328:             }
 4329:         }
 4330: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 4331:             my (@hidden,@unsolved);
 4332:             if (%typeparts) {
 4333:                 foreach my $id (keys(%typeparts)) {
 4334:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
 4335:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 4336:                         push(@hidden,$id);
 4337:                     } elsif ($identifier ne '') {
 4338:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
 4339:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
 4340:                                 ($hidestatus{$id})) {
 4341:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
 4342:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
 4343:                                 push(@{$solved{$id}},$version);
 4344:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
 4345:                                      (ref($solved{$id}) eq 'ARRAY')) {
 4346:                                 my $skip;
 4347:                                 if (ref($resets{$id}) eq 'ARRAY') {
 4348:                                     foreach my $reset (@{$resets{$id}}) {
 4349:                                         if ($reset > $solved{$id}[-1]) {
 4350:                                             $skip=1;
 4351:                                             last;
 4352:                                         }
 4353:                                     }
 4354:                                 }
 4355:                                 unless ($skip) {
 4356:                                     my ($ign,$partslist) = split(/\./,$id,2);
 4357:                                     push(@unsolved,$partslist);
 4358:                                 }
 4359:                             }
 4360:                         }
 4361:                     }
 4362:                 }
 4363:             }
 4364:             $prevattempts.=&start_data_table_row().
 4365:                            '<td>'.&mt('Transaction [_1]',$version);
 4366:             if (@unsolved) {
 4367:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
 4368:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
 4369:                                  &mt('Hide').'</label></span>';
 4370:             }
 4371:             $prevattempts .= '</td>';
 4372:             if (@hidden) {
 4373:                 foreach my $key (sort(keys(%lasthash))) {
 4374:                     next if ($key =~ /\.foilorder$/);
 4375:                     my $hide;
 4376:                     foreach my $id (@hidden) {
 4377:                         if ($key =~ /^\Q$id\E/) {
 4378:                             $hide = 1;
 4379:                             last;
 4380:                         }
 4381:                     }
 4382:                     if ($hide) {
 4383:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4384:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 4385:                             my $value = &format_previous_attempt_value($key,
 4386:                                              $returnhash{$version.':'.$key});
 4387:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4388:                         } else {
 4389:                             $prevattempts.='<td>&nbsp;</td>';
 4390:                         }
 4391:                     } else {
 4392:                         if ($key =~ /\./) {
 4393:                             my $value = $returnhash{$version.':'.$key};
 4394:                             if ($key =~ /\.rndseed$/) {
 4395:                                 my ($id) = ($key =~ /^(.+)\.rndseed$/);
 4396:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4397:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4398:                                 }
 4399:                             }
 4400:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4401:                                            '&nbsp;</td>';
 4402:                         } else {
 4403:                             $prevattempts.='<td>&nbsp;</td>';
 4404:                         }
 4405:                     }
 4406:                 }
 4407:             } else {
 4408: 	        foreach my $key (sort(keys(%lasthash))) {
 4409:                     next if ($key =~ /\.foilorder$/);
 4410:                     my $value = $returnhash{$version.':'.$key};
 4411:                     if ($key =~ /\.rndseed$/) {
 4412:                         my ($id) = ($key =~ /^(.+)\.rndseed$/);
 4413:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4414:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4415:                         }
 4416:                     }
 4417:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4418:                                    '&nbsp;</td>';
 4419: 	        }
 4420:             }
 4421: 	    $prevattempts.=&end_data_table_row();
 4422: 	 }
 4423:       }
 4424:       my @currhidden = keys(%lasthidden);
 4425:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 4426:       foreach my $key (sort(keys(%lasthash))) {
 4427:           next if ($key =~ /\.foilorder$/);
 4428:           if (%typeparts) {
 4429:               my $hidden;
 4430:               foreach my $id (@currhidden) {
 4431:                   if ($key =~ /^\Q$id\E/) {
 4432:                       $hidden = 1;
 4433:                       last;
 4434:                   }
 4435:               }
 4436:               if ($hidden) {
 4437:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4438:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 4439:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4440:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4441:                           $value = &$gradesub($value);
 4442:                       }
 4443:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4444:                   } else {
 4445:                       $prevattempts.='<td>&nbsp;</td>';
 4446:                   }
 4447:               } else {
 4448:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4449:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4450:                       $value = &$gradesub($value);
 4451:                   }
 4452:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4453:               }
 4454:           } else {
 4455: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4456: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4457:                   $value = &$gradesub($value);
 4458:               }
 4459: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4460:           }
 4461:       }
 4462:       $prevattempts.= &end_data_table_row().&end_data_table();
 4463:     } else {
 4464:       $prevattempts=
 4465: 	  &start_data_table().&start_data_table_row().
 4466: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 4467: 	  &end_data_table_row().&end_data_table();
 4468:     }
 4469:   } else {
 4470:     $prevattempts=
 4471: 	  &start_data_table().&start_data_table_row().
 4472: 	  '<td>'.&mt('No data.').'</td>'.
 4473: 	  &end_data_table_row().&end_data_table();
 4474:   }
 4475: }
 4476: 
 4477: sub format_previous_attempt_value {
 4478:     my ($key,$value) = @_;
 4479:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 4480: 	$value = &Apache::lonlocal::locallocaltime($value);
 4481:     } elsif (ref($value) eq 'ARRAY') {
 4482: 	$value = '('.join(', ', @{ $value }).')';
 4483:     } elsif ($key =~ /answerstring$/) {
 4484:         my %answers = &Apache::lonnet::str2hash($value);
 4485:         my @anskeys = sort(keys(%answers));
 4486:         if (@anskeys == 1) {
 4487:             my $answer = $answers{$anskeys[0]};
 4488:             if ($answer =~ m{\0}) {
 4489:                 $answer =~ s{\0}{,}g;
 4490:             }
 4491:             my $tag_internal_answer_name = 'INTERNAL';
 4492:             if ($anskeys[0] eq $tag_internal_answer_name) {
 4493:                 $value = $answer; 
 4494:             } else {
 4495:                 $value = $anskeys[0].'='.$answer;
 4496:             }
 4497:         } else {
 4498:             foreach my $ans (@anskeys) {
 4499:                 my $answer = $answers{$ans};
 4500:                 if ($answer =~ m{\0}) {
 4501:                     $answer =~ s{\0}{,}g;
 4502:                 }
 4503:                 $value .=  $ans.'='.$answer.'<br />';;
 4504:             } 
 4505:         }
 4506:     } else {
 4507: 	$value = &unescape($value);
 4508:     }
 4509:     return $value;
 4510: }
 4511: 
 4512: 
 4513: sub relative_to_absolute {
 4514:     my ($url,$output)=@_;
 4515:     my $parser=HTML::TokeParser->new(\$output);
 4516:     my $token;
 4517:     my $thisdir=$url;
 4518:     my @rlinks=();
 4519:     while ($token=$parser->get_token) {
 4520: 	if ($token->[0] eq 'S') {
 4521: 	    if ($token->[1] eq 'a') {
 4522: 		if ($token->[2]->{'href'}) {
 4523: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 4524: 		}
 4525: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 4526: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 4527: 	    } elsif ($token->[1] eq 'base') {
 4528: 		$thisdir=$token->[2]->{'href'};
 4529: 	    }
 4530: 	}
 4531:     }
 4532:     $thisdir=~s-/[^/]*$--;
 4533:     foreach my $link (@rlinks) {
 4534: 	unless (($link=~/^https?\:\/\//i) ||
 4535: 		($link=~/^\//) ||
 4536: 		($link=~/^javascript:/i) ||
 4537: 		($link=~/^mailto:/i) ||
 4538: 		($link=~/^\#/)) {
 4539: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 4540: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 4541: 	}
 4542:     }
 4543: # -------------------------------------------------- Deal with Applet codebases
 4544:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 4545:     return $output;
 4546: }
 4547: 
 4548: =pod
 4549: 
 4550: =item * &get_student_view()
 4551: 
 4552: show a snapshot of what student was looking at
 4553: 
 4554: =cut
 4555: 
 4556: sub get_student_view {
 4557:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 4558:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4559:   my (%form);
 4560:   my @elements=('symb','courseid','domain','username');
 4561:   foreach my $element (@elements) {
 4562:       $form{'grade_'.$element}=eval '$'.$element #'
 4563:   }
 4564:   if (defined($moreenv)) {
 4565:       %form=(%form,%{$moreenv});
 4566:   }
 4567:   if (defined($target)) { $form{'grade_target'} = $target; }
 4568:   $feedurl=&Apache::lonnet::clutter($feedurl);
 4569:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 4570:   $userview=~s/\<body[^\>]*\>//gi;
 4571:   $userview=~s/\<\/body\>//gi;
 4572:   $userview=~s/\<html\>//gi;
 4573:   $userview=~s/\<\/html\>//gi;
 4574:   $userview=~s/\<head\>//gi;
 4575:   $userview=~s/\<\/head\>//gi;
 4576:   $userview=~s/action\s*\=/would_be_action\=/gi;
 4577:   $userview=&relative_to_absolute($feedurl,$userview);
 4578:   if (wantarray) {
 4579:      return ($userview,$response);
 4580:   } else {
 4581:      return $userview;
 4582:   }
 4583: }
 4584: 
 4585: sub get_student_view_with_retries {
 4586:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 4587: 
 4588:     my $ok = 0;                 # True if we got a good response.
 4589:     my $content;
 4590:     my $response;
 4591: 
 4592:     # Try to get the student_view done. within the retries count:
 4593:     
 4594:     do {
 4595:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 4596:          $ok      = $response->is_success;
 4597:          if (!$ok) {
 4598:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 4599:          }
 4600:          $retries--;
 4601:     } while (!$ok && ($retries > 0));
 4602:     
 4603:     if (!$ok) {
 4604:        $content = '';          # On error return an empty content.
 4605:     }
 4606:     if (wantarray) {
 4607:        return ($content, $response);
 4608:     } else {
 4609:        return $content;
 4610:     }
 4611: }
 4612: 
 4613: sub css_links {
 4614:     my ($currsymb,$level) = @_;
 4615:     my ($links,@symbs,%cssrefs,%httpref);
 4616:     if ($level eq 'map') {
 4617:         my $navmap = Apache::lonnavmaps::navmap->new();
 4618:         if (ref($navmap)) {
 4619:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
 4620:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
 4621:             foreach my $res (@resources) {
 4622:                 if (ref($res) && $res->symb()) {
 4623:                     push(@symbs,$res->symb());
 4624:                 }
 4625:             }
 4626:         }
 4627:     } else {
 4628:         @symbs = ($currsymb);
 4629:     }
 4630:     foreach my $symb (@symbs) {
 4631:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
 4632:         if ($css_href =~ /\S/) {
 4633:             unless ($css_href =~ m{https?://}) {
 4634:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
 4635:                 my $proburl =  &Apache::lonnet::clutter($url);
 4636:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
 4637:                 unless ($css_href =~ m{^/}) {
 4638:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
 4639:                 }
 4640:                 if ($css_href =~ m{^/(res|uploaded)/}) {
 4641:                     unless (($httpref{'httpref.'.$css_href}) ||
 4642:                             (&Apache::lonnet::is_on_map($css_href))) {
 4643:                         my $thisurl = $proburl;
 4644:                         if ($env{'httpref.'.$proburl}) {
 4645:                             $thisurl = $env{'httpref.'.$proburl};
 4646:                         }
 4647:                         $httpref{'httpref.'.$css_href} = $thisurl;
 4648:                     }
 4649:                 }
 4650:             }
 4651:             $cssrefs{$css_href} = 1;
 4652:         }
 4653:     }
 4654:     if (keys(%httpref)) {
 4655:         &Apache::lonnet::appenv(\%httpref);
 4656:     }
 4657:     if (keys(%cssrefs)) {
 4658:         foreach my $css_href (keys(%cssrefs)) {
 4659:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
 4660:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
 4661:         }
 4662:     }
 4663:     return $links;
 4664: }
 4665: 
 4666: =pod
 4667: 
 4668: =item * &get_student_answers() 
 4669: 
 4670: show a snapshot of how student was answering problem
 4671: 
 4672: =cut
 4673: 
 4674: sub get_student_answers {
 4675:   my ($symb,$username,$domain,$courseid,%form) = @_;
 4676:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4677:   my (%moreenv);
 4678:   my @elements=('symb','courseid','domain','username');
 4679:   foreach my $element (@elements) {
 4680:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 4681:   }
 4682:   $moreenv{'grade_target'}='answer';
 4683:   %moreenv=(%form,%moreenv);
 4684:   $feedurl = &Apache::lonnet::clutter($feedurl);
 4685:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 4686:   return $userview;
 4687: }
 4688: 
 4689: =pod
 4690: 
 4691: =item * &submlink()
 4692: 
 4693: Inputs: $text $uname $udom $symb $target
 4694: 
 4695: Returns: A link to grades.pm such as to see the SUBM view of a student
 4696: 
 4697: =cut
 4698: 
 4699: ###############################################
 4700: sub submlink {
 4701:     my ($text,$uname,$udom,$symb,$target)=@_;
 4702:     if (!($uname && $udom)) {
 4703: 	(my $cursymb, my $courseid,$udom,$uname)=
 4704: 	    &Apache::lonnet::whichuser($symb);
 4705: 	if (!$symb) { $symb=$cursymb; }
 4706:     }
 4707:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4708:     $symb=&escape($symb);
 4709:     if ($target) { $target=" target=\"$target\""; }
 4710:     return
 4711:         '<a href="/adm/grades?command=submission'.
 4712:         '&amp;symb='.$symb.
 4713:         '&amp;student='.$uname.
 4714:         '&amp;userdom='.$udom.'"'.
 4715:         $target.'>'.$text.'</a>';
 4716: }
 4717: ##############################################
 4718: 
 4719: =pod
 4720: 
 4721: =item * &pgrdlink()
 4722: 
 4723: Inputs: $text $uname $udom $symb $target
 4724: 
 4725: Returns: A link to grades.pm such as to see the PGRD view of a student
 4726: 
 4727: =cut
 4728: 
 4729: ###############################################
 4730: sub pgrdlink {
 4731:     my $link=&submlink(@_);
 4732:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 4733:     return $link;
 4734: }
 4735: ##############################################
 4736: 
 4737: =pod
 4738: 
 4739: =item * &pprmlink()
 4740: 
 4741: Inputs: $text $uname $udom $symb $target
 4742: 
 4743: Returns: A link to parmset.pm such as to see the PPRM view of a
 4744: student and a specific resource
 4745: 
 4746: =cut
 4747: 
 4748: ###############################################
 4749: sub pprmlink {
 4750:     my ($text,$uname,$udom,$symb,$target)=@_;
 4751:     if (!($uname && $udom)) {
 4752: 	(my $cursymb, my $courseid,$udom,$uname)=
 4753: 	    &Apache::lonnet::whichuser($symb);
 4754: 	if (!$symb) { $symb=$cursymb; }
 4755:     }
 4756:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4757:     $symb=&escape($symb);
 4758:     if ($target) { $target="target=\"$target\""; }
 4759:     return '<a href="/adm/parmset?command=set&amp;'.
 4760: 	'symb='.$symb.'&amp;uname='.$uname.
 4761: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 4762: }
 4763: ##############################################
 4764: 
 4765: =pod
 4766: 
 4767: =back
 4768: 
 4769: =cut
 4770: 
 4771: ###############################################
 4772: 
 4773: 
 4774: sub timehash {
 4775:     my ($thistime) = @_;
 4776:     my $timezone = &Apache::lonlocal::gettimezone();
 4777:     my $dt = DateTime->from_epoch(epoch => $thistime)
 4778:                      ->set_time_zone($timezone);
 4779:     my $wday = $dt->day_of_week();
 4780:     if ($wday == 7) { $wday = 0; }
 4781:     return ( 'second' => $dt->second(),
 4782:              'minute' => $dt->minute(),
 4783:              'hour'   => $dt->hour(),
 4784:              'day'     => $dt->day_of_month(),
 4785:              'month'   => $dt->month(),
 4786:              'year'    => $dt->year(),
 4787:              'weekday' => $wday,
 4788:              'dayyear' => $dt->day_of_year(),
 4789:              'dlsav'   => $dt->is_dst() );
 4790: }
 4791: 
 4792: sub utc_string {
 4793:     my ($date)=@_;
 4794:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 4795: }
 4796: 
 4797: sub maketime {
 4798:     my %th=@_;
 4799:     my ($epoch_time,$timezone,$dt);
 4800:     $timezone = &Apache::lonlocal::gettimezone();
 4801:     eval {
 4802:         $dt = DateTime->new( year   => $th{'year'},
 4803:                              month  => $th{'month'},
 4804:                              day    => $th{'day'},
 4805:                              hour   => $th{'hour'},
 4806:                              minute => $th{'minute'},
 4807:                              second => $th{'second'},
 4808:                              time_zone => $timezone,
 4809:                          );
 4810:     };
 4811:     if (!$@) {
 4812:         $epoch_time = $dt->epoch;
 4813:         if ($epoch_time) {
 4814:             return $epoch_time;
 4815:         }
 4816:     }
 4817:     return POSIX::mktime(
 4818:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 4819:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 4820: }
 4821: 
 4822: #########################################
 4823: 
 4824: sub findallcourses {
 4825:     my ($roles,$uname,$udom) = @_;
 4826:     my %roles;
 4827:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 4828:     my %courses;
 4829:     my $now=time;
 4830:     if (!defined($uname)) {
 4831:         $uname = $env{'user.name'};
 4832:     }
 4833:     if (!defined($udom)) {
 4834:         $udom = $env{'user.domain'};
 4835:     }
 4836:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 4837:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 4838:         if (!%roles) {
 4839:             %roles = (
 4840:                        cc => 1,
 4841:                        co => 1,
 4842:                        in => 1,
 4843:                        ep => 1,
 4844:                        ta => 1,
 4845:                        cr => 1,
 4846:                        st => 1,
 4847:              );
 4848:         }
 4849:         foreach my $entry (keys(%roleshash)) {
 4850:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 4851:             if ($trole =~ /^cr/) { 
 4852:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 4853:             } else {
 4854:                 next if (!exists($roles{$trole}));
 4855:             }
 4856:             if ($tend) {
 4857:                 next if ($tend < $now);
 4858:             }
 4859:             if ($tstart) {
 4860:                 next if ($tstart > $now);
 4861:             }
 4862:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 4863:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 4864:             my $value = $trole.'/'.$cdom.'/';
 4865:             if ($secpart eq '') {
 4866:                 ($cnum,$role) = split(/_/,$cnumpart); 
 4867:                 $sec = 'none';
 4868:                 $value .= $cnum.'/';
 4869:             } else {
 4870:                 $cnum = $cnumpart;
 4871:                 ($sec,$role) = split(/_/,$secpart);
 4872:                 $value .= $cnum.'/'.$sec;
 4873:             }
 4874:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4875:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4876:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4877:                 }
 4878:             } else {
 4879:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4880:             }
 4881:         }
 4882:     } else {
 4883:         foreach my $key (keys(%env)) {
 4884: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 4885:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 4886: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 4887: 	        next if ($role eq 'ca' || $role eq 'aa');
 4888: 	        next if (%roles && !exists($roles{$role}));
 4889: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 4890:                 my $active=1;
 4891:                 if ($starttime) {
 4892: 		    if ($now<$starttime) { $active=0; }
 4893:                 }
 4894:                 if ($endtime) {
 4895:                     if ($now>$endtime) { $active=0; }
 4896:                 }
 4897:                 if ($active) {
 4898:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 4899:                     if ($sec eq '') {
 4900:                         $sec = 'none';
 4901:                     } else {
 4902:                         $value .= $sec;
 4903:                     }
 4904:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4905:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4906:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4907:                         }
 4908:                     } else {
 4909:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4910:                     }
 4911:                 }
 4912:             }
 4913:         }
 4914:     }
 4915:     return %courses;
 4916: }
 4917: 
 4918: ###############################################
 4919: 
 4920: sub blockcheck {
 4921:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
 4922: 
 4923:     unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
 4924:         my ($has_evb,$check_ipaccess);
 4925:         my $dom = $env{'user.domain'};
 4926:         if ($env{'request.course.id'}) {
 4927:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4928:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4929:             my $checkrole = "cm./$cdom/$cnum";
 4930:             my $sec = $env{'request.course.sec'};
 4931:             if ($sec ne '') {
 4932:                 $checkrole .= "/$sec";
 4933:             }
 4934:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 4935:                 ($env{'request.role'} !~ /^st/)) {
 4936:                 $has_evb = 1;
 4937:             }
 4938:             unless ($has_evb) {
 4939:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
 4940:                     ($activity eq 'boards') || ($activity eq 'groups') || ($activity eq 'chat')) {
 4941:                     if ($udom eq $cdom) {
 4942:                         $check_ipaccess = 1;
 4943:                     }
 4944:                 }
 4945:             }
 4946:         } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
 4947:                 ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
 4948:             my $checkrole;
 4949:             if ($env{'request.role.domain'} eq '') {
 4950:                 $checkrole = "cm./$env{'user.domain'}/";
 4951:             } else {
 4952:                 $checkrole = "cm./$env{'request.role.domain'}/";
 4953:             }
 4954:             if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
 4955:                 $has_evb = 1;
 4956:             }
 4957:         }
 4958:         unless ($has_evb || $check_ipaccess) {
 4959:             my @machinedoms = &Apache::lonnet::current_machine_domains();
 4960:             if (($dom eq 'public') && ($activity eq 'port')) {
 4961:                 $dom = $udom;
 4962:             }
 4963:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
 4964:                 $check_ipaccess = 1;
 4965:             } else {
 4966:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 4967:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
 4968:                 my $prim = &Apache::lonnet::domain($dom,'primary');
 4969:                 my $intdom = &Apache::lonnet::internet_dom($prim);
 4970:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
 4971:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
 4972:                         $check_ipaccess = 1;
 4973:                     }
 4974:                 }
 4975:             }
 4976:         }
 4977:         if ($check_ipaccess) {
 4978:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
 4979:             unless (defined($cached)) {
 4980:                 my %domconfig =
 4981:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
 4982:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
 4983:             }
 4984:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
 4985:                 foreach my $id (keys(%{$ipaccessref})) {
 4986:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
 4987:                         my $range = $ipaccessref->{$id}->{'ip'};
 4988:                         if ($range) {
 4989:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
 4990:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
 4991:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
 4992:                                         return ('','','',$id,$dom);
 4993:                                         last;
 4994:                                     }
 4995:                                 }
 4996:                             }
 4997:                         }
 4998:                     }
 4999:                 }
 5000:             }
 5001:         }
 5002:         if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
 5003:             return ();
 5004:         }
 5005:     }
 5006:     if (defined($udom) && defined($uname)) {
 5007:         # If uname and udom are for a course, check for blocks in the course.
 5008:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
 5009:             my ($startblock,$endblock,$triggerblock) =
 5010:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
 5011:             return ($startblock,$endblock,$triggerblock);
 5012:         }
 5013:     } else {
 5014:         $udom = $env{'user.domain'};
 5015:         $uname = $env{'user.name'};
 5016:     }
 5017: 
 5018:     my $startblock = 0;
 5019:     my $endblock = 0;
 5020:     my $triggerblock = '';
 5021:     my %live_courses;
 5022:     unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
 5023:         %live_courses = &findallcourses(undef,$uname,$udom);
 5024:     }
 5025: 
 5026:     # If uname is for a user, and activity is course-specific, i.e.,
 5027:     # boards, chat or groups, check for blocking in current course only.
 5028: 
 5029:     if (($activity eq 'boards' || $activity eq 'chat' ||
 5030:          $activity eq 'groups' || $activity eq 'printout' ||
 5031:          $activity eq 'search' || $activity eq 'reinit' ||
 5032:          $activity eq 'alert') && ($env{'request.course.id'})) {
 5033:         foreach my $key (keys(%live_courses)) {
 5034:             if ($key ne $env{'request.course.id'}) {
 5035:                 delete($live_courses{$key});
 5036:             }
 5037:         }
 5038:     }
 5039: 
 5040:     my $otheruser = 0;
 5041:     my %own_courses;
 5042:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 5043:         # Resource belongs to user other than current user.
 5044:         $otheruser = 1;
 5045:         # Gather courses for current user
 5046:         %own_courses = 
 5047:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 5048:     }
 5049: 
 5050:     # Gather active course roles - course coordinator, instructor, 
 5051:     # exam proctor, ta, student, or custom role.
 5052: 
 5053:     foreach my $course (keys(%live_courses)) {
 5054:         my ($cdom,$cnum);
 5055:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 5056:             $cdom = $env{'course.'.$course.'.domain'};
 5057:             $cnum = $env{'course.'.$course.'.num'};
 5058:         } else {
 5059:             ($cdom,$cnum) = split(/_/,$course); 
 5060:         }
 5061:         my $no_ownblock = 0;
 5062:         my $no_userblock = 0;
 5063:         if ($otheruser && $activity ne 'com') {
 5064:             # Check if current user has 'evb' priv for this
 5065:             if (defined($own_courses{$course})) {
 5066:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 5067:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5068:                     if ($sec ne 'none') {
 5069:                         $checkrole .= '/'.$sec;
 5070:                     }
 5071:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5072:                         $no_ownblock = 1;
 5073:                         last;
 5074:                     }
 5075:                 }
 5076:             }
 5077:             # if they have 'evb' priv and are currently not playing student
 5078:             next if (($no_ownblock) &&
 5079:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 5080:         }
 5081:         foreach my $sec (keys(%{$live_courses{$course}})) {
 5082:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5083:             if ($sec ne 'none') {
 5084:                 $checkrole .= '/'.$sec;
 5085:             }
 5086:             if ($otheruser) {
 5087:                 # Resource belongs to user other than current user.
 5088:                 # Assemble privs for that user, and check for 'evb' priv.
 5089:                 my (%allroles,%userroles);
 5090:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 5091:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 5092:                         my ($trole,$tdom,$tnum,$tsec);
 5093:                         if ($entry =~ /^cr/) {
 5094:                             ($trole,$tdom,$tnum,$tsec) = 
 5095:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 5096:                         } else {
 5097:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 5098:                         }
 5099:                         my ($spec,$area,$trest);
 5100:                         $area = '/'.$tdom.'/'.$tnum;
 5101:                         $trest = $tnum;
 5102:                         if ($tsec ne '') {
 5103:                             $area .= '/'.$tsec;
 5104:                             $trest .= '/'.$tsec;
 5105:                         }
 5106:                         $spec = $trole.'.'.$area;
 5107:                         if ($trole =~ /^cr/) {
 5108:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 5109:                                                               $tdom,$spec,$trest,$area);
 5110:                         } else {
 5111:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 5112:                                                                 $tdom,$spec,$trest,$area);
 5113:                         }
 5114:                     }
 5115:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 5116:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 5117:                         if ($1) {
 5118:                             $no_userblock = 1;
 5119:                             last;
 5120:                         }
 5121:                     }
 5122:                 }
 5123:             } else {
 5124:                 # Resource belongs to current user
 5125:                 # Check for 'evb' priv via lonnet::allowed().
 5126:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5127:                     $no_ownblock = 1;
 5128:                     last;
 5129:                 }
 5130:             }
 5131:         }
 5132:         # if they have the evb priv and are currently not playing student
 5133:         next if (($no_ownblock) &&
 5134:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 5135:         next if ($no_userblock);
 5136: 
 5137:         # Retrieve blocking times and identity of blocker for course
 5138:         # of specified user, unless user has 'evb' privilege.
 5139:         
 5140:         my ($start,$end,$trigger) = 
 5141:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
 5142:         if (($start != 0) && 
 5143:             (($startblock == 0) || ($startblock > $start))) {
 5144:             $startblock = $start;
 5145:             if ($trigger ne '') {
 5146:                 $triggerblock = $trigger;
 5147:             }
 5148:         }
 5149:         if (($end != 0)  &&
 5150:             (($endblock == 0) || ($endblock < $end))) {
 5151:             $endblock = $end;
 5152:             if ($trigger ne '') {
 5153:                 $triggerblock = $trigger;
 5154:             }
 5155:         }
 5156:     }
 5157:     return ($startblock,$endblock,$triggerblock);
 5158: }
 5159: 
 5160: sub get_blocks {
 5161:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
 5162:     my $startblock = 0;
 5163:     my $endblock = 0;
 5164:     my $triggerblock = '';
 5165:     my $course = $cdom.'_'.$cnum;
 5166:     $setters->{$course} = {};
 5167:     $setters->{$course}{'staff'} = [];
 5168:     $setters->{$course}{'times'} = [];
 5169:     $setters->{$course}{'triggers'} = [];
 5170:     my (@blockers,%triggered);
 5171:     my $now = time;
 5172:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 5173:     if ($activity eq 'docs') {
 5174:         my ($blocked,$nosymbcache,$noenccheck);
 5175:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
 5176:             $blocked = 1;
 5177:             $nosymbcache = 1;
 5178:             $noenccheck = 1;
 5179:         }
 5180:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
 5181:         foreach my $block (@blockers) {
 5182:             if ($block =~ /^firstaccess____(.+)$/) {
 5183:                 my $item = $1;
 5184:                 my $type = 'map';
 5185:                 my $timersymb = $item;
 5186:                 if ($item eq 'course') {
 5187:                     $type = 'course';
 5188:                 } elsif ($item =~ /___\d+___/) {
 5189:                     $type = 'resource';
 5190:                 } else {
 5191:                     $timersymb = &Apache::lonnet::symbread($item);
 5192:                 }
 5193:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5194:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 5195:                 $triggered{$block} = {
 5196:                                        start => $start,
 5197:                                        end   => $end,
 5198:                                        type  => $type,
 5199:                                      };
 5200:             }
 5201:         }
 5202:     } else {
 5203:         foreach my $block (keys(%commblocks)) {
 5204:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 5205:                 my ($start,$end) = ($1,$2);
 5206:                 if ($start <= time && $end >= time) {
 5207:                     if (ref($commblocks{$block}) eq 'HASH') {
 5208:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5209:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5210:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 5211:                                     push(@blockers,$block);
 5212:                                 }
 5213:                             }
 5214:                         }
 5215:                     }
 5216:                 }
 5217:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 5218:                 my $item = $1;
 5219:                 my $timersymb = $item; 
 5220:                 my $type = 'map';
 5221:                 if ($item eq 'course') {
 5222:                     $type = 'course';
 5223:                 } elsif ($item =~ /___\d+___/) {
 5224:                     $type = 'resource';
 5225:                 } else {
 5226:                     $timersymb = &Apache::lonnet::symbread($item);
 5227:                 }
 5228:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5229:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 5230:                 if ($start && $end) {
 5231:                     if (($start <= time) && ($end >= time)) {
 5232:                         if (ref($commblocks{$block}) eq 'HASH') {
 5233:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5234:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5235:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
 5236:                                         push(@blockers,$block);
 5237:                                         $triggered{$block} = {
 5238:                                                                start => $start,
 5239:                                                                end   => $end,
 5240:                                                                type  => $type,
 5241:                                                              };
 5242:                                     }
 5243:                                 }
 5244:                             }
 5245:                         }
 5246:                     }
 5247:                 }
 5248:             }
 5249:         }
 5250:     }
 5251:     foreach my $blocker (@blockers) {
 5252:         my ($staff_name,$staff_dom,$title,$blocks) =
 5253:             &parse_block_record($commblocks{$blocker});
 5254:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 5255:         my ($start,$end,$triggertype);
 5256:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 5257:             ($start,$end) = ($1,$2);
 5258:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 5259:             $start = $triggered{$blocker}{'start'};
 5260:             $end = $triggered{$blocker}{'end'};
 5261:             $triggertype = $triggered{$blocker}{'type'};
 5262:         }
 5263:         if ($start) {
 5264:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 5265:             if ($triggertype) {
 5266:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 5267:             } else {
 5268:                 push(@{$$setters{$course}{'triggers'}},0);
 5269:             }
 5270:             if ( ($startblock == 0) || ($startblock > $start) ) {
 5271:                 $startblock = $start;
 5272:                 if ($triggertype) {
 5273:                     $triggerblock = $blocker;
 5274:                 }
 5275:             }
 5276:             if ( ($endblock == 0) || ($endblock < $end) ) {
 5277:                $endblock = $end;
 5278:                if ($triggertype) {
 5279:                    $triggerblock = $blocker;
 5280:                }
 5281:             }
 5282:         }
 5283:     }
 5284:     return ($startblock,$endblock,$triggerblock);
 5285: }
 5286: 
 5287: sub parse_block_record {
 5288:     my ($record) = @_;
 5289:     my ($setuname,$setudom,$title,$blocks);
 5290:     if (ref($record) eq 'HASH') {
 5291:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 5292:         $title = &unescape($record->{'event'});
 5293:         $blocks = $record->{'blocks'};
 5294:     } else {
 5295:         my @data = split(/:/,$record,3);
 5296:         if (scalar(@data) eq 2) {
 5297:             $title = $data[1];
 5298:             ($setuname,$setudom) = split(/@/,$data[0]);
 5299:         } else {
 5300:             ($setuname,$setudom,$title) = @data;
 5301:         }
 5302:         $blocks = { 'com' => 'on' };
 5303:     }
 5304:     return ($setuname,$setudom,$title,$blocks);
 5305: }
 5306: 
 5307: sub blocking_status {
 5308:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
 5309:     my %setters;
 5310: 
 5311: # check for active blocking
 5312:     if ($clientip eq '') {
 5313:         $clientip = &Apache::lonnet::get_requestor_ip();
 5314:     }
 5315:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
 5316:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
 5317:     my $blocked = 0;
 5318:     if (($startblock && $endblock) || ($by_ip)) {
 5319:         $blocked = 1;
 5320:     }
 5321: 
 5322: # caller just wants to know whether a block is active
 5323:     if (!wantarray) { return $blocked; }
 5324: 
 5325: # build a link to a popup window containing the details
 5326:     my $querystring  = "?activity=$activity";
 5327: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
 5328:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
 5329:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/);
 5330:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
 5331:     } elsif ($activity eq 'docs') {
 5332:         my $showurl = &Apache::lonenc::check_encrypt($url);
 5333:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
 5334:         if ($symb) {
 5335:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
 5336:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
 5337:         }
 5338:     }
 5339: 
 5340:     my $output .= <<'END_MYBLOCK';
 5341: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 5342:     var options = "width=" + w + ",height=" + h + ",";
 5343:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 5344:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 5345:     var newWin = window.open(url, wdwName, options);
 5346:     newWin.focus();
 5347: }
 5348: END_MYBLOCK
 5349: 
 5350:     $output = Apache::lonhtmlcommon::scripttag($output);
 5351:   
 5352:     my $popupUrl = "/adm/blockingstatus/$querystring";
 5353:     my $text = &mt('Communication Blocked');
 5354:     my $class = 'LC_comblock';
 5355:     if ($activity eq 'docs') {
 5356:         $text = &mt('Content Access Blocked');
 5357:         $class = '';
 5358:     } elsif ($activity eq 'printout') {
 5359:         $text = &mt('Printing Blocked');
 5360:     } elsif ($activity eq 'passwd') {
 5361:         $text = &mt('Password Changing Blocked');
 5362:     } elsif ($activity eq 'grades') {
 5363:         $text = &mt('Gradebook Blocked');
 5364:     } elsif ($activity eq 'search') {
 5365:         $text = &mt('Search Blocked');
 5366:     } elsif ($activity eq 'alert') {
 5367:         $text = &mt('Checking Critical Messages Blocked');
 5368:     } elsif ($activity eq 'reinit') {
 5369:         $text = &mt('Checking Course Update Blocked');
 5370:     } elsif ($activity eq 'about') {
 5371:         $text = &mt('Access to User Information Pages Blocked');
 5372:     } elsif ($activity eq 'wishlist') {
 5373:         $text = &mt('Access to Stored Links Blocked');
 5374:     } elsif ($activity eq 'annotate') {
 5375:         $text = &mt('Access to Annotations Blocked');
 5376:     }
 5377:     $output .= <<"END_BLOCK";
 5378: <div class='$class'>
 5379:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 5380:   title='$text'>
 5381:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 5382:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 5383:   title='$text'>$text</a>
 5384: </div>
 5385: 
 5386: END_BLOCK
 5387: 
 5388:     return ($blocked, $output);
 5389: }
 5390: 
 5391: ###############################################
 5392: 
 5393: sub check_ip_acc {
 5394:     my ($acc,$clientip)=@_;
 5395:     &Apache::lonxml::debug("acc is $acc");
 5396:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 5397:         return 1;
 5398:     }
 5399:     my $allowed=0;
 5400:     my $ip;
 5401:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
 5402:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
 5403:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
 5404:     } else {
 5405:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
 5406:         $ip = $remote_ip || $env{'request.host'} || $clientip;
 5407:     }
 5408: 
 5409:     my $name;
 5410:     my %access = (
 5411:                      allowfrom => 1,
 5412:                      denyfrom  => 0,
 5413:                  );
 5414:     my @allows;
 5415:     my @denies;
 5416:     foreach my $item (split(',',$acc)) {
 5417:         $item =~ s/^\s*//;
 5418:         $item =~ s/\s*$//;
 5419:         if ($item =~ /^\!(.+)$/) {
 5420:             push(@denies,$1);
 5421:         } else {
 5422:             push(@allows,$item);
 5423:         }
 5424:     }
 5425:     my $numdenies = scalar(@denies);
 5426:     my $numallows = scalar(@allows);
 5427:     my $count = 0;
 5428:     foreach my $pattern (@denies,@allows) {
 5429:         $count ++;
 5430:         my $acctype = 'allowfrom';
 5431:         if ($count <= $numdenies) {
 5432:             $acctype = 'denyfrom';
 5433:         }
 5434:         if ($pattern =~ /\*$/) {
 5435:             #35.8.*
 5436:             $pattern=~s/\*//;
 5437:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 5438:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 5439:             #35.8.3.[34-56]
 5440:             my $low=$2;
 5441:             my $high=$3;
 5442:             $pattern=$1;
 5443:             if ($ip =~ /^\Q$pattern\E/) {
 5444:                 my $last=(split(/\./,$ip))[3];
 5445:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
 5446:             }
 5447:         } elsif ($pattern =~ /^\*/) {
 5448:             #*.msu.edu
 5449:             $pattern=~s/\*//;
 5450:             if (!defined($name)) {
 5451:                 use Socket;
 5452:                 my $netaddr=inet_aton($ip);
 5453:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5454:             }
 5455:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5456:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 5457:             #127.0.0.1
 5458:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 5459:         } else {
 5460:             #some.name.com
 5461:             if (!defined($name)) {
 5462:                 use Socket;
 5463:                 my $netaddr=inet_aton($ip);
 5464:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5465:             }
 5466:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5467:         }
 5468:         if ($allowed =~ /^(0|1)$/) { last; }
 5469:     }
 5470:     if ($allowed eq '') {
 5471:         if ($numdenies && !$numallows) {
 5472:             $allowed = 1;
 5473:         } else {
 5474:             $allowed = 0;
 5475:         }
 5476:     }
 5477:     return $allowed;
 5478: }
 5479: 
 5480: ###############################################
 5481: 
 5482: =pod
 5483: 
 5484: =head1 Domain Template Functions
 5485: 
 5486: =over 4
 5487: 
 5488: =item * &determinedomain()
 5489: 
 5490: Inputs: $domain (usually will be undef)
 5491: 
 5492: Returns: Determines which domain should be used for designs
 5493: 
 5494: =cut
 5495: 
 5496: ###############################################
 5497: sub determinedomain {
 5498:     my $domain=shift;
 5499:     if (! $domain) {
 5500:         # Determine domain if we have not been given one
 5501:         $domain = &Apache::lonnet::default_login_domain();
 5502:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 5503:         if ($env{'request.role.domain'}) { 
 5504:             $domain=$env{'request.role.domain'}; 
 5505:         }
 5506:     }
 5507:     return $domain;
 5508: }
 5509: ###############################################
 5510: 
 5511: sub devalidate_domconfig_cache {
 5512:     my ($udom)=@_;
 5513:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 5514: }
 5515: 
 5516: # ---------------------- Get domain configuration for a domain
 5517: sub get_domainconf {
 5518:     my ($udom) = @_;
 5519:     my $cachetime=1800;
 5520:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 5521:     if (defined($cached)) { return %{$result}; }
 5522: 
 5523:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 5524: 					     ['login','rolecolors','autoenroll'],$udom);
 5525:     my (%designhash,%legacy);
 5526:     if (keys(%domconfig) > 0) {
 5527:         if (ref($domconfig{'login'}) eq 'HASH') {
 5528:             if (keys(%{$domconfig{'login'}})) {
 5529:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 5530:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5531:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
 5532:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5533:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
 5534:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
 5535:                                         if ($key eq 'loginvia') {
 5536:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 5537:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 5538:                                                 $designhash{$udom.'.login.loginvia'} = $server;
 5539:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 5540:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 5541:                                                 } else {
 5542:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 5543:                                                 }
 5544:                                             }
 5545:                                         } elsif ($key eq 'headtag') {
 5546:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
 5547:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
 5548:                                             }
 5549:                                         }
 5550:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
 5551:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
 5552:                                         }
 5553:                                     }
 5554:                                 }
 5555:                             }
 5556:                         } elsif ($key eq 'saml') {
 5557:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5558:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
 5559:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
 5560:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
 5561:                                         foreach my $item ('text','img','alt','url','title','window','notsso') {
 5562:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
 5563:                                         }
 5564:                                     }
 5565:                                 }
 5566:                             }
 5567:                         } else {
 5568:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 5569:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 5570:                                     $domconfig{'login'}{$key}{$img};
 5571:                             }
 5572:                         }
 5573:                     } else {
 5574:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 5575:                     }
 5576:                 }
 5577:             } else {
 5578:                 $legacy{'login'} = 1;
 5579:             }
 5580:         } else {
 5581:             $legacy{'login'} = 1;
 5582:         }
 5583:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 5584:             if (keys(%{$domconfig{'rolecolors'}})) {
 5585:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 5586:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 5587:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 5588:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 5589:                         }
 5590:                     }
 5591:                 }
 5592:             } else {
 5593:                 $legacy{'rolecolors'} = 1;
 5594:             }
 5595:         } else {
 5596:             $legacy{'rolecolors'} = 1;
 5597:         }
 5598:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5599:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 5600:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 5601:             }
 5602:         }
 5603:         if (keys(%legacy) > 0) {
 5604:             my %legacyhash = &get_legacy_domconf($udom);
 5605:             foreach my $item (keys(%legacyhash)) {
 5606:                 if ($item =~ /^\Q$udom\E\.login/) {
 5607:                     if ($legacy{'login'}) { 
 5608:                         $designhash{$item} = $legacyhash{$item};
 5609:                     }
 5610:                 } else {
 5611:                     if ($legacy{'rolecolors'}) {
 5612:                         $designhash{$item} = $legacyhash{$item};
 5613:                     }
 5614:                 }
 5615:             }
 5616:         }
 5617:     } else {
 5618:         %designhash = &get_legacy_domconf($udom); 
 5619:     }
 5620:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 5621: 				  $cachetime);
 5622:     return %designhash;
 5623: }
 5624: 
 5625: sub get_legacy_domconf {
 5626:     my ($udom) = @_;
 5627:     my %legacyhash;
 5628:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 5629:     my $designfile =  $designdir.'/'.$udom.'.tab';
 5630:     if (-e $designfile) {
 5631:         if ( open (my $fh,'<',$designfile) ) {
 5632:             while (my $line = <$fh>) {
 5633:                 next if ($line =~ /^\#/);
 5634:                 chomp($line);
 5635:                 my ($key,$val)=(split(/\=/,$line));
 5636:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 5637:             }
 5638:             close($fh);
 5639:         }
 5640:     }
 5641:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 5642:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 5643:     }
 5644:     return %legacyhash;
 5645: }
 5646: 
 5647: =pod
 5648: 
 5649: =item * &domainlogo()
 5650: 
 5651: Inputs: $domain (usually will be undef)
 5652: 
 5653: Returns: A link to a domain logo, if the domain logo exists.
 5654: If the domain logo does not exist, a description of the domain.
 5655: 
 5656: =cut
 5657: 
 5658: ###############################################
 5659: sub domainlogo {
 5660:     my $domain = &determinedomain(shift);
 5661:     my %designhash = &get_domainconf($domain);    
 5662:     # See if there is a logo
 5663:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 5664:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 5665:         if ($imgsrc =~ m{^/(adm|res)/}) {
 5666: 	    if ($imgsrc =~ m{^/res/}) {
 5667: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 5668: 		&Apache::lonnet::repcopy($local_name);
 5669: 	    }
 5670: 	   $imgsrc = &lonhttpdurl($imgsrc);
 5671:         }
 5672:         my $alttext = $domain;
 5673:         if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
 5674:             $alttext = $designhash{$domain.'.login.alttext_domlogo'};
 5675:         }
 5676:         return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
 5677:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 5678:         return &Apache::lonnet::domain($domain,'description');
 5679:     } else {
 5680:         return '';
 5681:     }
 5682: }
 5683: ##############################################
 5684: 
 5685: =pod
 5686: 
 5687: =item * &designparm()
 5688: 
 5689: Inputs: $which parameter; $domain (usually will be undef)
 5690: 
 5691: Returns: value of designparamter $which
 5692: 
 5693: =cut
 5694: 
 5695: 
 5696: ##############################################
 5697: sub designparm {
 5698:     my ($which,$domain)=@_;
 5699:     if (exists($env{'environment.color.'.$which})) {
 5700:         return $env{'environment.color.'.$which};
 5701:     }
 5702:     $domain=&determinedomain($domain);
 5703:     my %domdesign;
 5704:     unless ($domain eq 'public') {
 5705:         %domdesign = &get_domainconf($domain);
 5706:     }
 5707:     my $output;
 5708:     if ($domdesign{$domain.'.'.$which} ne '') {
 5709:         $output = $domdesign{$domain.'.'.$which};
 5710:     } else {
 5711:         $output = $defaultdesign{$which};
 5712:     }
 5713:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 5714:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 5715:         if ($output =~ m{^/(adm|res)/}) {
 5716:             if ($output =~ m{^/res/}) {
 5717:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 5718:                 &Apache::lonnet::repcopy($local_name);
 5719:             }
 5720:             $output = &lonhttpdurl($output);
 5721:         }
 5722:     }
 5723:     return $output;
 5724: }
 5725: 
 5726: ##############################################
 5727: =pod
 5728: 
 5729: =item * &authorspace()
 5730: 
 5731: Inputs: $url (usually will be undef).
 5732: 
 5733: Returns: Path to Authoring Space containing the resource or 
 5734:          directory being viewed (or for which action is being taken). 
 5735:          If $url is provided, and begins /priv/<domain>/<uname>
 5736:          the path will be that portion of the $context argument.
 5737:          Otherwise the path will be for the author space of the current
 5738:          user when the current role is author, or for that of the 
 5739:          co-author/assistant co-author space when the current role 
 5740:          is co-author or assistant co-author.
 5741: 
 5742: =cut
 5743: 
 5744: sub authorspace {
 5745:     my ($url) = @_;
 5746:     if ($url ne '') {
 5747:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 5748:            return $1;
 5749:         }
 5750:     }
 5751:     my $caname = '';
 5752:     my $cadom = '';
 5753:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 5754:         ($cadom,$caname) =
 5755:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 5756:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 5757:         $caname = $env{'user.name'};
 5758:         $cadom = $env{'user.domain'};
 5759:     }
 5760:     if (($caname ne '') && ($cadom ne '')) {
 5761:         return "/priv/$cadom/$caname/";
 5762:     }
 5763:     return;
 5764: }
 5765: 
 5766: ##############################################
 5767: =pod
 5768: 
 5769: =item * &head_subbox()
 5770: 
 5771: Inputs: $content (contains HTML code with page functions, etc.)
 5772: 
 5773: Returns: HTML div with $content
 5774:          To be included in page header
 5775: 
 5776: =cut
 5777: 
 5778: sub head_subbox {
 5779:     my ($content)=@_;
 5780:     my $output =
 5781:         '<div class="LC_head_subbox">'
 5782:        .$content
 5783:        .'</div>'
 5784: }
 5785: 
 5786: ##############################################
 5787: =pod
 5788: 
 5789: =item * &CSTR_pageheader()
 5790: 
 5791: Input: (optional) filename from which breadcrumb trail is built.
 5792:        In most cases no input as needed, as $env{'request.filename'}
 5793:        is appropriate for use in building the breadcrumb trail.
 5794:        frameset flag
 5795:        If page header is being requested for use in a frameset, then
 5796:        the second (option) argument -- frameset will be true, and
 5797:        the target attribute set for links should be target="_parent".
 5798: 
 5799: Returns: HTML div with CSTR path and recent box
 5800:          To be included on Authoring Space pages
 5801: 
 5802: =cut
 5803: 
 5804: sub CSTR_pageheader {
 5805:     my ($trailfile,$frameset) = @_;
 5806:     if ($trailfile eq '') {
 5807:         $trailfile = $env{'request.filename'};
 5808:     }
 5809: 
 5810: # this is for resources; directories have customtitle, and crumbs
 5811: # and select recent are created in lonpubdir.pm
 5812: 
 5813:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 5814:     my ($udom,$uname,$thisdisfn)=
 5815:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 5816:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 5817:     $formaction =~ s{/+}{/}g;
 5818: 
 5819:     my $parentpath = '';
 5820:     my $lastitem = '';
 5821:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 5822:         $parentpath = $1;
 5823:         $lastitem = $2;
 5824:     } else {
 5825:         $lastitem = $thisdisfn;
 5826:     }
 5827: 
 5828:     my ($target,$crumbtarget) = (' target="_top"','_top');
 5829:     if ($frameset) {
 5830:         $target = ' target="_parent"';
 5831:         $crumbtarget = '_parent';
 5832:     } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
 5833:         $target = ' target="'.$env{'request.deeplink.target'}.'"';
 5834:         $crumbtarget = $env{'request.deeplink.target'};
 5835:     }
 5836: 
 5837:     my $output =
 5838:          '<div>'
 5839:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 5840:         .'<b>'.&mt('Authoring Space:').'</b> '
 5841:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
 5842:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
 5843: 
 5844:     if ($lastitem) {
 5845:         $output .=
 5846:              '<span class="LC_filename">'
 5847:             .$lastitem
 5848:             .'</span>';
 5849:     }
 5850:     $output .=
 5851:          '<br />'
 5852:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
 5853:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 5854:         .'</form>'
 5855:         .&Apache::lonmenu::constspaceform($frameset)
 5856:         .'</div>';
 5857: 
 5858:     return $output;
 5859: }
 5860: 
 5861: ###############################################
 5862: ###############################################
 5863: 
 5864: =pod
 5865: 
 5866: =back
 5867: 
 5868: =head1 HTML Helpers
 5869: 
 5870: =over 4
 5871: 
 5872: =item * &bodytag()
 5873: 
 5874: Returns a uniform header for LON-CAPA web pages.
 5875: 
 5876: Inputs: 
 5877: 
 5878: =over 4
 5879: 
 5880: =item * $title, A title to be displayed on the page.
 5881: 
 5882: =item * $function, the current role (can be undef).
 5883: 
 5884: =item * $addentries, extra parameters for the <body> tag.
 5885: 
 5886: =item * $bodyonly, if defined, only return the <body> tag.
 5887: 
 5888: =item * $domain, if defined, force a given domain.
 5889: 
 5890: =item * $forcereg, if page should register as content page (relevant for 
 5891:             text interface only)
 5892: 
 5893: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 5894:                      navigational links
 5895: 
 5896: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 5897: 
 5898: =item * $no_inline_link, if true and in remote mode, don't show the
 5899:          'Switch To Inline Menu' link
 5900: 
 5901: =item * $args, optional argument valid values are
 5902:             no_auto_mt_title -> prevents &mt()ing the title arg
 5903:             use_absolute     -> for external resource or syllabus, this will
 5904:                                 contain https://<hostname> if server uses
 5905:                                 https (as per hosts.tab), but request is for http
 5906:             hostname         -> hostname, from $r->hostname().
 5907: 
 5908: =item * $advtoolsref, optional argument, ref to an array containing
 5909:             inlineremote items to be added in "Functions" menu below
 5910:             breadcrumbs.
 5911: 
 5912: =item * $ltiscope, optional argument, will be one of: resource, map or
 5913:             course, if LON-CAPA is in LTI Provider context. Value is
 5914:             the scope of use, i.e., launch was for access to a single, a map
 5915:             or the entire course.
 5916: 
 5917: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
 5918:             context, this will contain the URL for the landing item in
 5919:             the course, after launch from an LTI Consumer
 5920: 
 5921: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
 5922:             context, this will contain a reference to hash of items
 5923:             to be included in the page header and/or inline menu.
 5924: 
 5925: =item * $menucoll, optional argument, if specific menu collection is in
 5926:             effect, either set as the default for the course, or set for
 5927:             the deeplink paramater for $env{'request.deeplink.login'}
 5928:             then $menucoll will be the number of that collection.
 5929: 
 5930: =item * $menuref, optional argument, reference to a hash, containing the
 5931:             menu options included for the menu in effect, based on the
 5932:             configuration for the numbered menu collection in use.
 5933: 
 5934: =item * $showncrumbsref, reference to a scalar. Calls to lonmenu::innerregister
 5935:             within &bodytag() can result in calls to lonhtmlcommon::breadcrumbs(),
 5936:             if so, $showncrumbsref is set there to 1, and will propagate back
 5937:             via &bodytag() to &start_page(), to prevent lonhtmlcommon::breadcrumbs()
 5938:             being called a second time.
 5939: 
 5940: =back
 5941: 
 5942: Returns: A uniform header for LON-CAPA web pages.  
 5943: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 5944: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 5945: other decorations will be returned.
 5946: 
 5947: =cut
 5948: 
 5949: sub bodytag {
 5950:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 5951:         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref,
 5952:         $ltiscope,$ltiuri,$ltimenu,$menucoll,$menuref,$showncrumbsref)=@_;
 5953: 
 5954:     my $public;
 5955:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 5956:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 5957:         $public = 1;
 5958:     }
 5959:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5960:     my $httphost = $args->{'use_absolute'};
 5961:     my $hostname = $args->{'hostname'};
 5962: 
 5963:     $function = &get_users_function() if (!$function);
 5964:     my $img =    &designparm($function.'.img',$domain);
 5965:     my $font =   &designparm($function.'.font',$domain);
 5966:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 5967: 
 5968:     my %design = ( 'style'   => 'margin-top: 0',
 5969: 		   'bgcolor' => $pgbg,
 5970: 		   'text'    => $font,
 5971:                    'alink'   => &designparm($function.'.alink',$domain),
 5972: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 5973: 		   'link'    => &designparm($function.'.link',$domain),);
 5974:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 5975: 
 5976:  # role and realm
 5977:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
 5978:     if ($realm) {
 5979:         $realm = '/'.$realm;
 5980:     }
 5981:     if ($role eq 'ca') {
 5982:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 5983:         $realm = &plainname($rname,$rdom);
 5984:     } 
 5985: # realm
 5986:     my ($cid,$sec);
 5987:     if ($env{'request.course.id'}) {
 5988:         $cid = $env{'request.course.id'};
 5989:         if ($env{'request.course.sec'}) {
 5990:             $sec = $env{'request.course.sec'};
 5991:         }
 5992:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
 5993:         if (&Apache::lonnet::is_course($1,$2)) {
 5994:             $cid = $1.'_'.$2;
 5995:             $sec = $3;
 5996:         }
 5997:     }
 5998:     if ($cid) {
 5999:         if ($env{'request.role'} !~ /^cr/) {
 6000:             $role = &Apache::lonnet::plaintext($role,&course_type());
 6001:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
 6002:             if ($env{'request.role.desc'}) {
 6003:                 $role = $env{'request.role.desc'};
 6004:             } else {
 6005:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
 6006:             }
 6007:         } else {
 6008:             $role = (split(/\//,$role,4))[-1];
 6009:         }
 6010:         if ($sec) {
 6011:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
 6012:         }   
 6013: 	$realm = $env{'course.'.$cid.'.description'};
 6014:     } else {
 6015:         $role = &Apache::lonnet::plaintext($role);
 6016:     }
 6017: 
 6018:     if (!$realm) { $realm='&nbsp;'; }
 6019: 
 6020:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 6021: 
 6022: # construct main body tag
 6023:     my $bodytag = "<body $extra_body_attr>".
 6024: 	&Apache::lontexconvert::init_math_support();
 6025: 
 6026:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 6027: 
 6028:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 6029:         return $bodytag;
 6030:     }
 6031: 
 6032:     if ($public) {
 6033: 	undef($role);
 6034:     }
 6035: 
 6036:     my $showcrstitle = 1;
 6037:     if (($cid) && ($env{'request.lti.login'})) {
 6038:         if (ref($ltimenu) eq 'HASH') {
 6039:             unless ($ltimenu->{'role'}) {
 6040:                 undef($role);
 6041:             }
 6042:             unless ($ltimenu->{'coursetitle'}) {
 6043:                 $realm='&nbsp;';
 6044:                 $showcrstitle = 0;
 6045:             }
 6046:         }
 6047:     } elsif (($cid) && ($menucoll)) {
 6048:         if (ref($menuref) eq 'HASH') {
 6049:             unless ($menuref->{'role'}) {
 6050:                 undef($role);
 6051:             }
 6052:             unless ($menuref->{'crs'}) {
 6053:                 $realm='&nbsp;';
 6054:                 $showcrstitle = 0;
 6055:             }
 6056:         }
 6057:     }
 6058: 
 6059:     my $titleinfo = '<h1>'.$title.'</h1>';
 6060:     #
 6061:     # Extra info if you are the DC
 6062:     my $dc_info = '';
 6063:     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
 6064:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
 6065:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 6066:         $dc_info =~ s/\s+$//;
 6067:     }
 6068: 
 6069:     my $crstype;
 6070:     if ($cid) {
 6071:         $crstype = $env{'course.'.$cid.'.type'};
 6072:     } elsif ($args->{'crstype'}) {
 6073:         $crstype = $args->{'crstype'};
 6074:     }
 6075: 
 6076:     $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
 6077: 
 6078:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 6079: 
 6080: 
 6081: 
 6082:     my $funclist;
 6083:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
 6084:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
 6085:                     Apache::lonmenu::serverform();
 6086:         my $forbodytag;
 6087:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 6088:                                             $forcereg,$args->{'group'},
 6089:                                             $args->{'bread_crumbs'},
 6090:                                             $advtoolsref,'','',\$forbodytag);
 6091:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 6092:             $funclist = $forbodytag;
 6093:         }
 6094:     } else {
 6095: 
 6096:         #    if ($env{'request.state'} eq 'construct') {
 6097:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 6098:         #    }
 6099: 
 6100:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 6101:             Apache::lonmenu::utilityfunctions($httphost), 'start');
 6102: 
 6103:         unless ($args->{'no_primary_menu'}) {
 6104:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
 6105:                                                               $args->{'links_disabled'},
 6106:                                                               $args->{'links_target'});
 6107:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 6108:                 if ($dc_info) {
 6109:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 6110:                 }
 6111:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 6112:                                <em>$realm</em> $dc_info</div>|;
 6113:                 return $bodytag;
 6114:             }
 6115: 
 6116:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 6117:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 6118:             }
 6119: 
 6120:             $bodytag .= $right;
 6121: 
 6122:             if ($dc_info) {
 6123:                 $dc_info = &dc_courseid_toggle($dc_info);
 6124:             }
 6125:             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 6126:         }
 6127: 
 6128:         #if directed to not display the secondary menu, don't.
 6129:         if ($args->{'no_secondary_menu'}) {
 6130:             return $bodytag;
 6131:         }
 6132:         #don't show menus for public users
 6133:         if (!$public){
 6134:             unless ($args->{'no_inline_menu'}) {
 6135:                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
 6136:                                                             $args->{'no_primary_menu'},
 6137:                                                             $menucoll,$menuref,
 6138:                                                             $args->{'links_disabled'},
 6139:                                                             $args->{'links_target'});
 6140:             }
 6141:             $bodytag .= Apache::lonmenu::serverform();
 6142:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 6143:             if ($env{'request.state'} eq 'construct') {
 6144:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 6145:                                 $args->{'bread_crumbs'},'','',$hostname,
 6146:                                 $ltiscope,$ltiuri,$showncrumbsref);
 6147:             } elsif ($forcereg) {
 6148:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 6149:                                 $args->{'group'},$args->{'hide_buttons'},
 6150:                                 $hostname,$ltiscope,$ltiuri,$showncrumbsref);
 6151:             } else {
 6152:                 my $forbodytag;
 6153:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 6154:                                                     $forcereg,$args->{'group'},
 6155:                                                     $args->{'bread_crumbs'},
 6156:                                                     $advtoolsref,'',$hostname,
 6157:                                                     \$forbodytag);
 6158:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 6159:                     $bodytag .= $forbodytag;
 6160:                 }
 6161:             }
 6162:         }else{
 6163:             # this is to seperate menu from content when there's no secondary
 6164:             # menu. Especially needed for public accessible ressources.
 6165:             $bodytag .= '<hr style="clear:both" />';
 6166:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 6167:         }
 6168: 
 6169:         return $bodytag;
 6170:     }
 6171: 
 6172: #
 6173: # Top frame rendering, Remote is up
 6174: #
 6175: 
 6176:     my $imgsrc = $img;
 6177:     if ($img =~ /^\/adm/) {
 6178:         $imgsrc = &lonhttpdurl($img);
 6179:     }
 6180:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 6181: 
 6182:     my $help=($no_inline_link?''
 6183:               :&Apache::loncommon::top_nav_help('Help'));
 6184: 
 6185:     # Explicit link to get inline menu
 6186:     my $menu= ($no_inline_link?''
 6187:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
 6188: 
 6189:     if ($dc_info) {
 6190:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
 6191:     }
 6192: 
 6193:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 6194:     unless ($public) {
 6195:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
 6196:                                 undef,'LC_menubuttons_link');
 6197:     }
 6198: 
 6199:     unless ($env{'form.inhibitmenu'}) {
 6200:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
 6201:                        <ol class="LC_primary_menu LC_floatright LC_right">
 6202:                        <li>$help</li>
 6203:                        <li>$menu</li>
 6204:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
 6205:     }
 6206:     if ($env{'request.state'} eq 'construct') {
 6207:         if (!$public){
 6208:             if ($env{'request.state'} eq 'construct') {
 6209:                 $funclist = &Apache::lonhtmlcommon::scripttag(
 6210:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
 6211:                             &Apache::lonhtmlcommon::scripttag('','end').
 6212:                             &Apache::lonmenu::innerregister($forcereg,
 6213:                                                             $args->{'bread_crumbs'});
 6214:             }
 6215:         }
 6216:     }
 6217:     return $bodytag."\n".$funclist;
 6218: }
 6219: 
 6220: sub dc_courseid_toggle {
 6221:     my ($dc_info) = @_;
 6222:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 6223:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 6224:            &mt('(More ...)').'</a></span>'.
 6225:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 6226: }
 6227: 
 6228: sub make_attr_string {
 6229:     my ($register,$attr_ref) = @_;
 6230: 
 6231:     if ($attr_ref && !ref($attr_ref)) {
 6232: 	die("addentries Must be a hash ref ".
 6233: 	    join(':',caller(1))." ".
 6234: 	    join(':',caller(0))." ");
 6235:     }
 6236: 
 6237:     if ($register) {
 6238: 	my ($on_load,$on_unload);
 6239: 	foreach my $key (keys(%{$attr_ref})) {
 6240: 	    if      (lc($key) eq 'onload') {
 6241: 		$on_load.=$attr_ref->{$key}.';';
 6242: 		delete($attr_ref->{$key});
 6243: 
 6244: 	    } elsif (lc($key) eq 'onunload') {
 6245: 		$on_unload.=$attr_ref->{$key}.';';
 6246: 		delete($attr_ref->{$key});
 6247: 	    }
 6248: 	}
 6249:         if ($env{'environment.remote'} eq 'on') {
 6250:             $attr_ref->{'onload'}  =
 6251:                 &Apache::lonmenu::loadevents().  $on_load;
 6252:             $attr_ref->{'onunload'}=
 6253:                 &Apache::lonmenu::unloadevents().$on_unload;
 6254:         } else {  
 6255: 	    $attr_ref->{'onload'}  = $on_load;
 6256: 	    $attr_ref->{'onunload'}= $on_unload;
 6257:         }
 6258:     }
 6259: 
 6260:     my $attr_string;
 6261:     foreach my $attr (sort(keys(%$attr_ref))) {
 6262: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 6263:     }
 6264:     return $attr_string;
 6265: }
 6266: 
 6267: 
 6268: ###############################################
 6269: ###############################################
 6270: 
 6271: =pod
 6272: 
 6273: =item * &endbodytag()
 6274: 
 6275: Returns a uniform footer for LON-CAPA web pages.
 6276: 
 6277: Inputs: 1 - optional reference to an args hash
 6278: If in the hash, key for noredirectlink has a value which evaluates to true,
 6279: a 'Continue' link is not displayed if the page contains an
 6280: internal redirect in the <head></head> section,
 6281: i.e., $env{'internal.head.redirect'} exists   
 6282: 
 6283: =cut
 6284: 
 6285: sub endbodytag {
 6286:     my ($args) = @_;
 6287:     my $endbodytag;
 6288:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 6289:         $endbodytag='</body>';
 6290:     }
 6291:     if ( exists( $env{'internal.head.redirect'} ) ) {
 6292:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 6293:             my ($endbodyjs,$idattr);
 6294:             if ($env{'internal.head.to_opener'}) {
 6295:                 my $linkid = 'LC_continue_link';
 6296:                 $idattr = ' id="'.$linkid.'"';
 6297:                 my $redirect_for_js = &js_escape($env{'internal.head.redirect'});
 6298:                 $endbodyjs=<<ENDJS;
 6299: <script type="text/javascript">
 6300: // <![CDATA[
 6301: function ebFunction(evt) {
 6302:     evt.preventDefault();
 6303:     var dest = '$redirect_for_js';
 6304:     if (window.opener != null && !window.opener.closed) {
 6305:         window.opener.location.href=dest;
 6306:         window.close();
 6307:     } else {
 6308:         window.location.href=dest;
 6309:     }
 6310:     return false;
 6311: }
 6312: 
 6313: \$(document).ready(function () {
 6314:   if (document.getElementById('$linkid')) {
 6315:     var clickelem = document.getElementById('$linkid');
 6316:     clickelem.addEventListener('click',ebFunction,false);
 6317:   }
 6318: });
 6319: // ]]>
 6320: </script>
 6321: ENDJS
 6322:             }
 6323: 	    $endbodytag=
 6324: 	        "$endbodyjs<br /><a href=\"$env{'internal.head.redirect'}\"$idattr>".
 6325: 	        &mt('Continue').'</a>'.
 6326: 	        $endbodytag;
 6327:         }
 6328:     }
 6329:     return $endbodytag;
 6330: }
 6331: 
 6332: =pod
 6333: 
 6334: =item * &standard_css()
 6335: 
 6336: Returns a style sheet
 6337: 
 6338: Inputs: (all optional)
 6339:             domain         -> force to color decorate a page for a specific
 6340:                                domain
 6341:             function       -> force usage of a specific rolish color scheme
 6342:             bgcolor        -> override the default page bgcolor
 6343: 
 6344: =cut
 6345: 
 6346: sub standard_css {
 6347:     my ($function,$domain,$bgcolor) = @_;
 6348:     $function  = &get_users_function() if (!$function);
 6349:     my $img    = &designparm($function.'.img',   $domain);
 6350:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 6351:     my $font   = &designparm($function.'.font',  $domain);
 6352:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 6353: #second colour for later usage
 6354:     my $sidebg = &designparm($function.'.sidebg',$domain);
 6355:     my $pgbg_or_bgcolor =
 6356: 	         $bgcolor ||
 6357: 	         &designparm($function.'.pgbg',  $domain);
 6358:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 6359:     my $alink  = &designparm($function.'.alink', $domain);
 6360:     my $vlink  = &designparm($function.'.vlink', $domain);
 6361:     my $link   = &designparm($function.'.link',  $domain);
 6362: 
 6363:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 6364:     my $mono                 = 'monospace';
 6365:     my $data_table_head      = $sidebg;
 6366:     my $data_table_light     = '#FAFAFA';
 6367:     my $data_table_dark      = '#E0E0E0';
 6368:     my $data_table_darker    = '#CCCCCC';
 6369:     my $data_table_highlight = '#FFFF00';
 6370:     my $mail_new             = '#FFBB77';
 6371:     my $mail_new_hover       = '#DD9955';
 6372:     my $mail_read            = '#BBBB77';
 6373:     my $mail_read_hover      = '#999944';
 6374:     my $mail_replied         = '#AAAA88';
 6375:     my $mail_replied_hover   = '#888855';
 6376:     my $mail_other           = '#99BBBB';
 6377:     my $mail_other_hover     = '#669999';
 6378:     my $table_header         = '#DDDDDD';
 6379:     my $feedback_link_bg     = '#BBBBBB';
 6380:     my $lg_border_color      = '#C8C8C8';
 6381:     my $button_hover         = '#BF2317';
 6382: 
 6383:     my $border = ($env{'browser.type'} eq 'explorer' ||
 6384:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 6385:                                              : '0 3px 0 4px';
 6386: 
 6387: 
 6388:     return <<END;
 6389: 
 6390: /* needed for iframe to allow 100% height in FF */
 6391: body, html { 
 6392:     margin: 0;
 6393:     padding: 0 0.5%;
 6394:     height: 99%; /* to avoid scrollbars */
 6395: }
 6396: 
 6397: body {
 6398:   font-family: $sans;
 6399:   line-height:130%;
 6400:   font-size:0.83em;
 6401:   color:$font;
 6402: }
 6403: 
 6404: a:focus,
 6405: a:focus img {
 6406:   color: red;
 6407: }
 6408: 
 6409: form, .inline {
 6410:   display: inline;
 6411: }
 6412: 
 6413: .LC_right {
 6414:   text-align:right;
 6415: }
 6416: 
 6417: .LC_middle {
 6418:   vertical-align:middle;
 6419: }
 6420: 
 6421: .LC_floatleft {
 6422:   float: left;
 6423: }
 6424: 
 6425: .LC_floatright {
 6426:   float: right;
 6427: }
 6428: 
 6429: .LC_400Box {
 6430:   width:400px;
 6431: }
 6432: 
 6433: .LC_iframecontainer {
 6434:     width: 98%;
 6435:     margin: 0;
 6436:     position: fixed;
 6437:     top: 8.5em;
 6438:     bottom: 0;
 6439: }
 6440: 
 6441: .LC_iframecontainer iframe{
 6442:     border: none;
 6443:     width: 100%;
 6444:     height: 100%;
 6445: }
 6446: 
 6447: .LC_filename {
 6448:   font-family: $mono;
 6449:   white-space:pre;
 6450:   font-size: 120%;
 6451: }
 6452: 
 6453: .LC_fileicon {
 6454:   border: none;
 6455:   height: 1.3em;
 6456:   vertical-align: text-bottom;
 6457:   margin-right: 0.3em;
 6458:   text-decoration:none;
 6459: }
 6460: 
 6461: .LC_setting {
 6462:   text-decoration:underline;
 6463: }
 6464: 
 6465: .LC_error {
 6466:   color: red;
 6467: }
 6468: 
 6469: .LC_warning {
 6470:   color: darkorange;
 6471: }
 6472: 
 6473: .LC_diff_removed {
 6474:   color: red;
 6475: }
 6476: 
 6477: .LC_info,
 6478: .LC_success,
 6479: .LC_diff_added {
 6480:   color: green;
 6481: }
 6482: 
 6483: div.LC_confirm_box {
 6484:   background-color: #FAFAFA;
 6485:   border: 1px solid $lg_border_color;
 6486:   margin-right: 0;
 6487:   padding: 5px;
 6488: }
 6489: 
 6490: div.LC_confirm_box .LC_error img,
 6491: div.LC_confirm_box .LC_success img {
 6492:   vertical-align: middle;
 6493: }
 6494: 
 6495: .LC_maxwidth {
 6496:   max-width: 100%;
 6497:   height: auto;
 6498: }
 6499: 
 6500: .LC_textsize_mobile {
 6501:   \@media only screen and (max-device-width: 480px) {
 6502:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
 6503:   }
 6504: }
 6505: 
 6506: .LC_icon {
 6507:   border: none;
 6508:   vertical-align: middle;
 6509: }
 6510: 
 6511: .LC_docs_spacer {
 6512:   width: 25px;
 6513:   height: 1px;
 6514:   border: none;
 6515: }
 6516: 
 6517: .LC_internal_info {
 6518:   color: #999999;
 6519: }
 6520: 
 6521: .LC_discussion {
 6522:   background: $data_table_dark;
 6523:   border: 1px solid black;
 6524:   margin: 2px;
 6525: }
 6526: 
 6527: .LC_disc_action_left {
 6528:   background: $sidebg;
 6529:   text-align: left;
 6530:   padding: 4px;
 6531:   margin: 2px;
 6532: }
 6533: 
 6534: .LC_disc_action_right {
 6535:   background: $sidebg;
 6536:   text-align: right;
 6537:   padding: 4px;
 6538:   margin: 2px;
 6539: }
 6540: 
 6541: .LC_disc_new_item {
 6542:   background: white;
 6543:   border: 2px solid red;
 6544:   margin: 4px;
 6545:   padding: 4px;
 6546: }
 6547: 
 6548: .LC_disc_old_item {
 6549:   background: white;
 6550:   margin: 4px;
 6551:   padding: 4px;
 6552: }
 6553: 
 6554: table.LC_pastsubmission {
 6555:   border: 1px solid black;
 6556:   margin: 2px;
 6557: }
 6558: 
 6559: table#LC_menubuttons {
 6560:   width: 100%;
 6561:   background: $pgbg;
 6562:   border: 2px;
 6563:   border-collapse: separate;
 6564:   padding: 0;
 6565: }
 6566: 
 6567: table#LC_title_bar a {
 6568:   color: $fontmenu;
 6569: }
 6570: 
 6571: table#LC_title_bar {
 6572:   clear: both;
 6573:   display: none;
 6574: }
 6575: 
 6576: table#LC_title_bar,
 6577: table.LC_breadcrumbs, /* obsolete? */
 6578: table#LC_title_bar.LC_with_remote {
 6579:   width: 100%;
 6580:   border-color: $pgbg;
 6581:   border-style: solid;
 6582:   border-width: $border;
 6583:   background: $pgbg;
 6584:   color: $fontmenu;
 6585:   border-collapse: collapse;
 6586:   padding: 0;
 6587:   margin: 0;
 6588: }
 6589: 
 6590: ul.LC_breadcrumb_tools_outerlist {
 6591:     margin: 0;
 6592:     padding: 0;
 6593:     position: relative;
 6594:     list-style: none;
 6595: }
 6596: ul.LC_breadcrumb_tools_outerlist li {
 6597:     display: inline;
 6598: }
 6599: 
 6600: .LC_breadcrumb_tools_navigation {
 6601:     padding: 0;
 6602:     margin: 0;
 6603:     float: left;
 6604: }
 6605: .LC_breadcrumb_tools_tools {
 6606:     padding: 0;
 6607:     margin: 0;
 6608:     float: right;
 6609: }
 6610: 
 6611: table#LC_title_bar td {
 6612:   background: $tabbg;
 6613: }
 6614: 
 6615: table#LC_menubuttons img {
 6616:   border: none;
 6617: }
 6618: 
 6619: .LC_breadcrumbs_component {
 6620:   float: right;
 6621:   margin: 0 1em;
 6622: }
 6623: .LC_breadcrumbs_component img {
 6624:   vertical-align: middle;
 6625: }
 6626: 
 6627: .LC_breadcrumbs_hoverable {
 6628:   background: $sidebg;
 6629: }
 6630: 
 6631: td.LC_table_cell_checkbox {
 6632:   text-align: center;
 6633: }
 6634: 
 6635: .LC_fontsize_small {
 6636:   font-size: 70%;
 6637: }
 6638: 
 6639: #LC_breadcrumbs {
 6640:   clear:both;
 6641:   background: $sidebg;
 6642:   border-bottom: 1px solid $lg_border_color;
 6643:   line-height: 2.5em;
 6644:   overflow: hidden;
 6645:   margin: 0;
 6646:   padding: 0;
 6647:   text-align: left;
 6648: }
 6649: 
 6650: .LC_head_subbox, .LC_actionbox {
 6651:   clear:both;
 6652:   background: #F8F8F8; /* $sidebg; */
 6653:   border: 1px solid $sidebg;
 6654:   margin: 0 0 10px 0;
 6655:   padding: 3px;
 6656:   text-align: left;
 6657: }
 6658: 
 6659: .LC_fontsize_medium {
 6660:   font-size: 85%;
 6661: }
 6662: 
 6663: .LC_fontsize_large {
 6664:   font-size: 120%;
 6665: }
 6666: 
 6667: .LC_menubuttons_inline_text {
 6668:   color: $font;
 6669:   font-size: 90%;
 6670:   padding-left:3px;
 6671: }
 6672: 
 6673: .LC_menubuttons_inline_text img{
 6674:   vertical-align: middle;
 6675: }
 6676: 
 6677: li.LC_menubuttons_inline_text img {
 6678:   cursor:pointer;
 6679:   text-decoration: none;
 6680: }
 6681: 
 6682: .LC_menubuttons_link {
 6683:   text-decoration: none;
 6684: }
 6685: 
 6686: .LC_menubuttons_category {
 6687:   color: $font;
 6688:   background: $pgbg;
 6689:   font-size: larger;
 6690:   font-weight: bold;
 6691: }
 6692: 
 6693: td.LC_menubuttons_text {
 6694:   color: $font;
 6695: }
 6696: 
 6697: .LC_current_location {
 6698:   background: $tabbg;
 6699: }
 6700: 
 6701: td.LC_zero_height {
 6702:   line-height: 0;
 6703:   cellpadding: 0;
 6704: }
 6705: 
 6706: table.LC_data_table {
 6707:   border: 1px solid #000000;
 6708:   border-collapse: separate;
 6709:   border-spacing: 1px;
 6710:   background: $pgbg;
 6711: }
 6712: 
 6713: .LC_data_table_dense {
 6714:   font-size: small;
 6715: }
 6716: 
 6717: table.LC_nested_outer {
 6718:   border: 1px solid #000000;
 6719:   border-collapse: collapse;
 6720:   border-spacing: 0;
 6721:   width: 100%;
 6722: }
 6723: 
 6724: table.LC_innerpickbox,
 6725: table.LC_nested {
 6726:   border: none;
 6727:   border-collapse: collapse;
 6728:   border-spacing: 0;
 6729:   width: 100%;
 6730: }
 6731: 
 6732: table.LC_data_table tr th,
 6733: table.LC_calendar tr th,
 6734: table.LC_prior_tries tr th,
 6735: table.LC_innerpickbox tr th {
 6736:   font-weight: bold;
 6737:   background-color: $data_table_head;
 6738:   color:$fontmenu;
 6739:   font-size:90%;
 6740: }
 6741: 
 6742: table.LC_innerpickbox tr th,
 6743: table.LC_innerpickbox tr td {
 6744:   vertical-align: top;
 6745: }
 6746: 
 6747: table.LC_data_table tr.LC_info_row > td {
 6748:   background-color: #CCCCCC;
 6749:   font-weight: bold;
 6750:   text-align: left;
 6751: }
 6752: 
 6753: table.LC_data_table tr.LC_odd_row > td {
 6754:   background-color: $data_table_light;
 6755:   padding: 2px;
 6756:   vertical-align: top;
 6757: }
 6758: 
 6759: table.LC_pick_box tr > td.LC_odd_row {
 6760:   background-color: $data_table_light;
 6761:   vertical-align: top;
 6762: }
 6763: 
 6764: table.LC_data_table tr.LC_even_row > td {
 6765:   background-color: $data_table_dark;
 6766:   padding: 2px;
 6767:   vertical-align: top;
 6768: }
 6769: 
 6770: table.LC_pick_box tr > td.LC_even_row {
 6771:   background-color: $data_table_dark;
 6772:   vertical-align: top;
 6773: }
 6774: 
 6775: table.LC_data_table tr.LC_data_table_highlight td {
 6776:   background-color: $data_table_darker;
 6777: }
 6778: 
 6779: table.LC_data_table tr td.LC_leftcol_header {
 6780:   background-color: $data_table_head;
 6781:   font-weight: bold;
 6782: }
 6783: 
 6784: table.LC_data_table tr.LC_empty_row td,
 6785: table.LC_nested tr.LC_empty_row td {
 6786:   font-weight: bold;
 6787:   font-style: italic;
 6788:   text-align: center;
 6789:   padding: 8px;
 6790: }
 6791: 
 6792: table.LC_data_table tr.LC_empty_row td,
 6793: table.LC_data_table tr.LC_footer_row td {
 6794:   background-color: $sidebg;
 6795: }
 6796: 
 6797: table.LC_nested tr.LC_empty_row td {
 6798:   background-color: #FFFFFF;
 6799: }
 6800: 
 6801: table.LC_caption {
 6802: }
 6803: 
 6804: table.LC_nested tr.LC_empty_row td {
 6805:   padding: 4ex
 6806: }
 6807: 
 6808: table.LC_nested_outer tr th {
 6809:   font-weight: bold;
 6810:   color:$fontmenu;
 6811:   background-color: $data_table_head;
 6812:   font-size: small;
 6813:   border-bottom: 1px solid #000000;
 6814: }
 6815: 
 6816: table.LC_nested_outer tr td.LC_subheader {
 6817:   background-color: $data_table_head;
 6818:   font-weight: bold;
 6819:   font-size: small;
 6820:   border-bottom: 1px solid #000000;
 6821:   text-align: right;
 6822: }
 6823: 
 6824: table.LC_nested tr.LC_info_row td {
 6825:   background-color: #CCCCCC;
 6826:   font-weight: bold;
 6827:   font-size: small;
 6828:   text-align: center;
 6829: }
 6830: 
 6831: table.LC_nested tr.LC_info_row td.LC_left_item,
 6832: table.LC_nested_outer tr th.LC_left_item {
 6833:   text-align: left;
 6834: }
 6835: 
 6836: table.LC_nested td {
 6837:   background-color: #FFFFFF;
 6838:   font-size: small;
 6839: }
 6840: 
 6841: table.LC_nested_outer tr th.LC_right_item,
 6842: table.LC_nested tr.LC_info_row td.LC_right_item,
 6843: table.LC_nested tr.LC_odd_row td.LC_right_item,
 6844: table.LC_nested tr td.LC_right_item {
 6845:   text-align: right;
 6846: }
 6847: 
 6848: table.LC_nested tr.LC_odd_row td {
 6849:   background-color: #EEEEEE;
 6850: }
 6851: 
 6852: table.LC_createuser {
 6853: }
 6854: 
 6855: table.LC_createuser tr.LC_section_row td {
 6856:   font-size: small;
 6857: }
 6858: 
 6859: table.LC_createuser tr.LC_info_row td  {
 6860:   background-color: #CCCCCC;
 6861:   font-weight: bold;
 6862:   text-align: center;
 6863: }
 6864: 
 6865: table.LC_calendar {
 6866:   border: 1px solid #000000;
 6867:   border-collapse: collapse;
 6868:   width: 98%;
 6869: }
 6870: 
 6871: table.LC_calendar_pickdate {
 6872:   font-size: xx-small;
 6873: }
 6874: 
 6875: table.LC_calendar tr td {
 6876:   border: 1px solid #000000;
 6877:   vertical-align: top;
 6878:   width: 14%;
 6879: }
 6880: 
 6881: table.LC_calendar tr td.LC_calendar_day_empty {
 6882:   background-color: $data_table_dark;
 6883: }
 6884: 
 6885: table.LC_calendar tr td.LC_calendar_day_current {
 6886:   background-color: $data_table_highlight;
 6887: }
 6888: 
 6889: table.LC_data_table tr td.LC_mail_new {
 6890:   background-color: $mail_new;
 6891: }
 6892: 
 6893: table.LC_data_table tr.LC_mail_new:hover {
 6894:   background-color: $mail_new_hover;
 6895: }
 6896: 
 6897: table.LC_data_table tr td.LC_mail_read {
 6898:   background-color: $mail_read;
 6899: }
 6900: 
 6901: /*
 6902: table.LC_data_table tr.LC_mail_read:hover {
 6903:   background-color: $mail_read_hover;
 6904: }
 6905: */
 6906: 
 6907: table.LC_data_table tr td.LC_mail_replied {
 6908:   background-color: $mail_replied;
 6909: }
 6910: 
 6911: /*
 6912: table.LC_data_table tr.LC_mail_replied:hover {
 6913:   background-color: $mail_replied_hover;
 6914: }
 6915: */
 6916: 
 6917: table.LC_data_table tr td.LC_mail_other {
 6918:   background-color: $mail_other;
 6919: }
 6920: 
 6921: /*
 6922: table.LC_data_table tr.LC_mail_other:hover {
 6923:   background-color: $mail_other_hover;
 6924: }
 6925: */
 6926: 
 6927: table.LC_data_table tr > td.LC_browser_file,
 6928: table.LC_data_table tr > td.LC_browser_file_published {
 6929:   background: #AAEE77;
 6930: }
 6931: 
 6932: table.LC_data_table tr > td.LC_browser_file_locked,
 6933: table.LC_data_table tr > td.LC_browser_file_unpublished {
 6934:   background: #FFAA99;
 6935: }
 6936: 
 6937: table.LC_data_table tr > td.LC_browser_file_obsolete {
 6938:   background: #888888;
 6939: }
 6940: 
 6941: table.LC_data_table tr > td.LC_browser_file_modified,
 6942: table.LC_data_table tr > td.LC_browser_file_metamodified {
 6943:   background: #F8F866;
 6944: }
 6945: 
 6946: table.LC_data_table tr.LC_browser_folder > td {
 6947:   background: #E0E8FF;
 6948: }
 6949: 
 6950: table.LC_data_table tr > td.LC_roles_is {
 6951:   /* background: #77FF77; */
 6952: }
 6953: 
 6954: table.LC_data_table tr > td.LC_roles_future {
 6955:   border-right: 8px solid #FFFF77;
 6956: }
 6957: 
 6958: table.LC_data_table tr > td.LC_roles_will {
 6959:   border-right: 8px solid #FFAA77;
 6960: }
 6961: 
 6962: table.LC_data_table tr > td.LC_roles_expired {
 6963:   border-right: 8px solid #FF7777;
 6964: }
 6965: 
 6966: table.LC_data_table tr > td.LC_roles_will_not {
 6967:   border-right: 8px solid #AAFF77;
 6968: }
 6969: 
 6970: table.LC_data_table tr > td.LC_roles_selected {
 6971:   border-right: 8px solid #11CC55;
 6972: }
 6973: 
 6974: span.LC_current_location {
 6975:   font-size:larger;
 6976:   background: $pgbg;
 6977: }
 6978: 
 6979: span.LC_current_nav_location {
 6980:   font-weight:bold;
 6981:   background: $sidebg;
 6982: }
 6983: 
 6984: span.LC_parm_menu_item {
 6985:   font-size: larger;
 6986: }
 6987: 
 6988: span.LC_parm_scope_all {
 6989:   color: red;
 6990: }
 6991: 
 6992: span.LC_parm_scope_folder {
 6993:   color: green;
 6994: }
 6995: 
 6996: span.LC_parm_scope_resource {
 6997:   color: orange;
 6998: }
 6999: 
 7000: span.LC_parm_part {
 7001:   color: blue;
 7002: }
 7003: 
 7004: span.LC_parm_folder,
 7005: span.LC_parm_symb {
 7006:   font-size: x-small;
 7007:   font-family: $mono;
 7008:   color: #AAAAAA;
 7009: }
 7010: 
 7011: ul.LC_parm_parmlist li {
 7012:   display: inline-block;
 7013:   padding: 0.3em 0.8em;
 7014:   vertical-align: top;
 7015:   width: 150px;
 7016:   border-top:1px solid $lg_border_color;
 7017: }
 7018: 
 7019: td.LC_parm_overview_level_menu,
 7020: td.LC_parm_overview_map_menu,
 7021: td.LC_parm_overview_parm_selectors,
 7022: td.LC_parm_overview_restrictions  {
 7023:   border: 1px solid black;
 7024:   border-collapse: collapse;
 7025: }
 7026: 
 7027: table.LC_parm_overview_restrictions td {
 7028:   border-width: 1px 4px 1px 4px;
 7029:   border-style: solid;
 7030:   border-color: $pgbg;
 7031:   text-align: center;
 7032: }
 7033: 
 7034: table.LC_parm_overview_restrictions th {
 7035:   background: $tabbg;
 7036:   border-width: 1px 4px 1px 4px;
 7037:   border-style: solid;
 7038:   border-color: $pgbg;
 7039: }
 7040: 
 7041: table#LC_helpmenu {
 7042:   border: none;
 7043:   height: 55px;
 7044:   border-spacing: 0;
 7045: }
 7046: 
 7047: table#LC_helpmenu fieldset legend {
 7048:   font-size: larger;
 7049: }
 7050: 
 7051: table#LC_helpmenu_links {
 7052:   width: 100%;
 7053:   border: 1px solid black;
 7054:   background: $pgbg;
 7055:   padding: 0;
 7056:   border-spacing: 1px;
 7057: }
 7058: 
 7059: table#LC_helpmenu_links tr td {
 7060:   padding: 1px;
 7061:   background: $tabbg;
 7062:   text-align: center;
 7063:   font-weight: bold;
 7064: }
 7065: 
 7066: table#LC_helpmenu_links a:link,
 7067: table#LC_helpmenu_links a:visited,
 7068: table#LC_helpmenu_links a:active {
 7069:   text-decoration: none;
 7070:   color: $font;
 7071: }
 7072: 
 7073: table#LC_helpmenu_links a:hover {
 7074:   text-decoration: underline;
 7075:   color: $vlink;
 7076: }
 7077: 
 7078: .LC_chrt_popup_exists {
 7079:   border: 1px solid #339933;
 7080:   margin: -1px;
 7081: }
 7082: 
 7083: .LC_chrt_popup_up {
 7084:   border: 1px solid yellow;
 7085:   margin: -1px;
 7086: }
 7087: 
 7088: .LC_chrt_popup {
 7089:   border: 1px solid #8888FF;
 7090:   background: #CCCCFF;
 7091: }
 7092: 
 7093: table.LC_pick_box {
 7094:   border-collapse: separate;
 7095:   background: white;
 7096:   border: 1px solid black;
 7097:   border-spacing: 1px;
 7098: }
 7099: 
 7100: table.LC_pick_box td.LC_pick_box_title {
 7101:   background: $sidebg;
 7102:   font-weight: bold;
 7103:   text-align: left;
 7104:   vertical-align: top;
 7105:   width: 184px;
 7106:   padding: 8px;
 7107: }
 7108: 
 7109: table.LC_pick_box td.LC_pick_box_value {
 7110:   text-align: left;
 7111:   padding: 8px;
 7112: }
 7113: 
 7114: table.LC_pick_box td.LC_pick_box_select {
 7115:   text-align: left;
 7116:   padding: 8px;
 7117: }
 7118: 
 7119: table.LC_pick_box td.LC_pick_box_separator {
 7120:   padding: 0;
 7121:   height: 1px;
 7122:   background: black;
 7123: }
 7124: 
 7125: table.LC_pick_box td.LC_pick_box_submit {
 7126:   text-align: right;
 7127: }
 7128: 
 7129: table.LC_pick_box td.LC_evenrow_value {
 7130:   text-align: left;
 7131:   padding: 8px;
 7132:   background-color: $data_table_light;
 7133: }
 7134: 
 7135: table.LC_pick_box td.LC_oddrow_value {
 7136:   text-align: left;
 7137:   padding: 8px;
 7138:   background-color: $data_table_light;
 7139: }
 7140: 
 7141: span.LC_helpform_receipt_cat {
 7142:   font-weight: bold;
 7143: }
 7144: 
 7145: table.LC_group_priv_box {
 7146:   background: white;
 7147:   border: 1px solid black;
 7148:   border-spacing: 1px;
 7149: }
 7150: 
 7151: table.LC_group_priv_box td.LC_pick_box_title {
 7152:   background: $tabbg;
 7153:   font-weight: bold;
 7154:   text-align: right;
 7155:   width: 184px;
 7156: }
 7157: 
 7158: table.LC_group_priv_box td.LC_groups_fixed {
 7159:   background: $data_table_light;
 7160:   text-align: center;
 7161: }
 7162: 
 7163: table.LC_group_priv_box td.LC_groups_optional {
 7164:   background: $data_table_dark;
 7165:   text-align: center;
 7166: }
 7167: 
 7168: table.LC_group_priv_box td.LC_groups_functionality {
 7169:   background: $data_table_darker;
 7170:   text-align: center;
 7171:   font-weight: bold;
 7172: }
 7173: 
 7174: table.LC_group_priv td {
 7175:   text-align: left;
 7176:   padding: 0;
 7177: }
 7178: 
 7179: .LC_navbuttons {
 7180:   margin: 2ex 0ex 2ex 0ex;
 7181: }
 7182: 
 7183: .LC_topic_bar {
 7184:   font-weight: bold;
 7185:   background: $tabbg;
 7186:   margin: 1em 0em 1em 2em;
 7187:   padding: 3px;
 7188:   font-size: 1.2em;
 7189: }
 7190: 
 7191: .LC_topic_bar span {
 7192:   left: 0.5em;
 7193:   position: absolute;
 7194:   vertical-align: middle;
 7195:   font-size: 1.2em;
 7196: }
 7197: 
 7198: table.LC_course_group_status {
 7199:   margin: 20px;
 7200: }
 7201: 
 7202: table.LC_status_selector td {
 7203:   vertical-align: top;
 7204:   text-align: center;
 7205:   padding: 4px;
 7206: }
 7207: 
 7208: div.LC_feedback_link {
 7209:   clear: both;
 7210:   background: $sidebg;
 7211:   width: 100%;
 7212:   padding-bottom: 10px;
 7213:   border: 1px $tabbg solid;
 7214:   height: 22px;
 7215:   line-height: 22px;
 7216:   padding-top: 5px;
 7217: }
 7218: 
 7219: div.LC_feedback_link img {
 7220:   height: 22px;
 7221:   vertical-align:middle;
 7222: }
 7223: 
 7224: div.LC_feedback_link a {
 7225:   text-decoration: none;
 7226: }
 7227: 
 7228: div.LC_comblock {
 7229:   display:inline;
 7230:   color:$font;
 7231:   font-size:90%;
 7232: }
 7233: 
 7234: div.LC_feedback_link div.LC_comblock {
 7235:   padding-left:5px;
 7236: }
 7237: 
 7238: div.LC_feedback_link div.LC_comblock a {
 7239:   color:$font;
 7240: }
 7241: 
 7242: span.LC_feedback_link {
 7243:   /* background: $feedback_link_bg; */
 7244:   font-size: larger;
 7245: }
 7246: 
 7247: span.LC_message_link {
 7248:   /* background: $feedback_link_bg; */
 7249:   font-size: larger;
 7250:   position: absolute;
 7251:   right: 1em;
 7252: }
 7253: 
 7254: table.LC_prior_tries {
 7255:   border: 1px solid #000000;
 7256:   border-collapse: separate;
 7257:   border-spacing: 1px;
 7258: }
 7259: 
 7260: table.LC_prior_tries td {
 7261:   padding: 2px;
 7262: }
 7263: 
 7264: .LC_answer_correct {
 7265:   background: lightgreen;
 7266:   color: darkgreen;
 7267:   padding: 6px;
 7268: }
 7269: 
 7270: .LC_answer_charged_try {
 7271:   background: #FFAAAA;
 7272:   color: darkred;
 7273:   padding: 6px;
 7274: }
 7275: 
 7276: .LC_answer_not_charged_try,
 7277: .LC_answer_no_grade,
 7278: .LC_answer_late {
 7279:   background: lightyellow;
 7280:   color: black;
 7281:   padding: 6px;
 7282: }
 7283: 
 7284: .LC_answer_previous {
 7285:   background: lightblue;
 7286:   color: darkblue;
 7287:   padding: 6px;
 7288: }
 7289: 
 7290: .LC_answer_no_message {
 7291:   background: #FFFFFF;
 7292:   color: black;
 7293:   padding: 6px;
 7294: }
 7295: 
 7296: .LC_answer_unknown,
 7297: .LC_answer_warning {
 7298:   background: orange;
 7299:   color: black;
 7300:   padding: 6px;
 7301: }
 7302: 
 7303: span.LC_prior_numerical,
 7304: span.LC_prior_string,
 7305: span.LC_prior_custom,
 7306: span.LC_prior_reaction,
 7307: span.LC_prior_math {
 7308:   font-family: $mono;
 7309:   white-space: pre;
 7310: }
 7311: 
 7312: span.LC_prior_string {
 7313:   font-family: $mono;
 7314:   white-space: pre;
 7315: }
 7316: 
 7317: table.LC_prior_option {
 7318:   width: 100%;
 7319:   border-collapse: collapse;
 7320: }
 7321: 
 7322: table.LC_prior_rank,
 7323: table.LC_prior_match {
 7324:   border-collapse: collapse;
 7325: }
 7326: 
 7327: table.LC_prior_option tr td,
 7328: table.LC_prior_rank tr td,
 7329: table.LC_prior_match tr td {
 7330:   border: 1px solid #000000;
 7331: }
 7332: 
 7333: .LC_nobreak {
 7334:   white-space: nowrap;
 7335: }
 7336: 
 7337: span.LC_cusr_emph {
 7338:   font-style: italic;
 7339: }
 7340: 
 7341: span.LC_cusr_subheading {
 7342:   font-weight: normal;
 7343:   font-size: 85%;
 7344: }
 7345: 
 7346: div.LC_docs_entry_move {
 7347:   border: 1px solid #BBBBBB;
 7348:   background: #DDDDDD;
 7349:   width: 22px;
 7350:   padding: 1px;
 7351:   margin: 0;
 7352: }
 7353: 
 7354: table.LC_data_table tr > td.LC_docs_entry_commands,
 7355: table.LC_data_table tr > td.LC_docs_entry_parameter {
 7356:   font-size: x-small;
 7357: }
 7358: 
 7359: .LC_docs_entry_parameter {
 7360:   white-space: nowrap;
 7361: }
 7362: 
 7363: .LC_docs_copy {
 7364:   color: #000099;
 7365: }
 7366: 
 7367: .LC_docs_cut {
 7368:   color: #550044;
 7369: }
 7370: 
 7371: .LC_docs_rename {
 7372:   color: #009900;
 7373: }
 7374: 
 7375: .LC_docs_remove {
 7376:   color: #990000;
 7377: }
 7378: 
 7379: .LC_domprefs_email,
 7380: .LC_docs_reinit_warn,
 7381: .LC_docs_ext_edit {
 7382:   font-size: x-small;
 7383: }
 7384: 
 7385: table.LC_docs_adddocs td,
 7386: table.LC_docs_adddocs th {
 7387:   border: 1px solid #BBBBBB;
 7388:   padding: 4px;
 7389:   background: #DDDDDD;
 7390: }
 7391: 
 7392: table.LC_sty_begin {
 7393:   background: #BBFFBB;
 7394: }
 7395: 
 7396: table.LC_sty_end {
 7397:   background: #FFBBBB;
 7398: }
 7399: 
 7400: table.LC_double_column {
 7401:   border-width: 0;
 7402:   border-collapse: collapse;
 7403:   width: 100%;
 7404:   padding: 2px;
 7405: }
 7406: 
 7407: table.LC_double_column tr td.LC_left_col {
 7408:   top: 2px;
 7409:   left: 2px;
 7410:   width: 47%;
 7411:   vertical-align: top;
 7412: }
 7413: 
 7414: table.LC_double_column tr td.LC_right_col {
 7415:   top: 2px;
 7416:   right: 2px;
 7417:   width: 47%;
 7418:   vertical-align: top;
 7419: }
 7420: 
 7421: div.LC_left_float {
 7422:   float: left;
 7423:   padding-right: 5%;
 7424:   padding-bottom: 4px;
 7425: }
 7426: 
 7427: div.LC_clear_float_header {
 7428:   padding-bottom: 2px;
 7429: }
 7430: 
 7431: div.LC_clear_float_footer {
 7432:   padding-top: 10px;
 7433:   clear: both;
 7434: }
 7435: 
 7436: div.LC_grade_show_user {
 7437: /*  border-left: 5px solid $sidebg; */
 7438:   border-top: 5px solid #000000;
 7439:   margin: 50px 0 0 0;
 7440:   padding: 15px 0 5px 10px;
 7441: }
 7442: 
 7443: div.LC_grade_show_user_odd_row {
 7444: /*  border-left: 5px solid #000000; */
 7445: }
 7446: 
 7447: div.LC_grade_show_user div.LC_Box {
 7448:   margin-right: 50px;
 7449: }
 7450: 
 7451: div.LC_grade_submissions,
 7452: div.LC_grade_message_center,
 7453: div.LC_grade_info_links {
 7454:   margin: 5px;
 7455:   width: 99%;
 7456:   background: #FFFFFF;
 7457: }
 7458: 
 7459: div.LC_grade_submissions_header,
 7460: div.LC_grade_message_center_header {
 7461:   font-weight: bold;
 7462:   font-size: large;
 7463: }
 7464: 
 7465: div.LC_grade_submissions_body,
 7466: div.LC_grade_message_center_body {
 7467:   border: 1px solid black;
 7468:   width: 99%;
 7469:   background: #FFFFFF;
 7470: }
 7471: 
 7472: table.LC_scantron_action {
 7473:   width: 100%;
 7474: }
 7475: 
 7476: table.LC_scantron_action tr th {
 7477:   font-weight:bold;
 7478:   font-style:normal;
 7479: }
 7480: 
 7481: .LC_edit_problem_header,
 7482: div.LC_edit_problem_footer {
 7483:   font-weight: normal;
 7484:   font-size:  medium;
 7485:   margin: 2px;
 7486:   background-color: $sidebg;
 7487: }
 7488: 
 7489: div.LC_edit_problem_header,
 7490: div.LC_edit_problem_header div,
 7491: div.LC_edit_problem_footer,
 7492: div.LC_edit_problem_footer div,
 7493: div.LC_edit_problem_editxml_header,
 7494: div.LC_edit_problem_editxml_header div {
 7495:   z-index: 100;
 7496: }
 7497: 
 7498: div.LC_edit_problem_header_title {
 7499:   font-weight: bold;
 7500:   font-size: larger;
 7501:   background: $tabbg;
 7502:   padding: 3px;
 7503:   margin: 0 0 5px 0;
 7504: }
 7505: 
 7506: table.LC_edit_problem_header_title {
 7507:   width: 100%;
 7508:   background: $tabbg;
 7509: }
 7510: 
 7511: div.LC_edit_actionbar {
 7512:     background-color: $sidebg;
 7513:     margin: 0;
 7514:     padding: 0;
 7515:     line-height: 200%;
 7516: }
 7517: 
 7518: div.LC_edit_actionbar div{
 7519:     padding: 0;
 7520:     margin: 0;
 7521:     display: inline-block;
 7522: }
 7523: 
 7524: .LC_edit_opt {
 7525:   padding-left: 1em;
 7526:   white-space: nowrap;
 7527: }
 7528: 
 7529: .LC_edit_problem_latexhelper{
 7530:     text-align: right;
 7531: }
 7532: 
 7533: #LC_edit_problem_colorful div{
 7534:     margin-left: 40px;
 7535: }
 7536: 
 7537: #LC_edit_problem_codemirror div{
 7538:     margin-left: 0px;
 7539: }
 7540: 
 7541: img.stift {
 7542:   border-width: 0;
 7543:   vertical-align: middle;
 7544: }
 7545: 
 7546: table td.LC_mainmenu_col_fieldset {
 7547:   vertical-align: top;
 7548: }
 7549: 
 7550: div.LC_createcourse {
 7551:   margin: 10px 10px 10px 10px;
 7552: }
 7553: 
 7554: .LC_dccid {
 7555:   float: right;
 7556:   margin: 0.2em 0 0 0;
 7557:   padding: 0;
 7558:   font-size: 90%;
 7559:   display:none;
 7560: }
 7561: 
 7562: ol.LC_primary_menu a:hover,
 7563: ol#LC_MenuBreadcrumbs a:hover,
 7564: ol#LC_PathBreadcrumbs a:hover,
 7565: ul#LC_secondary_menu a:hover,
 7566: .LC_FormSectionClearButton input:hover
 7567: ul.LC_TabContent   li:hover a {
 7568:   color:$button_hover;
 7569:   text-decoration:none;
 7570: }
 7571: 
 7572: h1 {
 7573:   padding: 0;
 7574:   line-height:130%;
 7575: }
 7576: 
 7577: h2,
 7578: h3,
 7579: h4,
 7580: h5,
 7581: h6 {
 7582:   margin: 5px 0 5px 0;
 7583:   padding: 0;
 7584:   line-height:130%;
 7585: }
 7586: 
 7587: .LC_hcell {
 7588:   padding:3px 15px 3px 15px;
 7589:   margin: 0;
 7590:   background-color:$tabbg;
 7591:   color:$fontmenu;
 7592:   border-bottom:solid 1px $lg_border_color;
 7593: }
 7594: 
 7595: .LC_Box > .LC_hcell {
 7596:   margin: 0 -10px 10px -10px;
 7597: }
 7598: 
 7599: .LC_noBorder {
 7600:   border: 0;
 7601: }
 7602: 
 7603: .LC_FormSectionClearButton input {
 7604:   background-color:transparent;
 7605:   border: none;
 7606:   cursor:pointer;
 7607:   text-decoration:underline;
 7608: }
 7609: 
 7610: .LC_help_open_topic {
 7611:   color: #FFFFFF;
 7612:   background-color: #EEEEFF;
 7613:   margin: 1px;
 7614:   padding: 4px;
 7615:   border: 1px solid #000033;
 7616:   white-space: nowrap;
 7617:   /* vertical-align: middle; */
 7618: }
 7619: 
 7620: dl,
 7621: ul,
 7622: div,
 7623: fieldset {
 7624:   margin: 10px 10px 10px 0;
 7625:   /* overflow: hidden; */
 7626: }
 7627: 
 7628: article.geogebraweb div {
 7629:     margin: 0;
 7630: }
 7631: 
 7632: fieldset > legend {
 7633:   font-weight: bold;
 7634:   padding: 0 5px 0 5px;
 7635: }
 7636: 
 7637: #LC_nav_bar {
 7638:   float: left;
 7639:   background-color: $pgbg_or_bgcolor;
 7640:   margin: 0 0 2px 0;
 7641: }
 7642: 
 7643: #LC_realm {
 7644:   margin: 0.2em 0 0 0;
 7645:   padding: 0;
 7646:   font-weight: bold;
 7647:   text-align: center;
 7648:   background-color: $pgbg_or_bgcolor;
 7649: }
 7650: 
 7651: #LC_nav_bar em {
 7652:   font-weight: bold;
 7653:   font-style: normal;
 7654: }
 7655: 
 7656: ol.LC_primary_menu {
 7657:   margin: 0;
 7658:   padding: 0;
 7659: }
 7660: 
 7661: ol#LC_PathBreadcrumbs {
 7662:   margin: 0;
 7663: }
 7664: 
 7665: ol.LC_primary_menu li {
 7666:   color: RGB(80, 80, 80);
 7667:   vertical-align: middle;
 7668:   text-align: left;
 7669:   list-style: none;
 7670:   position: relative;
 7671:   float: left;
 7672:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
 7673:   line-height: 1.5em;
 7674: }
 7675: 
 7676: ol.LC_primary_menu li a, 
 7677: ol.LC_primary_menu li p {
 7678:   display: block;
 7679:   margin: 0;
 7680:   padding: 0 5px 0 10px;
 7681:   text-decoration: none;
 7682: }
 7683: 
 7684: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
 7685:   display: inline-block;
 7686:   width: 95%;
 7687:   text-align: left;
 7688: }
 7689: 
 7690: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
 7691:   display: inline-block;
 7692:   width: 5%;
 7693:   float: right;
 7694:   text-align: right;
 7695:   font-size: 70%;
 7696: }
 7697: 
 7698: ol.LC_primary_menu ul {
 7699:   display: none;
 7700:   width: 15em;
 7701:   background-color: $data_table_light;
 7702:   position: absolute;
 7703:   top: 100%;
 7704: }
 7705: 
 7706: ol.LC_primary_menu ul ul {
 7707:   left: 100%;
 7708:   top: 0;
 7709: }
 7710: 
 7711: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
 7712:   display: block;
 7713:   position: absolute;
 7714:   margin: 0;
 7715:   padding: 0;
 7716:   z-index: 2;
 7717: }
 7718: 
 7719: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 7720: /* First Submenu -> size should be smaller than the menu title of the whole menu */
 7721:   font-size: 90%;
 7722:   vertical-align: top;
 7723:   float: none;
 7724:   border-left: 1px solid black;
 7725:   border-right: 1px solid black;
 7726: /* A dark bottom border to visualize different menu options;
 7727: overwritten in the create_submenu routine for the last border-bottom of the menu */
 7728:   border-bottom: 1px solid $data_table_dark;
 7729: }
 7730: 
 7731: ol.LC_primary_menu li li p:hover {
 7732:   color:$button_hover;
 7733:   text-decoration:none;
 7734:   background-color:$data_table_dark;
 7735: }
 7736: 
 7737: ol.LC_primary_menu li li a:hover {
 7738:    color:$button_hover;
 7739:    background-color:$data_table_dark;
 7740: }
 7741: 
 7742: /* Font-size equal to the size of the predecessors*/
 7743: ol.LC_primary_menu li:hover li li {
 7744:   font-size: 100%;
 7745: }
 7746: 
 7747: ol.LC_primary_menu li img {
 7748:   vertical-align: bottom;
 7749:   height: 1.1em;
 7750:   margin: 0.2em 0 0 0;
 7751: }
 7752: 
 7753: ol.LC_primary_menu a {
 7754:   color: RGB(80, 80, 80);
 7755:   text-decoration: none;
 7756: }
 7757: 
 7758: ol.LC_primary_menu a.LC_new_message {
 7759:   font-weight:bold;
 7760:   color: darkred;
 7761: }
 7762: 
 7763: ol.LC_docs_parameters {
 7764:   margin-left: 0;
 7765:   padding: 0;
 7766:   list-style: none;
 7767: }
 7768: 
 7769: ol.LC_docs_parameters li {
 7770:   margin: 0;
 7771:   padding-right: 20px;
 7772:   display: inline;
 7773: }
 7774: 
 7775: ol.LC_docs_parameters li:before {
 7776:   content: "\\002022 \\0020";
 7777: }
 7778: 
 7779: li.LC_docs_parameters_title {
 7780:   font-weight: bold;
 7781: }
 7782: 
 7783: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 7784:   content: "";
 7785: }
 7786: 
 7787: ul#LC_secondary_menu {
 7788:   clear: right;
 7789:   color: $fontmenu;
 7790:   background: $tabbg;
 7791:   list-style: none;
 7792:   padding: 0;
 7793:   margin: 0;
 7794:   width: 100%;
 7795:   text-align: left;
 7796:   float: left;
 7797: }
 7798: 
 7799: ul#LC_secondary_menu li {
 7800:   font-weight: bold;
 7801:   line-height: 1.8em;
 7802:   border-right: 1px solid black;
 7803:   float: left;
 7804: }
 7805: 
 7806: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 7807:   background-color: $data_table_light;
 7808: }
 7809: 
 7810: ul#LC_secondary_menu li a {
 7811:   padding: 0 0.8em;
 7812: }
 7813: 
 7814: ul#LC_secondary_menu li ul {
 7815:   display: none;
 7816: }
 7817: 
 7818: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 7819:   display: block;
 7820:   position: absolute;
 7821:   margin: 0;
 7822:   padding: 0;
 7823:   list-style:none;
 7824:   float: none;
 7825:   background-color: $data_table_light;
 7826:   z-index: 2;
 7827:   margin-left: -1px;
 7828: }
 7829: 
 7830: ul#LC_secondary_menu li ul li {
 7831:   font-size: 90%;
 7832:   vertical-align: top;
 7833:   border-left: 1px solid black;
 7834:   border-right: 1px solid black;
 7835:   background-color: $data_table_light;
 7836:   list-style:none;
 7837:   float: none;
 7838: }
 7839: 
 7840: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 7841:   background-color: $data_table_dark;
 7842: }
 7843: 
 7844: ul.LC_TabContent {
 7845:   display:block;
 7846:   background: $sidebg;
 7847:   border-bottom: solid 1px $lg_border_color;
 7848:   list-style:none;
 7849:   margin: -1px -10px 0 -10px;
 7850:   padding: 0;
 7851: }
 7852: 
 7853: ul.LC_TabContent li,
 7854: ul.LC_TabContentBigger li {
 7855:   float:left;
 7856: }
 7857: 
 7858: ul#LC_secondary_menu li a {
 7859:   color: $fontmenu;
 7860:   text-decoration: none;
 7861: }
 7862: 
 7863: ul.LC_TabContent {
 7864:   min-height:20px;
 7865: }
 7866: 
 7867: ul.LC_TabContent li {
 7868:   vertical-align:middle;
 7869:   padding: 0 16px 0 10px;
 7870:   background-color:$tabbg;
 7871:   border-bottom:solid 1px $lg_border_color;
 7872:   border-left: solid 1px $font;
 7873: }
 7874: 
 7875: ul.LC_TabContent .right {
 7876:   float:right;
 7877: }
 7878: 
 7879: ul.LC_TabContent li a,
 7880: ul.LC_TabContent li {
 7881:   color:rgb(47,47,47);
 7882:   text-decoration:none;
 7883:   font-size:95%;
 7884:   font-weight:bold;
 7885:   min-height:20px;
 7886: }
 7887: 
 7888: ul.LC_TabContent li a:hover,
 7889: ul.LC_TabContent li a:focus {
 7890:   color: $button_hover;
 7891:   background:none;
 7892:   outline:none;
 7893: }
 7894: 
 7895: ul.LC_TabContent li:hover {
 7896:   color: $button_hover;
 7897:   cursor:pointer;
 7898: }
 7899: 
 7900: ul.LC_TabContent li.active {
 7901:   color: $font;
 7902:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 7903:   border-bottom:solid 1px #FFFFFF;
 7904:   cursor: default;
 7905: }
 7906: 
 7907: ul.LC_TabContent li.active a {
 7908:   color:$font;
 7909:   background:#FFFFFF;
 7910:   outline: none;
 7911: }
 7912: 
 7913: ul.LC_TabContent li.goback {
 7914:   float: left;
 7915:   border-left: none;
 7916: }
 7917: 
 7918: #maincoursedoc {
 7919:   clear:both;
 7920: }
 7921: 
 7922: ul.LC_TabContentBigger {
 7923:   display:block;
 7924:   list-style:none;
 7925:   padding: 0;
 7926: }
 7927: 
 7928: ul.LC_TabContentBigger li {
 7929:   vertical-align:bottom;
 7930:   height: 30px;
 7931:   font-size:110%;
 7932:   font-weight:bold;
 7933:   color: #737373;
 7934: }
 7935: 
 7936: ul.LC_TabContentBigger li.active {
 7937:   position: relative;
 7938:   top: 1px;
 7939: }
 7940: 
 7941: ul.LC_TabContentBigger li a {
 7942:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 7943:   height: 30px;
 7944:   line-height: 30px;
 7945:   text-align: center;
 7946:   display: block;
 7947:   text-decoration: none;
 7948:   outline: none;  
 7949: }
 7950: 
 7951: ul.LC_TabContentBigger li.active a {
 7952:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 7953:   color:$font;
 7954: }
 7955: 
 7956: ul.LC_TabContentBigger li b {
 7957:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 7958:   display: block;
 7959:   float: left;
 7960:   padding: 0 30px;
 7961:   border-bottom: 1px solid $lg_border_color;
 7962: }
 7963: 
 7964: ul.LC_TabContentBigger li:hover b {
 7965:   color:$button_hover;
 7966: }
 7967: 
 7968: ul.LC_TabContentBigger li.active b {
 7969:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 7970:   color:$font;
 7971:   border: 0;
 7972: }
 7973: 
 7974: 
 7975: ul.LC_CourseBreadcrumbs {
 7976:   background: $sidebg;
 7977:   height: 2em;
 7978:   padding-left: 10px;
 7979:   margin: 0;
 7980:   list-style-position: inside;
 7981: }
 7982: 
 7983: ol#LC_MenuBreadcrumbs,
 7984: ol#LC_PathBreadcrumbs {
 7985:   padding-left: 10px;
 7986:   margin: 0;
 7987:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 7988: }
 7989: 
 7990: ol#LC_MenuBreadcrumbs li,
 7991: ol#LC_PathBreadcrumbs li,
 7992: ul.LC_CourseBreadcrumbs li {
 7993:   display: inline;
 7994:   white-space: normal;  
 7995: }
 7996: 
 7997: ol#LC_MenuBreadcrumbs li a,
 7998: ul.LC_CourseBreadcrumbs li a {
 7999:   text-decoration: none;
 8000:   font-size:90%;
 8001: }
 8002: 
 8003: ol#LC_MenuBreadcrumbs h1 {
 8004:   display: inline;
 8005:   font-size: 90%;
 8006:   line-height: 2.5em;
 8007:   margin: 0;
 8008:   padding: 0;
 8009: }
 8010: 
 8011: ol#LC_PathBreadcrumbs li a {
 8012:   text-decoration:none;
 8013:   font-size:100%;
 8014:   font-weight:bold;
 8015: }
 8016: 
 8017: .LC_Box {
 8018:   border: solid 1px $lg_border_color;
 8019:   padding: 0 10px 10px 10px;
 8020: }
 8021: 
 8022: .LC_DocsBox {
 8023:   border: solid 1px $lg_border_color;
 8024:   padding: 0 0 10px 10px;
 8025: }
 8026: 
 8027: .LC_AboutMe_Image {
 8028:   float:left;
 8029:   margin-right:10px;
 8030: }
 8031: 
 8032: .LC_Clear_AboutMe_Image {
 8033:   clear:left;
 8034: }
 8035: 
 8036: dl.LC_ListStyleClean dt {
 8037:   padding-right: 5px;
 8038:   display: table-header-group;
 8039: }
 8040: 
 8041: dl.LC_ListStyleClean dd {
 8042:   display: table-row;
 8043: }
 8044: 
 8045: .LC_ListStyleClean,
 8046: .LC_ListStyleSimple,
 8047: .LC_ListStyleNormal,
 8048: .LC_ListStyleSpecial {
 8049:   /* display:block; */
 8050:   list-style-position: inside;
 8051:   list-style-type: none;
 8052:   overflow: hidden;
 8053:   padding: 0;
 8054: }
 8055: 
 8056: .LC_ListStyleSimple li,
 8057: .LC_ListStyleSimple dd,
 8058: .LC_ListStyleNormal li,
 8059: .LC_ListStyleNormal dd,
 8060: .LC_ListStyleSpecial li,
 8061: .LC_ListStyleSpecial dd {
 8062:   margin: 0;
 8063:   padding: 5px 5px 5px 10px;
 8064:   clear: both;
 8065: }
 8066: 
 8067: .LC_ListStyleClean li,
 8068: .LC_ListStyleClean dd {
 8069:   padding-top: 0;
 8070:   padding-bottom: 0;
 8071: }
 8072: 
 8073: .LC_ListStyleSimple dd,
 8074: .LC_ListStyleSimple li {
 8075:   border-bottom: solid 1px $lg_border_color;
 8076: }
 8077: 
 8078: .LC_ListStyleSpecial li,
 8079: .LC_ListStyleSpecial dd {
 8080:   list-style-type: none;
 8081:   background-color: RGB(220, 220, 220);
 8082:   margin-bottom: 4px;
 8083: }
 8084: 
 8085: table.LC_SimpleTable {
 8086:   margin:5px;
 8087:   border:solid 1px $lg_border_color;
 8088: }
 8089: 
 8090: table.LC_SimpleTable tr {
 8091:   padding: 0;
 8092:   border:solid 1px $lg_border_color;
 8093: }
 8094: 
 8095: table.LC_SimpleTable thead {
 8096:   background:rgb(220,220,220);
 8097: }
 8098: 
 8099: div.LC_columnSection {
 8100:   display: block;
 8101:   clear: both;
 8102:   overflow: hidden;
 8103:   margin: 0;
 8104: }
 8105: 
 8106: div.LC_columnSection>* {
 8107:   float: left;
 8108:   margin: 10px 20px 10px 0;
 8109:   overflow:hidden;
 8110: }
 8111: 
 8112: table em {
 8113:   font-weight: bold;
 8114:   font-style: normal;
 8115: }
 8116: 
 8117: table.LC_tableBrowseRes,
 8118: table.LC_tableOfContent {
 8119:   border:none;
 8120:   border-spacing: 1px;
 8121:   padding: 3px;
 8122:   background-color: #FFFFFF;
 8123:   font-size: 90%;
 8124: }
 8125: 
 8126: table.LC_tableOfContent {
 8127:   border-collapse: collapse;
 8128: }
 8129: 
 8130: table.LC_tableBrowseRes a,
 8131: table.LC_tableOfContent a {
 8132:   background-color: transparent;
 8133:   text-decoration: none;
 8134: }
 8135: 
 8136: table.LC_tableOfContent img {
 8137:   border: none;
 8138:   height: 1.3em;
 8139:   vertical-align: text-bottom;
 8140:   margin-right: 0.3em;
 8141: }
 8142: 
 8143: a#LC_content_toolbar_firsthomework {
 8144:   background-image:url(/res/adm/pages/open-first-problem.gif);
 8145: }
 8146: 
 8147: a#LC_content_toolbar_everything {
 8148:   background-image:url(/res/adm/pages/show-all.gif);
 8149: }
 8150: 
 8151: a#LC_content_toolbar_uncompleted {
 8152:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 8153: }
 8154: 
 8155: #LC_content_toolbar_clearbubbles {
 8156:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 8157: }
 8158: 
 8159: a#LC_content_toolbar_changefolder {
 8160:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 8161: }
 8162: 
 8163: a#LC_content_toolbar_changefolder_toggled {
 8164:   background-image:url(/res/adm/pages/open-all-folders.gif);
 8165: }
 8166: 
 8167: a#LC_content_toolbar_edittoplevel {
 8168:   background-image:url(/res/adm/pages/edittoplevel.gif);
 8169: }
 8170: 
 8171: ul#LC_toolbar li a:hover {
 8172:   background-position: bottom center;
 8173: }
 8174: 
 8175: ul#LC_toolbar {
 8176:   padding: 0;
 8177:   margin: 2px;
 8178:   list-style:none;
 8179:   position:relative;
 8180:   background-color:white;
 8181:   overflow: auto;
 8182: }
 8183: 
 8184: ul#LC_toolbar li {
 8185:   border:1px solid white;
 8186:   padding: 0;
 8187:   margin: 0;
 8188:   float: left;
 8189:   display:inline;
 8190:   vertical-align:middle;
 8191:   white-space: nowrap;
 8192: }
 8193: 
 8194: 
 8195: a.LC_toolbarItem {
 8196:   display:block;
 8197:   padding: 0;
 8198:   margin: 0;
 8199:   height: 32px;
 8200:   width: 32px;
 8201:   color:white;
 8202:   border: none;
 8203:   background-repeat:no-repeat;
 8204:   background-color:transparent;
 8205: }
 8206: 
 8207: ul.LC_funclist {
 8208:     margin: 0;
 8209:     padding: 0.5em 1em 0.5em 0;
 8210: }
 8211: 
 8212: ul.LC_funclist > li:first-child {
 8213:     font-weight:bold; 
 8214:     margin-left:0.8em;
 8215: }
 8216: 
 8217: ul.LC_funclist + ul.LC_funclist {
 8218:     /* 
 8219:        left border as a seperator if we have more than
 8220:        one list 
 8221:     */
 8222:     border-left: 1px solid $sidebg;
 8223:     /* 
 8224:        this hides the left border behind the border of the 
 8225:        outer box if element is wrapped to the next 'line' 
 8226:     */
 8227:     margin-left: -1px;
 8228: }
 8229: 
 8230: ul.LC_funclist li {
 8231:   display: inline;
 8232:   white-space: nowrap;
 8233:   margin: 0 0 0 25px;
 8234:   line-height: 150%;
 8235: }
 8236: 
 8237: .LC_hidden {
 8238:   display: none;
 8239: }
 8240: 
 8241: .LCmodal-overlay {
 8242: 		position:fixed;
 8243: 		top:0;
 8244: 		right:0;
 8245: 		bottom:0;
 8246: 		left:0;
 8247: 		height:100%;
 8248: 		width:100%;
 8249: 		margin:0;
 8250: 		padding:0;
 8251: 		background:#999;
 8252: 		opacity:.75;
 8253: 		filter: alpha(opacity=75);
 8254: 		-moz-opacity: 0.75;
 8255: 		z-index:101;
 8256: }
 8257: 
 8258: * html .LCmodal-overlay {   
 8259: 		position: absolute;
 8260: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 8261: }
 8262: 
 8263: .LCmodal-window {
 8264: 		position:fixed;
 8265: 		top:50%;
 8266: 		left:50%;
 8267: 		margin:0;
 8268: 		padding:0;
 8269: 		z-index:102;
 8270: 	}
 8271: 
 8272: * html .LCmodal-window {
 8273: 		position:absolute;
 8274: }
 8275: 
 8276: .LCclose-window {
 8277: 		position:absolute;
 8278: 		width:32px;
 8279: 		height:32px;
 8280: 		right:8px;
 8281: 		top:8px;
 8282: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 8283: 		text-indent:-99999px;
 8284: 		overflow:hidden;
 8285: 		cursor:pointer;
 8286: }
 8287: 
 8288: .LCisDisabled {
 8289:   cursor: not-allowed;
 8290:   opacity: 0.5;
 8291: }
 8292: 
 8293: a[aria-disabled="true"] {
 8294:   color: currentColor;
 8295:   display: inline-block;  /* For IE11/ MS Edge bug */
 8296:   pointer-events: none;
 8297:   text-decoration: none;
 8298: }
 8299: 
 8300: pre.LC_wordwrap {
 8301:   white-space: pre-wrap;
 8302:   white-space: -moz-pre-wrap;
 8303:   white-space: -pre-wrap;
 8304:   white-space: -o-pre-wrap;
 8305:   word-wrap: break-word;
 8306: }
 8307: 
 8308: /*
 8309:   styles used by TTH when "Default set of options to pass to tth/m
 8310:   when converting TeX" in course settings has been set
 8311: 
 8312:   option passed: -t
 8313: 
 8314: */
 8315: 
 8316: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 8317: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 8318: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 8319: td div.norm {line-height:normal;}
 8320: 
 8321: /*
 8322:   option passed -y3
 8323: */
 8324: 
 8325: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 8326: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 8327: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 8328: 
 8329: #LC_minitab_header {
 8330:   float:left;
 8331:   width:100%;
 8332:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
 8333:   font-size:93%;
 8334:   line-height:normal;
 8335:   margin: 0.5em 0 0.5em 0;
 8336: }
 8337: #LC_minitab_header ul {
 8338:   margin:0;
 8339:   padding:10px 10px 0;
 8340:   list-style:none;
 8341: }
 8342: #LC_minitab_header li {
 8343:   float:left;
 8344:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
 8345:   margin:0;
 8346:   padding:0 0 0 9px;
 8347: }
 8348: #LC_minitab_header a {
 8349:   display:block;
 8350:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
 8351:   padding:5px 15px 4px 6px;
 8352: }
 8353: #LC_minitab_header #LC_current_minitab {
 8354:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
 8355: }
 8356: #LC_minitab_header #LC_current_minitab a {
 8357:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
 8358:   padding-bottom:5px;
 8359: }
 8360: 
 8361: 
 8362: END
 8363: }
 8364: 
 8365: =pod
 8366: 
 8367: =item * &headtag()
 8368: 
 8369: Returns a uniform footer for LON-CAPA web pages.
 8370: 
 8371: Inputs: $title - optional title for the head
 8372:         $head_extra - optional extra HTML to put inside the <head>
 8373:         $args - optional arguments
 8374:             force_register - if is true call registerurl so the remote is 
 8375:                              informed
 8376:             redirect       -> array ref of
 8377:                                    1- seconds before redirect occurs
 8378:                                    2- url to redirect to
 8379:                                    3- whether the side effect should occur
 8380:                            (side effect of setting 
 8381:                                $env{'internal.head.redirect'} to the url 
 8382:                                redirected to)
 8383:                                    4- whether the redirect target should be
 8384:                                       the opener of the current (pop-up)
 8385:                                       window (side effect of setting
 8386:                                       $env{'internal.head.to_opener'} to
 8387:                                       1, if true.
 8388:                                    5- whether encrypt check should be skipped
 8389:             domain         -> force to color decorate a page for a specific
 8390:                                domain
 8391:             function       -> force usage of a specific rolish color scheme
 8392:             bgcolor        -> override the default page bgcolor
 8393:             no_auto_mt_title
 8394:                            -> prevent &mt()ing the title arg
 8395: 
 8396: =cut
 8397: 
 8398: sub headtag {
 8399:     my ($title,$head_extra,$args) = @_;
 8400:     
 8401:     my $function = $args->{'function'} || &get_users_function();
 8402:     my $domain   = $args->{'domain'}   || &determinedomain();
 8403:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 8404:     my $httphost = $args->{'use_absolute'};
 8405:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 8406: 		   $Apache::lonnet::perlvar{'lonVersion'},
 8407: 		   #time(),
 8408: 		   $env{'environment.color.timestamp'},
 8409: 		   $function,$domain,$bgcolor);
 8410: 
 8411:     $url = '/adm/css/'.&escape($url).'.css';
 8412: 
 8413:     my $result =
 8414: 	'<head>'.
 8415: 	&font_settings($args);
 8416: 
 8417:     my $inhibitprint;
 8418:     if ($args->{'print_suppress'}) {
 8419:         $inhibitprint = &print_suppression();
 8420:     }
 8421: 
 8422:     if (!$args->{'frameset'}) {
 8423: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 8424:     }
 8425:     if ($args->{'force_register'}) {
 8426:         $result .= &Apache::lonmenu::registerurl(1);
 8427:     }
 8428:     if (!$args->{'no_nav_bar'} 
 8429: 	&& !$args->{'only_body'}
 8430: 	&& !$args->{'frameset'}) {
 8431: 	$result .= &help_menu_js($httphost);
 8432:         $result.=&modal_window();
 8433:         $result.=&togglebox_script();
 8434:         $result.=&wishlist_window();
 8435:         $result.=&LCprogressbarUpdate_script();
 8436:     } else {
 8437:         if ($args->{'add_modal'}) {
 8438:            $result.=&modal_window();
 8439:         }
 8440:         if ($args->{'add_wishlist'}) {
 8441:            $result.=&wishlist_window();
 8442:         }
 8443:         if ($args->{'add_togglebox'}) {
 8444:            $result.=&togglebox_script();
 8445:         }
 8446:         if ($args->{'add_progressbar'}) {
 8447:            $result.=&LCprogressbarUpdate_script();
 8448:         }
 8449:     }
 8450:     if (ref($args->{'redirect'})) {
 8451: 	my ($time,$url,$inhibit_continue,$to_opener,$skip_enc_check) = @{$args->{'redirect'}};
 8452:         if (!$skip_enc_check) {
 8453: 	    $url = &Apache::lonenc::check_encrypt($url);
 8454:         }
 8455: 	if (!$inhibit_continue) {
 8456: 	    $env{'internal.head.redirect'} = $url;
 8457: 	}
 8458:         $result.=<<"ADDMETA";
 8459: <meta http-equiv="pragma" content="no-cache" />
 8460: ADDMETA
 8461:         if ($to_opener) {
 8462:             $env{'internal.head.to_opener'} = 1;
 8463:             my $dest = &js_escape($url);
 8464:             my $timeout = int($time * 1000);
 8465:             $result .=<<"ENDJS";
 8466: <script type="text/javascript">
 8467: // <![CDATA[
 8468: function LC_To_Opener() {
 8469:     var dest = '$dest';
 8470:     if (dest != '') {
 8471:         if (window.opener != null && !window.opener.closed) {
 8472:             window.opener.location.href=dest;
 8473:             window.close();
 8474:         } else {
 8475:             window.location.href=dest;
 8476:         }
 8477:     }
 8478: }
 8479: \$(document).ready(function () {
 8480:     setTimeout('LC_To_Opener()',$timeout);
 8481: });
 8482: // ]]>
 8483: </script>
 8484: ENDJS
 8485:         } else {
 8486:             $result.=<<"ADDMETA";
 8487: <meta http-equiv="Refresh" content="$time; url=$url" />
 8488: ADDMETA
 8489:         }
 8490:     } else {
 8491:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
 8492:             my $requrl = $env{'request.uri'};
 8493:             if ($requrl eq '') {
 8494:                 $requrl = $ENV{'REQUEST_URI'};
 8495:                 $requrl =~ s/\?.+$//;
 8496:             }
 8497:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
 8498:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
 8499:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
 8500:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
 8501:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
 8502:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
 8503:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 8504:                     my ($offload,$offloadoth);
 8505:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
 8506:                         if ($domdefs{'offloadnow'}{$lonhost}) {
 8507:                             $offload = 1;
 8508:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
 8509:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
 8510:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
 8511:                                     $offloadoth = 1;
 8512:                                     $dom_in_use = $env{'user.domain'};
 8513:                                 }
 8514:                             }
 8515:                         }
 8516:                     }
 8517:                     unless ($offload) {
 8518:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
 8519:                             if ($domdefs{'offloadoth'}{$lonhost}) {
 8520:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
 8521:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
 8522:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
 8523:                                         $offload = 1;
 8524:                                         $offloadoth = 1;
 8525:                                         $dom_in_use = $env{'user.domain'};
 8526:                                     }
 8527:                                 }
 8528:                             }
 8529:                         }
 8530:                     }
 8531:                     if ($offload) {
 8532:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
 8533:                         if (($newserver eq '') && ($offloadoth)) {
 8534:                             my @domains = &Apache::lonnet::current_machine_domains();
 8535:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) {
 8536:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
 8537:                             }
 8538:                         }
 8539:                         if (($newserver) && ($newserver ne $lonhost)) {
 8540:                             my $numsec = 5;
 8541:                             my $timeout = $numsec * 1000;
 8542:                             my ($newurl,$locknum,%locks,$msg);
 8543:                             if ($env{'request.role.adv'}) {
 8544:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
 8545:                             }
 8546:                             my $disable_submit = 0;
 8547:                             if ($requrl =~ /$LONCAPA::assess_re/) {
 8548:                                 $disable_submit = 1;
 8549:                             }
 8550:                             if ($locknum) {
 8551:                                 my @lockinfo = sort(values(%locks));
 8552:                                 $msg = &mt('Once the following tasks are complete:')." \n".
 8553:                                        join(", ",sort(values(%locks)))."\n";
 8554:                                 if (&show_course()) {
 8555:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
 8556:                                 } else {
 8557:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
 8558:                                 }
 8559:                             } else {
 8560:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
 8561:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
 8562:                                 }
 8563:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
 8564:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
 8565:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
 8566:                                     $newurl .= '&role='.$env{'request.role'};
 8567:                                 }
 8568:                                 if ($env{'request.symb'}) {
 8569:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
 8570:                                     if ($shownsymb =~ m{^/enc/}) {
 8571:                                         my $reqdmajor = 2;
 8572:                                         my $reqdminor = 11;
 8573:                                         my $reqdsubminor = 3;
 8574:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
 8575:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
 8576:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
 8577:                                         if (($major eq '' && $minor eq '') ||
 8578:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
 8579:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
 8580:                                              ($reqdsubminor > $subminor))))) {
 8581:                                             undef($shownsymb);
 8582:                                         }
 8583:                                     }
 8584:                                     if ($shownsymb) {
 8585:                                         &js_escape(\$shownsymb);
 8586:                                         $newurl .= '&symb='.$shownsymb;
 8587:                                     }
 8588:                                 } else {
 8589:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
 8590:                                     &js_escape(\$shownurl);
 8591:                                     $newurl .= '&origurl='.$shownurl;
 8592:                                 }
 8593:                             }
 8594:                             &js_escape(\$msg);
 8595:                             $result.=<<OFFLOAD
 8596: <meta http-equiv="pragma" content="no-cache" />
 8597: <script type="text/javascript">
 8598: // <![CDATA[
 8599: function LC_Offload_Now() {
 8600:     var dest = "$newurl";
 8601:     if (dest != '') {
 8602:         window.location.href="$newurl";
 8603:     }
 8604: }
 8605: \$(document).ready(function () {
 8606:     window.alert('$msg');
 8607:     if ($disable_submit) {
 8608:         \$(".LC_hwk_submit").prop("disabled", true);
 8609:         \$( ".LC_textline" ).prop( "readonly", "readonly");
 8610:     }
 8611:     setTimeout('LC_Offload_Now()', $timeout);
 8612: });
 8613: // ]]>
 8614: </script>
 8615: OFFLOAD
 8616:                         }
 8617:                     }
 8618:                 }
 8619:             }
 8620:         }
 8621:     }
 8622:     if (!defined($title)) {
 8623: 	$title = 'The LearningOnline Network with CAPA';
 8624:     }
 8625:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 8626:     $result .= '<title> LON-CAPA '.$title.'</title>'
 8627: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
 8628:     if (!$args->{'frameset'}) {
 8629:         $result .= ' /';
 8630:     }
 8631:     $result .= '>'
 8632:         .$inhibitprint
 8633: 	.$head_extra;
 8634:     my $clientmobile;
 8635:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 8636:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
 8637:     } else {
 8638:         $clientmobile = $env{'browser.mobile'};
 8639:     }
 8640:     if ($clientmobile) {
 8641:         $result .= '
 8642: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 8643: <meta name="apple-mobile-web-app-capable" content="yes" />';
 8644:     }
 8645:     $result .= '<meta name="google" content="notranslate" />'."\n";
 8646:     return $result.'</head>';
 8647: }
 8648: 
 8649: =pod
 8650: 
 8651: =item * &font_settings()
 8652: 
 8653: Returns neccessary <meta> to set the proper encoding
 8654: 
 8655: Inputs: optional reference to HASH -- $args passed to &headtag()
 8656: 
 8657: =cut
 8658: 
 8659: sub font_settings {
 8660:     my ($args) = @_;
 8661:     my $headerstring='';
 8662:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
 8663:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
 8664: 	$headerstring.=
 8665: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
 8666:         if (!$args->{'frameset'}) {
 8667:             $headerstring.= ' /';
 8668:         }
 8669:         $headerstring .= '>'."\n";
 8670:     }
 8671:     return $headerstring;
 8672: }
 8673: 
 8674: =pod
 8675: 
 8676: =item * &print_suppression()
 8677: 
 8678: In course context returns css which causes the body to be blank when media="print",
 8679: if printout generation is unavailable for the current resource.
 8680: 
 8681: This could be because:
 8682: 
 8683: (a) printstartdate is in the future
 8684: 
 8685: (b) printenddate is in the past
 8686: 
 8687: (c) there is an active exam block with "printout"
 8688: functionality blocked
 8689: 
 8690: Users with pav, pfo or evb privileges are exempt.
 8691: 
 8692: Inputs: none
 8693: 
 8694: =cut
 8695: 
 8696: 
 8697: sub print_suppression {
 8698:     my $noprint;
 8699:     if ($env{'request.course.id'}) {
 8700:         my $scope = $env{'request.course.id'};
 8701:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8702:             (&Apache::lonnet::allowed('pfo',$scope))) {
 8703:             return;
 8704:         }
 8705:         if ($env{'request.course.sec'} ne '') {
 8706:             $scope .= "/$env{'request.course.sec'}";
 8707:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8708:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 8709:                 return;
 8710:             }
 8711:         }
 8712:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8713:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8714:         my $clientip = &Apache::lonnet::get_requestor_ip();
 8715:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
 8716:         if ($blocked) {
 8717:             my $checkrole = "cm./$cdom/$cnum";
 8718:             if ($env{'request.course.sec'} ne '') {
 8719:                 $checkrole .= "/$env{'request.course.sec'}";
 8720:             }
 8721:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 8722:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 8723:                 $noprint = 1;
 8724:             }
 8725:         }
 8726:         unless ($noprint) {
 8727:             my $symb = &Apache::lonnet::symbread();
 8728:             if ($symb ne '') {
 8729:                 my $navmap = Apache::lonnavmaps::navmap->new();
 8730:                 if (ref($navmap)) {
 8731:                     my $res = $navmap->getBySymb($symb);
 8732:                     if (ref($res)) {
 8733:                         if (!$res->resprintable()) {
 8734:                             $noprint = 1;
 8735:                         }
 8736:                     }
 8737:                 }
 8738:             }
 8739:         }
 8740:         if ($noprint) {
 8741:             return <<"ENDSTYLE";
 8742: <style type="text/css" media="print">
 8743:     body { display:none }
 8744: </style>
 8745: ENDSTYLE
 8746:         }
 8747:     }
 8748:     return;
 8749: }
 8750: 
 8751: =pod
 8752: 
 8753: =item * &xml_begin()
 8754: 
 8755: Returns the needed doctype and <html>
 8756: 
 8757: Inputs: none
 8758: 
 8759: =cut
 8760: 
 8761: sub xml_begin {
 8762:     my ($is_frameset) = @_;
 8763:     my $output='';
 8764: 
 8765:     if ($env{'browser.mathml'}) {
 8766: 	$output='<?xml version="1.0"?>'
 8767:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 8768: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 8769:             
 8770: #	    .'<!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">] >'
 8771: 	    .'<!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">'
 8772:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 8773: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 8774:     } elsif ($is_frameset) {
 8775:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
 8776:                 '<html>'."\n";
 8777:     } else {
 8778: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
 8779:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
 8780:     }
 8781:     return $output;
 8782: }
 8783: 
 8784: =pod
 8785: 
 8786: =item * &start_page()
 8787: 
 8788: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 8789: 
 8790: Inputs:
 8791: 
 8792: =over 4
 8793: 
 8794: $title - optional title for the page
 8795: 
 8796: $head_extra - optional extra HTML to incude inside the <head>
 8797: 
 8798: $args - additional optional args supported are:
 8799: 
 8800: =over 8
 8801: 
 8802:              only_body      -> is true will set &bodytag() onlybodytag
 8803:                                     arg on
 8804:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 8805:              add_entries    -> additional attributes to add to the  <body>
 8806:              domain         -> force to color decorate a page for a 
 8807:                                     specific domain
 8808:              function       -> force usage of a specific rolish color
 8809:                                     scheme
 8810:              redirect       -> see &headtag()
 8811:              bgcolor        -> override the default page bg color
 8812:              js_ready       -> return a string ready for being used in 
 8813:                                     a javascript writeln
 8814:              html_encode    -> return a string ready for being used in 
 8815:                                     a html attribute
 8816:              force_register -> if is true will turn on the &bodytag()
 8817:                                     $forcereg arg
 8818:              frameset       -> if true will start with a <frameset>
 8819:                                     rather than <body>
 8820:              skip_phases    -> hash ref of 
 8821:                                     head -> skip the <html><head> generation
 8822:                                     body -> skip all <body> generation
 8823:              no_inline_link -> if true and in remote mode, don't show the
 8824:                                     'Switch To Inline Menu' link
 8825:              no_auto_mt_title -> prevent &mt()ing the title arg
 8826:              bread_crumbs ->             Array containing breadcrumbs
 8827:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 8828:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
 8829:                                     to lonhtmlcommon::breadcrumbs
 8830:              group          -> includes the current group, if page is for a
 8831:                                specific group
 8832:              use_absolute   -> for request for external resource or syllabus, this
 8833:                                will contain https://<hostname> if server uses
 8834:                                https (as per hosts.tab), but request is for http
 8835:              hostname       -> hostname, originally from $r->hostname(), (optional).
 8836:              links_disabled -> Links in primary and secondary menus are disabled
 8837:                                (Can enable them once page has loaded - see lonroles.pm
 8838:                                for an example).
 8839:              links_target   -> Target for links, e.g., _parent (optional).
 8840: 
 8841: =back
 8842: 
 8843: =back
 8844: 
 8845: =cut
 8846: 
 8847: sub start_page {
 8848:     my ($title,$head_extra,$args) = @_;
 8849:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 8850: 
 8851:     $env{'internal.start_page'}++;
 8852:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
 8853: 
 8854:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 8855:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
 8856:     }
 8857: 
 8858:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
 8859:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
 8860:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
 8861:                 $args->{'no_primary_menu'} = 1;
 8862:             }
 8863:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
 8864:                 $args->{'no_inline_menu'} = 1;
 8865:             }
 8866:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
 8867:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
 8868:             }
 8869:         } else {
 8870:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8871:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
 8872:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
 8873:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
 8874:                     $args->{'no_primary_menu'} = 1;
 8875:                 }
 8876:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
 8877:                     $args->{'no_inline_menu'} = 1;
 8878:                 }
 8879:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
 8880:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
 8881:                 }
 8882:             }
 8883:         }
 8884:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
 8885:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
 8886:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
 8887:     } elsif ($env{'request.course.id'}) {
 8888:         my $expiretime=600;
 8889:         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
 8890:             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
 8891:         }
 8892:         my ($deeplinkmenu,$menuref);
 8893:         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
 8894:         if ($menucoll) {
 8895:             if (ref($menuref) eq 'HASH') {
 8896:                 %menu = %{$menuref};
 8897:             }
 8898:             if ($menu{'top'} eq 'n') {
 8899:                 $args->{'no_primary_menu'} = 1;
 8900:             }
 8901:             if ($menu{'inline'} eq 'n') {
 8902:                 unless (&Apache::lonnet::allowed('opa')) {
 8903:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8904:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8905:                     my $crstype = &course_type();
 8906:                     my $now = time;
 8907:                     my $ccrole;
 8908:                     if ($crstype eq 'Community') {
 8909:                         $ccrole = 'co';
 8910:                     } else {
 8911:                         $ccrole = 'cc';
 8912:                     }
 8913:                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
 8914:                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
 8915:                         if ((($start) && ($start<0)) ||
 8916:                             (($end) && ($end<$now))  ||
 8917:                             (($start) && ($now<$start))) {
 8918:                             $args->{'no_inline_menu'} = 1;
 8919:                         }
 8920:                     } else {
 8921:                         $args->{'no_inline_menu'} = 1;
 8922:                     }
 8923:                 }
 8924:             }
 8925:         }
 8926:     }
 8927: 
 8928:     my $showncrumbs;
 8929:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 8930: 	if ($args->{'frameset'}) {
 8931: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 8932: 						$args->{'add_entries'});
 8933: 	    $result .= "\n<frameset $attr_string>\n";
 8934:         } else {
 8935:             $result .=
 8936:                 &bodytag($title, 
 8937:                          $args->{'function'},       $args->{'add_entries'},
 8938:                          $args->{'only_body'},      $args->{'domain'},
 8939:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 8940:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
 8941:                          $args,                     \@advtools,
 8942:                          $ltiscope,$ltiuri,\%ltimenu,$menucoll,\%menu,\$showncrumbs);
 8943:         }
 8944:     }
 8945: 
 8946:     if ($args->{'js_ready'}) {
 8947: 		$result = &js_ready($result);
 8948:     }
 8949:     if ($args->{'html_encode'}) {
 8950: 		$result = &html_encode($result);
 8951:     }
 8952: 
 8953:     # Preparation for new and consistent functionlist at top of screen
 8954:     # if ($args->{'functionlist'}) {
 8955:     #            $result .= &build_functionlist();
 8956:     #}
 8957: 
 8958:     # Don't add anything more if only_body wanted or in const space
 8959:     return $result if    $args->{'only_body'} 
 8960:                       || $env{'request.state'} eq 'construct';
 8961: 
 8962:     #Breadcrumbs
 8963:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 8964:         unless ($showncrumbs) {
 8965: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 8966: 		#if any br links exists, add them to the breadcrumbs
 8967: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 8968: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 8969: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 8970: 			}
 8971: 		}
 8972:                 # if @advtools array contains items add then to the breadcrumbs
 8973:                 if (@advtools > 0) {
 8974:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 8975:                 }
 8976:                 my $menulink;
 8977:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
 8978:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
 8979:                     ($ltiscope eq 'map') || ($ltiscope eq 'resource')) {
 8980:                     $menulink = 0;
 8981:                 } else {
 8982:                     undef($menulink);
 8983:                 }
 8984:                 my $linkprotout;
 8985:                 if ($env{'request.deeplink.login'}) {
 8986:                     my $linkprotout = &Apache::lonmenu::linkprot_exit();
 8987:                     if ($linkprotout) {
 8988:                         &Apache::lonhtmlcommon::add_breadcrumb_tool('tools',$linkprotout);
 8989:                     }
 8990:                 }
 8991: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 8992: 		if(exists($args->{'bread_crumbs_component'})){
 8993: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
 8994: 		} else {
 8995: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
 8996: 		}
 8997:         }
 8998:     } elsif (($env{'environment.remote'} eq 'on') &&
 8999:              ($env{'form.inhibitmenu'} ne 'yes') &&
 9000:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
 9001:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
 9002:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
 9003:     }
 9004:     return $result;
 9005: }
 9006: 
 9007: sub end_page {
 9008:     my ($args) = @_;
 9009:     $env{'internal.end_page'}++;
 9010:     my $result;
 9011:     if ($args->{'discussion'}) {
 9012: 	my ($target,$parser);
 9013: 	if (ref($args->{'discussion'})) {
 9014: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 9015: 				$args->{'discussion'}{'parser'});
 9016: 	}
 9017: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 9018:     }
 9019:     if ($args->{'frameset'}) {
 9020: 	$result .= '</frameset>';
 9021:     } else {
 9022: 	$result .= &endbodytag($args);
 9023:     }
 9024:     unless ($args->{'notbody'}) {
 9025:         $result .= "\n</html>";
 9026:     }
 9027: 
 9028:     if ($args->{'js_ready'}) {
 9029: 	$result = &js_ready($result);
 9030:     }
 9031: 
 9032:     if ($args->{'html_encode'}) {
 9033: 	$result = &html_encode($result);
 9034:     }
 9035: 
 9036:     return $result;
 9037: }
 9038: 
 9039: sub menucoll_in_effect {
 9040:     my ($menucoll,$deeplinkmenu,%menu);
 9041:     if ($env{'request.course.id'}) {
 9042:         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
 9043:         if ($env{'request.deeplink.login'}) {
 9044:             my ($deeplink_symb,$deeplink,$check_login_symb);
 9045:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9046:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9047:             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
 9048:                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
 9049:                     my $navmap = Apache::lonnavmaps::navmap->new();
 9050:                     if (ref($navmap)) {
 9051:                         $deeplink = $navmap->get_mapparam(undef,
 9052:                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
 9053:                                                           '0.deeplink');
 9054:                     } else {
 9055:                         $check_login_symb = 1;
 9056:                     }
 9057:                 } else {
 9058:                     my $symb=&Apache::lonnet::symbread();
 9059:                     if ($symb) {
 9060:                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
 9061:                     } else {
 9062:                         $check_login_symb = 1;
 9063:                     }
 9064:                 }
 9065:             } else {
 9066:                 $check_login_symb = 1;
 9067:             }
 9068:             if ($check_login_symb) {
 9069:                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
 9070:                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
 9071:                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
 9072:                     my $navmap = Apache::lonnavmaps::navmap->new();
 9073:                     if (ref($navmap)) {
 9074:                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
 9075:                     }
 9076:                 } else {
 9077:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
 9078:                 }
 9079:             }
 9080:             if ($deeplink ne '') {
 9081:                 my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
 9082:                 if ($display =~ /^\d+$/) {
 9083:                     $deeplinkmenu = 1;
 9084:                     $menucoll = $display;
 9085:                 }
 9086:             }
 9087:         }
 9088:         if ($menucoll) {
 9089:             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
 9090:         }
 9091:     }
 9092:     return ($menucoll,$deeplinkmenu,\%menu);
 9093: }
 9094: 
 9095: sub deeplink_login_symb {
 9096:     my ($cnum,$cdom) = @_;
 9097:     my $login_symb;
 9098:     if ($env{'request.deeplink.login'}) {
 9099:         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
 9100:     }
 9101:     return $login_symb;
 9102: }
 9103: 
 9104: sub symb_from_tinyurl {
 9105:     my ($url,$cnum,$cdom) = @_;
 9106:     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
 9107:         my $key = $1;
 9108:         my ($tinyurl,$login);
 9109:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
 9110:         if (defined($cached)) {
 9111:             $tinyurl = $result;
 9112:         } else {
 9113:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
 9114:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
 9115:             if ($currtiny{$key} ne '') {
 9116:                 $tinyurl = $currtiny{$key};
 9117:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
 9118:             }
 9119:         }
 9120:         if ($tinyurl ne '') {
 9121:             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
 9122:             if (wantarray) {
 9123:                 return ($cnumreq,$symb);
 9124:             } elsif ($cnumreq eq $cnum) {
 9125:                 return $symb;
 9126:             }
 9127:         }
 9128:     }
 9129:     if (wantarray) {
 9130:         return ();
 9131:     } else {
 9132:         return;
 9133:     }
 9134: }
 9135: 
 9136: sub wishlist_window {
 9137:     return(<<'ENDWISHLIST');
 9138: <script type="text/javascript">
 9139: // <![CDATA[
 9140: // <!-- BEGIN LON-CAPA Internal
 9141: function set_wishlistlink(title, path) {
 9142:     if (!title) {
 9143:         title = document.title;
 9144:         title = title.replace(/^LON-CAPA /,'');
 9145:     }
 9146:     title = encodeURIComponent(title);
 9147:     title = title.replace("'","\\\'");
 9148:     if (!path) {
 9149:         path = location.pathname;
 9150:     }
 9151:     path = encodeURIComponent(path);
 9152:     path = path.replace("'","\\\'");
 9153:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 9154:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 9155: }
 9156: // END LON-CAPA Internal -->
 9157: // ]]>
 9158: </script>
 9159: ENDWISHLIST
 9160: }
 9161: 
 9162: sub modal_window {
 9163:     return(<<'ENDMODAL');
 9164: <script type="text/javascript">
 9165: // <![CDATA[
 9166: // <!-- BEGIN LON-CAPA Internal
 9167: var modalWindow = {
 9168: 	parent:"body",
 9169: 	windowId:null,
 9170: 	content:null,
 9171: 	width:null,
 9172: 	height:null,
 9173: 	close:function()
 9174: 	{
 9175: 	        $(".LCmodal-window").remove();
 9176: 	        $(".LCmodal-overlay").remove();
 9177: 	},
 9178: 	open:function()
 9179: 	{
 9180: 		var modal = "";
 9181: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 9182: 		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;\">";
 9183: 		modal += this.content;
 9184: 		modal += "</div>";	
 9185: 
 9186: 		$(this.parent).append(modal);
 9187: 
 9188: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 9189: 		$(".LCclose-window").click(function(){modalWindow.close();});
 9190: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 9191: 	}
 9192: };
 9193: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
 9194: 	{
 9195:                 source = source.replace(/'/g,"&#39;");
 9196: 		modalWindow.windowId = "myModal";
 9197: 		modalWindow.width = width;
 9198: 		modalWindow.height = height;
 9199: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
 9200: 		modalWindow.open();
 9201: 	};
 9202: // END LON-CAPA Internal -->
 9203: // ]]>
 9204: </script>
 9205: ENDMODAL
 9206: }
 9207: 
 9208: sub modal_link {
 9209:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
 9210:     unless ($width) { $width=480; }
 9211:     unless ($height) { $height=400; }
 9212:     unless ($scrolling) { $scrolling='yes'; }
 9213:     unless ($transparency) { $transparency='true'; }
 9214: 
 9215:     my $target_attr;
 9216:     if (defined($target)) {
 9217:         $target_attr = 'target="'.$target.'"';
 9218:     }
 9219:     return <<"ENDLINK";
 9220: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
 9221: ENDLINK
 9222: }
 9223: 
 9224: sub modal_adhoc_script {
 9225:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
 9226:     my $mathjax;
 9227:     if ($possmathjax) {
 9228:         $mathjax = <<'ENDJAX';
 9229:                if (typeof MathJax == 'object') {
 9230:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
 9231:                }
 9232: ENDJAX
 9233:     }
 9234:     return (<<ENDADHOC);
 9235: <script type="text/javascript">
 9236: // <![CDATA[
 9237:         var $funcname = function()
 9238:         {
 9239:                 modalWindow.windowId = "myModal";
 9240:                 modalWindow.width = $width;
 9241:                 modalWindow.height = $height;
 9242:                 modalWindow.content = '$content';
 9243:                 modalWindow.open();
 9244:                 $mathjax
 9245:         };  
 9246: // ]]>
 9247: </script>
 9248: ENDADHOC
 9249: }
 9250: 
 9251: sub modal_adhoc_inner {
 9252:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
 9253:     my $innerwidth=$width-20;
 9254:     $content=&js_ready(
 9255:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 9256:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
 9257:                  $content.
 9258:                  &end_scrollbox().
 9259:                  &end_page()
 9260:              );
 9261:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
 9262: }
 9263: 
 9264: sub modal_adhoc_window {
 9265:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
 9266:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
 9267:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 9268: }
 9269: 
 9270: sub modal_adhoc_launch {
 9271:     my ($funcname,$width,$height,$content)=@_;
 9272:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 9273: <script type="text/javascript">
 9274: // <![CDATA[
 9275: $funcname();
 9276: // ]]>
 9277: </script>
 9278: ENDLAUNCH
 9279: }
 9280: 
 9281: sub modal_adhoc_close {
 9282:     return (<<ENDCLOSE);
 9283: <script type="text/javascript">
 9284: // <![CDATA[
 9285: modalWindow.close();
 9286: // ]]>
 9287: </script>
 9288: ENDCLOSE
 9289: }
 9290: 
 9291: sub togglebox_script {
 9292:    return(<<ENDTOGGLE);
 9293: <script type="text/javascript"> 
 9294: // <![CDATA[
 9295: function LCtoggleDisplay(id,hidetext,showtext) {
 9296:    link = document.getElementById(id + "link").childNodes[0];
 9297:    with (document.getElementById(id).style) {
 9298:       if (display == "none" ) {
 9299:           display = "inline";
 9300:           link.nodeValue = hidetext;
 9301:         } else {
 9302:           display = "none";
 9303:           link.nodeValue = showtext;
 9304:        }
 9305:    }
 9306: }
 9307: // ]]>
 9308: </script>
 9309: ENDTOGGLE
 9310: }
 9311: 
 9312: sub start_togglebox {
 9313:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 9314:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 9315:     unless ($showtext) { $showtext=&mt('show'); }
 9316:     unless ($hidetext) { $hidetext=&mt('hide'); }
 9317:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 9318:     return &start_data_table().
 9319:            &start_data_table_header_row().
 9320:            '<td bgcolor="'.$headerbg.'">'.$heading.
 9321:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 9322:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 9323:            &end_data_table_header_row().
 9324:            '<tr id="'.$id.'" style="display:none""><td>';
 9325: }
 9326: 
 9327: sub end_togglebox {
 9328:     return '</td></tr>'.&end_data_table();
 9329: }
 9330: 
 9331: sub LCprogressbar_script {
 9332:    my ($id,$number_to_do)=@_;
 9333:    if ($number_to_do) {
 9334:        return(<<ENDPROGRESS);
 9335: <script type="text/javascript">
 9336: // <![CDATA[
 9337: \$('#progressbar$id').progressbar({
 9338:   value: 0,
 9339:   change: function(event, ui) {
 9340:     var newVal = \$(this).progressbar('option', 'value');
 9341:     \$('.pblabel', this).text(LCprogressTxt);
 9342:   }
 9343: });
 9344: // ]]>
 9345: </script>
 9346: ENDPROGRESS
 9347:    } else {
 9348:        return(<<ENDPROGRESS);
 9349: <script type="text/javascript">
 9350: // <![CDATA[
 9351: \$('#progressbar$id').progressbar({
 9352:   value: false,
 9353:   create: function(event, ui) {
 9354:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
 9355:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
 9356:   }
 9357: });
 9358: // ]]>
 9359: </script>
 9360: ENDPROGRESS
 9361:    }
 9362: }
 9363: 
 9364: sub LCprogressbarUpdate_script {
 9365:    return(<<ENDPROGRESSUPDATE);
 9366: <style type="text/css">
 9367: .ui-progressbar { position:relative; }
 9368: .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%; }
 9369: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 9370: </style>
 9371: <script type="text/javascript">
 9372: // <![CDATA[
 9373: var LCprogressTxt='---';
 9374: 
 9375: function LCupdateProgress(percent,progresstext,id,maxnum) {
 9376:    LCprogressTxt=progresstext;
 9377:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
 9378:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
 9379:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
 9380:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
 9381:    } else {
 9382:        \$('#progressbar'+id).progressbar('value',percent);
 9383:    }
 9384: }
 9385: // ]]>
 9386: </script>
 9387: ENDPROGRESSUPDATE
 9388: }
 9389: 
 9390: my $LClastpercent;
 9391: my $LCidcnt;
 9392: my $LCcurrentid;
 9393: 
 9394: sub LCprogressbar {
 9395:     my ($r,$number_to_do,$preamble)=@_;
 9396:     $LClastpercent=0;
 9397:     $LCidcnt++;
 9398:     $LCcurrentid=$$.'_'.$LCidcnt;
 9399:     my ($starting,$content);
 9400:     if ($number_to_do) {
 9401:         $starting=&mt('Starting');
 9402:         $content=(<<ENDPROGBAR);
 9403: $preamble
 9404:   <div id="progressbar$LCcurrentid">
 9405:     <span class="pblabel">$starting</span>
 9406:   </div>
 9407: ENDPROGBAR
 9408:     } else {
 9409:         $starting=&mt('Loading...');
 9410:         $LClastpercent='false';
 9411:         $content=(<<ENDPROGBAR);
 9412: $preamble
 9413:   <div id="progressbar$LCcurrentid">
 9414:       <div class="progress-label">$starting</div>
 9415:   </div>
 9416: ENDPROGBAR
 9417:     }
 9418:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
 9419: }
 9420: 
 9421: sub LCprogressbarUpdate {
 9422:     my ($r,$val,$text,$number_to_do)=@_;
 9423:     if ($number_to_do) {
 9424:         unless ($val) { 
 9425:             if ($LClastpercent) {
 9426:                 $val=$LClastpercent;
 9427:             } else {
 9428:                 $val=0;
 9429:             }
 9430:         }
 9431:         if ($val<0) { $val=0; }
 9432:         if ($val>100) { $val=0; }
 9433:         $LClastpercent=$val;
 9434:         unless ($text) { $text=$val.'%'; }
 9435:     } else {
 9436:         $val = 'false';
 9437:     }
 9438:     $text=&js_ready($text);
 9439:     &r_print($r,<<ENDUPDATE);
 9440: <script type="text/javascript">
 9441: // <![CDATA[
 9442: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
 9443: // ]]>
 9444: </script>
 9445: ENDUPDATE
 9446: }
 9447: 
 9448: sub LCprogressbarClose {
 9449:     my ($r)=@_;
 9450:     $LClastpercent=0;
 9451:     &r_print($r,<<ENDCLOSE);
 9452: <script type="text/javascript">
 9453: // <![CDATA[
 9454: \$("#progressbar$LCcurrentid").hide('slow'); 
 9455: // ]]>
 9456: </script>
 9457: ENDCLOSE
 9458: }
 9459: 
 9460: sub r_print {
 9461:     my ($r,$to_print)=@_;
 9462:     if ($r) {
 9463:       $r->print($to_print);
 9464:       $r->rflush();
 9465:     } else {
 9466:       print($to_print);
 9467:     }
 9468: }
 9469: 
 9470: sub html_encode {
 9471:     my ($result) = @_;
 9472: 
 9473:     $result = &HTML::Entities::encode($result,'<>&"');
 9474:     
 9475:     return $result;
 9476: }
 9477: 
 9478: sub js_ready {
 9479:     my ($result) = @_;
 9480: 
 9481:     $result =~ s/[\n\r]/ /xmsg;
 9482:     $result =~ s/\\/\\\\/xmsg;
 9483:     $result =~ s/'/\\'/xmsg;
 9484:     $result =~ s{</}{<\\/}xmsg;
 9485:     
 9486:     return $result;
 9487: }
 9488: 
 9489: sub validate_page {
 9490:     if (  exists($env{'internal.start_page'})
 9491: 	  &&     $env{'internal.start_page'} > 1) {
 9492: 	&Apache::lonnet::logthis('start_page called multiple times '.
 9493: 				 $env{'internal.start_page'}.' '.
 9494: 				 $ENV{'request.filename'});
 9495:     }
 9496:     if (  exists($env{'internal.end_page'})
 9497: 	  &&     $env{'internal.end_page'} > 1) {
 9498: 	&Apache::lonnet::logthis('end_page called multiple times '.
 9499: 				 $env{'internal.end_page'}.' '.
 9500: 				 $env{'request.filename'});
 9501:     }
 9502:     if (     exists($env{'internal.start_page'})
 9503: 	&& ! exists($env{'internal.end_page'})) {
 9504: 	&Apache::lonnet::logthis('start_page called without end_page '.
 9505: 				 $env{'request.filename'});
 9506:     }
 9507:     if (   ! exists($env{'internal.start_page'})
 9508: 	&&   exists($env{'internal.end_page'})) {
 9509: 	&Apache::lonnet::logthis('end_page called without start_page'.
 9510: 				 $env{'request.filename'});
 9511:     }
 9512: }
 9513: 
 9514: 
 9515: sub start_scrollbox {
 9516:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
 9517:     unless ($outerwidth) { $outerwidth='520px'; }
 9518:     unless ($width) { $width='500px'; }
 9519:     unless ($height) { $height='200px'; }
 9520:     my ($table_id,$div_id,$tdcol);
 9521:     if ($id ne '') {
 9522:         $table_id = ' id="table_'.$id.'"';
 9523:         $div_id = ' id="div_'.$id.'"';
 9524:     }
 9525:     if ($bgcolor ne '') {
 9526:         $tdcol = "background-color: $bgcolor;";
 9527:     }
 9528:     my $nicescroll_js;
 9529:     if ($env{'browser.mobile'}) {
 9530:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
 9531:     }
 9532:     return <<"END";
 9533: $nicescroll_js
 9534: 
 9535: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
 9536: <div style="overflow:auto; width:$width; height:$height;"$div_id>
 9537: END
 9538: }
 9539: 
 9540: sub end_scrollbox {
 9541:     return '</div></td></tr></table>';
 9542: }
 9543: 
 9544: sub nicescroll_javascript {
 9545:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
 9546:     my %options;
 9547:     if (ref($cursor) eq 'HASH') {
 9548:         %options = %{$cursor};
 9549:     }
 9550:     unless ($options{'railalign'} =~ /^left|right$/) {
 9551:         $options{'railalign'} = 'left';
 9552:     }
 9553:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 9554:         my $function  = &get_users_function();
 9555:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
 9556:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 9557:             $options{'cursorcolor'} = '#00F';
 9558:         }
 9559:     }
 9560:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
 9561:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
 9562:             $options{'cursoropacity'}='1.0';
 9563:         }
 9564:     } else {
 9565:         $options{'cursoropacity'}='1.0';
 9566:     }
 9567:     if ($options{'cursorfixedheight'} eq 'none') {
 9568:         delete($options{'cursorfixedheight'});
 9569:     } else {
 9570:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
 9571:     }
 9572:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
 9573:         delete($options{'railoffset'});
 9574:     }
 9575:     my @niceoptions;
 9576:     while (my($key,$value) = each(%options)) {
 9577:         if ($value =~ /^\{.+\}$/) {
 9578:             push(@niceoptions,$key.':'.$value);
 9579:         } else {
 9580:             push(@niceoptions,$key.':"'.$value.'"');
 9581:         }
 9582:     }
 9583:     my $nicescroll_js = '
 9584: $(document).ready(
 9585:       function() {
 9586:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
 9587:       }
 9588: );
 9589: ';
 9590:     if ($framecheck) {
 9591:         $nicescroll_js .= '
 9592: function expand_div(caller) {
 9593:     if (top === self) {
 9594:         document.getElementById("'.$id.'").style.width = "auto";
 9595:         document.getElementById("'.$id.'").style.height = "auto";
 9596:     } else {
 9597:         try {
 9598:             if (parent.frames) {
 9599:                 if (parent.frames.length > 1) {
 9600:                     var framesrc = parent.frames[1].location.href;
 9601:                     var currsrc = framesrc.replace(/\#.*$/,"");
 9602:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
 9603:                         document.getElementById("'.$id.'").style.width = "auto";
 9604:                         document.getElementById("'.$id.'").style.height = "auto";
 9605:                     }
 9606:                 }
 9607:             }
 9608:         } catch (e) {
 9609:             return;
 9610:         }
 9611:     }
 9612:     return;
 9613: }
 9614: ';
 9615:     }
 9616:     if ($needjsready) {
 9617:         $nicescroll_js = '
 9618: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
 9619:     } else {
 9620:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
 9621:     }
 9622:     return $nicescroll_js;
 9623: }
 9624: 
 9625: sub simple_error_page {
 9626:     my ($r,$title,$msg,$args) = @_;
 9627:     my %displayargs;
 9628:     if (ref($args) eq 'HASH') {
 9629:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
 9630:         if ($args->{'only_body'}) {
 9631:             $displayargs{'only_body'} = 1;
 9632:         }
 9633:         if ($args->{'no_nav_bar'}) {
 9634:             $displayargs{'no_nav_bar'} = 1;
 9635:         }
 9636:     } else {
 9637:         $msg = &mt($msg);
 9638:     }
 9639: 
 9640:     my $page =
 9641: 	&Apache::loncommon::start_page($title,'',\%displayargs).
 9642: 	'<p class="LC_error">'.$msg.'</p>'.
 9643: 	&Apache::loncommon::end_page();
 9644:     if (ref($r)) {
 9645: 	$r->print($page);
 9646: 	return;
 9647:     }
 9648:     return $page;
 9649: }
 9650: 
 9651: {
 9652:     my @row_count;
 9653: 
 9654:     sub start_data_table_count {
 9655:         unshift(@row_count, 0);
 9656:         return;
 9657:     }
 9658: 
 9659:     sub end_data_table_count {
 9660:         shift(@row_count);
 9661:         return;
 9662:     }
 9663: 
 9664:     sub start_data_table {
 9665: 	my ($add_class,$id) = @_;
 9666: 	my $css_class = (join(' ','LC_data_table',$add_class));
 9667:         my $table_id;
 9668:         if (defined($id)) {
 9669:             $table_id = ' id="'.$id.'"';
 9670:         }
 9671: 	&start_data_table_count();
 9672: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 9673:     }
 9674: 
 9675:     sub end_data_table {
 9676: 	&end_data_table_count();
 9677: 	return '</table>'."\n";;
 9678:     }
 9679: 
 9680:     sub start_data_table_row {
 9681: 	my ($add_class, $id) = @_;
 9682: 	$row_count[0]++;
 9683: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 9684: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 9685:         $id = (' id="'.$id.'"') unless ($id eq '');
 9686:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 9687:     }
 9688:     
 9689:     sub continue_data_table_row {
 9690: 	my ($add_class, $id) = @_;
 9691: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 9692: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 9693:         $id = (' id="'.$id.'"') unless ($id eq '');
 9694:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 9695:     }
 9696: 
 9697:     sub end_data_table_row {
 9698: 	return '</tr>'."\n";;
 9699:     }
 9700: 
 9701:     sub start_data_table_empty_row {
 9702: #	$row_count[0]++;
 9703: 	return  '<tr class="LC_empty_row" >'."\n";;
 9704:     }
 9705: 
 9706:     sub end_data_table_empty_row {
 9707: 	return '</tr>'."\n";;
 9708:     }
 9709: 
 9710:     sub start_data_table_header_row {
 9711: 	return  '<tr class="LC_header_row">'."\n";;
 9712:     }
 9713: 
 9714:     sub end_data_table_header_row {
 9715: 	return '</tr>'."\n";;
 9716:     }
 9717: 
 9718:     sub data_table_caption {
 9719:         my $caption = shift;
 9720:         return "<caption class=\"LC_caption\">$caption</caption>";
 9721:     }
 9722: }
 9723: 
 9724: =pod
 9725: 
 9726: =item * &inhibit_menu_check($arg)
 9727: 
 9728: Checks for a inhibitmenu state and generates output to preserve it
 9729: 
 9730: Inputs:         $arg - can be any of
 9731:                      - undef - in which case the return value is a string 
 9732:                                to add  into arguments list of a uri
 9733:                      - 'input' - in which case the return value is a HTML
 9734:                                  <form> <input> field of type hidden to
 9735:                                  preserve the value
 9736:                      - a url - in which case the return value is the url with
 9737:                                the neccesary cgi args added to preserve the
 9738:                                inhibitmenu state
 9739:                      - a ref to a url - no return value, but the string is
 9740:                                         updated to include the neccessary cgi
 9741:                                         args to preserve the inhibitmenu state
 9742: 
 9743: =cut
 9744: 
 9745: sub inhibit_menu_check {
 9746:     my ($arg) = @_;
 9747:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 9748:     if ($arg eq 'input') {
 9749: 	if ($env{'form.inhibitmenu'}) {
 9750: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 9751: 	} else {
 9752: 	    return
 9753: 	}
 9754:     }
 9755:     if ($env{'form.inhibitmenu'}) {
 9756: 	if (ref($arg)) {
 9757: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 9758: 	} elsif ($arg eq '') {
 9759: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 9760: 	} else {
 9761: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 9762: 	}
 9763:     }
 9764:     if (!ref($arg)) {
 9765: 	return $arg;
 9766:     }
 9767: }
 9768: 
 9769: ###############################################
 9770: 
 9771: =pod
 9772: 
 9773: =back
 9774: 
 9775: =head1 User Information Routines
 9776: 
 9777: =over 4
 9778: 
 9779: =item * &get_users_function()
 9780: 
 9781: Used by &bodytag to determine the current users primary role.
 9782: Returns either 'student','coordinator','admin', or 'author'.
 9783: 
 9784: =cut
 9785: 
 9786: ###############################################
 9787: sub get_users_function {
 9788:     my $function = 'norole';
 9789:     if ($env{'request.role'}=~/^(st)/) {
 9790:         $function='student';
 9791:     }
 9792:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 9793:         $function='coordinator';
 9794:     }
 9795:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 9796:         $function='admin';
 9797:     }
 9798:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 9799:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 9800:         $function='author';
 9801:     }
 9802:     return $function;
 9803: }
 9804: 
 9805: ###############################################
 9806: 
 9807: =pod
 9808: 
 9809: =item * &show_course()
 9810: 
 9811: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 9812: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 9813: 
 9814: Inputs:
 9815: None
 9816: 
 9817: Outputs:
 9818: Scalar: 1 if 'Course' to be used, 0 otherwise.
 9819: 
 9820: =cut
 9821: 
 9822: ###############################################
 9823: sub show_course {
 9824:     my $course = !$env{'user.adv'};
 9825:     if (!$env{'user.adv'}) {
 9826:         foreach my $env (keys(%env)) {
 9827:             next if ($env !~ m/^user\.priv\./);
 9828:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 9829:                 $course = 0;
 9830:                 last;
 9831:             }
 9832:         }
 9833:     }
 9834:     return $course;
 9835: }
 9836: 
 9837: ###############################################
 9838: 
 9839: =pod
 9840: 
 9841: =item * &check_user_status()
 9842: 
 9843: Determines current status of supplied role for a
 9844: specific user. Roles can be active, previous or future.
 9845: 
 9846: Inputs: 
 9847: user's domain, user's username, course's domain,
 9848: course's number, optional section ID.
 9849: 
 9850: Outputs:
 9851: role status: active, previous or future. 
 9852: 
 9853: =cut
 9854: 
 9855: sub check_user_status {
 9856:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 9857:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 9858:     my @uroles = keys(%userinfo);
 9859:     my $srchstr;
 9860:     my $active_chk = 'none';
 9861:     my $now = time;
 9862:     if (@uroles > 0) {
 9863:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 9864:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 9865:         } else {
 9866:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 9867:         }
 9868:         if (grep/^\Q$srchstr\E$/,@uroles) {
 9869:             my $role_end = 0;
 9870:             my $role_start = 0;
 9871:             $active_chk = 'active';
 9872:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 9873:                 $role_end = $1;
 9874:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 9875:                     $role_start = $1;
 9876:                 }
 9877:             }
 9878:             if ($role_start > 0) {
 9879:                 if ($now < $role_start) {
 9880:                     $active_chk = 'future';
 9881:                 }
 9882:             }
 9883:             if ($role_end > 0) {
 9884:                 if ($now > $role_end) {
 9885:                     $active_chk = 'previous';
 9886:                 }
 9887:             }
 9888:         }
 9889:     }
 9890:     return $active_chk;
 9891: }
 9892: 
 9893: ###############################################
 9894: 
 9895: =pod
 9896: 
 9897: =item * &get_sections()
 9898: 
 9899: Determines all the sections for a course including
 9900: sections with students and sections containing other roles.
 9901: Incoming parameters: 
 9902: 
 9903: 1. domain
 9904: 2. course number 
 9905: 3. reference to array containing roles for which sections should 
 9906: be gathered (optional).
 9907: 4. reference to array containing status types for which sections 
 9908: should be gathered (optional).
 9909: 
 9910: If the third argument is undefined, sections are gathered for any role. 
 9911: If the fourth argument is undefined, sections are gathered for any status.
 9912: Permissible values are 'active' or 'future' or 'previous'.
 9913:  
 9914: Returns section hash (keys are section IDs, values are
 9915: number of users in each section), subject to the
 9916: optional roles filter, optional status filter 
 9917: 
 9918: =cut
 9919: 
 9920: ###############################################
 9921: sub get_sections {
 9922:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 9923:     if (!defined($cdom) || !defined($cnum)) {
 9924:         my $cid =  $env{'request.course.id'};
 9925: 
 9926: 	return if (!defined($cid));
 9927: 
 9928:         $cdom = $env{'course.'.$cid.'.domain'};
 9929:         $cnum = $env{'course.'.$cid.'.num'};
 9930:     }
 9931: 
 9932:     my %sectioncount;
 9933:     my $now = time;
 9934: 
 9935:     my $check_students = 1;
 9936:     my $only_students = 0;
 9937:     if (ref($possible_roles) eq 'ARRAY') {
 9938:         if (grep(/^st$/,@{$possible_roles})) {
 9939:             if (@{$possible_roles} == 1) {
 9940:                 $only_students = 1;
 9941:             }
 9942:         } else {
 9943:             $check_students = 0;
 9944:         }
 9945:     }
 9946: 
 9947:     if ($check_students) {
 9948: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 9949: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 9950: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 9951:         my $start_index = &Apache::loncoursedata::CL_START();
 9952:         my $end_index = &Apache::loncoursedata::CL_END();
 9953:         my $status;
 9954: 	while (my ($student,$data) = each(%$classlist)) {
 9955: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 9956: 				                     $data->[$status_index],
 9957:                                                      $data->[$start_index],
 9958:                                                      $data->[$end_index]);
 9959:             if ($stu_status eq 'Active') {
 9960:                 $status = 'active';
 9961:             } elsif ($end < $now) {
 9962:                 $status = 'previous';
 9963:             } elsif ($start > $now) {
 9964:                 $status = 'future';
 9965:             } 
 9966: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 9967:                 if ((!defined($possible_status)) || (($status ne '') && 
 9968:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 9969: 		    $sectioncount{$section}++;
 9970:                 }
 9971: 	    }
 9972: 	}
 9973:     }
 9974:     if ($only_students) {
 9975:         return %sectioncount;
 9976:     }
 9977:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9978:     foreach my $user (sort(keys(%courseroles))) {
 9979: 	if ($user !~ /^(\w{2})/) { next; }
 9980: 	my ($role) = ($user =~ /^(\w{2})/);
 9981: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 9982: 	my ($section,$status);
 9983: 	if ($role eq 'cr' &&
 9984: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 9985: 	    $section=$1;
 9986: 	}
 9987: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 9988: 	if (!defined($section) || $section eq '-1') { next; }
 9989:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 9990:         if ($end == -1 && $start == -1) {
 9991:             next; #deleted role
 9992:         }
 9993:         if (!defined($possible_status)) { 
 9994:             $sectioncount{$section}++;
 9995:         } else {
 9996:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 9997:                 $status = 'active';
 9998:             } elsif ($end < $now) {
 9999:                 $status = 'future';
10000:             } elsif ($start > $now) {
10001:                 $status = 'previous';
10002:             }
10003:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
10004:                 $sectioncount{$section}++;
10005:             }
10006:         }
10007:     }
10008:     return %sectioncount;
10009: }
10010: 
10011: ###############################################
10012: 
10013: =pod
10014: 
10015: =item * &get_course_users()
10016: 
10017: Retrieves usernames:domains for users in the specified course
10018: with specific role(s), and access status. 
10019: 
10020: Incoming parameters:
10021: 1. course domain
10022: 2. course number
10023: 3. access status: users must have - either active, 
10024: previous, future, or all.
10025: 4. reference to array of permissible roles
10026: 5. reference to array of section restrictions (optional)
10027: 6. reference to results object (hash of hashes).
10028: 7. reference to optional userdata hash
10029: 8. reference to optional statushash
10030: 9. flag if privileged users (except those set to unhide in
10031:    course settings) should be excluded    
10032: Keys of top level results hash are roles.
10033: Keys of inner hashes are username:domain, with 
10034: values set to access type.
10035: Optional userdata hash returns an array with arguments in the 
10036: same order as loncoursedata::get_classlist() for student data.
10037: 
10038: Optional statushash returns
10039: 
10040: Entries for end, start, section and status are blank because
10041: of the possibility of multiple values for non-student roles.
10042: 
10043: =cut
10044: 
10045: ###############################################
10046: 
10047: sub get_course_users {
10048:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
10049:     my %idx = ();
10050:     my %seclists;
10051: 
10052:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
10053:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
10054:     $idx{end} = &Apache::loncoursedata::CL_END();
10055:     $idx{start} = &Apache::loncoursedata::CL_START();
10056:     $idx{id} = &Apache::loncoursedata::CL_ID();
10057:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
10058:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
10059:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
10060: 
10061:     if (grep(/^st$/,@{$roles})) {
10062:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
10063:         my $now = time;
10064:         foreach my $student (keys(%{$classlist})) {
10065:             my $match = 0;
10066:             my $secmatch = 0;
10067:             my $section = $$classlist{$student}[$idx{section}];
10068:             my $status = $$classlist{$student}[$idx{status}];
10069:             if ($section eq '') {
10070:                 $section = 'none';
10071:             }
10072:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
10073:                 if (grep(/^all$/,@{$sections})) {
10074:                     $secmatch = 1;
10075:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
10076:                     if (grep(/^none$/,@{$sections})) {
10077:                         $secmatch = 1;
10078:                     }
10079:                 } else {  
10080: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
10081: 		        $secmatch = 1;
10082:                     }
10083: 		}
10084:                 if (!$secmatch) {
10085:                     next;
10086:                 }
10087:             }
10088:             if (defined($$types{'active'})) {
10089:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
10090:                     push(@{$$users{st}{$student}},'active');
10091:                     $match = 1;
10092:                 }
10093:             }
10094:             if (defined($$types{'previous'})) {
10095:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
10096:                     push(@{$$users{st}{$student}},'previous');
10097:                     $match = 1;
10098:                 }
10099:             }
10100:             if (defined($$types{'future'})) {
10101:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
10102:                     push(@{$$users{st}{$student}},'future');
10103:                     $match = 1;
10104:                 }
10105:             }
10106:             if ($match) {
10107:                 push(@{$seclists{$student}},$section);
10108:                 if (ref($userdata) eq 'HASH') {
10109:                     $$userdata{$student} = $$classlist{$student};
10110:                 }
10111:                 if (ref($statushash) eq 'HASH') {
10112:                     $statushash->{$student}{'st'}{$section} = $status;
10113:                 }
10114:             }
10115:         }
10116:     }
10117:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
10118:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10119:         my $now = time;
10120:         my %displaystatus = ( previous => 'Expired',
10121:                               active   => 'Active',
10122:                               future   => 'Future',
10123:                             );
10124:         my (%nothide,@possdoms);
10125:         if ($hidepriv) {
10126:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
10127:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
10128:                 if ($user !~ /:/) {
10129:                     $nothide{join(':',split(/[\@]/,$user))}=1;
10130:                 } else {
10131:                     $nothide{$user} = 1;
10132:                 }
10133:             }
10134:             my @possdoms = ($cdom);
10135:             if ($coursehash{'checkforpriv'}) {
10136:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
10137:             }
10138:         }
10139:         foreach my $person (sort(keys(%coursepersonnel))) {
10140:             my $match = 0;
10141:             my $secmatch = 0;
10142:             my $status;
10143:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
10144:             $user =~ s/:$//;
10145:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
10146:             if ($end == -1 || $start == -1) {
10147:                 next;
10148:             }
10149:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
10150:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
10151:                 my ($uname,$udom) = split(/:/,$user);
10152:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
10153:                     if (grep(/^all$/,@{$sections})) {
10154:                         $secmatch = 1;
10155:                     } elsif ($usec eq '') {
10156:                         if (grep(/^none$/,@{$sections})) {
10157:                             $secmatch = 1;
10158:                         }
10159:                     } else {
10160:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
10161:                             $secmatch = 1;
10162:                         }
10163:                     }
10164:                     if (!$secmatch) {
10165:                         next;
10166:                     }
10167:                 }
10168:                 if ($usec eq '') {
10169:                     $usec = 'none';
10170:                 }
10171:                 if ($uname ne '' && $udom ne '') {
10172:                     if ($hidepriv) {
10173:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
10174:                             (!$nothide{$uname.':'.$udom})) {
10175:                             next;
10176:                         }
10177:                     }
10178:                     if ($end > 0 && $end < $now) {
10179:                         $status = 'previous';
10180:                     } elsif ($start > $now) {
10181:                         $status = 'future';
10182:                     } else {
10183:                         $status = 'active';
10184:                     }
10185:                     foreach my $type (keys(%{$types})) { 
10186:                         if ($status eq $type) {
10187:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
10188:                                 push(@{$$users{$role}{$user}},$type);
10189:                             }
10190:                             $match = 1;
10191:                         }
10192:                     }
10193:                     if (($match) && (ref($userdata) eq 'HASH')) {
10194:                         if (!exists($$userdata{$uname.':'.$udom})) {
10195: 			    &get_user_info($udom,$uname,\%idx,$userdata);
10196:                         }
10197:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
10198:                             push(@{$seclists{$uname.':'.$udom}},$usec);
10199:                         }
10200:                         if (ref($statushash) eq 'HASH') {
10201:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
10202:                         }
10203:                     }
10204:                 }
10205:             }
10206:         }
10207:         if (grep(/^ow$/,@{$roles})) {
10208:             if ((defined($cdom)) && (defined($cnum))) {
10209:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
10210:                 if ( defined($csettings{'internal.courseowner'}) ) {
10211:                     my $owner = $csettings{'internal.courseowner'};
10212:                     next if ($owner eq '');
10213:                     my ($ownername,$ownerdom);
10214:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
10215:                         $ownername = $1;
10216:                         $ownerdom = $2;
10217:                     } else {
10218:                         $ownername = $owner;
10219:                         $ownerdom = $cdom;
10220:                         $owner = $ownername.':'.$ownerdom;
10221:                     }
10222:                     @{$$users{'ow'}{$owner}} = 'any';
10223:                     if (defined($userdata) && 
10224: 			!exists($$userdata{$owner})) {
10225: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
10226:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
10227:                             push(@{$seclists{$owner}},'none');
10228:                         }
10229:                         if (ref($statushash) eq 'HASH') {
10230:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
10231:                         }
10232: 		    }
10233:                 }
10234:             }
10235:         }
10236:         foreach my $user (keys(%seclists)) {
10237:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
10238:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
10239:         }
10240:     }
10241:     return;
10242: }
10243: 
10244: sub get_user_info {
10245:     my ($udom,$uname,$idx,$userdata) = @_;
10246:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
10247: 	&plainname($uname,$udom,'lastname');
10248:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
10249:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
10250:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
10251:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
10252:     return;
10253: }
10254: 
10255: ###############################################
10256: 
10257: =pod
10258: 
10259: =item * &get_user_quota()
10260: 
10261: Retrieves quota assigned for storage of user files.
10262: Default is to report quota for portfolio files.
10263: 
10264: Incoming parameters:
10265: 1. user's username
10266: 2. user's domain
10267: 3. quota name - portfolio, author, or course
10268:    (if no quota name provided, defaults to portfolio).
10269: 4. crstype - official, unofficial, textbook or community, if quota name is
10270:    course
10271: 
10272: Returns:
10273: 1. Disk quota (in MB) assigned to student.
10274: 2. (Optional) Type of setting: custom or default
10275:    (individually assigned or default for user's 
10276:    institutional status).
10277: 3. (Optional) - User's institutional status (e.g., faculty, staff
10278:    or student - types as defined in localenroll::inst_usertypes 
10279:    for user's domain, which determines default quota for user.
10280: 4. (Optional) - Default quota which would apply to the user.
10281: 
10282: If a value has been stored in the user's environment, 
10283: it will return that, otherwise it returns the maximal default
10284: defined for the user's institutional status(es) in the domain.
10285: 
10286: =cut
10287: 
10288: ###############################################
10289: 
10290: 
10291: sub get_user_quota {
10292:     my ($uname,$udom,$quotaname,$crstype) = @_;
10293:     my ($quota,$quotatype,$settingstatus,$defquota);
10294:     if (!defined($udom)) {
10295:         $udom = $env{'user.domain'};
10296:     }
10297:     if (!defined($uname)) {
10298:         $uname = $env{'user.name'};
10299:     }
10300:     if (($udom eq '' || $uname eq '') ||
10301:         ($udom eq 'public') && ($uname eq 'public')) {
10302:         $quota = 0;
10303:         $quotatype = 'default';
10304:         $defquota = 0; 
10305:     } else {
10306:         my $inststatus;
10307:         if ($quotaname eq 'course') {
10308:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
10309:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
10310:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
10311:             } else {
10312:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
10313:                 $quota = $cenv{'internal.uploadquota'};
10314:             }
10315:         } else {
10316:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
10317:                 if ($quotaname eq 'author') {
10318:                     $quota = $env{'environment.authorquota'};
10319:                 } else {
10320:                     $quota = $env{'environment.portfolioquota'};
10321:                 }
10322:                 $inststatus = $env{'environment.inststatus'};
10323:             } else {
10324:                 my %userenv = 
10325:                     &Apache::lonnet::get('environment',['portfolioquota',
10326:                                          'authorquota','inststatus'],$udom,$uname);
10327:                 my ($tmp) = keys(%userenv);
10328:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10329:                     if ($quotaname eq 'author') {
10330:                         $quota = $userenv{'authorquota'};
10331:                     } else {
10332:                         $quota = $userenv{'portfolioquota'};
10333:                     }
10334:                     $inststatus = $userenv{'inststatus'};
10335:                 } else {
10336:                     undef(%userenv);
10337:                 }
10338:             }
10339:         }
10340:         if ($quota eq '' || wantarray) {
10341:             if ($quotaname eq 'course') {
10342:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
10343:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
10344:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
10345:                     $defquota = $domdefs{$crstype.'quota'};
10346:                 }
10347:                 if ($defquota eq '') {
10348:                     $defquota = 500;
10349:                 }
10350:             } else {
10351:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
10352:             }
10353:             if ($quota eq '') {
10354:                 $quota = $defquota;
10355:                 $quotatype = 'default';
10356:             } else {
10357:                 $quotatype = 'custom';
10358:             }
10359:         }
10360:     }
10361:     if (wantarray) {
10362:         return ($quota,$quotatype,$settingstatus,$defquota);
10363:     } else {
10364:         return $quota;
10365:     }
10366: }
10367: 
10368: ###############################################
10369: 
10370: =pod
10371: 
10372: =item * &default_quota()
10373: 
10374: Retrieves default quota assigned for storage of user portfolio files,
10375: given an (optional) user's institutional status.
10376: 
10377: Incoming parameters:
10378: 
10379: 1. domain
10380: 2. (Optional) institutional status(es).  This is a : separated list of 
10381:    status types (e.g., faculty, staff, student etc.)
10382:    which apply to the user for whom the default is being retrieved.
10383:    If the institutional status string in undefined, the domain
10384:    default quota will be returned.
10385: 3.  quota name - portfolio, author, or course
10386:    (if no quota name provided, defaults to portfolio).
10387: 
10388: Returns:
10389: 
10390: 1. Default disk quota (in MB) for user portfolios in the domain.
10391: 2. (Optional) institutional type which determined the value of the
10392:    default quota.
10393: 
10394: If a value has been stored in the domain's configuration db,
10395: it will return that, otherwise it returns 20 (for backwards 
10396: compatibility with domains which have not set up a configuration
10397: db file; the original statically defined portfolio quota was 20 MB). 
10398: 
10399: If the user's status includes multiple types (e.g., staff and student),
10400: the largest default quota which applies to the user determines the
10401: default quota returned.
10402: 
10403: =cut
10404: 
10405: ###############################################
10406: 
10407: 
10408: sub default_quota {
10409:     my ($udom,$inststatus,$quotaname) = @_;
10410:     my ($defquota,$settingstatus);
10411:     my %quotahash = &Apache::lonnet::get_dom('configuration',
10412:                                             ['quotas'],$udom);
10413:     my $key = 'defaultquota';
10414:     if ($quotaname eq 'author') {
10415:         $key = 'authorquota';
10416:     }
10417:     if (ref($quotahash{'quotas'}) eq 'HASH') {
10418:         if ($inststatus ne '') {
10419:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
10420:             foreach my $item (@statuses) {
10421:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
10422:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
10423:                         if ($defquota eq '') {
10424:                             $defquota = $quotahash{'quotas'}{$key}{$item};
10425:                             $settingstatus = $item;
10426:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
10427:                             $defquota = $quotahash{'quotas'}{$key}{$item};
10428:                             $settingstatus = $item;
10429:                         }
10430:                     }
10431:                 } elsif ($key eq 'defaultquota') {
10432:                     if ($quotahash{'quotas'}{$item} ne '') {
10433:                         if ($defquota eq '') {
10434:                             $defquota = $quotahash{'quotas'}{$item};
10435:                             $settingstatus = $item;
10436:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
10437:                             $defquota = $quotahash{'quotas'}{$item};
10438:                             $settingstatus = $item;
10439:                         }
10440:                     }
10441:                 }
10442:             }
10443:         }
10444:         if ($defquota eq '') {
10445:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
10446:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
10447:             } elsif ($key eq 'defaultquota') {
10448:                 $defquota = $quotahash{'quotas'}{'default'};
10449:             }
10450:             $settingstatus = 'default';
10451:             if ($defquota eq '') {
10452:                 if ($quotaname eq 'author') {
10453:                     $defquota = 500;
10454:                 }
10455:             }
10456:         }
10457:     } else {
10458:         $settingstatus = 'default';
10459:         if ($quotaname eq 'author') {
10460:             $defquota = 500;
10461:         } else {
10462:             $defquota = 20;
10463:         }
10464:     }
10465:     if (wantarray) {
10466:         return ($defquota,$settingstatus);
10467:     } else {
10468:         return $defquota;
10469:     }
10470: }
10471: 
10472: ###############################################
10473: 
10474: =pod
10475: 
10476: =item * &excess_filesize_warning()
10477: 
10478: Returns warning message if upload of file to authoring space, or copying
10479: of existing file within authoring space will cause quota for the authoring
10480: space to be exceeded.
10481: 
10482: Same, if upload of a file directly to a course/community via Course Editor
10483: will cause quota for uploaded content for the course to be exceeded.
10484: 
10485: Inputs: 7 
10486: 1. username or coursenum
10487: 2. domain
10488: 3. context ('author' or 'course')
10489: 4. filename of file for which action is being requested
10490: 5. filesize (kB) of file
10491: 6. action being taken: copy or upload.
10492: 7. quotatype (in course context -- official, unofficial, community or textbook).
10493: 
10494: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
10495:          otherwise return null.
10496: 
10497: =back
10498: 
10499: =cut
10500: 
10501: sub excess_filesize_warning {
10502:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
10503:     my $current_disk_usage = 0;
10504:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
10505:     if ($context eq 'author') {
10506:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
10507:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
10508:     } else {
10509:         foreach my $subdir ('docs','supplemental') {
10510:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
10511:         }
10512:     }
10513:     $disk_quota = int($disk_quota * 1000);
10514:     if (($current_disk_usage + $filesize) > $disk_quota) {
10515:         return '<p class="LC_warning">'.
10516:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
10517:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
10518:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
10519:                             $disk_quota,$current_disk_usage).
10520:                '</p>';
10521:     }
10522:     return;
10523: }
10524: 
10525: ###############################################
10526: 
10527: 
10528: sub get_secgrprole_info {
10529:     my ($cdom,$cnum,$needroles,$type)  = @_;
10530:     my %sections_count = &get_sections($cdom,$cnum);
10531:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
10532:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
10533:     my @groups = sort(keys(%curr_groups));
10534:     my $allroles = [];
10535:     my $rolehash;
10536:     my $accesshash = {
10537:                      active => 'Currently has access',
10538:                      future => 'Will have future access',
10539:                      previous => 'Previously had access',
10540:                   };
10541:     if ($needroles) {
10542:         $rolehash = {'all' => 'all'};
10543:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10544: 	if (&Apache::lonnet::error(%user_roles)) {
10545: 	    undef(%user_roles);
10546: 	}
10547:         foreach my $item (keys(%user_roles)) {
10548:             my ($role)=split(/\:/,$item,2);
10549:             if ($role eq 'cr') { next; }
10550:             if ($role =~ /^cr/) {
10551:                 $$rolehash{$role} = (split('/',$role))[3];
10552:             } else {
10553:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
10554:             }
10555:         }
10556:         foreach my $key (sort(keys(%{$rolehash}))) {
10557:             push(@{$allroles},$key);
10558:         }
10559:         push (@{$allroles},'st');
10560:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
10561:     }
10562:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
10563: }
10564: 
10565: sub user_picker {
10566:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
10567:     my $currdom = $dom;
10568:     my @alldoms = &Apache::lonnet::all_domains();
10569:     if (@alldoms == 1) {
10570:         my %domsrch = &Apache::lonnet::get_dom('configuration',
10571:                                                ['directorysrch'],$alldoms[0]);
10572:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
10573:         my $showdom = $domdesc;
10574:         if ($showdom eq '') {
10575:             $showdom = $dom;
10576:         }
10577:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
10578:             if ((!$domsrch{'directorysrch'}{'available'}) &&
10579:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
10580:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
10581:             }
10582:         }
10583:     }
10584:     my %curr_selected = (
10585:                         srchin => 'dom',
10586:                         srchby => 'lastname',
10587:                       );
10588:     my $srchterm;
10589:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
10590:         if ($srch->{'srchby'} ne '') {
10591:             $curr_selected{'srchby'} = $srch->{'srchby'};
10592:         }
10593:         if ($srch->{'srchin'} ne '') {
10594:             $curr_selected{'srchin'} = $srch->{'srchin'};
10595:         }
10596:         if ($srch->{'srchtype'} ne '') {
10597:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
10598:         }
10599:         if ($srch->{'srchdomain'} ne '') {
10600:             $currdom = $srch->{'srchdomain'};
10601:         }
10602:         $srchterm = $srch->{'srchterm'};
10603:     }
10604:     my %html_lt=&Apache::lonlocal::texthash(
10605:                     'usr'       => 'Search criteria',
10606:                     'doma'      => 'Domain/institution to search',
10607:                     'uname'     => 'username',
10608:                     'lastname'  => 'last name',
10609:                     'lastfirst' => 'last name, first name',
10610:                     'crs'       => 'in this course',
10611:                     'dom'       => 'in selected LON-CAPA domain', 
10612:                     'alc'       => 'all LON-CAPA',
10613:                     'instd'     => 'in institutional directory for selected domain',
10614:                     'exact'     => 'is',
10615:                     'contains'  => 'contains',
10616:                     'begins'    => 'begins with',
10617:                                        );
10618:     my %js_lt=&Apache::lonlocal::texthash(
10619:                     'youm'      => "You must include some text to search for.",
10620:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
10621:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
10622:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
10623:                     'ymcd'      => "You must choose a domain when using a domain search.",
10624:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
10625:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
10626:                      'thfo'     => "The following need to be corrected before the search can be run:",
10627:                                        );
10628:     &html_escape(\%html_lt);
10629:     &js_escape(\%js_lt);
10630:     my $domform;
10631:     my $allow_blank = 1;
10632:     if ($fixeddom) {
10633:         $allow_blank = 0;
10634:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
10635:     } else {
10636:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1);
10637:     }
10638:     my $srchinsel = ' <select name="srchin">';
10639: 
10640:     my @srchins = ('crs','dom','alc','instd');
10641: 
10642:     foreach my $option (@srchins) {
10643:         # FIXME 'alc' option unavailable until 
10644:         #       loncreateuser::print_user_query_page()
10645:         #       has been completed.
10646:         next if ($option eq 'alc');
10647:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
10648:         next if ($option eq 'crs' && !$env{'request.course.id'});
10649:         next if (($option eq 'instd') && ($noinstd));
10650:         if ($curr_selected{'srchin'} eq $option) {
10651:             $srchinsel .= ' 
10652:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10653:         } else {
10654:             $srchinsel .= '
10655:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10656:         }
10657:     }
10658:     $srchinsel .= "\n  </select>\n";
10659: 
10660:     my $srchbysel =  ' <select name="srchby">';
10661:     foreach my $option ('lastname','lastfirst','uname') {
10662:         if ($curr_selected{'srchby'} eq $option) {
10663:             $srchbysel .= '
10664:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10665:         } else {
10666:             $srchbysel .= '
10667:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10668:          }
10669:     }
10670:     $srchbysel .= "\n  </select>\n";
10671: 
10672:     my $srchtypesel = ' <select name="srchtype">';
10673:     foreach my $option ('begins','contains','exact') {
10674:         if ($curr_selected{'srchtype'} eq $option) {
10675:             $srchtypesel .= '
10676:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10677:         } else {
10678:             $srchtypesel .= '
10679:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10680:         }
10681:     }
10682:     $srchtypesel .= "\n  </select>\n";
10683: 
10684:     my ($newuserscript,$new_user_create);
10685:     my $context_dom = $env{'request.role.domain'};
10686:     if ($context eq 'requestcrs') {
10687:         if ($env{'form.coursedom'} ne '') { 
10688:             $context_dom = $env{'form.coursedom'};
10689:         }
10690:     }
10691:     if ($forcenewuser) {
10692:         if (ref($srch) eq 'HASH') {
10693:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
10694:                 if ($cancreate) {
10695:                     $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>';
10696:                 } else {
10697:                     my $helplink = 'javascript:helpMenu('."'display'".')';
10698:                     my %usertypetext = (
10699:                         official   => 'institutional',
10700:                         unofficial => 'non-institutional',
10701:                     );
10702:                     $new_user_create = '<p class="LC_warning">'
10703:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
10704:                                       .' '
10705:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
10706:                                           ,'<a href="'.$helplink.'">','</a>')
10707:                                       .'</p><br />';
10708:                 }
10709:             }
10710:         }
10711: 
10712:         $newuserscript = <<"ENDSCRIPT";
10713: 
10714: function setSearch(createnew,callingForm) {
10715:     if (createnew == 1) {
10716:         for (var i=0; i<callingForm.srchby.length; i++) {
10717:             if (callingForm.srchby.options[i].value == 'uname') {
10718:                 callingForm.srchby.selectedIndex = i;
10719:             }
10720:         }
10721:         for (var i=0; i<callingForm.srchin.length; i++) {
10722:             if ( callingForm.srchin.options[i].value == 'dom') {
10723: 		callingForm.srchin.selectedIndex = i;
10724:             }
10725:         }
10726:         for (var i=0; i<callingForm.srchtype.length; i++) {
10727:             if (callingForm.srchtype.options[i].value == 'exact') {
10728:                 callingForm.srchtype.selectedIndex = i;
10729:             }
10730:         }
10731:         for (var i=0; i<callingForm.srchdomain.length; i++) {
10732:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
10733:                 callingForm.srchdomain.selectedIndex = i;
10734:             }
10735:         }
10736:     }
10737: }
10738: ENDSCRIPT
10739: 
10740:     }
10741: 
10742:     my $output = <<"END_BLOCK";
10743: <script type="text/javascript">
10744: // <![CDATA[
10745: function validateEntry(callingForm) {
10746: 
10747:     var checkok = 1;
10748:     var srchin;
10749:     for (var i=0; i<callingForm.srchin.length; i++) {
10750: 	if ( callingForm.srchin[i].checked ) {
10751: 	    srchin = callingForm.srchin[i].value;
10752: 	}
10753:     }
10754: 
10755:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
10756:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
10757:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
10758:     var srchterm =  callingForm.srchterm.value;
10759:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
10760:     var msg = "";
10761: 
10762:     if (srchterm == "") {
10763:         checkok = 0;
10764:         msg += "$js_lt{'youm'}\\n";
10765:     }
10766: 
10767:     if (srchtype== 'begins') {
10768:         if (srchterm.length < 2) {
10769:             checkok = 0;
10770:             msg += "$js_lt{'thte'}\\n";
10771:         }
10772:     }
10773: 
10774:     if (srchtype== 'contains') {
10775:         if (srchterm.length < 3) {
10776:             checkok = 0;
10777:             msg += "$js_lt{'thet'}\\n";
10778:         }
10779:     }
10780:     if (srchin == 'instd') {
10781:         if (srchdomain == '') {
10782:             checkok = 0;
10783:             msg += "$js_lt{'yomc'}\\n";
10784:         }
10785:     }
10786:     if (srchin == 'dom') {
10787:         if (srchdomain == '') {
10788:             checkok = 0;
10789:             msg += "$js_lt{'ymcd'}\\n";
10790:         }
10791:     }
10792:     if (srchby == 'lastfirst') {
10793:         if (srchterm.indexOf(",") == -1) {
10794:             checkok = 0;
10795:             msg += "$js_lt{'whus'}\\n";
10796:         }
10797:         if (srchterm.indexOf(",") == srchterm.length -1) {
10798:             checkok = 0;
10799:             msg += "$js_lt{'whse'}\\n";
10800:         }
10801:     }
10802:     if (checkok == 0) {
10803:         alert("$js_lt{'thfo'}\\n"+msg);
10804:         return;
10805:     }
10806:     if (checkok == 1) {
10807:         callingForm.submit();
10808:     }
10809: }
10810: 
10811: $newuserscript
10812: 
10813: // ]]>
10814: </script>
10815: 
10816: $new_user_create
10817: 
10818: END_BLOCK
10819: 
10820:     $output .= &Apache::lonhtmlcommon::start_pick_box().
10821:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
10822:                $domform.
10823:                &Apache::lonhtmlcommon::row_closure().
10824:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
10825:                $srchbysel.
10826:                $srchtypesel. 
10827:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
10828:                $srchinsel.
10829:                &Apache::lonhtmlcommon::row_closure(1). 
10830:                &Apache::lonhtmlcommon::end_pick_box().
10831:                '<br />';
10832:     return ($output,1);
10833: }
10834: 
10835: sub user_rule_check {
10836:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
10837:     my ($response,%inst_response);
10838:     if (ref($usershash) eq 'HASH') {
10839:         if (keys(%{$usershash}) > 1) {
10840:             my (%by_username,%by_id,%userdoms);
10841:             my $checkid;
10842:             if (ref($checks) eq 'HASH') {
10843:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
10844:                     $checkid = 1;
10845:                 }
10846:             }
10847:             foreach my $user (keys(%{$usershash})) {
10848:                 my ($uname,$udom) = split(/:/,$user);
10849:                 if ($checkid) {
10850:                     if (ref($usershash->{$user}) eq 'HASH') {
10851:                         if ($usershash->{$user}->{'id'} ne '') {
10852:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
10853:                             $userdoms{$udom} = 1;
10854:                             if (ref($inst_results) eq 'HASH') {
10855:                                 $inst_results->{$uname.':'.$udom} = {};
10856:                             }
10857:                         }
10858:                     }
10859:                 } else {
10860:                     $by_username{$udom}{$uname} = 1;
10861:                     $userdoms{$udom} = 1;
10862:                     if (ref($inst_results) eq 'HASH') {
10863:                         $inst_results->{$uname.':'.$udom} = {};
10864:                     }
10865:                 }
10866:             }
10867:             foreach my $udom (keys(%userdoms)) {
10868:                 if (!$got_rules->{$udom}) {
10869:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
10870:                                                              ['usercreation'],$udom);
10871:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
10872:                         foreach my $item ('username','id') {
10873:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10874:                                 $$curr_rules{$udom}{$item} =
10875:                                     $domconfig{'usercreation'}{$item.'_rule'};
10876:                             }
10877:                         }
10878:                     }
10879:                     $got_rules->{$udom} = 1;
10880:                 }
10881:             }
10882:             if ($checkid) {
10883:                 foreach my $udom (keys(%by_id)) {
10884:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
10885:                     if ($outcome eq 'ok') {
10886:                         foreach my $id (keys(%{$by_id{$udom}})) {
10887:                             my $uname = $by_id{$udom}{$id};
10888:                             $inst_response{$uname.':'.$udom} = $outcome;
10889:                         }
10890:                         if (ref($results) eq 'HASH') {
10891:                             foreach my $uname (keys(%{$results})) {
10892:                                 if (exists($inst_response{$uname.':'.$udom})) {
10893:                                     $inst_response{$uname.':'.$udom} = $outcome;
10894:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
10895:                                 }
10896:                             }
10897:                         }
10898:                     }
10899:                 }
10900:             } else {
10901:                 foreach my $udom (keys(%by_username)) {
10902:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
10903:                     if ($outcome eq 'ok') {
10904:                         foreach my $uname (keys(%{$by_username{$udom}})) {
10905:                             $inst_response{$uname.':'.$udom} = $outcome;
10906:                         }
10907:                         if (ref($results) eq 'HASH') {
10908:                             foreach my $uname (keys(%{$results})) {
10909:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
10910:                             }
10911:                         }
10912:                     }
10913:                 }
10914:             }
10915:         } elsif (keys(%{$usershash}) == 1) {
10916:             my $user = (keys(%{$usershash}))[0];
10917:             my ($uname,$udom) = split(/:/,$user);
10918:             if (($udom ne '') && ($uname ne '')) {
10919:                 if (ref($usershash->{$user}) eq 'HASH') {
10920:                     if (ref($checks) eq 'HASH') {
10921:                         if (defined($checks->{'username'})) {
10922:                             ($inst_response{$user},%{$inst_results->{$user}}) =
10923:                                 &Apache::lonnet::get_instuser($udom,$uname);
10924:                         } elsif (defined($checks->{'id'})) {
10925:                             if ($usershash->{$user}->{'id'} ne '') {
10926:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
10927:                                     &Apache::lonnet::get_instuser($udom,undef,
10928:                                                                   $usershash->{$user}->{'id'});
10929:                             } else {
10930:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
10931:                                     &Apache::lonnet::get_instuser($udom,$uname);
10932:                             }
10933:                         }
10934:                     } else {
10935:                        ($inst_response{$user},%{$inst_results->{$user}}) =
10936:                             &Apache::lonnet::get_instuser($udom,$uname);
10937:                        return;
10938:                     }
10939:                     if (!$got_rules->{$udom}) {
10940:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
10941:                                                                  ['usercreation'],$udom);
10942:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
10943:                             foreach my $item ('username','id') {
10944:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10945:                                    $$curr_rules{$udom}{$item} =
10946:                                        $domconfig{'usercreation'}{$item.'_rule'};
10947:                                 }
10948:                             }
10949:                         }
10950:                         $got_rules->{$udom} = 1;
10951:                     }
10952:                 }
10953:             } else {
10954:                 return;
10955:             }
10956:         } else {
10957:             return;
10958:         }
10959:         foreach my $user (keys(%{$usershash})) {
10960:             my ($uname,$udom) = split(/:/,$user);
10961:             next if (($udom eq '') || ($uname eq ''));
10962:             my $id;
10963:             if (ref($inst_results) eq 'HASH') {
10964:                 if (ref($inst_results->{$user}) eq 'HASH') {
10965:                     $id = $inst_results->{$user}->{'id'};
10966:                 }
10967:             }
10968:             if ($id eq '') {
10969:                 if (ref($usershash->{$user})) {
10970:                     $id = $usershash->{$user}->{'id'};
10971:                 }
10972:             }
10973:             foreach my $item (keys(%{$checks})) {
10974:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
10975:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
10976:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
10977:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
10978:                                                                              $$curr_rules{$udom}{$item});
10979:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
10980:                                 if ($rule_check{$rule}) {
10981:                                     $$rulematch{$user}{$item} = $rule;
10982:                                     if ($inst_response{$user} eq 'ok') {
10983:                                         if (ref($inst_results) eq 'HASH') {
10984:                                             if (ref($inst_results->{$user}) eq 'HASH') {
10985:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
10986:                                                     $$alerts{$item}{$udom}{$uname} = 1;
10987:                                                 } elsif ($item eq 'id') {
10988:                                                     if ($inst_results->{$user}->{'id'} eq '') {
10989:                                                         $$alerts{$item}{$udom}{$uname} = 1;
10990:                                                     }
10991:                                                 }
10992:                                             }
10993:                                         }
10994:                                     }
10995:                                     last;
10996:                                 }
10997:                             }
10998:                         }
10999:                     }
11000:                 }
11001:             }
11002:         }
11003:     }
11004:     return;
11005: }
11006: 
11007: sub user_rule_formats {
11008:     my ($domain,$domdesc,$curr_rules,$check) = @_;
11009:     my %text = ( 
11010:                  'username' => 'Usernames',
11011:                  'id'       => 'IDs',
11012:                );
11013:     my $output;
11014:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
11015:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
11016:         if (@{$ruleorder} > 0) {
11017:             $output = '<br />'.
11018:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
11019:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
11020:                       ' <ul>';
11021:             foreach my $rule (@{$ruleorder}) {
11022:                 if (ref($curr_rules) eq 'ARRAY') {
11023:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
11024:                         if (ref($rules->{$rule}) eq 'HASH') {
11025:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
11026:                                         $rules->{$rule}{'desc'}.'</li>';
11027:                         }
11028:                     }
11029:                 }
11030:             }
11031:             $output .= '</ul>';
11032:         }
11033:     }
11034:     return $output;
11035: }
11036: 
11037: sub instrule_disallow_msg {
11038:     my ($checkitem,$domdesc,$count,$mode) = @_;
11039:     my $response;
11040:     my %text = (
11041:                   item   => 'username',
11042:                   items  => 'usernames',
11043:                   match  => 'matches',
11044:                   do     => 'does',
11045:                   action => 'a username',
11046:                   one    => 'one',
11047:                );
11048:     if ($count > 1) {
11049:         $text{'item'} = 'usernames';
11050:         $text{'match'} ='match';
11051:         $text{'do'} = 'do';
11052:         $text{'action'} = 'usernames',
11053:         $text{'one'} = 'ones';
11054:     }
11055:     if ($checkitem eq 'id') {
11056:         $text{'items'} = 'IDs';
11057:         $text{'item'} = 'ID';
11058:         $text{'action'} = 'an ID';
11059:         if ($count > 1) {
11060:             $text{'item'} = 'IDs';
11061:             $text{'action'} = 'IDs';
11062:         }
11063:     }
11064:     $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 />';
11065:     if ($mode eq 'upload') {
11066:         if ($checkitem eq 'username') {
11067:             $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'}.");
11068:         } elsif ($checkitem eq 'id') {
11069:             $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.");
11070:         }
11071:     } elsif ($mode eq 'selfcreate') {
11072:         if ($checkitem eq 'id') {
11073:             $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.");
11074:         }
11075:     } else {
11076:         if ($checkitem eq 'username') {
11077:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
11078:         } elsif ($checkitem eq 'id') {
11079:             $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.");
11080:         }
11081:     }
11082:     return $response;
11083: }
11084: 
11085: sub personal_data_fieldtitles {
11086:     my %fieldtitles = &Apache::lonlocal::texthash (
11087:                         id => 'Student/Employee ID',
11088:                         permanentemail => 'E-mail address',
11089:                         lastname => 'Last Name',
11090:                         firstname => 'First Name',
11091:                         middlename => 'Middle Name',
11092:                         generation => 'Generation',
11093:                         gen => 'Generation',
11094:                         inststatus => 'Affiliation',
11095:                    );
11096:     return %fieldtitles;
11097: }
11098: 
11099: sub sorted_inst_types {
11100:     my ($dom) = @_;
11101:     my ($usertypes,$order);
11102:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
11103:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
11104:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
11105:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
11106:     } else {
11107:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
11108:     }
11109:     my $othertitle = &mt('All users');
11110:     if ($env{'request.course.id'}) {
11111:         $othertitle  = &mt('Any users');
11112:     }
11113:     my @types;
11114:     if (ref($order) eq 'ARRAY') {
11115:         @types = @{$order};
11116:     }
11117:     if (@types == 0) {
11118:         if (ref($usertypes) eq 'HASH') {
11119:             @types = sort(keys(%{$usertypes}));
11120:         }
11121:     }
11122:     if (keys(%{$usertypes}) > 0) {
11123:         $othertitle = &mt('Other users');
11124:     }
11125:     return ($othertitle,$usertypes,\@types);
11126: }
11127: 
11128: sub get_institutional_codes {
11129:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
11130: # Get complete list of course sections to update
11131:     my @currsections = ();
11132:     my @currxlists = ();
11133:     my (%unclutteredsec,%unclutteredlcsec);
11134:     my $coursecode = $$settings{'internal.coursecode'};
11135:     my $crskey = $crs.':'.$coursecode;
11136:     @{$unclutteredsec{$crskey}} = ();
11137:     @{$unclutteredlcsec{$crskey}} = ();
11138: 
11139:     if ($$settings{'internal.sectionnums'} ne '') {
11140:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
11141:     }
11142: 
11143:     if ($$settings{'internal.crosslistings'} ne '') {
11144:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
11145:     }
11146: 
11147:     if (@currxlists > 0) {
11148:         foreach my $xl (@currxlists) {
11149:             if ($xl =~ /^([^:]+):(\w*)$/) {
11150:                 unless (grep/^$1$/,@{$allcourses}) {
11151:                     push(@{$allcourses},$1);
11152:                     $$LC_code{$1} = $2;
11153:                 }
11154:             }
11155:         }
11156:     }
11157: 
11158:     if (@currsections > 0) {
11159:         foreach my $sec (@currsections) {
11160:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
11161:                 my $instsec = $1;
11162:                 my $lc_sec = $2;
11163:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
11164:                     push(@{$unclutteredsec{$crskey}},$instsec);
11165:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
11166:                 }
11167:             }
11168:         }
11169:     }
11170: 
11171:     if (@{$unclutteredsec{$crskey}} > 0) {
11172:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
11173:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
11174:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
11175:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
11176:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
11177:                     push(@{$allcourses},$sec);
11178:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
11179:                 }
11180:             }
11181:         }
11182:     }
11183:     return;
11184: }
11185: 
11186: sub get_standard_codeitems {
11187:     return ('Year','Semester','Department','Number','Section');
11188: }
11189: 
11190: =pod
11191: 
11192: =head1 Slot Helpers
11193: 
11194: =over 4
11195: 
11196: =item * sorted_slots()
11197: 
11198: Sorts an array of slot names in order of an optional sort key,
11199: default sort is by slot start time (earliest first). 
11200: 
11201: Inputs:
11202: 
11203: =over 4
11204: 
11205: slotsarr  - Reference to array of unsorted slot names.
11206: 
11207: slots     - Reference to hash of hash, where outer hash keys are slot names.
11208: 
11209: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
11210: 
11211: =back
11212: 
11213: Returns:
11214: 
11215: =over 4
11216: 
11217: sorted   - An array of slot names sorted by a specified sort key 
11218:            (default sort key is start time of the slot).
11219: 
11220: =back
11221: 
11222: =cut
11223: 
11224: 
11225: sub sorted_slots {
11226:     my ($slotsarr,$slots,$sortkey) = @_;
11227:     if ($sortkey eq '') {
11228:         $sortkey = 'starttime';
11229:     }
11230:     my @sorted;
11231:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
11232:         @sorted =
11233:             sort {
11234:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
11235:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
11236:                      }
11237:                      if (ref($slots->{$a})) { return -1;}
11238:                      if (ref($slots->{$b})) { return 1;}
11239:                      return 0;
11240:                  } @{$slotsarr};
11241:     }
11242:     return @sorted;
11243: }
11244: 
11245: =pod
11246: 
11247: =item * get_future_slots()
11248: 
11249: Inputs:
11250: 
11251: =over 4
11252: 
11253: cnum - course number
11254: 
11255: cdom - course domain
11256: 
11257: now - current UNIX time
11258: 
11259: symb - optional symb
11260: 
11261: =back
11262: 
11263: Returns:
11264: 
11265: =over 4
11266: 
11267: sorted_reservable - ref to array of student_schedulable slots currently 
11268:                     reservable, ordered by end date of reservation period.
11269: 
11270: reservable_now - ref to hash of student_schedulable slots currently
11271:                  reservable.
11272: 
11273:     Keys in inner hash are:
11274:     (a) symb: either blank or symb to which slot use is restricted.
11275:     (b) endreserve: end date of reservation period.
11276:     (c) uniqueperiod: start,end dates when slot is to be uniquely
11277:         selected.
11278: 
11279: sorted_future - ref to array of student_schedulable slots reservable in
11280:                 the future, ordered by start date of reservation period.
11281: 
11282: future_reservable - ref to hash of student_schedulable slots reservable
11283:                     in the future.
11284: 
11285:     Keys in inner hash are:
11286:     (a) symb: either blank or symb to which slot use is restricted.
11287:     (b) startreserve:  start date of reservation period.
11288:     (c) uniqueperiod: start,end dates when slot is to be uniquely
11289:         selected.
11290: 
11291: =back
11292: 
11293: =cut
11294: 
11295: sub get_future_slots {
11296:     my ($cnum,$cdom,$now,$symb) = @_;
11297:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
11298:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
11299:     foreach my $slot (keys(%slots)) {
11300:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
11301:         if ($symb) {
11302:             next if (($slots{$slot}->{'symb'} ne '') && 
11303:                      ($slots{$slot}->{'symb'} ne $symb));
11304:         }
11305:         if (($slots{$slot}->{'starttime'} > $now) &&
11306:             ($slots{$slot}->{'endtime'} > $now)) {
11307:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
11308:                 my $userallowed = 0;
11309:                 if ($slots{$slot}->{'allowedsections'}) {
11310:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
11311:                     if (!defined($env{'request.role.sec'})
11312:                         && grep(/^No section assigned$/,@allowed_sec)) {
11313:                         $userallowed=1;
11314:                     } else {
11315:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
11316:                             $userallowed=1;
11317:                         }
11318:                     }
11319:                     unless ($userallowed) {
11320:                         if (defined($env{'request.course.groups'})) {
11321:                             my @groups = split(/:/,$env{'request.course.groups'});
11322:                             foreach my $group (@groups) {
11323:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
11324:                                     $userallowed=1;
11325:                                     last;
11326:                                 }
11327:                             }
11328:                         }
11329:                     }
11330:                 }
11331:                 if ($slots{$slot}->{'allowedusers'}) {
11332:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
11333:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
11334:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
11335:                         $userallowed = 1;
11336:                     }
11337:                 }
11338:                 next unless($userallowed);
11339:             }
11340:             my $startreserve = $slots{$slot}->{'startreserve'};
11341:             my $endreserve = $slots{$slot}->{'endreserve'};
11342:             my $symb = $slots{$slot}->{'symb'};
11343:             my $uniqueperiod;
11344:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
11345:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
11346:             }
11347:             if (($startreserve < $now) &&
11348:                 (!$endreserve || $endreserve > $now)) {
11349:                 my $lastres = $endreserve;
11350:                 if (!$lastres) {
11351:                     $lastres = $slots{$slot}->{'starttime'};
11352:                 }
11353:                 $reservable_now{$slot} = {
11354:                                            symb       => $symb,
11355:                                            endreserve => $lastres,
11356:                                            uniqueperiod => $uniqueperiod,   
11357:                                          };
11358:             } elsif (($startreserve > $now) &&
11359:                      (!$endreserve || $endreserve > $startreserve)) {
11360:                 $future_reservable{$slot} = {
11361:                                               symb         => $symb,
11362:                                               startreserve => $startreserve,
11363:                                               uniqueperiod => $uniqueperiod,
11364:                                             };
11365:             }
11366:         }
11367:     }
11368:     my @unsorted_reservable = keys(%reservable_now);
11369:     if (@unsorted_reservable > 0) {
11370:         @sorted_reservable = 
11371:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
11372:     }
11373:     my @unsorted_future = keys(%future_reservable);
11374:     if (@unsorted_future > 0) {
11375:         @sorted_future =
11376:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
11377:     }
11378:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
11379: }
11380: 
11381: =pod
11382: 
11383: =back
11384: 
11385: =head1 HTTP Helpers
11386: 
11387: =over 4
11388: 
11389: =item * &get_unprocessed_cgi($query,$possible_names)
11390: 
11391: Modify the %env hash to contain unprocessed CGI form parameters held in
11392: $query.  The parameters listed in $possible_names (an array reference),
11393: will be set in $env{'form.name'} if they do not already exist.
11394: 
11395: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
11396: $possible_names is an ref to an array of form element names.  As an example:
11397: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
11398: will result in $env{'form.uname'} and $env{'form.udom'} being set.
11399: 
11400: =cut
11401: 
11402: sub get_unprocessed_cgi {
11403:   my ($query,$possible_names)= @_;
11404:   # $Apache::lonxml::debug=1;
11405:   foreach my $pair (split(/&/,$query)) {
11406:     my ($name, $value) = split(/=/,$pair);
11407:     $name = &unescape($name);
11408:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
11409:       $value =~ tr/+/ /;
11410:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
11411:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
11412:     }
11413:   }
11414: }
11415: 
11416: =pod
11417: 
11418: =item * &cacheheader() 
11419: 
11420: returns cache-controlling header code
11421: 
11422: =cut
11423: 
11424: sub cacheheader {
11425:     unless ($env{'request.method'} eq 'GET') { return ''; }
11426:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
11427:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
11428:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
11429:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
11430:     return $output;
11431: }
11432: 
11433: =pod
11434: 
11435: =item * &no_cache($r) 
11436: 
11437: specifies header code to not have cache
11438: 
11439: =cut
11440: 
11441: sub no_cache {
11442:     my ($r) = @_;
11443:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
11444: 	$env{'request.method'} ne 'GET') { return ''; }
11445:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
11446:     $r->no_cache(1);
11447:     $r->header_out("Expires" => $date);
11448:     $r->header_out("Pragma" => "no-cache");
11449: }
11450: 
11451: sub content_type {
11452:     my ($r,$type,$charset) = @_;
11453:     if ($r) {
11454: 	#  Note that printout.pl calls this with undef for $r.
11455: 	&no_cache($r);
11456:     }
11457:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
11458:     unless ($charset) {
11459: 	$charset=&Apache::lonlocal::current_encoding;
11460:     }
11461:     if ($charset) { $type.='; charset='.$charset; }
11462:     if ($r) {
11463: 	$r->content_type($type);
11464:     } else {
11465: 	print("Content-type: $type\n\n");
11466:     }
11467: }
11468: 
11469: =pod
11470: 
11471: =item * &add_to_env($name,$value) 
11472: 
11473: adds $name to the %env hash with value
11474: $value, if $name already exists, the entry is converted to an array
11475: reference and $value is added to the array.
11476: 
11477: =cut
11478: 
11479: sub add_to_env {
11480:   my ($name,$value)=@_;
11481:   if (defined($env{$name})) {
11482:     if (ref($env{$name})) {
11483:       #already have multiple values
11484:       push(@{ $env{$name} },$value);
11485:     } else {
11486:       #first time seeing multiple values, convert hash entry to an arrayref
11487:       my $first=$env{$name};
11488:       undef($env{$name});
11489:       push(@{ $env{$name} },$first,$value);
11490:     }
11491:   } else {
11492:     $env{$name}=$value;
11493:   }
11494: }
11495: 
11496: =pod
11497: 
11498: =item * &get_env_multiple($name) 
11499: 
11500: gets $name from the %env hash, it seemlessly handles the cases where multiple
11501: values may be defined and end up as an array ref.
11502: 
11503: returns an array of values
11504: 
11505: =cut
11506: 
11507: sub get_env_multiple {
11508:     my ($name) = @_;
11509:     my @values;
11510:     if (defined($env{$name})) {
11511:         # exists is it an array
11512:         if (ref($env{$name})) {
11513:             @values=@{ $env{$name} };
11514:         } else {
11515:             $values[0]=$env{$name};
11516:         }
11517:     }
11518:     return(@values);
11519: }
11520: 
11521: sub ask_for_embedded_content {
11522:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
11523:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
11524:         %currsubfile,%unused,$rem);
11525:     my $counter = 0;
11526:     my $numnew = 0;
11527:     my $numremref = 0;
11528:     my $numinvalid = 0;
11529:     my $numpathchg = 0;
11530:     my $numexisting = 0;
11531:     my $numunused = 0;
11532:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
11533:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
11534:     my $heading = &mt('Upload embedded files');
11535:     my $buttontext = &mt('Upload');
11536: 
11537:     if ($env{'request.course.id'}) {
11538:         if ($actionurl eq '/adm/dependencies') {
11539:             $navmap = Apache::lonnavmaps::navmap->new();
11540:         }
11541:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11542:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11543:     }
11544:     if (($actionurl eq '/adm/portfolio') ||
11545:         ($actionurl eq '/adm/coursegrp_portfolio')) {
11546:         my $current_path='/';
11547:         if ($env{'form.currentpath'}) {
11548:             $current_path = $env{'form.currentpath'};
11549:         }
11550:         if ($actionurl eq '/adm/coursegrp_portfolio') {
11551:             $udom = $cdom;
11552:             $uname = $cnum;
11553:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
11554:         } else {
11555:             $udom = $env{'user.domain'};
11556:             $uname = $env{'user.name'};
11557:             $url = '/userfiles/portfolio';
11558:         }
11559:         $toplevel = $url.'/';
11560:         $url .= $current_path;
11561:         $getpropath = 1;
11562:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
11563:              ($actionurl eq '/adm/imsimport')) { 
11564:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
11565:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
11566:         $toplevel = $url;
11567:         if ($rest ne '') {
11568:             $url .= $rest;
11569:         }
11570:     } elsif ($actionurl eq '/adm/coursedocs') {
11571:         if (ref($args) eq 'HASH') {
11572:             $url = $args->{'docs_url'};
11573:             $toplevel = $url;
11574:             if ($args->{'context'} eq 'paste') {
11575:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
11576:                 ($path) =
11577:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
11578:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
11579:                 $fileloc =~ s{^/}{};
11580:             }
11581:         }
11582:     } elsif ($actionurl eq '/adm/dependencies') {
11583:         if ($env{'request.course.id'} ne '') {
11584:             if (ref($args) eq 'HASH') {
11585:                 $url = $args->{'docs_url'};
11586:                 $title = $args->{'docs_title'};
11587:                 $toplevel = $url;
11588:                 unless ($toplevel =~ m{^/}) {
11589:                     $toplevel = "/$url";
11590:                 }
11591:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
11592:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
11593:                     $path = $1;
11594:                 } else {
11595:                     ($path) =
11596:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
11597:                 }
11598:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
11599:                     $fileloc = $toplevel;
11600:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
11601:                     my ($udom,$uname,$fname) =
11602:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
11603:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
11604:                 } else {
11605:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
11606:                 }
11607:                 $fileloc =~ s{^/}{};
11608:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
11609:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
11610:             }
11611:         }
11612:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
11613:         $udom = $cdom;
11614:         $uname = $cnum;
11615:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
11616:         $toplevel = $url;
11617:         $path = $url;
11618:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
11619:         $fileloc =~ s{^/}{};
11620:     }
11621:     foreach my $file (keys(%{$allfiles})) {
11622:         my $embed_file;
11623:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
11624:             $embed_file = $1;
11625:         } else {
11626:             $embed_file = $file;
11627:         }
11628:         my ($absolutepath,$cleaned_file);
11629:         if ($embed_file =~ m{^\w+://}) {
11630:             $cleaned_file = $embed_file;
11631:             $newfiles{$cleaned_file} = 1;
11632:             $mapping{$cleaned_file} = $embed_file;
11633:         } else {
11634:             $cleaned_file = &clean_path($embed_file);
11635:             if ($embed_file =~ m{^/}) {
11636:                 $absolutepath = $embed_file;
11637:             }
11638:             if ($cleaned_file =~ m{/}) {
11639:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
11640:                 $path = &check_for_traversal($path,$url,$toplevel);
11641:                 my $item = $fname;
11642:                 if ($path ne '') {
11643:                     $item = $path.'/'.$fname;
11644:                     $subdependencies{$path}{$fname} = 1;
11645:                 } else {
11646:                     $dependencies{$item} = 1;
11647:                 }
11648:                 if ($absolutepath) {
11649:                     $mapping{$item} = $absolutepath;
11650:                 } else {
11651:                     $mapping{$item} = $embed_file;
11652:                 }
11653:             } else {
11654:                 $dependencies{$embed_file} = 1;
11655:                 if ($absolutepath) {
11656:                     $mapping{$cleaned_file} = $absolutepath;
11657:                 } else {
11658:                     $mapping{$cleaned_file} = $embed_file;
11659:                 }
11660:             }
11661:         }
11662:     }
11663:     my $dirptr = 16384;
11664:     foreach my $path (keys(%subdependencies)) {
11665:         $currsubfile{$path} = {};
11666:         if (($actionurl eq '/adm/portfolio') ||
11667:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
11668:             my ($sublistref,$listerror) =
11669:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
11670:             if (ref($sublistref) eq 'ARRAY') {
11671:                 foreach my $line (@{$sublistref}) {
11672:                     my ($file_name,$rest) = split(/\&/,$line,2);
11673:                     $currsubfile{$path}{$file_name} = 1;
11674:                 }
11675:             }
11676:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11677:             if (opendir(my $dir,$url.'/'.$path)) {
11678:                 my @subdir_list = grep(!/^\./,readdir($dir));
11679:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
11680:             }
11681:         } elsif (($actionurl eq '/adm/dependencies') ||
11682:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11683:                   ($args->{'context'} eq 'paste')) ||
11684:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
11685:             if ($env{'request.course.id'} ne '') {
11686:                 my $dir;
11687:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
11688:                     $dir = $fileloc;
11689:                 } else {
11690:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
11691:                 }
11692:                 if ($dir ne '') {
11693:                     my ($sublistref,$listerror) =
11694:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
11695:                     if (ref($sublistref) eq 'ARRAY') {
11696:                         foreach my $line (@{$sublistref}) {
11697:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
11698:                                 undef,$mtime)=split(/\&/,$line,12);
11699:                             unless (($testdir&$dirptr) ||
11700:                                     ($file_name =~ /^\.\.?$/)) {
11701:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
11702:                             }
11703:                         }
11704:                     }
11705:                 }
11706:             }
11707:         }
11708:         foreach my $file (keys(%{$subdependencies{$path}})) {
11709:             if (exists($currsubfile{$path}{$file})) {
11710:                 my $item = $path.'/'.$file;
11711:                 unless ($mapping{$item} eq $item) {
11712:                     $pathchanges{$item} = 1;
11713:                 }
11714:                 $existing{$item} = 1;
11715:                 $numexisting ++;
11716:             } else {
11717:                 $newfiles{$path.'/'.$file} = 1;
11718:             }
11719:         }
11720:         if ($actionurl eq '/adm/dependencies') {
11721:             foreach my $path (keys(%currsubfile)) {
11722:                 if (ref($currsubfile{$path}) eq 'HASH') {
11723:                     foreach my $file (keys(%{$currsubfile{$path}})) {
11724:                          unless ($subdependencies{$path}{$file}) {
11725:                              next if (($rem ne '') &&
11726:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
11727:                                        (ref($navmap) &&
11728:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
11729:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
11730:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
11731:                              $unused{$path.'/'.$file} = 1; 
11732:                          }
11733:                     }
11734:                 }
11735:             }
11736:         }
11737:     }
11738:     my %currfile;
11739:     if (($actionurl eq '/adm/portfolio') ||
11740:         ($actionurl eq '/adm/coursegrp_portfolio')) {
11741:         my ($dirlistref,$listerror) =
11742:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
11743:         if (ref($dirlistref) eq 'ARRAY') {
11744:             foreach my $line (@{$dirlistref}) {
11745:                 my ($file_name,$rest) = split(/\&/,$line,2);
11746:                 $currfile{$file_name} = 1;
11747:             }
11748:         }
11749:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11750:         if (opendir(my $dir,$url)) {
11751:             my @dir_list = grep(!/^\./,readdir($dir));
11752:             map {$currfile{$_} = 1;} @dir_list;
11753:         }
11754:     } elsif (($actionurl eq '/adm/dependencies') ||
11755:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11756:               ($args->{'context'} eq 'paste')) ||
11757:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
11758:         if ($env{'request.course.id'} ne '') {
11759:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
11760:             if ($dir ne '') {
11761:                 my ($dirlistref,$listerror) =
11762:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
11763:                 if (ref($dirlistref) eq 'ARRAY') {
11764:                     foreach my $line (@{$dirlistref}) {
11765:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
11766:                             $size,undef,$mtime)=split(/\&/,$line,12);
11767:                         unless (($testdir&$dirptr) ||
11768:                                 ($file_name =~ /^\.\.?$/)) {
11769:                             $currfile{$file_name} = [$size,$mtime];
11770:                         }
11771:                     }
11772:                 }
11773:             }
11774:         }
11775:     }
11776:     foreach my $file (keys(%dependencies)) {
11777:         if (exists($currfile{$file})) {
11778:             unless ($mapping{$file} eq $file) {
11779:                 $pathchanges{$file} = 1;
11780:             }
11781:             $existing{$file} = 1;
11782:             $numexisting ++;
11783:         } else {
11784:             $newfiles{$file} = 1;
11785:         }
11786:     }
11787:     foreach my $file (keys(%currfile)) {
11788:         unless (($file eq $filename) ||
11789:                 ($file eq $filename.'.bak') ||
11790:                 ($dependencies{$file})) {
11791:             if ($actionurl eq '/adm/dependencies') {
11792:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
11793:                     next if (($rem ne '') &&
11794:                              (($env{"httpref.$rem".$file} ne '') ||
11795:                               (ref($navmap) &&
11796:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
11797:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
11798:                                 ($navmap->getResourceByUrl($rem.$1)))))));
11799:                 }
11800:             }
11801:             $unused{$file} = 1;
11802:         }
11803:     }
11804:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11805:         ($args->{'context'} eq 'paste')) {
11806:         $counter = scalar(keys(%existing));
11807:         $numpathchg = scalar(keys(%pathchanges));
11808:         return ($output,$counter,$numpathchg,\%existing);
11809:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
11810:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
11811:         $counter = scalar(keys(%existing));
11812:         $numpathchg = scalar(keys(%pathchanges));
11813:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
11814:     }
11815:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
11816:         if ($actionurl eq '/adm/dependencies') {
11817:             next if ($embed_file =~ m{^\w+://});
11818:         }
11819:         $upload_output .= &start_data_table_row().
11820:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
11821:                           '<span class="LC_filename">'.$embed_file.'</span>';
11822:         unless ($mapping{$embed_file} eq $embed_file) {
11823:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
11824:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
11825:         }
11826:         $upload_output .= '</td>';
11827:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
11828:             $upload_output.='<td align="right">'.
11829:                             '<span class="LC_info LC_fontsize_medium">'.
11830:                             &mt("URL points to web address").'</span>';
11831:             $numremref++;
11832:         } elsif ($args->{'error_on_invalid_names'}
11833:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
11834:             $upload_output.='<td align="right"><span class="LC_warning">'.
11835:                             &mt('Invalid characters').'</span>';
11836:             $numinvalid++;
11837:         } else {
11838:             $upload_output .= '<td>'.
11839:                               &embedded_file_element('upload_embedded',$counter,
11840:                                                      $embed_file,\%mapping,
11841:                                                      $allfiles,$codebase,'upload');
11842:             $counter ++;
11843:             $numnew ++;
11844:         }
11845:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
11846:     }
11847:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
11848:         if ($actionurl eq '/adm/dependencies') {
11849:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
11850:             $modify_output .= &start_data_table_row().
11851:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
11852:                               '<img src="'.&icon($embed_file).'" border="0" />'.
11853:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
11854:                               '<td>'.$size.'</td>'.
11855:                               '<td>'.$mtime.'</td>'.
11856:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
11857:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
11858:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
11859:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
11860:                               &embedded_file_element('upload_embedded',$counter,
11861:                                                      $embed_file,\%mapping,
11862:                                                      $allfiles,$codebase,'modify').
11863:                               '</div></td>'.
11864:                               &end_data_table_row()."\n";
11865:             $counter ++;
11866:         } else {
11867:             $upload_output .= &start_data_table_row().
11868:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
11869:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
11870:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
11871:                               &Apache::loncommon::end_data_table_row()."\n";
11872:         }
11873:     }
11874:     my $delidx = $counter;
11875:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
11876:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
11877:         $delete_output .= &start_data_table_row().
11878:                           '<td><img src="'.&icon($oldfile).'" />'.
11879:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
11880:                           '<td>'.$size.'</td>'.
11881:                           '<td>'.$mtime.'</td>'.
11882:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
11883:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
11884:                           &embedded_file_element('upload_embedded',$delidx,
11885:                                                  $oldfile,\%mapping,$allfiles,
11886:                                                  $codebase,'delete').'</td>'.
11887:                           &end_data_table_row()."\n"; 
11888:         $numunused ++;
11889:         $delidx ++;
11890:     }
11891:     if ($upload_output) {
11892:         $upload_output = &start_data_table().
11893:                          $upload_output.
11894:                          &end_data_table()."\n";
11895:     }
11896:     if ($modify_output) {
11897:         $modify_output = &start_data_table().
11898:                          &start_data_table_header_row().
11899:                          '<th>'.&mt('File').'</th>'.
11900:                          '<th>'.&mt('Size (KB)').'</th>'.
11901:                          '<th>'.&mt('Modified').'</th>'.
11902:                          '<th>'.&mt('Upload replacement?').'</th>'.
11903:                          &end_data_table_header_row().
11904:                          $modify_output.
11905:                          &end_data_table()."\n";
11906:     }
11907:     if ($delete_output) {
11908:         $delete_output = &start_data_table().
11909:                          &start_data_table_header_row().
11910:                          '<th>'.&mt('File').'</th>'.
11911:                          '<th>'.&mt('Size (KB)').'</th>'.
11912:                          '<th>'.&mt('Modified').'</th>'.
11913:                          '<th>'.&mt('Delete?').'</th>'.
11914:                          &end_data_table_header_row().
11915:                          $delete_output.
11916:                          &end_data_table()."\n";
11917:     }
11918:     my $applies = 0;
11919:     if ($numremref) {
11920:         $applies ++;
11921:     }
11922:     if ($numinvalid) {
11923:         $applies ++;
11924:     }
11925:     if ($numexisting) {
11926:         $applies ++;
11927:     }
11928:     if ($counter || $numunused) {
11929:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
11930:                   ' method="post" enctype="multipart/form-data">'."\n".
11931:                   $state.'<h3>'.$heading.'</h3>'; 
11932:         if ($actionurl eq '/adm/dependencies') {
11933:             if ($numnew) {
11934:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
11935:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
11936:                            $upload_output.'<br />'."\n";
11937:             }
11938:             if ($numexisting) {
11939:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
11940:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
11941:                            $modify_output.'<br />'."\n";
11942:                            $buttontext = &mt('Save changes');
11943:             }
11944:             if ($numunused) {
11945:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
11946:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
11947:                            $delete_output.'<br />'."\n";
11948:                            $buttontext = &mt('Save changes');
11949:             }
11950:         } else {
11951:             $output .= $upload_output.'<br />'."\n";
11952:         }
11953:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
11954:                    $counter.'" />'."\n";
11955:         if ($actionurl eq '/adm/dependencies') { 
11956:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
11957:                        $numnew.'" />'."\n";
11958:         } elsif ($actionurl eq '') {
11959:             $output .=  '<input type="hidden" name="phase" value="three" />';
11960:         }
11961:     } elsif ($applies) {
11962:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
11963:         if ($applies > 1) {
11964:             $output .=  
11965:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
11966:             if ($numremref) {
11967:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
11968:             }
11969:             if ($numinvalid) {
11970:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
11971:             }
11972:             if ($numexisting) {
11973:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
11974:             }
11975:             $output .= '</ul><br />';
11976:         } elsif ($numremref) {
11977:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
11978:         } elsif ($numinvalid) {
11979:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
11980:         } elsif ($numexisting) {
11981:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
11982:         }
11983:         $output .= $upload_output.'<br />';
11984:     }
11985:     my ($pathchange_output,$chgcount);
11986:     $chgcount = $counter;
11987:     if (keys(%pathchanges) > 0) {
11988:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
11989:             if ($counter) {
11990:                 $output .= &embedded_file_element('pathchange',$chgcount,
11991:                                                   $embed_file,\%mapping,
11992:                                                   $allfiles,$codebase,'change');
11993:             } else {
11994:                 $pathchange_output .= 
11995:                     &start_data_table_row().
11996:                     '<td><input type ="checkbox" name="namechange" value="'.
11997:                     $chgcount.'" checked="checked" /></td>'.
11998:                     '<td>'.$mapping{$embed_file}.'</td>'.
11999:                     '<td>'.$embed_file.
12000:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
12001:                                            \%mapping,$allfiles,$codebase,'change').
12002:                     '</td>'.&end_data_table_row();
12003:             }
12004:             $numpathchg ++;
12005:             $chgcount ++;
12006:         }
12007:     }
12008:     if (($counter) || ($numunused)) {
12009:         if ($numpathchg) {
12010:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
12011:                        $numpathchg.'" />'."\n";
12012:         }
12013:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
12014:             ($actionurl eq '/adm/imsimport')) {
12015:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
12016:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
12017:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
12018:         } elsif ($actionurl eq '/adm/dependencies') {
12019:             $output .= '<input type="hidden" name="action" value="process_changes" />';
12020:         }
12021:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
12022:     } elsif ($numpathchg) {
12023:         my %pathchange = ();
12024:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
12025:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
12026:             $output .= '<p>'.&mt('or').'</p>'; 
12027:         }
12028:     }
12029:     return ($output,$counter,$numpathchg);
12030: }
12031: 
12032: =pod
12033: 
12034: =item * clean_path($name)
12035: 
12036: Performs clean-up of directories, subdirectories and filename in an
12037: embedded object, referenced in an HTML file which is being uploaded
12038: to a course or portfolio, where
12039: "Upload embedded images/multimedia files if HTML file" checkbox was
12040: checked.
12041: 
12042: Clean-up is similar to replacements in lonnet::clean_filename()
12043: except each / between sub-directory and next level is preserved.
12044: 
12045: =cut
12046: 
12047: sub clean_path {
12048:     my ($embed_file) = @_;
12049:     $embed_file =~s{^/+}{};
12050:     my @contents;
12051:     if ($embed_file =~ m{/}) {
12052:         @contents = split(/\//,$embed_file);
12053:     } else {
12054:         @contents = ($embed_file);
12055:     }
12056:     my $lastidx = scalar(@contents)-1;
12057:     for (my $i=0; $i<=$lastidx; $i++) {
12058:         $contents[$i]=~s{\\}{/}g;
12059:         $contents[$i]=~s/\s+/\_/g;
12060:         $contents[$i]=~s{[^/\w\.\-]}{}g;
12061:         if ($i == $lastidx) {
12062:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
12063:         }
12064:     }
12065:     if ($lastidx > 0) {
12066:         return join('/',@contents);
12067:     } else {
12068:         return $contents[0];
12069:     }
12070: }
12071: 
12072: sub embedded_file_element {
12073:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
12074:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
12075:                    (ref($codebase) eq 'HASH'));
12076:     my $output;
12077:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
12078:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
12079:     }
12080:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
12081:                &escape($embed_file).'" />';
12082:     unless (($context eq 'upload_embedded') && 
12083:             ($mapping->{$embed_file} eq $embed_file)) {
12084:         $output .='
12085:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
12086:     }
12087:     my $attrib;
12088:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
12089:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
12090:     }
12091:     $output .=
12092:         "\n\t\t".
12093:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
12094:         $attrib.'" />';
12095:     if (exists($codebase->{$mapping->{$embed_file}})) {
12096:         $output .=
12097:             "\n\t\t".
12098:             '<input name="codebase_'.$num.'" type="hidden" value="'.
12099:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
12100:     }
12101:     return $output;
12102: }
12103: 
12104: sub get_dependency_details {
12105:     my ($currfile,$currsubfile,$embed_file) = @_;
12106:     my ($size,$mtime,$showsize,$showmtime);
12107:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
12108:         if ($embed_file =~ m{/}) {
12109:             my ($path,$fname) = split(/\//,$embed_file);
12110:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
12111:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
12112:             }
12113:         } else {
12114:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
12115:                 ($size,$mtime) = @{$currfile->{$embed_file}};
12116:             }
12117:         }
12118:         $showsize = $size/1024.0;
12119:         $showsize = sprintf("%.1f",$showsize);
12120:         if ($mtime > 0) {
12121:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
12122:         }
12123:     }
12124:     return ($showsize,$showmtime);
12125: }
12126: 
12127: sub ask_embedded_js {
12128:     return <<"END";
12129: <script type="text/javascript"">
12130: // <![CDATA[
12131: function toggleBrowse(counter) {
12132:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
12133:     var fileid = document.getElementById('embedded_item_'+counter);
12134:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
12135:     if (chkboxid.checked == true) {
12136:         uploaddivid.style.display='block';
12137:     } else {
12138:         uploaddivid.style.display='none';
12139:         fileid.value = '';
12140:     }
12141: }
12142: // ]]>
12143: </script>
12144: 
12145: END
12146: }
12147: 
12148: sub upload_embedded {
12149:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
12150:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
12151:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
12152:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
12153:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
12154:         my $orig_uploaded_filename =
12155:             $env{'form.embedded_item_'.$i.'.filename'};
12156:         foreach my $type ('orig','ref','attrib','codebase') {
12157:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
12158:                 $env{'form.embedded_'.$type.'_'.$i} =
12159:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
12160:             }
12161:         }
12162:         my ($path,$fname) =
12163:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
12164:         # no path, whole string is fname
12165:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
12166:         $fname = &Apache::lonnet::clean_filename($fname);
12167:         # See if there is anything left
12168:         next if ($fname eq '');
12169: 
12170:         # Check if file already exists as a file or directory.
12171:         my ($state,$msg);
12172:         if ($context eq 'portfolio') {
12173:             my $port_path = $dirpath;
12174:             if ($group ne '') {
12175:                 $port_path = "groups/$group/$port_path";
12176:             }
12177:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
12178:                                               $fname,$group,'embedded_item_'.$i,
12179:                                               $dir_root,$port_path,$disk_quota,
12180:                                               $current_disk_usage,$uname,$udom);
12181:             if ($state eq 'will_exceed_quota'
12182:                 || $state eq 'file_locked') {
12183:                 $output .= $msg;
12184:                 next;
12185:             }
12186:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
12187:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
12188:             if ($state eq 'exists') {
12189:                 $output .= $msg;
12190:                 next;
12191:             }
12192:         }
12193:         # Check if extension is valid
12194:         if (($fname =~ /\.(\w+)$/) &&
12195:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
12196:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
12197:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
12198:             next;
12199:         } elsif (($fname =~ /\.(\w+)$/) &&
12200:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
12201:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
12202:             next;
12203:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
12204:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
12205:             next;
12206:         }
12207:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
12208:         my $subdir = $path;
12209:         $subdir =~ s{/+$}{};
12210:         if ($context eq 'portfolio') {
12211:             my $result;
12212:             if ($state eq 'existingfile') {
12213:                 $result=
12214:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
12215:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
12216:             } else {
12217:                 $result=
12218:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
12219:                                                     $dirpath.
12220:                                                     $env{'form.currentpath'}.$subdir);
12221:                 if ($result !~ m|^/uploaded/|) {
12222:                     $output .= '<span class="LC_error">'
12223:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
12224:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
12225:                                .'</span><br />';
12226:                     next;
12227:                 } else {
12228:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
12229:                                $path.$fname.'</span>').'<br />';     
12230:                 }
12231:             }
12232:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
12233:             my $extendedsubdir = $dirpath.'/'.$subdir;
12234:             $extendedsubdir =~ s{/+$}{};
12235:             my $result =
12236:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
12237:             if ($result !~ m|^/uploaded/|) {
12238:                 $output .= '<span class="LC_error">'
12239:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
12240:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
12241:                            .'</span><br />';
12242:                     next;
12243:             } else {
12244:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
12245:                            $path.$fname.'</span>').'<br />';
12246:                 if ($context eq 'syllabus') {
12247:                     &Apache::lonnet::make_public_indefinitely($result);
12248:                 }
12249:             }
12250:         } else {
12251: # Save the file
12252:             my $target = $env{'form.embedded_item_'.$i};
12253:             my $fullpath = $dir_root.$dirpath.'/'.$path;
12254:             my $dest = $fullpath.$fname;
12255:             my $url = $url_root.$dirpath.'/'.$path.$fname;
12256:             my @parts=split(/\//,"$dirpath/$path");
12257:             my $count;
12258:             my $filepath = $dir_root;
12259:             foreach my $subdir (@parts) {
12260:                 $filepath .= "/$subdir";
12261:                 if (!-e $filepath) {
12262:                     mkdir($filepath,0770);
12263:                 }
12264:             }
12265:             my $fh;
12266:             if (!open($fh,'>'.$dest)) {
12267:                 &Apache::lonnet::logthis('Failed to create '.$dest);
12268:                 $output .= '<span class="LC_error">'.
12269:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
12270:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
12271:                            '</span><br />';
12272:             } else {
12273:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
12274:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
12275:                     $output .= '<span class="LC_error">'.
12276:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
12277:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
12278:                               '</span><br />';
12279:                 } else {
12280:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
12281:                                $url.'</span>').'<br />';
12282:                     unless ($context eq 'testbank') {
12283:                         $footer .= &mt('View embedded file: [_1]',
12284:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
12285:                     }
12286:                 }
12287:                 close($fh);
12288:             }
12289:         }
12290:         if ($env{'form.embedded_ref_'.$i}) {
12291:             $pathchange{$i} = 1;
12292:         }
12293:     }
12294:     if ($output) {
12295:         $output = '<p>'.$output.'</p>';
12296:     }
12297:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
12298:     $returnflag = 'ok';
12299:     my $numpathchgs = scalar(keys(%pathchange));
12300:     if ($numpathchgs > 0) {
12301:         if ($context eq 'portfolio') {
12302:             $output .= '<p>'.&mt('or').'</p>';
12303:         } elsif ($context eq 'testbank') {
12304:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
12305:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
12306:             $returnflag = 'modify_orightml';
12307:         }
12308:     }
12309:     return ($output.$footer,$returnflag,$numpathchgs);
12310: }
12311: 
12312: sub modify_html_form {
12313:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
12314:     my $end = 0;
12315:     my $modifyform;
12316:     if ($context eq 'upload_embedded') {
12317:         return unless (ref($pathchange) eq 'HASH');
12318:         if ($env{'form.number_embedded_items'}) {
12319:             $end += $env{'form.number_embedded_items'};
12320:         }
12321:         if ($env{'form.number_pathchange_items'}) {
12322:             $end += $env{'form.number_pathchange_items'};
12323:         }
12324:         if ($end) {
12325:             for (my $i=0; $i<$end; $i++) {
12326:                 if ($i < $env{'form.number_embedded_items'}) {
12327:                     next unless($pathchange->{$i});
12328:                 }
12329:                 $modifyform .=
12330:                     &start_data_table_row().
12331:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
12332:                     'checked="checked" /></td>'.
12333:                     '<td>'.$env{'form.embedded_ref_'.$i}.
12334:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
12335:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
12336:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
12337:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
12338:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
12339:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
12340:                     '<td>'.$env{'form.embedded_orig_'.$i}.
12341:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
12342:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
12343:                     &end_data_table_row();
12344:             }
12345:         }
12346:     } else {
12347:         $modifyform = $pathchgtable;
12348:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12349:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
12350:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
12351:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
12352:         }
12353:     }
12354:     if ($modifyform) {
12355:         if ($actionurl eq '/adm/dependencies') {
12356:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
12357:         }
12358:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
12359:                '<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".
12360:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
12361:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
12362:                '</ol></p>'."\n".'<p>'.
12363:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
12364:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
12365:                &start_data_table()."\n".
12366:                &start_data_table_header_row().
12367:                '<th>'.&mt('Change?').'</th>'.
12368:                '<th>'.&mt('Current reference').'</th>'.
12369:                '<th>'.&mt('Required reference').'</th>'.
12370:                &end_data_table_header_row()."\n".
12371:                $modifyform.
12372:                &end_data_table().'<br />'."\n".$hiddenstate.
12373:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
12374:                '</form>'."\n";
12375:     }
12376:     return;
12377: }
12378: 
12379: sub modify_html_refs {
12380:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
12381:     my $container;
12382:     if ($context eq 'portfolio') {
12383:         $container = $env{'form.container'};
12384:     } elsif ($context eq 'coursedoc') {
12385:         $container = $env{'form.primaryurl'};
12386:     } elsif ($context eq 'manage_dependencies') {
12387:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
12388:         $container = "/$container";
12389:     } elsif ($context eq 'syllabus') {
12390:         $container = $url;
12391:     } else {
12392:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
12393:     }
12394:     my (%allfiles,%codebase,$output,$content);
12395:     my @changes = &get_env_multiple('form.namechange');
12396:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
12397:         if (wantarray) {
12398:             return ('',0,0); 
12399:         } else {
12400:             return;
12401:         }
12402:     }
12403:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
12404:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
12405:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
12406:             if (wantarray) {
12407:                 return ('',0,0);
12408:             } else {
12409:                 return;
12410:             }
12411:         } 
12412:         $content = &Apache::lonnet::getfile($container);
12413:         if ($content eq '-1') {
12414:             if (wantarray) {
12415:                 return ('',0,0);
12416:             } else {
12417:                 return;
12418:             }
12419:         }
12420:     } else {
12421:         unless ($container =~ /^\Q$dir_root\E/) {
12422:             if (wantarray) {
12423:                 return ('',0,0);
12424:             } else {
12425:                 return;
12426:             }
12427:         } 
12428:         if (open(my $fh,'<',$container)) {
12429:             $content = join('', <$fh>);
12430:             close($fh);
12431:         } else {
12432:             if (wantarray) {
12433:                 return ('',0,0);
12434:             } else {
12435:                 return;
12436:             }
12437:         }
12438:     }
12439:     my ($count,$codebasecount) = (0,0);
12440:     my $mm = new File::MMagic;
12441:     my $mime_type = $mm->checktype_contents($content);
12442:     if ($mime_type eq 'text/html') {
12443:         my $parse_result = 
12444:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
12445:                                                     \%codebase,\$content);
12446:         if ($parse_result eq 'ok') {
12447:             foreach my $i (@changes) {
12448:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
12449:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
12450:                 if ($allfiles{$ref}) {
12451:                     my $newname =  $orig;
12452:                     my ($attrib_regexp,$codebase);
12453:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
12454:                     if ($attrib_regexp =~ /:/) {
12455:                         $attrib_regexp =~ s/\:/|/g;
12456:                     }
12457:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
12458:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
12459:                         $count += $numchg;
12460:                         $allfiles{$newname} = $allfiles{$ref};
12461:                         delete($allfiles{$ref});
12462:                     }
12463:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
12464:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
12465:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
12466:                         $codebasecount ++;
12467:                     }
12468:                 }
12469:             }
12470:             my $skiprewrites;
12471:             if ($count || $codebasecount) {
12472:                 my $saveresult;
12473:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
12474:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
12475:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
12476:                     if ($url eq $container) {
12477:                         my ($fname) = ($container =~ m{/([^/]+)$});
12478:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
12479:                                             $count,'<span class="LC_filename">'.
12480:                                             $fname.'</span>').'</p>';
12481:                     } else {
12482:                          $output = '<p class="LC_error">'.
12483:                                    &mt('Error: update failed for: [_1].',
12484:                                    '<span class="LC_filename">'.
12485:                                    $container.'</span>').'</p>';
12486:                     }
12487:                     if ($context eq 'syllabus') {
12488:                         unless ($saveresult eq 'ok') {
12489:                             $skiprewrites = 1;
12490:                         }
12491:                     }
12492:                 } else {
12493:                     if (open(my $fh,'>',$container)) {
12494:                         print $fh $content;
12495:                         close($fh);
12496:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
12497:                                   $count,'<span class="LC_filename">'.
12498:                                   $container.'</span>').'</p>';
12499:                     } else {
12500:                          $output = '<p class="LC_error">'.
12501:                                    &mt('Error: could not update [_1].',
12502:                                    '<span class="LC_filename">'.
12503:                                    $container.'</span>').'</p>';
12504:                     }
12505:                 }
12506:             }
12507:             if (($context eq 'syllabus') && (!$skiprewrites)) {
12508:                 my ($actionurl,$state);
12509:                 $actionurl = "/public/$udom/$uname/syllabus";
12510:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
12511:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
12512:                                               \%codebase,
12513:                                               {'context' => 'rewrites',
12514:                                                'ignore_remote_references' => 1,});
12515:                 if (ref($mapping) eq 'HASH') {
12516:                     my $rewrites = 0;
12517:                     foreach my $key (keys(%{$mapping})) {
12518:                         next if ($key =~ m{^https?://});
12519:                         my $ref = $mapping->{$key};
12520:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
12521:                         my $attrib;
12522:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
12523:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
12524:                         }
12525:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
12526:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
12527:                             $rewrites += $numchg;
12528:                         }
12529:                     }
12530:                     if ($rewrites) {
12531:                         my $saveresult;
12532:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
12533:                         if ($url eq $container) {
12534:                             my ($fname) = ($container =~ m{/([^/]+)$});
12535:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
12536:                                             $count,'<span class="LC_filename">'.
12537:                                             $fname.'</span>').'</p>';
12538:                         } else {
12539:                             $output .= '<p class="LC_error">'.
12540:                                        &mt('Error: could not update links in [_1].',
12541:                                        '<span class="LC_filename">'.
12542:                                        $container.'</span>').'</p>';
12543: 
12544:                         }
12545:                     }
12546:                 }
12547:             }
12548:         } else {
12549:             &logthis('Failed to parse '.$container.
12550:                      ' to modify references: '.$parse_result);
12551:         }
12552:     }
12553:     if (wantarray) {
12554:         return ($output,$count,$codebasecount);
12555:     } else {
12556:         return $output;
12557:     }
12558: }
12559: 
12560: sub check_for_existing {
12561:     my ($path,$fname,$element) = @_;
12562:     my ($state,$msg);
12563:     if (-d $path.'/'.$fname) {
12564:         $state = 'exists';
12565:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
12566:     } elsif (-e $path.'/'.$fname) {
12567:         $state = 'exists';
12568:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
12569:     }
12570:     if ($state eq 'exists') {
12571:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
12572:     }
12573:     return ($state,$msg);
12574: }
12575: 
12576: sub check_for_upload {
12577:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
12578:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
12579:     my $filesize = length($env{'form.'.$element});
12580:     if (!$filesize) {
12581:         my $msg = '<span class="LC_error">'.
12582:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
12583:                       '<span class="LC_filename">'.$fname.'</span>',
12584:                       $filesize).'<br />'.
12585:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
12586:                   '</span>';
12587:         return ('zero_bytes',$msg);
12588:     }
12589:     $filesize =  $filesize/1000; #express in k (1024?)
12590:     my $getpropath = 1;
12591:     my ($dirlistref,$listerror) =
12592:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
12593:     my $found_file = 0;
12594:     my $locked_file = 0;
12595:     my @lockers;
12596:     my $navmap;
12597:     if ($env{'request.course.id'}) {
12598:         $navmap = Apache::lonnavmaps::navmap->new();
12599:     }
12600:     if (ref($dirlistref) eq 'ARRAY') {
12601:         foreach my $line (@{$dirlistref}) {
12602:             my ($file_name,$rest)=split(/\&/,$line,2);
12603:             if ($file_name eq $fname){
12604:                 $file_name = $path.$file_name;
12605:                 if ($group ne '') {
12606:                     $file_name = $group.$file_name;
12607:                 }
12608:                 $found_file = 1;
12609:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
12610:                     foreach my $lock (@lockers) {
12611:                         if (ref($lock) eq 'ARRAY') {
12612:                             my ($symb,$crsid) = @{$lock};
12613:                             if ($crsid eq $env{'request.course.id'}) {
12614:                                 if (ref($navmap)) {
12615:                                     my $res = $navmap->getBySymb($symb);
12616:                                     foreach my $part (@{$res->parts()}) { 
12617:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
12618:                                         unless (($slot_status == $res->RESERVED) ||
12619:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
12620:                                             $locked_file = 1;
12621:                                         }
12622:                                     }
12623:                                 } else {
12624:                                     $locked_file = 1;
12625:                                 }
12626:                             } else {
12627:                                 $locked_file = 1;
12628:                             }
12629:                         }
12630:                    }
12631:                 } else {
12632:                     my @info = split(/\&/,$rest);
12633:                     my $currsize = $info[6]/1000;
12634:                     if ($currsize < $filesize) {
12635:                         my $extra = $filesize - $currsize;
12636:                         if (($current_disk_usage + $extra) > $disk_quota) {
12637:                             my $msg = '<p class="LC_warning">'.
12638:                                       &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.',
12639:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
12640:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
12641:                                                    $disk_quota,$current_disk_usage).'</p>';
12642:                             return ('will_exceed_quota',$msg);
12643:                         }
12644:                     }
12645:                 }
12646:             }
12647:         }
12648:     }
12649:     if (($current_disk_usage + $filesize) > $disk_quota){
12650:         my $msg = '<p class="LC_warning">'.
12651:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
12652:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
12653:         return ('will_exceed_quota',$msg);
12654:     } elsif ($found_file) {
12655:         if ($locked_file) {
12656:             my $msg = '<p class="LC_warning">';
12657:             $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>');
12658:             $msg .= '</p>';
12659:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
12660:             return ('file_locked',$msg);
12661:         } else {
12662:             my $msg = '<p class="LC_error">';
12663:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
12664:             $msg .= '</p>';
12665:             return ('existingfile',$msg);
12666:         }
12667:     }
12668: }
12669: 
12670: sub check_for_traversal {
12671:     my ($path,$url,$toplevel) = @_;
12672:     my @parts=split(/\//,$path);
12673:     my $cleanpath;
12674:     my $fullpath = $url;
12675:     for (my $i=0;$i<@parts;$i++) {
12676:         next if ($parts[$i] eq '.');
12677:         if ($parts[$i] eq '..') {
12678:             $fullpath =~ s{([^/]+/)$}{};
12679:         } else {
12680:             $fullpath .= $parts[$i].'/';
12681:         }
12682:     }
12683:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
12684:         $cleanpath = $1;
12685:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
12686:         my $curr_toprel = $1;
12687:         my @parts = split(/\//,$curr_toprel);
12688:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
12689:         my @urlparts = split(/\//,$url_toprel);
12690:         my $doubledots;
12691:         my $startdiff = -1;
12692:         for (my $i=0; $i<@urlparts; $i++) {
12693:             if ($startdiff == -1) {
12694:                 unless ($urlparts[$i] eq $parts[$i]) {
12695:                     $startdiff = $i;
12696:                     $doubledots .= '../';
12697:                 }
12698:             } else {
12699:                 $doubledots .= '../';
12700:             }
12701:         }
12702:         if ($startdiff > -1) {
12703:             $cleanpath = $doubledots;
12704:             for (my $i=$startdiff; $i<@parts; $i++) {
12705:                 $cleanpath .= $parts[$i].'/';
12706:             }
12707:         }
12708:     }
12709:     $cleanpath =~ s{(/)$}{};
12710:     return $cleanpath;
12711: }
12712: 
12713: sub is_archive_file {
12714:     my ($mimetype) = @_;
12715:     if (($mimetype eq 'application/octet-stream') ||
12716:         ($mimetype eq 'application/x-stuffit') ||
12717:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
12718:         return 1;
12719:     }
12720:     return;
12721: }
12722: 
12723: sub decompress_form {
12724:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
12725:     my %lt = &Apache::lonlocal::texthash (
12726:         this => 'This file is an archive file.',
12727:         camt => 'This file is a Camtasia archive file.',
12728:         itsc => 'Its contents are as follows:',
12729:         youm => 'You may wish to extract its contents.',
12730:         extr => 'Extract contents',
12731:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
12732:         proa => 'Process automatically?',
12733:         yes  => 'Yes',
12734:         no   => 'No',
12735:         fold => 'Title for folder containing movie',
12736:         movi => 'Title for page containing embedded movie', 
12737:     );
12738:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
12739:     my ($is_camtasia,$topdir,%toplevel,@paths);
12740:     my $info = &list_archive_contents($fileloc,\@paths);
12741:     if (@paths) {
12742:         foreach my $path (@paths) {
12743:             $path =~ s{^/}{};
12744:             if ($path =~ m{^([^/]+)/$}) {
12745:                 $topdir = $1;
12746:             }
12747:             if ($path =~ m{^([^/]+)/}) {
12748:                 $toplevel{$1} = $path;
12749:             } else {
12750:                 $toplevel{$path} = $path;
12751:             }
12752:         }
12753:     }
12754:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
12755:         my @camtasia6 = ("$topdir/","$topdir/index.html",
12756:                         "$topdir/media/",
12757:                         "$topdir/media/$topdir.mp4",
12758:                         "$topdir/media/FirstFrame.png",
12759:                         "$topdir/media/player.swf",
12760:                         "$topdir/media/swfobject.js",
12761:                         "$topdir/media/expressInstall.swf");
12762:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
12763:                          "$topdir/$topdir.mp4",
12764:                          "$topdir/$topdir\_config.xml",
12765:                          "$topdir/$topdir\_controller.swf",
12766:                          "$topdir/$topdir\_embed.css",
12767:                          "$topdir/$topdir\_First_Frame.png",
12768:                          "$topdir/$topdir\_player.html",
12769:                          "$topdir/$topdir\_Thumbnails.png",
12770:                          "$topdir/playerProductInstall.swf",
12771:                          "$topdir/scripts/",
12772:                          "$topdir/scripts/config_xml.js",
12773:                          "$topdir/scripts/handlebars.js",
12774:                          "$topdir/scripts/jquery-1.7.1.min.js",
12775:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
12776:                          "$topdir/scripts/modernizr.js",
12777:                          "$topdir/scripts/player-min.js",
12778:                          "$topdir/scripts/swfobject.js",
12779:                          "$topdir/skins/",
12780:                          "$topdir/skins/configuration_express.xml",
12781:                          "$topdir/skins/express_show/",
12782:                          "$topdir/skins/express_show/player-min.css",
12783:                          "$topdir/skins/express_show/spritesheet.png");
12784:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
12785:                          "$topdir/$topdir.mp4",
12786:                          "$topdir/$topdir\_config.xml",
12787:                          "$topdir/$topdir\_controller.swf",
12788:                          "$topdir/$topdir\_embed.css",
12789:                          "$topdir/$topdir\_First_Frame.png",
12790:                          "$topdir/$topdir\_player.html",
12791:                          "$topdir/$topdir\_Thumbnails.png",
12792:                          "$topdir/playerProductInstall.swf",
12793:                          "$topdir/scripts/",
12794:                          "$topdir/scripts/config_xml.js",
12795:                          "$topdir/scripts/techsmith-smart-player.min.js",
12796:                          "$topdir/skins/",
12797:                          "$topdir/skins/configuration_express.xml",
12798:                          "$topdir/skins/express_show/",
12799:                          "$topdir/skins/express_show/spritesheet.min.css",
12800:                          "$topdir/skins/express_show/spritesheet.png",
12801:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
12802:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
12803:         if (@diffs == 0) {
12804:             $is_camtasia = 6;
12805:         } else {
12806:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
12807:             if (@diffs == 0) {
12808:                 $is_camtasia = 8;
12809:             } else {
12810:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
12811:                 if (@diffs == 0) {
12812:                     $is_camtasia = 8;
12813:                 }
12814:             }
12815:         }
12816:     }
12817:     my $output;
12818:     if ($is_camtasia) {
12819:         $output = <<"ENDCAM";
12820: <script type="text/javascript" language="Javascript">
12821: // <![CDATA[
12822: 
12823: function camtasiaToggle() {
12824:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
12825:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
12826:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
12827:                 document.getElementById('camtasia_titles').style.display='block';
12828:             } else {
12829:                 document.getElementById('camtasia_titles').style.display='none';
12830:             }
12831:         }
12832:     }
12833:     return;
12834: }
12835: 
12836: // ]]>
12837: </script>
12838: <p>$lt{'camt'}</p>
12839: ENDCAM
12840:     } else {
12841:         $output = '<p>'.$lt{'this'};
12842:         if ($info eq '') {
12843:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
12844:         } else {
12845:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
12846:                        '<div><pre>'.$info.'</pre></div>';
12847:         }
12848:     }
12849:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
12850:     my $duplicates;
12851:     my $num = 0;
12852:     if (ref($dirlist) eq 'ARRAY') {
12853:         foreach my $item (@{$dirlist}) {
12854:             if (ref($item) eq 'ARRAY') {
12855:                 if (exists($toplevel{$item->[0]})) {
12856:                     $duplicates .= 
12857:                         &start_data_table_row().
12858:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
12859:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
12860:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
12861:                         'value="1" />'.&mt('Yes').'</label>'.
12862:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
12863:                         '<td>'.$item->[0].'</td>';
12864:                     if ($item->[2]) {
12865:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
12866:                     } else {
12867:                         $duplicates .= '<td>'.&mt('File').'</td>';
12868:                     }
12869:                     $duplicates .= '<td>'.$item->[3].'</td>'.
12870:                                    '<td>'.
12871:                                    &Apache::lonlocal::locallocaltime($item->[4]).
12872:                                    '</td>'.
12873:                                    &end_data_table_row();
12874:                     $num ++;
12875:                 }
12876:             }
12877:         }
12878:     }
12879:     my $itemcount;
12880:     if (@paths > 0) {
12881:         $itemcount = scalar(@paths);
12882:     } else {
12883:         $itemcount = 1;
12884:     }
12885:     if ($is_camtasia) {
12886:         $output .= $lt{'auto'}.'<br />'.
12887:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
12888:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
12889:                    $lt{'yes'}.'</label>&nbsp;<label>'.
12890:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
12891:                    $lt{'no'}.'</label></span><br />'.
12892:                    '<div id="camtasia_titles" style="display:block">'.
12893:                    &Apache::lonhtmlcommon::start_pick_box().
12894:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
12895:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
12896:                    &Apache::lonhtmlcommon::row_closure().
12897:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
12898:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
12899:                    &Apache::lonhtmlcommon::row_closure(1).
12900:                    &Apache::lonhtmlcommon::end_pick_box().
12901:                    '</div>';
12902:     }
12903:     $output .= 
12904:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
12905:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
12906:         "\n";
12907:     if ($duplicates ne '') {
12908:         $output .= '<p><span class="LC_warning">'.
12909:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
12910:                    &start_data_table().
12911:                    &start_data_table_header_row().
12912:                    '<th>'.&mt('Overwrite?').'</th>'.
12913:                    '<th>'.&mt('Name').'</th>'.
12914:                    '<th>'.&mt('Type').'</th>'.
12915:                    '<th>'.&mt('Size').'</th>'.
12916:                    '<th>'.&mt('Last modified').'</th>'.
12917:                    &end_data_table_header_row().
12918:                    $duplicates.
12919:                    &end_data_table().
12920:                    '</p>';
12921:     }
12922:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
12923:     if (ref($hiddenelements) eq 'HASH') {
12924:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
12925:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
12926:         }
12927:     }
12928:     $output .= <<"END";
12929: <br />
12930: <input type="submit" name="decompress" value="$lt{'extr'}" />
12931: </form>
12932: $noextract
12933: END
12934:     return $output;
12935: }
12936: 
12937: sub decompression_utility {
12938:     my ($program) = @_;
12939:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
12940:     my $location;
12941:     if (grep(/^\Q$program\E$/,@utilities)) { 
12942:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
12943:                          '/usr/sbin/') {
12944:             if (-x $dir.$program) {
12945:                 $location = $dir.$program;
12946:                 last;
12947:             }
12948:         }
12949:     }
12950:     return $location;
12951: }
12952: 
12953: sub list_archive_contents {
12954:     my ($file,$pathsref) = @_;
12955:     my (@cmd,$output);
12956:     my $needsregexp;
12957:     if ($file =~ /\.zip$/) {
12958:         @cmd = (&decompression_utility('unzip'),"-l");
12959:         $needsregexp = 1;
12960:     } elsif (($file =~ m/\.tar\.gz$/) ||
12961:              ($file =~ /\.tgz$/)) {
12962:         @cmd = (&decompression_utility('tar'),"-ztf");
12963:     } elsif ($file =~ /\.tar\.bz2$/) {
12964:         @cmd = (&decompression_utility('tar'),"-jtf");
12965:     } elsif ($file =~ m|\.tar$|) {
12966:         @cmd = (&decompression_utility('tar'),"-tf");
12967:     }
12968:     if (@cmd) {
12969:         undef($!);
12970:         undef($@);
12971:         if (open(my $fh,"-|", @cmd, $file)) {
12972:             while (my $line = <$fh>) {
12973:                 $output .= $line;
12974:                 chomp($line);
12975:                 my $item;
12976:                 if ($needsregexp) {
12977:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
12978:                 } else {
12979:                     $item = $line;
12980:                 }
12981:                 if ($item ne '') {
12982:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
12983:                         push(@{$pathsref},$item);
12984:                     } 
12985:                 }
12986:             }
12987:             close($fh);
12988:         }
12989:     }
12990:     return $output;
12991: }
12992: 
12993: sub decompress_uploaded_file {
12994:     my ($file,$dir) = @_;
12995:     &Apache::lonnet::appenv({'cgi.file' => $file});
12996:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
12997:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
12998:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
12999:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
13000:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
13001:     my $decompressed = $env{'cgi.decompressed'};
13002:     &Apache::lonnet::delenv('cgi.file');
13003:     &Apache::lonnet::delenv('cgi.dir');
13004:     &Apache::lonnet::delenv('cgi.decompressed');
13005:     return ($decompressed,$result);
13006: }
13007: 
13008: sub process_decompression {
13009:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
13010:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
13011:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13012:                &mt('Unexpected file path.').'</p>'."\n";
13013:     }
13014:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
13015:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13016:                &mt('Unexpected course context.').'</p>'."\n";
13017:     }
13018:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
13019:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13020:                &mt('Filename contained unexpected characters.').'</p>'."\n";
13021:     }
13022:     my ($dir,$error,$warning,$output);
13023:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
13024:         $error = &mt('Filename not a supported archive file type.').
13025:                  '<br />'.&mt('Filename should end with one of: [_1].',
13026:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
13027:     } else {
13028:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
13029:         if ($docuhome eq 'no_host') {
13030:             $error = &mt('Could not determine home server for course.');
13031:         } else {
13032:             my @ids=&Apache::lonnet::current_machine_ids();
13033:             my $currdir = "$dir_root/$destination";
13034:             if (grep(/^\Q$docuhome\E$/,@ids)) {
13035:                 $dir = &LONCAPA::propath($docudom,$docuname).
13036:                        "$dir_root/$destination";
13037:             } else {
13038:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
13039:                        "$dir_root/$docudom/$docuname/$destination";
13040:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
13041:                     $error = &mt('Archive file not found.');
13042:                 }
13043:             }
13044:             my (@to_overwrite,@to_skip);
13045:             if ($env{'form.archive_overwrite_total'} > 0) {
13046:                 my $total = $env{'form.archive_overwrite_total'};
13047:                 for (my $i=0; $i<$total; $i++) {
13048:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
13049:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
13050:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
13051:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
13052:                     }
13053:                 }
13054:             }
13055:             my $numskip = scalar(@to_skip);
13056:             my $numoverwrite = scalar(@to_overwrite);
13057:             if (($numskip) && (!$numoverwrite)) {
13058:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
13059:             } elsif ($dir eq '') {
13060:                 $error = &mt('Directory containing archive file unavailable.');
13061:             } elsif (!$error) {
13062:                 my ($decompressed,$display);
13063:                 if (($numskip) || ($numoverwrite)) {
13064:                     my $tempdir = time.'_'.$$.int(rand(10000));
13065:                     mkdir("$dir/$tempdir",0755);
13066:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
13067:                         ($decompressed,$display) =
13068:                             &decompress_uploaded_file($file,"$dir/$tempdir");
13069:                         foreach my $item (@to_skip) {
13070:                             if (($item ne '') && ($item !~ /\.\./)) {
13071:                                 if (-f "$dir/$tempdir/$item") {
13072:                                     unlink("$dir/$tempdir/$item");
13073:                                 } elsif (-d "$dir/$tempdir/$item") {
13074:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
13075:                                 }
13076:                             }
13077:                         }
13078:                         foreach my $item (@to_overwrite) {
13079:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
13080:                                 if (($item ne '') && ($item !~ /\.\./)) {
13081:                                     if (-f "$dir/$item") {
13082:                                         unlink("$dir/$item");
13083:                                     } elsif (-d "$dir/$item") {
13084:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
13085:                                     }
13086:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
13087:                                 }
13088:                             }
13089:                         }
13090:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
13091:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
13092:                         }
13093:                     }
13094:                 } else {
13095:                     ($decompressed,$display) = 
13096:                         &decompress_uploaded_file($file,$dir);
13097:                 }
13098:                 if ($decompressed eq 'ok') {
13099:                     $output = '<p class="LC_info">'.
13100:                               &mt('Files extracted successfully from archive.').
13101:                               '</p>'."\n";
13102:                     my ($warning,$result,@contents);
13103:                     my ($newdirlistref,$newlisterror) =
13104:                         &Apache::lonnet::dirlist($currdir,$docudom,
13105:                                                  $docuname,1);
13106:                     my (%is_dir,%changes,@newitems);
13107:                     my $dirptr = 16384;
13108:                     if (ref($newdirlistref) eq 'ARRAY') {
13109:                         foreach my $dir_line (@{$newdirlistref}) {
13110:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
13111:                             unless (($item =~ /^\.+$/) || ($item eq $file)) { 
13112:                                 push(@newitems,$item);
13113:                                 if ($dirptr&$testdir) {
13114:                                     $is_dir{$item} = 1;
13115:                                 }
13116:                                 $changes{$item} = 1;
13117:                             }
13118:                         }
13119:                     }
13120:                     if (keys(%changes) > 0) {
13121:                         foreach my $item (sort(@newitems)) {
13122:                             if ($changes{$item}) {
13123:                                 push(@contents,$item);
13124:                             }
13125:                         }
13126:                     }
13127:                     if (@contents > 0) {
13128:                         my $wantform;
13129:                         unless ($env{'form.autoextract_camtasia'}) {
13130:                             $wantform = 1;
13131:                         }
13132:                         my (%children,%parent,%dirorder,%titles);
13133:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
13134:                                                                 $currdir,\%is_dir,
13135:                                                                 \%children,\%parent,
13136:                                                                 \@contents,\%dirorder,
13137:                                                                 \%titles,$wantform);
13138:                         if ($datatable ne '') {
13139:                             $output .= &archive_options_form('decompressed',$datatable,
13140:                                                              $count,$hiddenelem);
13141:                             my $startcount = 6;
13142:                             $output .= &archive_javascript($startcount,$count,
13143:                                                            \%titles,\%children);
13144:                         }
13145:                         if ($env{'form.autoextract_camtasia'}) {
13146:                             my $version = $env{'form.autoextract_camtasia'};
13147:                             my %displayed;
13148:                             my $total = 1;
13149:                             $env{'form.archive_directory'} = [];
13150:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
13151:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
13152:                                 $path =~ s{/$}{};
13153:                                 my $item;
13154:                                 if ($path ne '') {
13155:                                     $item = "$path/$titles{$i}";
13156:                                 } else {
13157:                                     $item = $titles{$i};
13158:                                 }
13159:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
13160:                                 if ($item eq $contents[0]) {
13161:                                     push(@{$env{'form.archive_directory'}},$i);
13162:                                     $env{'form.archive_'.$i} = 'display';
13163:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
13164:                                     $displayed{'folder'} = $i;
13165:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
13166:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
13167:                                     $env{'form.archive_'.$i} = 'display';
13168:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
13169:                                     $displayed{'web'} = $i;
13170:                                 } else {
13171:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
13172:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
13173:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
13174:                                         push(@{$env{'form.archive_directory'}},$i);
13175:                                     }
13176:                                     $env{'form.archive_'.$i} = 'dependency';
13177:                                 }
13178:                                 $total ++;
13179:                             }
13180:                             for (my $i=1; $i<$total; $i++) {
13181:                                 next if ($i == $displayed{'web'});
13182:                                 next if ($i == $displayed{'folder'});
13183:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
13184:                             }
13185:                             $env{'form.phase'} = 'decompress_cleanup';
13186:                             $env{'form.archivedelete'} = 1;
13187:                             $env{'form.archive_count'} = $total-1;
13188:                             $output .=
13189:                                 &process_extracted_files('coursedocs',$docudom,
13190:                                                          $docuname,$destination,
13191:                                                          $dir_root,$hiddenelem);
13192:                         }
13193:                     } else {
13194:                         $warning = &mt('No new items extracted from archive file.');
13195:                     }
13196:                 } else {
13197:                     $output = $display;
13198:                     $error = &mt('An error occurred during extraction from the archive file.');
13199:                 }
13200:             }
13201:         }
13202:     }
13203:     if ($error) {
13204:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13205:                    $error.'</p>'."\n";
13206:     }
13207:     if ($warning) {
13208:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
13209:     }
13210:     return $output;
13211: }
13212: 
13213: sub get_extracted {
13214:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
13215:         $titles,$wantform) = @_;
13216:     my $count = 0;
13217:     my $depth = 0;
13218:     my $datatable;
13219:     my @hierarchy;
13220:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
13221:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
13222:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
13223:     foreach my $item (@{$contents}) {
13224:         $count ++;
13225:         @{$dirorder->{$count}} = @hierarchy;
13226:         $titles->{$count} = $item;
13227:         &archive_hierarchy($depth,$count,$parent,$children);
13228:         if ($wantform) {
13229:             $datatable .= &archive_row($is_dir->{$item},$item,
13230:                                        $currdir,$depth,$count);
13231:         }
13232:         if ($is_dir->{$item}) {
13233:             $depth ++;
13234:             push(@hierarchy,$count);
13235:             $parent->{$depth} = $count;
13236:             $datatable .=
13237:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
13238:                                            \$depth,\$count,\@hierarchy,$dirorder,
13239:                                            $children,$parent,$titles,$wantform);
13240:             $depth --;
13241:             pop(@hierarchy);
13242:         }
13243:     }
13244:     return ($count,$datatable);
13245: }
13246: 
13247: sub recurse_extracted_archive {
13248:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
13249:         $children,$parent,$titles,$wantform) = @_;
13250:     my $result='';
13251:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
13252:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
13253:             (ref($dirorder) eq 'HASH')) {
13254:         return $result;
13255:     }
13256:     my $dirptr = 16384;
13257:     my ($newdirlistref,$newlisterror) =
13258:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
13259:     if (ref($newdirlistref) eq 'ARRAY') {
13260:         foreach my $dir_line (@{$newdirlistref}) {
13261:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
13262:             unless ($item =~ /^\.+$/) {
13263:                 $$count ++;
13264:                 @{$dirorder->{$$count}} = @{$hierarchy};
13265:                 $titles->{$$count} = $item;
13266:                 &archive_hierarchy($$depth,$$count,$parent,$children);
13267: 
13268:                 my $is_dir;
13269:                 if ($dirptr&$testdir) {
13270:                     $is_dir = 1;
13271:                 }
13272:                 if ($wantform) {
13273:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
13274:                 }
13275:                 if ($is_dir) {
13276:                     $$depth ++;
13277:                     push(@{$hierarchy},$$count);
13278:                     $parent->{$$depth} = $$count;
13279:                     $result .=
13280:                         &recurse_extracted_archive("$currdir/$item",$docudom,
13281:                                                    $docuname,$depth,$count,
13282:                                                    $hierarchy,$dirorder,$children,
13283:                                                    $parent,$titles,$wantform);
13284:                     $$depth --;
13285:                     pop(@{$hierarchy});
13286:                 }
13287:             }
13288:         }
13289:     }
13290:     return $result;
13291: }
13292: 
13293: sub archive_hierarchy {
13294:     my ($depth,$count,$parent,$children) =@_;
13295:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
13296:         if (exists($parent->{$depth})) {
13297:              $children->{$parent->{$depth}} .= $count.':';
13298:         }
13299:     }
13300:     return;
13301: }
13302: 
13303: sub archive_row {
13304:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
13305:     my ($name) = ($item =~ m{([^/]+)$});
13306:     my %choices = &Apache::lonlocal::texthash (
13307:                                        'display'    => 'Add as file',
13308:                                        'dependency' => 'Include as dependency',
13309:                                        'discard'    => 'Discard',
13310:                                       );
13311:     if ($is_dir) {
13312:         $choices{'display'} = &mt('Add as folder'); 
13313:     }
13314:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
13315:     my $offset = 0;
13316:     foreach my $action ('display','dependency','discard') {
13317:         $offset ++;
13318:         if ($action ne 'display') {
13319:             $offset ++;
13320:         }  
13321:         $output .= '<td><span class="LC_nobreak">'.
13322:                    '<label><input type="radio" name="archive_'.$count.
13323:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
13324:         my $text = $choices{$action};
13325:         if ($is_dir) {
13326:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
13327:             if ($action eq 'display') {
13328:                 $text = &mt('Add as folder');
13329:             }
13330:         } else {
13331:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
13332: 
13333:         }
13334:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
13335:         if ($action eq 'dependency') {
13336:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
13337:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
13338:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
13339:                        '<option value=""></option>'."\n".
13340:                        '</select>'."\n".
13341:                        '</div>';
13342:         } elsif ($action eq 'display') {
13343:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
13344:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
13345:                        '</div>';
13346:         }
13347:         $output .= '</td>';
13348:     }
13349:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
13350:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
13351:     for (my $i=0; $i<$depth; $i++) {
13352:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
13353:     }
13354:     if ($is_dir) {
13355:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
13356:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
13357:     } else {
13358:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
13359:     }
13360:     $output .= '&nbsp;'.$name.'</td>'."\n".
13361:                &end_data_table_row();
13362:     return $output;
13363: }
13364: 
13365: sub archive_options_form {
13366:     my ($form,$display,$count,$hiddenelem) = @_;
13367:     my %lt = &Apache::lonlocal::texthash(
13368:                perm => 'Permanently remove archive file?',
13369:                hows => 'How should each extracted item be incorporated in the course?',
13370:                cont => 'Content actions for all',
13371:                addf => 'Add as folder/file',
13372:                incd => 'Include as dependency for a displayed file',
13373:                disc => 'Discard',
13374:                no   => 'No',
13375:                yes  => 'Yes',
13376:                save => 'Save',
13377:     );
13378:     my $output = <<"END";
13379: <form name="$form" method="post" action="">
13380: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
13381: <label>
13382:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
13383: </label>
13384: &nbsp;
13385: <label>
13386:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
13387: </span>
13388: </p>
13389: <input type="hidden" name="phase" value="decompress_cleanup" />
13390: <br />$lt{'hows'}
13391: <div class="LC_columnSection">
13392:   <fieldset>
13393:     <legend>$lt{'cont'}</legend>
13394:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
13395:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
13396:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
13397:   </fieldset>
13398: </div>
13399: END
13400:     return $output.
13401:            &start_data_table()."\n".
13402:            $display."\n".
13403:            &end_data_table()."\n".
13404:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
13405:            $hiddenelem.
13406:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
13407:            '</form>';
13408: }
13409: 
13410: sub archive_javascript {
13411:     my ($startcount,$numitems,$titles,$children) = @_;
13412:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
13413:     my $maintitle = $env{'form.comment'};
13414:     my $scripttag = <<START;
13415: <script type="text/javascript">
13416: // <![CDATA[
13417: 
13418: function checkAll(form,prefix) {
13419:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
13420:     for (var i=0; i < form.elements.length; i++) {
13421:         var id = form.elements[i].id;
13422:         if ((id != '') && (id != undefined)) {
13423:             if (idstr.test(id)) {
13424:                 if (form.elements[i].type == 'radio') {
13425:                     form.elements[i].checked = true;
13426:                     var nostart = i-$startcount;
13427:                     var offset = nostart%7;
13428:                     var count = (nostart-offset)/7;    
13429:                     dependencyCheck(form,count,offset);
13430:                 }
13431:             }
13432:         }
13433:     }
13434: }
13435: 
13436: function propagateCheck(form,count) {
13437:     if (count > 0) {
13438:         var startelement = $startcount + ((count-1) * 7);
13439:         for (var j=1; j<6; j++) {
13440:             if ((j != 2) && (j != 4)) {
13441:                 var item = startelement + j; 
13442:                 if (form.elements[item].type == 'radio') {
13443:                     if (form.elements[item].checked) {
13444:                         containerCheck(form,count,j);
13445:                         break;
13446:                     }
13447:                 }
13448:             }
13449:         }
13450:     }
13451: }
13452: 
13453: numitems = $numitems
13454: var titles = new Array(numitems);
13455: var parents = new Array(numitems);
13456: for (var i=0; i<numitems; i++) {
13457:     parents[i] = new Array;
13458: }
13459: var maintitle = '$maintitle';
13460: 
13461: START
13462: 
13463:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
13464:         my @contents = split(/:/,$children->{$container});
13465:         for (my $i=0; $i<@contents; $i ++) {
13466:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
13467:         }
13468:     }
13469: 
13470:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
13471:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
13472:     }
13473: 
13474:     $scripttag .= <<END;
13475: 
13476: function containerCheck(form,count,offset) {
13477:     if (count > 0) {
13478:         dependencyCheck(form,count,offset);
13479:         var item = (offset+$startcount)+7*(count-1);
13480:         form.elements[item].checked = true;
13481:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
13482:             if (parents[count].length > 0) {
13483:                 for (var j=0; j<parents[count].length; j++) {
13484:                     containerCheck(form,parents[count][j],offset);
13485:                 }
13486:             }
13487:         }
13488:     }
13489: }
13490: 
13491: function dependencyCheck(form,count,offset) {
13492:     if (count > 0) {
13493:         var chosen = (offset+$startcount)+7*(count-1);
13494:         var depitem = $startcount + ((count-1) * 7) + 4;
13495:         var currtype = form.elements[depitem].type;
13496:         if (form.elements[chosen].value == 'dependency') {
13497:             document.getElementById('arc_depon_'+count).style.display='block'; 
13498:             form.elements[depitem].options.length = 0;
13499:             form.elements[depitem].options[0] = new Option('Select','',true,true);
13500:             for (var i=1; i<=numitems; i++) {
13501:                 if (i == count) {
13502:                     continue;
13503:                 }
13504:                 var startelement = $startcount + (i-1) * 7;
13505:                 for (var j=1; j<6; j++) {
13506:                     if ((j != 2) && (j!= 4)) {
13507:                         var item = startelement + j;
13508:                         if (form.elements[item].type == 'radio') {
13509:                             if (form.elements[item].checked) {
13510:                                 if (form.elements[item].value == 'display') {
13511:                                     var n = form.elements[depitem].options.length;
13512:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
13513:                                 }
13514:                             }
13515:                         }
13516:                     }
13517:                 }
13518:             }
13519:         } else {
13520:             document.getElementById('arc_depon_'+count).style.display='none';
13521:             form.elements[depitem].options.length = 0;
13522:             form.elements[depitem].options[0] = new Option('Select','',true,true);
13523:         }
13524:         titleCheck(form,count,offset);
13525:     }
13526: }
13527: 
13528: function propagateSelect(form,count,offset) {
13529:     if (count > 0) {
13530:         var item = (1+offset+$startcount)+7*(count-1);
13531:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
13532:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
13533:             if (parents[count].length > 0) {
13534:                 for (var j=0; j<parents[count].length; j++) {
13535:                     containerSelect(form,parents[count][j],offset,picked);
13536:                 }
13537:             }
13538:         }
13539:     }
13540: }
13541: 
13542: function containerSelect(form,count,offset,picked) {
13543:     if (count > 0) {
13544:         var item = (offset+$startcount)+7*(count-1);
13545:         if (form.elements[item].type == 'radio') {
13546:             if (form.elements[item].value == 'dependency') {
13547:                 if (form.elements[item+1].type == 'select-one') {
13548:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
13549:                         if (form.elements[item+1].options[i].value == picked) {
13550:                             form.elements[item+1].selectedIndex = i;
13551:                             break;
13552:                         }
13553:                     }
13554:                 }
13555:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
13556:                     if (parents[count].length > 0) {
13557:                         for (var j=0; j<parents[count].length; j++) {
13558:                             containerSelect(form,parents[count][j],offset,picked);
13559:                         }
13560:                     }
13561:                 }
13562:             }
13563:         }
13564:     }
13565: }
13566: 
13567: function titleCheck(form,count,offset) {
13568:     if (count > 0) {
13569:         var chosen = (offset+$startcount)+7*(count-1);
13570:         var depitem = $startcount + ((count-1) * 7) + 2;
13571:         var currtype = form.elements[depitem].type;
13572:         if (form.elements[chosen].value == 'display') {
13573:             document.getElementById('arc_title_'+count).style.display='block';
13574:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
13575:                 document.getElementById('archive_title_'+count).value=maintitle;
13576:             }
13577:         } else {
13578:             document.getElementById('arc_title_'+count).style.display='none';
13579:             if (currtype == 'text') { 
13580:                 document.getElementById('archive_title_'+count).value='';
13581:             }
13582:         }
13583:     }
13584:     return;
13585: }
13586: 
13587: // ]]>
13588: </script>
13589: END
13590:     return $scripttag;
13591: }
13592: 
13593: sub process_extracted_files {
13594:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
13595:     my $numitems = $env{'form.archive_count'};
13596:     return if ((!$numitems) || ($numitems =~ /\D/));
13597:     my @ids=&Apache::lonnet::current_machine_ids();
13598:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
13599:         %folders,%containers,%mapinner,%prompttofetch);
13600:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
13601:     if (grep(/^\Q$docuhome\E$/,@ids)) {
13602:         $prefix = &LONCAPA::propath($docudom,$docuname);
13603:         $pathtocheck = "$dir_root/$destination";
13604:         $dir = $dir_root;
13605:         $ishome = 1;
13606:     } else {
13607:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
13608:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
13609:         $dir = "$dir_root/$docudom/$docuname";
13610:     }
13611:     my $currdir = "$dir_root/$destination";
13612:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
13613:     if ($env{'form.folderpath'}) {
13614:         my @items = split('&',$env{'form.folderpath'});
13615:         $folders{'0'} = $items[-2];
13616:         if ($env{'form.folderpath'} =~ /\:1$/) {
13617:             $containers{'0'}='page';
13618:         } else {
13619:             $containers{'0'}='sequence';
13620:         }
13621:     }
13622:     my @archdirs = &get_env_multiple('form.archive_directory');
13623:     if ($numitems) {
13624:         for (my $i=1; $i<=$numitems; $i++) {
13625:             my $path = $env{'form.archive_content_'.$i};
13626:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
13627:                 my $item = $1;
13628:                 $toplevelitems{$item} = $i;
13629:                 if (grep(/^\Q$i\E$/,@archdirs)) {
13630:                     $is_dir{$item} = 1;
13631:                 }
13632:             }
13633:         }
13634:     }
13635:     my ($output,%children,%parent,%titles,%dirorder,$result);
13636:     if (keys(%toplevelitems) > 0) {
13637:         my @contents = sort(keys(%toplevelitems));
13638:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
13639:                                            \%parent,\@contents,\%dirorder,\%titles);
13640:     }
13641:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
13642:     if ($numitems) {
13643:         for (my $i=1; $i<=$numitems; $i++) {
13644:             next if ($env{'form.archive_'.$i} eq 'dependency');
13645:             my $path = $env{'form.archive_content_'.$i};
13646:             if ($path =~ /^\Q$pathtocheck\E/) {
13647:                 if ($env{'form.archive_'.$i} eq 'discard') {
13648:                     if ($prefix ne '' && $path ne '') {
13649:                         if (-e $prefix.$path) {
13650:                             if ((@archdirs > 0) && 
13651:                                 (grep(/^\Q$i\E$/,@archdirs))) {
13652:                                 $todeletedir{$prefix.$path} = 1;
13653:                             } else {
13654:                                 $todelete{$prefix.$path} = 1;
13655:                             }
13656:                         }
13657:                     }
13658:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
13659:                     my ($docstitle,$title,$url,$outer);
13660:                     ($title) = ($path =~ m{/([^/]+)$});
13661:                     $docstitle = $env{'form.archive_title_'.$i};
13662:                     if ($docstitle eq '') {
13663:                         $docstitle = $title;
13664:                     }
13665:                     $outer = 0;
13666:                     if (ref($dirorder{$i}) eq 'ARRAY') {
13667:                         if (@{$dirorder{$i}} > 0) {
13668:                             foreach my $item (reverse(@{$dirorder{$i}})) {
13669:                                 if ($env{'form.archive_'.$item} eq 'display') {
13670:                                     $outer = $item;
13671:                                     last;
13672:                                 }
13673:                             }
13674:                         }
13675:                     }
13676:                     my ($errtext,$fatal) = 
13677:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
13678:                                                '/'.$folders{$outer}.'.'.
13679:                                                $containers{$outer});
13680:                     next if ($fatal);
13681:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
13682:                         if ($context eq 'coursedocs') {
13683:                             $mapinner{$i} = time;
13684:                             $folders{$i} = 'default_'.$mapinner{$i};
13685:                             $containers{$i} = 'sequence';
13686:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
13687:                                       $folders{$i}.'.'.$containers{$i};
13688:                             my $newidx = &LONCAPA::map::getresidx();
13689:                             $LONCAPA::map::resources[$newidx]=
13690:                                 $docstitle.':'.$url.':false:normal:res';
13691:                             push(@LONCAPA::map::order,$newidx);
13692:                             my ($outtext,$errtext) =
13693:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
13694:                                                         $docuname.'/'.$folders{$outer}.
13695:                                                         '.'.$containers{$outer},1,1);
13696:                             $newseqid{$i} = $newidx;
13697:                             unless ($errtext) {
13698:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
13699:                                                        &HTML::Entities::encode($docstitle,'<>&"'))..
13700:                                             '</li>'."\n";
13701:                             }
13702:                         }
13703:                     } else {
13704:                         if ($context eq 'coursedocs') {
13705:                             my $newidx=&LONCAPA::map::getresidx();
13706:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
13707:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
13708:                                       $title;
13709:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
13710:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
13711:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
13712:                                 }
13713:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
13714:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
13715:                                 }
13716:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
13717:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
13718:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
13719:                                         unless ($ishome) {
13720:                                             my $fetch = "$newdest{$i}/$title";
13721:                                             $fetch =~ s/^\Q$prefix$dir\E//;
13722:                                             $prompttofetch{$fetch} = 1;
13723:                                         }
13724:                                    }
13725:                                 }
13726:                                 $LONCAPA::map::resources[$newidx]=
13727:                                     $docstitle.':'.$url.':false:normal:res';
13728:                                 push(@LONCAPA::map::order, $newidx);
13729:                                 my ($outtext,$errtext)=
13730:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
13731:                                                             $docuname.'/'.$folders{$outer}.
13732:                                                             '.'.$containers{$outer},1,1);
13733:                                 unless ($errtext) {
13734:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
13735:                                         $result .= '<li>'.&mt('File: [_1] added to course',
13736:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
13737:                                                    '</li>'."\n";
13738:                                     }
13739:                                 }
13740:                             } else {
13741:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13742:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
13743:                             }
13744:                         }
13745:                     }
13746:                 }
13747:             } else {
13748:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13749:                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
13750:             }
13751:         }
13752:         for (my $i=1; $i<=$numitems; $i++) {
13753:             next unless ($env{'form.archive_'.$i} eq 'dependency');
13754:             my $path = $env{'form.archive_content_'.$i};
13755:             if ($path =~ /^\Q$pathtocheck\E/) {
13756:                 my ($title) = ($path =~ m{/([^/]+)$});
13757:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
13758:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
13759:                     if (ref($dirorder{$i}) eq 'ARRAY') {
13760:                         my ($itemidx,$fullpath,$relpath);
13761:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
13762:                             my $container = $dirorder{$referrer{$i}}->[-1];
13763:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
13764:                                 if ($dirorder{$i}->[$j] eq $container) {
13765:                                     $itemidx = $j;
13766:                                 }
13767:                             }
13768:                         }
13769:                         if ($itemidx eq '') {
13770:                             $itemidx =  0;
13771:                         }
13772:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
13773:                             if ($mapinner{$referrer{$i}}) {
13774:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
13775:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
13776:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
13777:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
13778:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
13779:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
13780:                                             if (!-e $fullpath) {
13781:                                                 mkdir($fullpath,0755);
13782:                                             }
13783:                                         }
13784:                                     } else {
13785:                                         last;
13786:                                     }
13787:                                 }
13788:                             }
13789:                         } elsif ($newdest{$referrer{$i}}) {
13790:                             $fullpath = $newdest{$referrer{$i}};
13791:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
13792:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
13793:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
13794:                                     last;
13795:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
13796:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
13797:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
13798:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
13799:                                         if (!-e $fullpath) {
13800:                                             mkdir($fullpath,0755);
13801:                                         }
13802:                                     }
13803:                                 } else {
13804:                                     last;
13805:                                 }
13806:                             }
13807:                         }
13808:                         if ($fullpath ne '') {
13809:                             if (-e "$prefix$path") {
13810:                                 unless (rename("$prefix$path","$fullpath/$title")) {
13811:                                      $warning .= &mt('Failed to rename dependency').'<br />';
13812:                                 }
13813:                             }
13814:                             if (-e "$fullpath/$title") {
13815:                                 my $showpath;
13816:                                 if ($relpath ne '') {
13817:                                     $showpath = "$relpath/$title";
13818:                                 } else {
13819:                                     $showpath = "/$title";
13820:                                 }
13821:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
13822:                                                       &HTML::Entities::encode($showpath,'<>&"')).
13823:                                            '</li>'."\n";
13824:                                 unless ($ishome) {
13825:                                     my $fetch = "$fullpath/$title";
13826:                                     $fetch =~ s/^\Q$prefix$dir\E//;
13827:                                     $prompttofetch{$fetch} = 1;
13828:                                 }
13829:                             }
13830:                         }
13831:                     }
13832:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
13833:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
13834:                                     &HTML::Entities::encode($path,'<>&"'),
13835:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
13836:                                 '<br />';
13837:                 }
13838:             } else {
13839:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13840:                                 &HTML::Entities::encode($path)).'<br />';
13841:             }
13842:         }
13843:         if (keys(%todelete)) {
13844:             foreach my $key (keys(%todelete)) {
13845:                 unlink($key);
13846:             }
13847:         }
13848:         if (keys(%todeletedir)) {
13849:             foreach my $key (keys(%todeletedir)) {
13850:                 rmdir($key);
13851:             }
13852:         }
13853:         foreach my $dir (sort(keys(%is_dir))) {
13854:             if (($pathtocheck ne '') && ($dir ne ''))  {
13855:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
13856:             }
13857:         }
13858:         if ($result ne '') {
13859:             $output .= '<ul>'."\n".
13860:                        $result."\n".
13861:                        '</ul>';
13862:         }
13863:         unless ($ishome) {
13864:             my $replicationfail;
13865:             foreach my $item (keys(%prompttofetch)) {
13866:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
13867:                 unless ($fetchresult eq 'ok') {
13868:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
13869:                 }
13870:             }
13871:             if ($replicationfail) {
13872:                 $output .= '<p class="LC_error">'.
13873:                            &mt('Course home server failed to retrieve:').'<ul>'.
13874:                            $replicationfail.
13875:                            '</ul></p>';
13876:             }
13877:         }
13878:     } else {
13879:         $warning = &mt('No items found in archive.');
13880:     }
13881:     if ($error) {
13882:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13883:                    $error.'</p>'."\n";
13884:     }
13885:     if ($warning) {
13886:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
13887:     }
13888:     return $output;
13889: }
13890: 
13891: sub cleanup_empty_dirs {
13892:     my ($path) = @_;
13893:     if (($path ne '') && (-d $path)) {
13894:         if (opendir(my $dirh,$path)) {
13895:             my @dircontents = grep(!/^\./,readdir($dirh));
13896:             my $numitems = 0;
13897:             foreach my $item (@dircontents) {
13898:                 if (-d "$path/$item") {
13899:                     &cleanup_empty_dirs("$path/$item");
13900:                     if (-e "$path/$item") {
13901:                         $numitems ++;
13902:                     }
13903:                 } else {
13904:                     $numitems ++;
13905:                 }
13906:             }
13907:             if ($numitems == 0) {
13908:                 rmdir($path);
13909:             }
13910:             closedir($dirh);
13911:         }
13912:     }
13913:     return;
13914: }
13915: 
13916: =pod
13917: 
13918: =item * &get_folder_hierarchy()
13919: 
13920: Provides hierarchy of names of folders/sub-folders containing the current
13921: item,
13922: 
13923: Inputs: 3
13924:      - $navmap - navmaps object
13925: 
13926:      - $map - url for map (either the trigger itself, or map containing
13927:                            the resource, which is the trigger).
13928: 
13929:      - $showitem - 1 => show title for map itself; 0 => do not show.
13930: 
13931: Outputs: 1 @pathitems - array of folder/subfolder names.
13932: 
13933: =cut
13934: 
13935: sub get_folder_hierarchy {
13936:     my ($navmap,$map,$showitem) = @_;
13937:     my @pathitems;
13938:     if (ref($navmap)) {
13939:         my $mapres = $navmap->getResourceByUrl($map);
13940:         if (ref($mapres)) {
13941:             my $pcslist = $mapres->map_hierarchy();
13942:             if ($pcslist ne '') {
13943:                 my @pcs = split(/,/,$pcslist);
13944:                 foreach my $pc (@pcs) {
13945:                     if ($pc == 1) {
13946:                         push(@pathitems,&mt('Main Content'));
13947:                     } else {
13948:                         my $res = $navmap->getByMapPc($pc);
13949:                         if (ref($res)) {
13950:                             my $title = $res->compTitle();
13951:                             $title =~ s/\W+/_/g;
13952:                             if ($title ne '') {
13953:                                 push(@pathitems,$title);
13954:                             }
13955:                         }
13956:                     }
13957:                 }
13958:             }
13959:             if ($showitem) {
13960:                 if ($mapres->{ID} eq '0.0') {
13961:                     push(@pathitems,&mt('Main Content'));
13962:                 } else {
13963:                     my $maptitle = $mapres->compTitle();
13964:                     $maptitle =~ s/\W+/_/g;
13965:                     if ($maptitle ne '') {
13966:                         push(@pathitems,$maptitle);
13967:                     }
13968:                 }
13969:             }
13970:         }
13971:     }
13972:     return @pathitems;
13973: }
13974: 
13975: =pod
13976: 
13977: =item * &get_turnedin_filepath()
13978: 
13979: Determines path in a user's portfolio file for storage of files uploaded
13980: to a specific essayresponse or dropbox item.
13981: 
13982: Inputs: 3 required + 1 optional.
13983: $symb is symb for resource, $uname and $udom are for current user (required).
13984: $caller is optional (can be "submission", if routine is called when storing
13985: an upoaded file when "Submit Answer" button was pressed).
13986: 
13987: Returns array containing $path and $multiresp. 
13988: $path is path in portfolio.  $multiresp is 1 if this resource contains more
13989: than one file upload item.  Callers of routine should append partid as a 
13990: subdirectory to $path in cases where $multiresp is 1.
13991: 
13992: Called by: homework/essayresponse.pm and homework/structuretags.pm
13993: 
13994: =cut
13995: 
13996: sub get_turnedin_filepath {
13997:     my ($symb,$uname,$udom,$caller) = @_;
13998:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
13999:     my $turnindir;
14000:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
14001:     $turnindir = $userhash{'turnindir'};
14002:     my ($path,$multiresp);
14003:     if ($turnindir eq '') {
14004:         if ($caller eq 'submission') {
14005:             $turnindir = &mt('turned in');
14006:             $turnindir =~ s/\W+/_/g;
14007:             my %newhash = (
14008:                             'turnindir' => $turnindir,
14009:                           );
14010:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
14011:         }
14012:     }
14013:     if ($turnindir ne '') {
14014:         $path = '/'.$turnindir.'/';
14015:         my ($multipart,$turnin,@pathitems);
14016:         my $navmap = Apache::lonnavmaps::navmap->new();
14017:         if (defined($navmap)) {
14018:             my $mapres = $navmap->getResourceByUrl($map);
14019:             if (ref($mapres)) {
14020:                 my $pcslist = $mapres->map_hierarchy();
14021:                 if ($pcslist ne '') {
14022:                     foreach my $pc (split(/,/,$pcslist)) {
14023:                         my $res = $navmap->getByMapPc($pc);
14024:                         if (ref($res)) {
14025:                             my $title = $res->compTitle();
14026:                             $title =~ s/\W+/_/g;
14027:                             if ($title ne '') {
14028:                                 if (($pc > 1) && (length($title) > 12)) {
14029:                                     $title = substr($title,0,12);
14030:                                 }
14031:                                 push(@pathitems,$title);
14032:                             }
14033:                         }
14034:                     }
14035:                 }
14036:                 my $maptitle = $mapres->compTitle();
14037:                 $maptitle =~ s/\W+/_/g;
14038:                 if ($maptitle ne '') {
14039:                     if (length($maptitle) > 12) {
14040:                         $maptitle = substr($maptitle,0,12);
14041:                     }
14042:                     push(@pathitems,$maptitle);
14043:                 }
14044:                 unless ($env{'request.state'} eq 'construct') {
14045:                     my $res = $navmap->getBySymb($symb);
14046:                     if (ref($res)) {
14047:                         my $partlist = $res->parts();
14048:                         my $totaluploads = 0;
14049:                         if (ref($partlist) eq 'ARRAY') {
14050:                             foreach my $part (@{$partlist}) {
14051:                                 my @types = $res->responseType($part);
14052:                                 my @ids = $res->responseIds($part);
14053:                                 for (my $i=0; $i < scalar(@ids); $i++) {
14054:                                     if ($types[$i] eq 'essay') {
14055:                                         my $partid = $part.'_'.$ids[$i];
14056:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
14057:                                             $totaluploads ++;
14058:                                         }
14059:                                     }
14060:                                 }
14061:                             }
14062:                             if ($totaluploads > 1) {
14063:                                 $multiresp = 1;
14064:                             }
14065:                         }
14066:                     }
14067:                 }
14068:             } else {
14069:                 return;
14070:             }
14071:         } else {
14072:             return;
14073:         }
14074:         my $restitle=&Apache::lonnet::gettitle($symb);
14075:         $restitle =~ s/\W+/_/g;
14076:         if ($restitle eq '') {
14077:             $restitle = ($resurl =~ m{/[^/]+$});
14078:             if ($restitle eq '') {
14079:                 $restitle = time;
14080:             }
14081:         }
14082:         if (length($restitle) > 12) {
14083:             $restitle = substr($restitle,0,12);
14084:         }
14085:         push(@pathitems,$restitle);
14086:         $path .= join('/',@pathitems);
14087:     }
14088:     return ($path,$multiresp);
14089: }
14090: 
14091: =pod
14092: 
14093: =back
14094: 
14095: =head1 CSV Upload/Handling functions
14096: 
14097: =over 4
14098: 
14099: =item * &upfile_store($r)
14100: 
14101: Store uploaded file, $r should be the HTTP Request object,
14102: needs $env{'form.upfile'}
14103: returns $datatoken to be put into hidden field
14104: 
14105: =cut
14106: 
14107: sub upfile_store {
14108:     my $r=shift;
14109:     $env{'form.upfile'}=~s/\r/\n/gs;
14110:     $env{'form.upfile'}=~s/\f/\n/gs;
14111:     $env{'form.upfile'}=~s/\n+/\n/gs;
14112:     $env{'form.upfile'}=~s/\n+$//gs;
14113: 
14114:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
14115:                                      '_enroll_'.$env{'request.course.id'}.'_'.
14116:                                      time.'_'.$$);
14117:     return if ($datatoken eq '');
14118: 
14119:     {
14120:         my $datafile = $r->dir_config('lonDaemons').
14121:                            '/tmp/'.$datatoken.'.tmp';
14122:         if ( open(my $fh,'>',$datafile) ) {
14123:             print $fh $env{'form.upfile'};
14124:             close($fh);
14125:         }
14126:     }
14127:     return $datatoken;
14128: }
14129: 
14130: =pod
14131: 
14132: =item * &load_tmp_file($r,$datatoken)
14133: 
14134: Load uploaded file from tmp, $r should be the HTTP Request object,
14135: $datatoken is the name to assign to the temporary file.
14136: sets $env{'form.upfile'} to the contents of the file
14137: 
14138: =cut
14139: 
14140: sub load_tmp_file {
14141:     my ($r,$datatoken) = @_;
14142:     return if ($datatoken eq '');
14143:     my @studentdata=();
14144:     {
14145:         my $studentfile = $r->dir_config('lonDaemons').
14146:                               '/tmp/'.$datatoken.'.tmp';
14147:         if ( open(my $fh,'<',$studentfile) ) {
14148:             @studentdata=<$fh>;
14149:             close($fh);
14150:         }
14151:     }
14152:     $env{'form.upfile'}=join('',@studentdata);
14153: }
14154: 
14155: sub valid_datatoken {
14156:     my ($datatoken) = @_;
14157:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
14158:         return $datatoken;
14159:     }
14160:     return;
14161: }
14162: 
14163: =pod
14164: 
14165: =item * &upfile_record_sep()
14166: 
14167: Separate uploaded file into records
14168: returns array of records,
14169: needs $env{'form.upfile'} and $env{'form.upfiletype'}
14170: 
14171: =cut
14172: 
14173: sub upfile_record_sep {
14174:     if ($env{'form.upfiletype'} eq 'xml') {
14175:     } else {
14176: 	my @records;
14177: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
14178: 	    if ($line=~/^\s*$/) { next; }
14179: 	    push(@records,$line);
14180: 	}
14181: 	return @records;
14182:     }
14183: }
14184: 
14185: =pod
14186: 
14187: =item * &record_sep($record)
14188: 
14189: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
14190: 
14191: =cut
14192: 
14193: sub takeleft {
14194:     my $index=shift;
14195:     return substr('0000'.$index,-4,4);
14196: }
14197: 
14198: sub record_sep {
14199:     my $record=shift;
14200:     my %components=();
14201:     if ($env{'form.upfiletype'} eq 'xml') {
14202:     } elsif ($env{'form.upfiletype'} eq 'space') {
14203:         my $i=0;
14204:         foreach my $field (split(/\s+/,$record)) {
14205:             $field=~s/^(\"|\')//;
14206:             $field=~s/(\"|\')$//;
14207:             $components{&takeleft($i)}=$field;
14208:             $i++;
14209:         }
14210:     } elsif ($env{'form.upfiletype'} eq 'tab') {
14211:         my $i=0;
14212:         foreach my $field (split(/\t/,$record)) {
14213:             $field=~s/^(\"|\')//;
14214:             $field=~s/(\"|\')$//;
14215:             $components{&takeleft($i)}=$field;
14216:             $i++;
14217:         }
14218:     } else {
14219:         my $separator=',';
14220:         if ($env{'form.upfiletype'} eq 'semisv') {
14221:             $separator=';';
14222:         }
14223:         my $i=0;
14224: # the character we are looking for to indicate the end of a quote or a record 
14225:         my $looking_for=$separator;
14226: # do not add the characters to the fields
14227:         my $ignore=0;
14228: # we just encountered a separator (or the beginning of the record)
14229:         my $just_found_separator=1;
14230: # store the field we are working on here
14231:         my $field='';
14232: # work our way through all characters in record
14233:         foreach my $character ($record=~/(.)/g) {
14234:             if ($character eq $looking_for) {
14235:                if ($character ne $separator) {
14236: # Found the end of a quote, again looking for separator
14237:                   $looking_for=$separator;
14238:                   $ignore=1;
14239:                } else {
14240: # Found a separator, store away what we got
14241:                   $components{&takeleft($i)}=$field;
14242: 	          $i++;
14243:                   $just_found_separator=1;
14244:                   $ignore=0;
14245:                   $field='';
14246:                }
14247:                next;
14248:             }
14249: # single or double quotation marks after a separator indicate beginning of a quote
14250: # we are now looking for the end of the quote and need to ignore separators
14251:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
14252:                $looking_for=$character;
14253:                next;
14254:             }
14255: # ignore would be true after we reached the end of a quote
14256:             if ($ignore) { next; }
14257:             if (($just_found_separator) && ($character=~/\s/)) { next; }
14258:             $field.=$character;
14259:             $just_found_separator=0; 
14260:         }
14261: # catch the very last entry, since we never encountered the separator
14262:         $components{&takeleft($i)}=$field;
14263:     }
14264:     return %components;
14265: }
14266: 
14267: ######################################################
14268: ######################################################
14269: 
14270: =pod
14271: 
14272: =item * &upfile_select_html()
14273: 
14274: Return HTML code to select a file from the users machine and specify 
14275: the file type.
14276: 
14277: =cut
14278: 
14279: ######################################################
14280: ######################################################
14281: sub upfile_select_html {
14282:     my %Types = (
14283:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
14284:                  semisv => &mt('Semicolon separated values'),
14285:                  space => &mt('Space separated'),
14286:                  tab   => &mt('Tabulator separated'),
14287: #                 xml   => &mt('HTML/XML'),
14288:                  );
14289:     my $Str = '<input type="file" name="upfile" size="50" />'.
14290:         '<br />'.&mt('Type').': <select name="upfiletype">';
14291:     foreach my $type (sort(keys(%Types))) {
14292:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
14293:     }
14294:     $Str .= "</select>\n";
14295:     return $Str;
14296: }
14297: 
14298: sub get_samples {
14299:     my ($records,$toget) = @_;
14300:     my @samples=({});
14301:     my $got=0;
14302:     foreach my $rec (@$records) {
14303: 	my %temp = &record_sep($rec);
14304: 	if (! grep(/\S/, values(%temp))) { next; }
14305: 	if (%temp) {
14306: 	    $samples[$got]=\%temp;
14307: 	    $got++;
14308: 	    if ($got == $toget) { last; }
14309: 	}
14310:     }
14311:     return \@samples;
14312: }
14313: 
14314: ######################################################
14315: ######################################################
14316: 
14317: =pod
14318: 
14319: =item * &csv_print_samples($r,$records)
14320: 
14321: Prints a table of sample values from each column uploaded $r is an
14322: Apache Request ref, $records is an arrayref from
14323: &Apache::loncommon::upfile_record_sep
14324: 
14325: =cut
14326: 
14327: ######################################################
14328: ######################################################
14329: sub csv_print_samples {
14330:     my ($r,$records) = @_;
14331:     my $samples = &get_samples($records,5);
14332: 
14333:     $r->print(&mt('Samples').'<br />'.&start_data_table().
14334:               &start_data_table_header_row());
14335:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
14336:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
14337:     $r->print(&end_data_table_header_row());
14338:     foreach my $hash (@$samples) {
14339: 	$r->print(&start_data_table_row());
14340: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
14341: 	    $r->print('<td>');
14342: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
14343: 	    $r->print('</td>');
14344: 	}
14345: 	$r->print(&end_data_table_row());
14346:     }
14347:     $r->print(&end_data_table().'<br />'."\n");
14348: }
14349: 
14350: ######################################################
14351: ######################################################
14352: 
14353: =pod
14354: 
14355: =item * &csv_print_select_table($r,$records,$d)
14356: 
14357: Prints a table to create associations between values and table columns.
14358: 
14359: $r is an Apache Request ref,
14360: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
14361: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
14362: 
14363: =cut
14364: 
14365: ######################################################
14366: ######################################################
14367: sub csv_print_select_table {
14368:     my ($r,$records,$d) = @_;
14369:     my $i=0;
14370:     my $samples = &get_samples($records,1);
14371:     $r->print(&mt('Associate columns with student attributes.')."\n".
14372: 	      &start_data_table().&start_data_table_header_row().
14373:               '<th>'.&mt('Attribute').'</th>'.
14374:               '<th>'.&mt('Column').'</th>'.
14375:               &end_data_table_header_row()."\n");
14376:     foreach my $array_ref (@$d) {
14377: 	my ($value,$display,$defaultcol)=@{ $array_ref };
14378: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
14379: 
14380: 	$r->print('<td><select name="f'.$i.'"'.
14381: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
14382: 	$r->print('<option value="none"></option>');
14383: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
14384: 	    $r->print('<option value="'.$sample.'"'.
14385:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
14386:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
14387: 	}
14388: 	$r->print('</select></td>'.&end_data_table_row()."\n");
14389: 	$i++;
14390:     }
14391:     $r->print(&end_data_table());
14392:     $i--;
14393:     return $i;
14394: }
14395: 
14396: ######################################################
14397: ######################################################
14398: 
14399: =pod
14400: 
14401: =item * &csv_samples_select_table($r,$records,$d)
14402: 
14403: Prints a table of sample values from the upload and can make associate samples to internal names.
14404: 
14405: $r is an Apache Request ref,
14406: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
14407: $d is an array of 2 element arrays (internal name, displayed name)
14408: 
14409: =cut
14410: 
14411: ######################################################
14412: ######################################################
14413: sub csv_samples_select_table {
14414:     my ($r,$records,$d) = @_;
14415:     my $i=0;
14416:     #
14417:     my $max_samples = 5;
14418:     my $samples = &get_samples($records,$max_samples);
14419:     $r->print(&start_data_table().
14420:               &start_data_table_header_row().'<th>'.
14421:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
14422:               &end_data_table_header_row());
14423: 
14424:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
14425: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
14426: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
14427: 	foreach my $option (@$d) {
14428: 	    my ($value,$display,$defaultcol)=@{ $option };
14429: 	    $r->print('<option value="'.$value.'"'.
14430:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
14431:                       $display.'</option>');
14432: 	}
14433: 	$r->print('</select></td><td>');
14434: 	foreach my $line (0..($max_samples-1)) {
14435: 	    if (defined($samples->[$line]{$key})) { 
14436: 		$r->print($samples->[$line]{$key}."<br />\n"); 
14437: 	    }
14438: 	}
14439: 	$r->print('</td>'.&end_data_table_row());
14440: 	$i++;
14441:     }
14442:     $r->print(&end_data_table());
14443:     $i--;
14444:     return($i);
14445: }
14446: 
14447: ######################################################
14448: ######################################################
14449: 
14450: =pod
14451: 
14452: =item * &clean_excel_name($name)
14453: 
14454: Returns a replacement for $name which does not contain any illegal characters.
14455: 
14456: =cut
14457: 
14458: ######################################################
14459: ######################################################
14460: sub clean_excel_name {
14461:     my ($name) = @_;
14462:     $name =~ s/[:\*\?\/\\]//g;
14463:     if (length($name) > 31) {
14464:         $name = substr($name,0,31);
14465:     }
14466:     return $name;
14467: }
14468: 
14469: =pod
14470: 
14471: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
14472: 
14473: Returns either 1 or undef
14474: 
14475: 1 if the part is to be hidden, undef if it is to be shown
14476: 
14477: Arguments are:
14478: 
14479: $id the id of the part to be checked
14480: $symb, optional the symb of the resource to check
14481: $udom, optional the domain of the user to check for
14482: $uname, optional the username of the user to check for
14483: 
14484: =cut
14485: 
14486: sub check_if_partid_hidden {
14487:     my ($id,$symb,$udom,$uname) = @_;
14488:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
14489: 					 $symb,$udom,$uname);
14490:     my $truth=1;
14491:     #if the string starts with !, then the list is the list to show not hide
14492:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
14493:     my @hiddenlist=split(/,/,$hiddenparts);
14494:     foreach my $checkid (@hiddenlist) {
14495: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
14496:     }
14497:     return !$truth;
14498: }
14499: 
14500: 
14501: ############################################################
14502: ############################################################
14503: 
14504: =pod
14505: 
14506: =back 
14507: 
14508: =head1 cgi-bin script and graphing routines
14509: 
14510: =over 4
14511: 
14512: =item * &get_cgi_id()
14513: 
14514: Inputs: none
14515: 
14516: Returns an id which can be used to pass environment variables
14517: to various cgi-bin scripts.  These environment variables will
14518: be removed from the users environment after a given time by
14519: the routine &Apache::lonnet::transfer_profile_to_env.
14520: 
14521: =cut
14522: 
14523: ############################################################
14524: ############################################################
14525: my $uniq=0;
14526: sub get_cgi_id {
14527:     $uniq=($uniq+1)%100000;
14528:     return (time.'_'.$$.'_'.$uniq);
14529: }
14530: 
14531: ############################################################
14532: ############################################################
14533: 
14534: =pod
14535: 
14536: =item * &DrawBarGraph()
14537: 
14538: Facilitates the plotting of data in a (stacked) bar graph.
14539: Puts plot definition data into the users environment in order for 
14540: graph.png to plot it.  Returns an <img> tag for the plot.
14541: The bars on the plot are labeled '1','2',...,'n'.
14542: 
14543: Inputs:
14544: 
14545: =over 4
14546: 
14547: =item $Title: string, the title of the plot
14548: 
14549: =item $xlabel: string, text describing the X-axis of the plot
14550: 
14551: =item $ylabel: string, text describing the Y-axis of the plot
14552: 
14553: =item $Max: scalar, the maximum Y value to use in the plot
14554: If $Max is < any data point, the graph will not be rendered.
14555: 
14556: =item $colors: array ref holding the colors to be used for the data sets when
14557: they are plotted.  If undefined, default values will be used.
14558: 
14559: =item $labels: array ref holding the labels to use on the x-axis for the bars.
14560: 
14561: =item @Values: An array of array references.  Each array reference holds data
14562: to be plotted in a stacked bar chart.
14563: 
14564: =item If the final element of @Values is a hash reference the key/value
14565: pairs will be added to the graph definition.
14566: 
14567: =back
14568: 
14569: Returns:
14570: 
14571: An <img> tag which references graph.png and the appropriate identifying
14572: information for the plot.
14573: 
14574: =cut
14575: 
14576: ############################################################
14577: ############################################################
14578: sub DrawBarGraph {
14579:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
14580:     #
14581:     if (! defined($colors)) {
14582:         $colors = ['#33ff00', 
14583:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
14584:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
14585:                   ]; 
14586:     }
14587:     my $extra_settings = {};
14588:     if (ref($Values[-1]) eq 'HASH') {
14589:         $extra_settings = pop(@Values);
14590:     }
14591:     #
14592:     my $identifier = &get_cgi_id();
14593:     my $id = 'cgi.'.$identifier;        
14594:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
14595:         return '';
14596:     }
14597:     #
14598:     my @Labels;
14599:     if (defined($labels)) {
14600:         @Labels = @$labels;
14601:     } else {
14602:         for (my $i=0;$i<@{$Values[0]};$i++) {
14603:             push(@Labels,$i+1);
14604:         }
14605:     }
14606:     #
14607:     my $NumBars = scalar(@{$Values[0]});
14608:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
14609:     my %ValuesHash;
14610:     my $NumSets=1;
14611:     foreach my $array (@Values) {
14612:         next if (! ref($array));
14613:         $ValuesHash{$id.'.data.'.$NumSets++} = 
14614:             join(',',@$array);
14615:     }
14616:     #
14617:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
14618:     if ($NumBars < 3) {
14619:         $width = 120+$NumBars*32;
14620:         $xskip = 1;
14621:         $bar_width = 30;
14622:     } elsif ($NumBars < 5) {
14623:         $width = 120+$NumBars*20;
14624:         $xskip = 1;
14625:         $bar_width = 20;
14626:     } elsif ($NumBars < 10) {
14627:         $width = 120+$NumBars*15;
14628:         $xskip = 1;
14629:         $bar_width = 15;
14630:     } elsif ($NumBars <= 25) {
14631:         $width = 120+$NumBars*11;
14632:         $xskip = 5;
14633:         $bar_width = 8;
14634:     } elsif ($NumBars <= 50) {
14635:         $width = 120+$NumBars*8;
14636:         $xskip = 5;
14637:         $bar_width = 4;
14638:     } else {
14639:         $width = 120+$NumBars*8;
14640:         $xskip = 5;
14641:         $bar_width = 4;
14642:     }
14643:     #
14644:     $Max = 1 if ($Max < 1);
14645:     if ( int($Max) < $Max ) {
14646:         $Max++;
14647:         $Max = int($Max);
14648:     }
14649:     $Title  = '' if (! defined($Title));
14650:     $xlabel = '' if (! defined($xlabel));
14651:     $ylabel = '' if (! defined($ylabel));
14652:     $ValuesHash{$id.'.title'}    = &escape($Title);
14653:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
14654:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
14655:     $ValuesHash{$id.'.y_max_value'} = $Max;
14656:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
14657:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
14658:     $ValuesHash{$id.'.PlotType'} = 'bar';
14659:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14660:     $ValuesHash{$id.'.height'}   = $height;
14661:     $ValuesHash{$id.'.width'}    = $width;
14662:     $ValuesHash{$id.'.xskip'}    = $xskip;
14663:     $ValuesHash{$id.'.bar_width'} = $bar_width;
14664:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
14665:     #
14666:     # Deal with other parameters
14667:     while (my ($key,$value) = each(%$extra_settings)) {
14668:         $ValuesHash{$id.'.'.$key} = $value;
14669:     }
14670:     #
14671:     &Apache::lonnet::appenv(\%ValuesHash);
14672:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14673: }
14674: 
14675: ############################################################
14676: ############################################################
14677: 
14678: =pod
14679: 
14680: =item * &DrawXYGraph()
14681: 
14682: Facilitates the plotting of data in an XY graph.
14683: Puts plot definition data into the users environment in order for 
14684: graph.png to plot it.  Returns an <img> tag for the plot.
14685: 
14686: Inputs:
14687: 
14688: =over 4
14689: 
14690: =item $Title: string, the title of the plot
14691: 
14692: =item $xlabel: string, text describing the X-axis of the plot
14693: 
14694: =item $ylabel: string, text describing the Y-axis of the plot
14695: 
14696: =item $Max: scalar, the maximum Y value to use in the plot
14697: If $Max is < any data point, the graph will not be rendered.
14698: 
14699: =item $colors: Array ref containing the hex color codes for the data to be 
14700: plotted in.  If undefined, default values will be used.
14701: 
14702: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
14703: 
14704: =item $Ydata: Array ref containing Array refs.  
14705: Each of the contained arrays will be plotted as a separate curve.
14706: 
14707: =item %Values: hash indicating or overriding any default values which are 
14708: passed to graph.png.  
14709: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
14710: 
14711: =back
14712: 
14713: Returns:
14714: 
14715: An <img> tag which references graph.png and the appropriate identifying
14716: information for the plot.
14717: 
14718: =cut
14719: 
14720: ############################################################
14721: ############################################################
14722: sub DrawXYGraph {
14723:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
14724:     #
14725:     # Create the identifier for the graph
14726:     my $identifier = &get_cgi_id();
14727:     my $id = 'cgi.'.$identifier;
14728:     #
14729:     $Title  = '' if (! defined($Title));
14730:     $xlabel = '' if (! defined($xlabel));
14731:     $ylabel = '' if (! defined($ylabel));
14732:     my %ValuesHash = 
14733:         (
14734:          $id.'.title'  => &escape($Title),
14735:          $id.'.xlabel' => &escape($xlabel),
14736:          $id.'.ylabel' => &escape($ylabel),
14737:          $id.'.y_max_value'=> $Max,
14738:          $id.'.labels'     => join(',',@$Xlabels),
14739:          $id.'.PlotType'   => 'XY',
14740:          );
14741:     #
14742:     if (defined($colors) && ref($colors) eq 'ARRAY') {
14743:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14744:     }
14745:     #
14746:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
14747:         return '';
14748:     }
14749:     my $NumSets=1;
14750:     foreach my $array (@{$Ydata}){
14751:         next if (! ref($array));
14752:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
14753:     }
14754:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
14755:     #
14756:     # Deal with other parameters
14757:     while (my ($key,$value) = each(%Values)) {
14758:         $ValuesHash{$id.'.'.$key} = $value;
14759:     }
14760:     #
14761:     &Apache::lonnet::appenv(\%ValuesHash);
14762:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14763: }
14764: 
14765: ############################################################
14766: ############################################################
14767: 
14768: =pod
14769: 
14770: =item * &DrawXYYGraph()
14771: 
14772: Facilitates the plotting of data in an XY graph with two Y axes.
14773: Puts plot definition data into the users environment in order for 
14774: graph.png to plot it.  Returns an <img> tag for the plot.
14775: 
14776: Inputs:
14777: 
14778: =over 4
14779: 
14780: =item $Title: string, the title of the plot
14781: 
14782: =item $xlabel: string, text describing the X-axis of the plot
14783: 
14784: =item $ylabel: string, text describing the Y-axis of the plot
14785: 
14786: =item $colors: Array ref containing the hex color codes for the data to be 
14787: plotted in.  If undefined, default values will be used.
14788: 
14789: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
14790: 
14791: =item $Ydata1: The first data set
14792: 
14793: =item $Min1: The minimum value of the left Y-axis
14794: 
14795: =item $Max1: The maximum value of the left Y-axis
14796: 
14797: =item $Ydata2: The second data set
14798: 
14799: =item $Min2: The minimum value of the right Y-axis
14800: 
14801: =item $Max2: The maximum value of the left Y-axis
14802: 
14803: =item %Values: hash indicating or overriding any default values which are 
14804: passed to graph.png.  
14805: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
14806: 
14807: =back
14808: 
14809: Returns:
14810: 
14811: An <img> tag which references graph.png and the appropriate identifying
14812: information for the plot.
14813: 
14814: =cut
14815: 
14816: ############################################################
14817: ############################################################
14818: sub DrawXYYGraph {
14819:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
14820:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
14821:     #
14822:     # Create the identifier for the graph
14823:     my $identifier = &get_cgi_id();
14824:     my $id = 'cgi.'.$identifier;
14825:     #
14826:     $Title  = '' if (! defined($Title));
14827:     $xlabel = '' if (! defined($xlabel));
14828:     $ylabel = '' if (! defined($ylabel));
14829:     my %ValuesHash = 
14830:         (
14831:          $id.'.title'  => &escape($Title),
14832:          $id.'.xlabel' => &escape($xlabel),
14833:          $id.'.ylabel' => &escape($ylabel),
14834:          $id.'.labels' => join(',',@$Xlabels),
14835:          $id.'.PlotType' => 'XY',
14836:          $id.'.NumSets' => 2,
14837:          $id.'.two_axes' => 1,
14838:          $id.'.y1_max_value' => $Max1,
14839:          $id.'.y1_min_value' => $Min1,
14840:          $id.'.y2_max_value' => $Max2,
14841:          $id.'.y2_min_value' => $Min2,
14842:          );
14843:     #
14844:     if (defined($colors) && ref($colors) eq 'ARRAY') {
14845:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14846:     }
14847:     #
14848:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
14849:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
14850:         return '';
14851:     }
14852:     my $NumSets=1;
14853:     foreach my $array ($Ydata1,$Ydata2){
14854:         next if (! ref($array));
14855:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
14856:     }
14857:     #
14858:     # Deal with other parameters
14859:     while (my ($key,$value) = each(%Values)) {
14860:         $ValuesHash{$id.'.'.$key} = $value;
14861:     }
14862:     #
14863:     &Apache::lonnet::appenv(\%ValuesHash);
14864:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14865: }
14866: 
14867: ############################################################
14868: ############################################################
14869: 
14870: =pod
14871: 
14872: =back 
14873: 
14874: =head1 Statistics helper routines?  
14875: 
14876: Bad place for them but what the hell.
14877: 
14878: =over 4
14879: 
14880: =item * &chartlink()
14881: 
14882: Returns a link to the chart for a specific student.  
14883: 
14884: Inputs:
14885: 
14886: =over 4
14887: 
14888: =item $linktext: The text of the link
14889: 
14890: =item $sname: The students username
14891: 
14892: =item $sdomain: The students domain
14893: 
14894: =back
14895: 
14896: =back
14897: 
14898: =cut
14899: 
14900: ############################################################
14901: ############################################################
14902: sub chartlink {
14903:     my ($linktext, $sname, $sdomain) = @_;
14904:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
14905:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
14906:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
14907:        '">'.$linktext.'</a>';
14908: }
14909: 
14910: #######################################################
14911: #######################################################
14912: 
14913: =pod
14914: 
14915: =head1 Course Environment Routines
14916: 
14917: =over 4
14918: 
14919: =item * &restore_course_settings()
14920: 
14921: =item * &store_course_settings()
14922: 
14923: Restores/Store indicated form parameters from the course environment.
14924: Will not overwrite existing values of the form parameters.
14925: 
14926: Inputs: 
14927: a scalar describing the data (e.g. 'chart', 'problem_analysis')
14928: 
14929: a hash ref describing the data to be stored.  For example:
14930:    
14931: %Save_Parameters = ('Status' => 'scalar',
14932:     'chartoutputmode' => 'scalar',
14933:     'chartoutputdata' => 'scalar',
14934:     'Section' => 'array',
14935:     'Group' => 'array',
14936:     'StudentData' => 'array',
14937:     'Maps' => 'array');
14938: 
14939: Returns: both routines return nothing
14940: 
14941: =back
14942: 
14943: =cut
14944: 
14945: #######################################################
14946: #######################################################
14947: sub store_course_settings {
14948:     return &store_settings($env{'request.course.id'},@_);
14949: }
14950: 
14951: sub store_settings {
14952:     # save to the environment
14953:     # appenv the same items, just to be safe
14954:     my $udom  = $env{'user.domain'};
14955:     my $uname = $env{'user.name'};
14956:     my ($context,$prefix,$Settings) = @_;
14957:     my %SaveHash;
14958:     my %AppHash;
14959:     while (my ($setting,$type) = each(%$Settings)) {
14960:         my $basename = join('.','internal',$context,$prefix,$setting);
14961:         my $envname = 'environment.'.$basename;
14962:         if (exists($env{'form.'.$setting})) {
14963:             # Save this value away
14964:             if ($type eq 'scalar' &&
14965:                 (! exists($env{$envname}) || 
14966:                  $env{$envname} ne $env{'form.'.$setting})) {
14967:                 $SaveHash{$basename} = $env{'form.'.$setting};
14968:                 $AppHash{$envname}   = $env{'form.'.$setting};
14969:             } elsif ($type eq 'array') {
14970:                 my $stored_form;
14971:                 if (ref($env{'form.'.$setting})) {
14972:                     $stored_form = join(',',
14973:                                         map {
14974:                                             &escape($_);
14975:                                         } sort(@{$env{'form.'.$setting}}));
14976:                 } else {
14977:                     $stored_form = 
14978:                         &escape($env{'form.'.$setting});
14979:                 }
14980:                 # Determine if the array contents are the same.
14981:                 if ($stored_form ne $env{$envname}) {
14982:                     $SaveHash{$basename} = $stored_form;
14983:                     $AppHash{$envname}   = $stored_form;
14984:                 }
14985:             }
14986:         }
14987:     }
14988:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
14989:                                           $udom,$uname);
14990:     if ($put_result !~ /^(ok|delayed)/) {
14991:         &Apache::lonnet::logthis('unable to save form parameters, '.
14992:                                  'got error:'.$put_result);
14993:     }
14994:     # Make sure these settings stick around in this session, too
14995:     &Apache::lonnet::appenv(\%AppHash);
14996:     return;
14997: }
14998: 
14999: sub restore_course_settings {
15000:     return &restore_settings($env{'request.course.id'},@_);
15001: }
15002: 
15003: sub restore_settings {
15004:     my ($context,$prefix,$Settings) = @_;
15005:     while (my ($setting,$type) = each(%$Settings)) {
15006:         next if (exists($env{'form.'.$setting}));
15007:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
15008:             '.'.$setting;
15009:         if (exists($env{$envname})) {
15010:             if ($type eq 'scalar') {
15011:                 $env{'form.'.$setting} = $env{$envname};
15012:             } elsif ($type eq 'array') {
15013:                 $env{'form.'.$setting} = [ 
15014:                                            map { 
15015:                                                &unescape($_); 
15016:                                            } split(',',$env{$envname})
15017:                                            ];
15018:             }
15019:         }
15020:     }
15021: }
15022: 
15023: #######################################################
15024: #######################################################
15025: 
15026: =pod
15027: 
15028: =head1 Domain E-mail Routines  
15029: 
15030: =over 4
15031: 
15032: =item * &build_recipient_list()
15033: 
15034: Build recipient lists for following types of e-mail:
15035: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
15036: (d) Help requests, (e) Course requests needing approval, (f) loncapa
15037: module change checking, student/employee ID conflict checks, as
15038: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
15039: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
15040: 
15041: Inputs:
15042: defmail (scalar - email address of default recipient),
15043: mailing type (scalar: errormail, packagesmail, helpdeskmail,
15044: requestsmail, updatesmail, or idconflictsmail).
15045: 
15046: defdom (domain for which to retrieve configuration settings),
15047: 
15048: origmail (scalar - email address of recipient from loncapa.conf,
15049: i.e., predates configuration by DC via domainprefs.pm
15050: 
15051: $requname username of requester (if mailing type is helpdeskmail)
15052: 
15053: $requdom domain of requester (if mailing type is helpdeskmail)
15054: 
15055: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
15056: 
15057: Returns: comma separated list of addresses to which to send e-mail.
15058: 
15059: =back
15060: 
15061: =cut
15062: 
15063: ############################################################
15064: ############################################################
15065: sub build_recipient_list {
15066:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
15067:     my @recipients;
15068:     my ($otheremails,$lastresort,$allbcc,$addtext);
15069:     my %domconfig =
15070:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
15071:     if (ref($domconfig{'contacts'}) eq 'HASH') {
15072:         if (exists($domconfig{'contacts'}{$mailing})) {
15073:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
15074:                 my @contacts = ('adminemail','supportemail');
15075:                 foreach my $item (@contacts) {
15076:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
15077:                         my $addr = $domconfig{'contacts'}{$item}; 
15078:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
15079:                             push(@recipients,$addr);
15080:                         }
15081:                     }
15082:                 }
15083:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
15084:                 if ($mailing eq 'helpdeskmail') {
15085:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
15086:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
15087:                         my @ok_bccs;
15088:                         foreach my $bcc (@bccs) {
15089:                             $bcc =~ s/^\s+//g;
15090:                             $bcc =~ s/\s+$//g;
15091:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15092:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15093:                                     push(@ok_bccs,$bcc);
15094:                                 }
15095:                             }
15096:                         }
15097:                         if (@ok_bccs > 0) {
15098:                             $allbcc = join(', ',@ok_bccs);
15099:                         }
15100:                     }
15101:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
15102:                 }
15103:             }
15104:         } elsif ($origmail ne '') {
15105:             $lastresort = $origmail;
15106:         }
15107:         if ($mailing eq 'helpdeskmail') {
15108:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
15109:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
15110:                 my ($inststatus,$inststatus_checked);
15111:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
15112:                     ($env{'user.domain'} ne 'public')) {
15113:                     $inststatus_checked = 1;
15114:                     $inststatus = $env{'environment.inststatus'};
15115:                 }
15116:                 unless ($inststatus_checked) {
15117:                     if (($requname ne '') && ($requdom ne '')) {
15118:                         if (($requname =~ /^$match_username$/) &&
15119:                             ($requdom =~ /^$match_domain$/) &&
15120:                             (&Apache::lonnet::domain($requdom))) {
15121:                             my $requhome = &Apache::lonnet::homeserver($requname,
15122:                                                                       $requdom);
15123:                             unless ($requhome eq 'no_host') {
15124:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
15125:                                 $inststatus = $userenv{'inststatus'};
15126:                                 $inststatus_checked = 1;
15127:                             }
15128:                         }
15129:                     }
15130:                 }
15131:                 unless ($inststatus_checked) {
15132:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
15133:                         my %srch = (srchby     => 'email',
15134:                                     srchdomain => $defdom,
15135:                                     srchterm   => $reqemail,
15136:                                     srchtype   => 'exact');
15137:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
15138:                         foreach my $uname (keys(%srch_results)) {
15139:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
15140:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
15141:                                 $inststatus_checked = 1;
15142:                                 last;
15143:                             }
15144:                         }
15145:                         unless ($inststatus_checked) {
15146:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
15147:                             if ($dirsrchres eq 'ok') {
15148:                                 foreach my $uname (keys(%srch_results)) {
15149:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
15150:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
15151:                                         $inststatus_checked = 1;
15152:                                         last;
15153:                                     }
15154:                                 }
15155:                             }
15156:                         }
15157:                     }
15158:                 }
15159:                 if ($inststatus ne '') {
15160:                     foreach my $status (split(/\:/,$inststatus)) {
15161:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
15162:                             my @contacts = ('adminemail','supportemail');
15163:                             foreach my $item (@contacts) {
15164:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
15165:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
15166:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
15167:                                         push(@recipients,$addr);
15168:                                     }
15169:                                 }
15170:                             }
15171:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
15172:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
15173:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
15174:                                 my @ok_bccs;
15175:                                 foreach my $bcc (@bccs) {
15176:                                     $bcc =~ s/^\s+//g;
15177:                                     $bcc =~ s/\s+$//g;
15178:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15179:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15180:                                             push(@ok_bccs,$bcc);
15181:                                         }
15182:                                     }
15183:                                 }
15184:                                 if (@ok_bccs > 0) {
15185:                                     $allbcc = join(', ',@ok_bccs);
15186:                                 }
15187:                             }
15188:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
15189:                             last;
15190:                         }
15191:                     }
15192:                 }
15193:             }
15194:         }
15195:     } elsif ($origmail ne '') {
15196:         $lastresort = $origmail;
15197:     }
15198:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
15199:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
15200:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
15201:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
15202:             my %what = (
15203:                           perlvar => 1,
15204:                        );
15205:             my $primary = &Apache::lonnet::domain($defdom,'primary');
15206:             if ($primary) {
15207:                 my $gotaddr;
15208:                 my ($result,$returnhash) =
15209:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
15210:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
15211:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
15212:                         $lastresort = $returnhash->{'lonSupportEMail'};
15213:                         $gotaddr = 1;
15214:                     }
15215:                 }
15216:                 unless ($gotaddr) {
15217:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
15218:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
15219:                     unless ($uintdom eq $intdom) {
15220:                         my %domconfig =
15221:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
15222:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
15223:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
15224:                                 my @contacts = ('adminemail','supportemail');
15225:                                 foreach my $item (@contacts) {
15226:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
15227:                                         my $addr = $domconfig{'contacts'}{$item};
15228:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
15229:                                             push(@recipients,$addr);
15230:                                         }
15231:                                     }
15232:                                 }
15233:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
15234:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
15235:                                 }
15236:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
15237:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
15238:                                     my @ok_bccs;
15239:                                     foreach my $bcc (@bccs) {
15240:                                         $bcc =~ s/^\s+//g;
15241:                                         $bcc =~ s/\s+$//g;
15242:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15243:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15244:                                                 push(@ok_bccs,$bcc);
15245:                                             }
15246:                                         }
15247:                                     }
15248:                                     if (@ok_bccs > 0) {
15249:                                         $allbcc = join(', ',@ok_bccs);
15250:                                     }
15251:                                 }
15252:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
15253:                             }
15254:                         }
15255:                     }
15256:                 }
15257:             }
15258:         }
15259:     }
15260:     if (defined($defmail)) {
15261:         if ($defmail ne '') {
15262:             push(@recipients,$defmail);
15263:         }
15264:     }
15265:     if ($otheremails) {
15266:         my @others;
15267:         if ($otheremails =~ /,/) {
15268:             @others = split(/,/,$otheremails);
15269:         } else {
15270:             push(@others,$otheremails);
15271:         }
15272:         foreach my $addr (@others) {
15273:             if (!grep(/^\Q$addr\E$/,@recipients)) {
15274:                 push(@recipients,$addr);
15275:             }
15276:         }
15277:     }
15278:     if ($mailing eq 'helpdeskmail') {
15279:         if ((!@recipients) && ($lastresort ne '')) {
15280:             push(@recipients,$lastresort);
15281:         }
15282:     } elsif ($lastresort ne '') {
15283:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
15284:             push(@recipients,$lastresort);
15285:         }
15286:     }
15287:     my $recipientlist = join(',',@recipients);
15288:     if (wantarray) {
15289:         return ($recipientlist,$allbcc,$addtext);
15290:     } else {
15291:         return $recipientlist;
15292:     }
15293: }
15294: 
15295: ############################################################
15296: ############################################################
15297: 
15298: =pod
15299: 
15300: =head1 Course Catalog Routines
15301: 
15302: =over 4
15303: 
15304: =item * &gather_categories()
15305: 
15306: Converts category definitions - keys of categories hash stored in  
15307: coursecategories in configuration.db on the primary library server in a 
15308: domain - to an array.  Also generates javascript and idx hash used to 
15309: generate Domain Coordinator interface for editing Course Categories.
15310: 
15311: Inputs:
15312: 
15313: categories (reference to hash of category definitions).
15314: 
15315: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15316:       categories and subcategories).
15317: 
15318: idx (reference to hash of counters used in Domain Coordinator interface for 
15319:       editing Course Categories).
15320: 
15321: jsarray (reference to array of categories used to create Javascript arrays for
15322:          Domain Coordinator interface for editing Course Categories).
15323: 
15324: Returns: nothing
15325: 
15326: Side effects: populates cats, idx and jsarray. 
15327: 
15328: =cut
15329: 
15330: sub gather_categories {
15331:     my ($categories,$cats,$idx,$jsarray) = @_;
15332:     my %counters;
15333:     my $num = 0;
15334:     foreach my $item (keys(%{$categories})) {
15335:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
15336:         if ($container eq '' && $depth == 0) {
15337:             $cats->[$depth][$categories->{$item}] = $cat;
15338:         } else {
15339:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
15340:         }
15341:         my ($escitem,$tail) = split(/:/,$item,2);
15342:         if ($counters{$tail} eq '') {
15343:             $counters{$tail} = $num;
15344:             $num ++;
15345:         }
15346:         if (ref($idx) eq 'HASH') {
15347:             $idx->{$item} = $counters{$tail};
15348:         }
15349:         if (ref($jsarray) eq 'ARRAY') {
15350:             push(@{$jsarray->[$counters{$tail}]},$item);
15351:         }
15352:     }
15353:     return;
15354: }
15355: 
15356: =pod
15357: 
15358: =item * &extract_categories()
15359: 
15360: Used to generate breadcrumb trails for course categories.
15361: 
15362: Inputs:
15363: 
15364: categories (reference to hash of category definitions).
15365: 
15366: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15367:       categories and subcategories).
15368: 
15369: trails (reference to array of breacrumb trails for each category).
15370: 
15371: allitems (reference to hash - key is category key 
15372:          (format: escaped(name):escaped(parent category):depth in hierarchy).
15373: 
15374: idx (reference to hash of counters used in Domain Coordinator interface for
15375:       editing Course Categories).
15376: 
15377: jsarray (reference to array of categories used to create Javascript arrays for
15378:          Domain Coordinator interface for editing Course Categories).
15379: 
15380: subcats (reference to hash of arrays containing all subcategories within each 
15381:          category, -recursive)
15382: 
15383: maxd (reference to hash used to hold max depth for all top-level categories).
15384: 
15385: Returns: nothing
15386: 
15387: Side effects: populates trails and allitems hash references.
15388: 
15389: =cut
15390: 
15391: sub extract_categories {
15392:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
15393:     if (ref($categories) eq 'HASH') {
15394:         &gather_categories($categories,$cats,$idx,$jsarray);
15395:         if (ref($cats->[0]) eq 'ARRAY') {
15396:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
15397:                 my $name = $cats->[0][$i];
15398:                 my $item = &escape($name).'::0';
15399:                 my $trailstr;
15400:                 if ($name eq 'instcode') {
15401:                     $trailstr = &mt('Official courses (with institutional codes)');
15402:                 } elsif ($name eq 'communities') {
15403:                     $trailstr = &mt('Communities');
15404:                 } else {
15405:                     $trailstr = $name;
15406:                 }
15407:                 if ($allitems->{$item} eq '') {
15408:                     push(@{$trails},$trailstr);
15409:                     $allitems->{$item} = scalar(@{$trails})-1;
15410:                 }
15411:                 my @parents = ($name);
15412:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
15413:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
15414:                         my $category = $cats->[1]{$name}[$j];
15415:                         if (ref($subcats) eq 'HASH') {
15416:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
15417:                         }
15418:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
15419:                     }
15420:                 } else {
15421:                     if (ref($subcats) eq 'HASH') {
15422:                         $subcats->{$item} = [];
15423:                     }
15424:                     if (ref($maxd) eq 'HASH') {
15425:                         $maxd->{$name} = 1;
15426:                     }
15427:                 }
15428:             }
15429:         }
15430:     }
15431:     return;
15432: }
15433: 
15434: =pod
15435: 
15436: =item * &recurse_categories()
15437: 
15438: Recursively used to generate breadcrumb trails for course categories.
15439: 
15440: Inputs:
15441: 
15442: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15443:       categories and subcategories).
15444: 
15445: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
15446: 
15447: category (current course category, for which breadcrumb trail is being generated).
15448: 
15449: trails (reference to array of breadcrumb trails for each category).
15450: 
15451: allitems (reference to hash - key is category key
15452:          (format: escaped(name):escaped(parent category):depth in hierarchy).
15453: 
15454: parents (array containing containers directories for current category, 
15455:          back to top level). 
15456: 
15457: Returns: nothing
15458: 
15459: Side effects: populates trails and allitems hash references
15460: 
15461: =cut
15462: 
15463: sub recurse_categories {
15464:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
15465:     my $shallower = $depth - 1;
15466:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
15467:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
15468:             my $name = $cats->[$depth]{$category}[$k];
15469:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
15470:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
15471:             if ($allitems->{$item} eq '') {
15472:                 push(@{$trails},$trailstr);
15473:                 $allitems->{$item} = scalar(@{$trails})-1;
15474:             }
15475:             my $deeper = $depth+1;
15476:             push(@{$parents},$category);
15477:             if (ref($subcats) eq 'HASH') {
15478:                 my $subcat = &escape($name).':'.$category.':'.$depth;
15479:                 for (my $j=@{$parents}; $j>=0; $j--) {
15480:                     my $higher;
15481:                     if ($j > 0) {
15482:                         $higher = &escape($parents->[$j]).':'.
15483:                                   &escape($parents->[$j-1]).':'.$j;
15484:                     } else {
15485:                         $higher = &escape($parents->[$j]).'::'.$j;
15486:                     }
15487:                     push(@{$subcats->{$higher}},$subcat);
15488:                 }
15489:             }
15490:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
15491:                                 $subcats,$maxd);
15492:             pop(@{$parents});
15493:         }
15494:     } else {
15495:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
15496:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
15497:         if ($allitems->{$item} eq '') {
15498:             push(@{$trails},$trailstr);
15499:             $allitems->{$item} = scalar(@{$trails})-1;
15500:         }
15501:         if (ref($maxd) eq 'HASH') {
15502:             if ($depth > $maxd->{$parents->[0]}) {
15503:                 $maxd->{$parents->[0]} = $depth;
15504:             }
15505:         }
15506:     }
15507:     return;
15508: }
15509: 
15510: =pod
15511: 
15512: =item * &assign_categories_table()
15513: 
15514: Create a datatable for display of hierarchical categories in a domain,
15515: with checkboxes to allow a course to be categorized. 
15516: 
15517: Inputs:
15518: 
15519: cathash - reference to hash of categories defined for the domain (from
15520:           configuration.db)
15521: 
15522: currcat - scalar with an & separated list of categories assigned to a course. 
15523: 
15524: type    - scalar contains course type (Course or Community).
15525: 
15526: disabled - scalar (optional) contains disabled="disabled" if input elements are
15527:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
15528: 
15529: Returns: $output (markup to be displayed) 
15530: 
15531: =cut
15532: 
15533: sub assign_categories_table {
15534:     my ($cathash,$currcat,$type,$disabled) = @_;
15535:     my $output;
15536:     if (ref($cathash) eq 'HASH') {
15537:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
15538:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
15539:         $maxdepth = scalar(@cats);
15540:         if (@cats > 0) {
15541:             my $itemcount = 0;
15542:             if (ref($cats[0]) eq 'ARRAY') {
15543:                 my @currcategories;
15544:                 if ($currcat ne '') {
15545:                     @currcategories = split('&',$currcat);
15546:                 }
15547:                 my $table;
15548:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
15549:                     my $parent = $cats[0][$i];
15550:                     next if ($parent eq 'instcode');
15551:                     if ($type eq 'Community') {
15552:                         next unless ($parent eq 'communities');
15553:                     } else {
15554:                         next if ($parent eq 'communities');
15555:                     }
15556:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
15557:                     my $item = &escape($parent).'::0';
15558:                     my $checked = '';
15559:                     if (@currcategories > 0) {
15560:                         if (grep(/^\Q$item\E$/,@currcategories)) {
15561:                             $checked = ' checked="checked"';
15562:                         }
15563:                     }
15564:                     my $parent_title = $parent;
15565:                     if ($parent eq 'communities') {
15566:                         $parent_title = &mt('Communities');
15567:                     }
15568:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
15569:                               '<input type="checkbox" name="usecategory" value="'.
15570:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
15571:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
15572:                     my $depth = 1;
15573:                     push(@path,$parent);
15574:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
15575:                     pop(@path);
15576:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
15577:                     $itemcount ++;
15578:                 }
15579:                 if ($itemcount) {
15580:                     $output = &Apache::loncommon::start_data_table().
15581:                               $table.
15582:                               &Apache::loncommon::end_data_table();
15583:                 }
15584:             }
15585:         }
15586:     }
15587:     return $output;
15588: }
15589: 
15590: =pod
15591: 
15592: =item * &assign_category_rows()
15593: 
15594: Create a datatable row for display of nested categories in a domain,
15595: with checkboxes to allow a course to be categorized,called recursively.
15596: 
15597: Inputs:
15598: 
15599: itemcount - track row number for alternating colors
15600: 
15601: cats - reference to array of arrays/hashes which encapsulates hierarchy of
15602:       categories and subcategories.
15603: 
15604: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
15605: 
15606: parent - parent of current category item
15607: 
15608: path - Array containing all categories back up through the hierarchy from the
15609:        current category to the top level.
15610: 
15611: currcategories - reference to array of current categories assigned to the course
15612: 
15613: disabled - scalar (optional) contains disabled="disabled" if input elements are
15614:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
15615: 
15616: Returns: $output (markup to be displayed).
15617: 
15618: =cut
15619: 
15620: sub assign_category_rows {
15621:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
15622:     my ($text,$name,$item,$chgstr);
15623:     if (ref($cats) eq 'ARRAY') {
15624:         my $maxdepth = scalar(@{$cats});
15625:         if (ref($cats->[$depth]) eq 'HASH') {
15626:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
15627:                 my $numchildren = @{$cats->[$depth]{$parent}};
15628:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
15629:                 $text .= '<td><table class="LC_data_table">';
15630:                 for (my $j=0; $j<$numchildren; $j++) {
15631:                     $name = $cats->[$depth]{$parent}[$j];
15632:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
15633:                     my $deeper = $depth+1;
15634:                     my $checked = '';
15635:                     if (ref($currcategories) eq 'ARRAY') {
15636:                         if (@{$currcategories} > 0) {
15637:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
15638:                                 $checked = ' checked="checked"';
15639:                             }
15640:                         }
15641:                     }
15642:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
15643:                              '<input type="checkbox" name="usecategory" value="'.
15644:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
15645:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
15646:                              '</td><td>';
15647:                     if (ref($path) eq 'ARRAY') {
15648:                         push(@{$path},$name);
15649:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
15650:                         pop(@{$path});
15651:                     }
15652:                     $text .= '</td></tr>';
15653:                 }
15654:                 $text .= '</table></td>';
15655:             }
15656:         }
15657:     }
15658:     return $text;
15659: }
15660: 
15661: =pod
15662: 
15663: =back
15664: 
15665: =cut
15666: 
15667: ############################################################
15668: ############################################################
15669: 
15670: 
15671: sub commit_customrole {
15672:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
15673:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
15674:                          ($start?', '.&mt('starting').' '.localtime($start):'').
15675:                          ($end?', ending '.localtime($end):'').': <b>'.
15676:               &Apache::lonnet::assigncustomrole(
15677:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
15678:                  '</b><br />';
15679:     return $output;
15680: }
15681: 
15682: sub commit_standardrole {
15683:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
15684:     my ($output,$logmsg,$linefeed);
15685:     if ($context eq 'auto') {
15686:         $linefeed = "\n";
15687:     } else {
15688:         $linefeed = "<br />\n";
15689:     }  
15690:     if ($three eq 'st') {
15691:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
15692:                                          $one,$two,$sec,$context,$credits);
15693:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
15694:             ($result eq 'unknown_course') || ($result eq 'refused')) {
15695:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
15696:         } else {
15697:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
15698:                ($start?', '.&mt('starting').' '.localtime($start):'').
15699:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
15700:             if ($context eq 'auto') {
15701:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
15702:             } else {
15703:                $output .= '<b>'.$result.'</b>'.$linefeed.
15704:                &mt('Add to classlist').': <b>ok</b>';
15705:             }
15706:             $output .= $linefeed;
15707:         }
15708:     } else {
15709:         $output = &mt('Assigning').' '.$three.' in '.$url.
15710:                ($start?', '.&mt('starting').' '.localtime($start):'').
15711:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
15712:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
15713:         if ($context eq 'auto') {
15714:             $output .= $result.$linefeed;
15715:         } else {
15716:             $output .= '<b>'.$result.'</b>'.$linefeed;
15717:         }
15718:     }
15719:     return $output;
15720: }
15721: 
15722: sub commit_studentrole {
15723:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
15724:         $credits) = @_;
15725:     my ($result,$linefeed,$oldsecurl,$newsecurl);
15726:     if ($context eq 'auto') {
15727:         $linefeed = "\n";
15728:     } else {
15729:         $linefeed = '<br />'."\n";
15730:     }
15731:     if (defined($one) && defined($two)) {
15732:         my $cid=$one.'_'.$two;
15733:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
15734:         my $secchange = 0;
15735:         my $expire_role_result;
15736:         my $modify_section_result;
15737:         if ($oldsec ne '-1') { 
15738:             if ($oldsec ne $sec) {
15739:                 $secchange = 1;
15740:                 my $now = time;
15741:                 my $uurl='/'.$cid;
15742:                 $uurl=~s/\_/\//g;
15743:                 if ($oldsec) {
15744:                     $uurl.='/'.$oldsec;
15745:                 }
15746:                 $oldsecurl = $uurl;
15747:                 $expire_role_result = 
15748:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
15749:                 if ($env{'request.course.sec'} ne '') { 
15750:                     if ($expire_role_result eq 'refused') {
15751:                         my @roles = ('st');
15752:                         my @statuses = ('previous');
15753:                         my @roledoms = ($one);
15754:                         my $withsec = 1;
15755:                         my %roleshash = 
15756:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
15757:                                               \@statuses,\@roles,\@roledoms,$withsec);
15758:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
15759:                             my ($oldstart,$oldend) = 
15760:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
15761:                             if ($oldend > 0 && $oldend <= $now) {
15762:                                 $expire_role_result = 'ok';
15763:                             }
15764:                         }
15765:                     }
15766:                 }
15767:                 $result = $expire_role_result;
15768:             }
15769:         }
15770:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
15771:             $modify_section_result = 
15772:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
15773:                                                            undef,undef,undef,$sec,
15774:                                                            $end,$start,'','',$cid,
15775:                                                            '',$context,$credits);
15776:             if ($modify_section_result =~ /^ok/) {
15777:                 if ($secchange == 1) {
15778:                     if ($sec eq '') {
15779:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
15780:                     } else {
15781:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
15782:                     }
15783:                 } elsif ($oldsec eq '-1') {
15784:                     if ($sec eq '') {
15785:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
15786:                     } else {
15787:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
15788:                     }
15789:                 } else {
15790:                     if ($sec eq '') {
15791:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
15792:                     } else {
15793:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
15794:                     }
15795:                 }
15796:             } else {
15797:                 if ($secchange) {       
15798:                     $$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;
15799:                 } else {
15800:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
15801:                 }
15802:             }
15803:             $result = $modify_section_result;
15804:         } elsif ($secchange == 1) {
15805:             if ($oldsec eq '') {
15806:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
15807:             } else {
15808:                 $$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;
15809:             }
15810:             if ($expire_role_result eq 'refused') {
15811:                 my $newsecurl = '/'.$cid;
15812:                 $newsecurl =~ s/\_/\//g;
15813:                 if ($sec ne '') {
15814:                     $newsecurl.='/'.$sec;
15815:                 }
15816:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
15817:                     if ($sec eq '') {
15818:                         $$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;
15819:                     } else {
15820:                         $$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;
15821:                     }
15822:                 }
15823:             }
15824:         }
15825:     } else {
15826:         $$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;
15827:         $result = "error: incomplete course id\n";
15828:     }
15829:     return $result;
15830: }
15831: 
15832: sub show_role_extent {
15833:     my ($scope,$context,$role) = @_;
15834:     $scope =~ s{^/}{};
15835:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
15836:     push(@courseroles,'co');
15837:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
15838:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
15839:         $scope =~ s{/}{_};
15840:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
15841:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
15842:         my ($audom,$auname) = split(/\//,$scope);
15843:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
15844:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
15845:     } else {
15846:         $scope =~ s{/$}{};
15847:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
15848:                    &Apache::lonnet::domain($scope,'description').'</span>');
15849:     }
15850: }
15851: 
15852: ############################################################
15853: ############################################################
15854: 
15855: sub check_clone {
15856:     my ($args,$linefeed) = @_;
15857:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
15858:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
15859:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
15860:     my $clonetitle;
15861:     my @clonemsg;
15862:     my $can_clone = 0;
15863:     my $lctype = lc($args->{'crstype'});
15864:     if ($lctype ne 'community') {
15865:         $lctype = 'course';
15866:     }
15867:     if ($clonehome eq 'no_host') {
15868:         if ($args->{'crstype'} eq 'Community') {
15869:             push(@clonemsg,({
15870:                               mt => 'No new community created.',
15871:                               args => [],
15872:                             },
15873:                             {
15874:                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
15875:                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
15876:                             }));
15877:         } else {
15878:             push(@clonemsg,({
15879:                               mt => 'No new course created.',
15880:                               args => [],
15881:                             },
15882:                             {
15883:                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
15884:                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
15885:                             }));
15886:         }
15887:     } else {
15888: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
15889:         $clonetitle = $clonedesc{'description'};
15890:         if ($args->{'crstype'} eq 'Community') {
15891:             if ($clonedesc{'type'} ne 'Community') {
15892:                 push(@clonemsg,({
15893:                                   mt => 'No new community created.',
15894:                                   args => [],
15895:                                 },
15896:                                 {
15897:                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
15898:                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
15899:                                 }));
15900:                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
15901:             }
15902:         }
15903: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
15904:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
15905: 	    $can_clone = 1;
15906: 	} else {
15907: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
15908: 						 $args->{'clonedomain'},$args->{'clonecourse'});
15909:             if ($clonehash{'cloners'} eq '') {
15910:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
15911:                 if ($domdefs{'canclone'}) {
15912:                     unless ($domdefs{'canclone'} eq 'none') {
15913:                         if ($domdefs{'canclone'} eq 'domain') {
15914:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
15915:                                 $can_clone = 1;
15916:                             }
15917:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
15918:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
15919:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
15920:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
15921:                                 $can_clone = 1;
15922:                             }
15923:                         }
15924:                     }
15925:                 }
15926:             } else {
15927: 	        my @cloners = split(/,/,$clonehash{'cloners'});
15928:                 if (grep(/^\*$/,@cloners)) {
15929:                     $can_clone = 1;
15930:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
15931:                     $can_clone = 1;
15932:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
15933:                     $can_clone = 1;
15934:                 }
15935:                 unless ($can_clone) {
15936:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
15937:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
15938:                         my (%gotdomdefaults,%gotcodedefaults);
15939:                         foreach my $cloner (@cloners) {
15940:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
15941:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
15942:                                 my (%codedefaults,@code_order);
15943:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
15944:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
15945:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
15946:                                     }
15947:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
15948:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
15949:                                     }
15950:                                 } else {
15951:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
15952:                                                                             \%codedefaults,
15953:                                                                             \@code_order);
15954:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
15955:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
15956:                                 }
15957:                                 if (@code_order > 0) {
15958:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
15959:                                                                                 $cloner,$clonehash{'internal.coursecode'},
15960:                                                                                 $args->{'crscode'})) {
15961:                                         $can_clone = 1;
15962:                                         last;
15963:                                     }
15964:                                 }
15965:                             }
15966:                         }
15967:                     }
15968:                 }
15969:             }
15970:             unless ($can_clone) {
15971:                 my $ccrole = 'cc';
15972:                 if ($args->{'crstype'} eq 'Community') {
15973:                     $ccrole = 'co';
15974:                 }
15975:                 my %roleshash =
15976:                     &Apache::lonnet::get_my_roles($args->{'ccuname'},
15977:                                                   $args->{'ccdomain'},
15978:                                                   'userroles',['active'],[$ccrole],
15979:                                                   [$args->{'clonedomain'}]);
15980:                 if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
15981:                     $can_clone = 1;
15982:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
15983:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
15984:                     $can_clone = 1;
15985:                 }
15986:             }
15987:             unless ($can_clone) {
15988:                 if ($args->{'crstype'} eq 'Community') {
15989:                     push(@clonemsg,({
15990:                                       mt => 'No new community created.',
15991:                                       args => [],
15992:                                     },
15993:                                     {
15994:                                       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]).',
15995:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
15996:                                     }));
15997:                 } else {
15998:                     push(@clonemsg,({
15999:                                       mt => 'No new course created.',
16000:                                       args => [],
16001:                                     },
16002:                                     {
16003:                                       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]).',
16004:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
16005:                                     }));
16006: 	        }
16007: 	    }
16008:         }
16009:     }
16010:     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
16011: }
16012: 
16013: sub construct_course {
16014:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
16015:         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
16016:     my ($outcome,$msgref,$clonemsgref);
16017:     my $linefeed =  '<br />'."\n";
16018:     if ($context eq 'auto') {
16019:         $linefeed = "\n";
16020:     }
16021: 
16022: #
16023: # Are we cloning?
16024: #
16025:     my ($can_clone,$cloneid,$clonehome,$clonetitle);
16026:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
16027: 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
16028:         if (!$can_clone) {
16029: 	    return (0,$outcome,$clonemsgref);
16030: 	}
16031:     }
16032: 
16033: #
16034: # Open course
16035: #
16036:     my $crstype = lc($args->{'crstype'});
16037:     my %cenv=();
16038:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
16039:                                              $args->{'cdescr'},
16040:                                              $args->{'curl'},
16041:                                              $args->{'course_home'},
16042:                                              $args->{'nonstandard'},
16043:                                              $args->{'crscode'},
16044:                                              $args->{'ccuname'}.':'.
16045:                                              $args->{'ccdomain'},
16046:                                              $args->{'crstype'},
16047:                                              $cnum,$context,$category,
16048:                                              $callercontext);
16049: 
16050:     # Note: The testing routines depend on this being output; see 
16051:     # Utils::Course. This needs to at least be output as a comment
16052:     # if anyone ever decides to not show this, and Utils::Course::new
16053:     # will need to be suitably modified.
16054:     if (($callercontext eq 'auto') && ($user_lh ne '')) {
16055:         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
16056:     } else {
16057:         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
16058:     }
16059:     if ($$courseid =~ /^error:/) {
16060:         return (0,$outcome,$clonemsgref);
16061:     }
16062: 
16063: #
16064: # Check if created correctly
16065: #
16066:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
16067:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
16068:     if ($crsuhome eq 'no_host') {
16069:         if (($callercontext eq 'auto') && ($user_lh ne '')) {
16070:             $outcome .= &mt_user($user_lh,
16071:                             'Course creation failed, unrecognized course home server.');
16072:         } else {
16073:             $outcome .= &mt('Course creation failed, unrecognized course home server.');
16074:         }
16075:         $outcome .= $linefeed;
16076:         return (0,$outcome,$clonemsgref);
16077:     }
16078:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
16079: 
16080: #
16081: # Do the cloning
16082: #
16083:     my @clonemsg;
16084:     if ($can_clone && $cloneid) {
16085:         push(@clonemsg,
16086:                       {
16087:                           mt => 'Created [_1] by cloning from [_2]',
16088:                           args => [$crstype,$clonetitle],
16089:                       });
16090: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
16091: # Copy all files
16092:         my @info =
16093:             &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
16094:                                                      $args->{'dateshift'},$args->{'crscode'},
16095:                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
16096:                                                      $args->{'tinyurls'});
16097:         if (@info) {
16098:             push(@clonemsg,@info);
16099:         }
16100: # Restore URL
16101: 	$cenv{'url'}=$oldcenv{'url'};
16102: # Restore title
16103: 	$cenv{'description'}=$oldcenv{'description'};
16104: # Restore creation date, creator and creation context.
16105:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
16106:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
16107:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
16108: # Mark as cloned
16109: 	$cenv{'clonedfrom'}=$cloneid;
16110: # Need to clone grading mode
16111:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
16112:         $cenv{'grading'}=$newenv{'grading'};
16113: # Do not clone these environment entries
16114:         &Apache::lonnet::del('environment',
16115:                   ['default_enrollment_start_date',
16116:                    'default_enrollment_end_date',
16117:                    'question.email',
16118:                    'policy.email',
16119:                    'comment.email',
16120:                    'pch.users.denied',
16121:                    'plc.users.denied',
16122:                    'hidefromcat',
16123:                    'checkforpriv',
16124:                    'categories'],
16125:                    $$crsudom,$$crsunum);
16126:         if ($args->{'textbook'}) {
16127:             $cenv{'internal.textbook'} = $args->{'textbook'};
16128:         }
16129:     }
16130: 
16131: #
16132: # Set environment (will override cloned, if existing)
16133: #
16134:     my @sections = ();
16135:     my @xlists = ();
16136:     if ($args->{'crstype'}) {
16137:         $cenv{'type'}=$args->{'crstype'};
16138:     }
16139:     if ($args->{'crsid'}) {
16140:         $cenv{'courseid'}=$args->{'crsid'};
16141:     }
16142:     if ($args->{'crscode'}) {
16143:         $cenv{'internal.coursecode'}=$args->{'crscode'};
16144:     }
16145:     if ($args->{'crsquota'} ne '') {
16146:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
16147:     } else {
16148:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
16149:     }
16150:     if ($args->{'ccuname'}) {
16151:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
16152:                                         ':'.$args->{'ccdomain'};
16153:     } else {
16154:         $cenv{'internal.courseowner'} = $args->{'curruser'};
16155:     }
16156:     if ($args->{'defaultcredits'}) {
16157:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
16158:     }
16159:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
16160:     if ($args->{'crssections'}) {
16161:         $cenv{'internal.sectionnums'} = '';
16162:         if ($args->{'crssections'} =~ m/,/) {
16163:             @sections = split/,/,$args->{'crssections'};
16164:         } else {
16165:             $sections[0] = $args->{'crssections'};
16166:         }
16167:         if (@sections > 0) {
16168:             foreach my $item (@sections) {
16169:                 my ($sec,$gp) = split/:/,$item;
16170:                 my $class = $args->{'crscode'}.$sec;
16171:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
16172:                 $cenv{'internal.sectionnums'} .= $item.',';
16173:                 unless ($addcheck eq 'ok') {
16174:                     push(@badclasses,$class);
16175:                 }
16176:             }
16177:             $cenv{'internal.sectionnums'} =~ s/,$//;
16178:         }
16179:     }
16180: # do not hide course coordinator from staff listing, 
16181: # even if privileged
16182:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16183: # add course coordinator's domain to domains to check for privileged users
16184: # if different to course domain
16185:     if ($$crsudom ne $args->{'ccdomain'}) {
16186:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
16187:     }
16188: # add crosslistings
16189:     if ($args->{'crsxlist'}) {
16190:         $cenv{'internal.crosslistings'}='';
16191:         if ($args->{'crsxlist'} =~ m/,/) {
16192:             @xlists = split/,/,$args->{'crsxlist'};
16193:         } else {
16194:             $xlists[0] = $args->{'crsxlist'};
16195:         }
16196:         if (@xlists > 0) {
16197:             foreach my $item (@xlists) {
16198:                 my ($xl,$gp) = split/:/,$item;
16199:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
16200:                 $cenv{'internal.crosslistings'} .= $item.',';
16201:                 unless ($addcheck eq 'ok') {
16202:                     push(@badclasses,$xl);
16203:                 }
16204:             }
16205:             $cenv{'internal.crosslistings'} =~ s/,$//;
16206:         }
16207:     }
16208:     if ($args->{'autoadds'}) {
16209:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
16210:     }
16211:     if ($args->{'autodrops'}) {
16212:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
16213:     }
16214: # check for notification of enrollment changes
16215:     my @notified = ();
16216:     if ($args->{'notify_owner'}) {
16217:         if ($args->{'ccuname'} ne '') {
16218:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
16219:         }
16220:     }
16221:     if ($args->{'notify_dc'}) {
16222:         if ($uname ne '') { 
16223:             push(@notified,$uname.':'.$udom);
16224:         }
16225:     }
16226:     if (@notified > 0) {
16227:         my $notifylist;
16228:         if (@notified > 1) {
16229:             $notifylist = join(',',@notified);
16230:         } else {
16231:             $notifylist = $notified[0];
16232:         }
16233:         $cenv{'internal.notifylist'} = $notifylist;
16234:     }
16235:     if (@badclasses > 0) {
16236:         my %lt=&Apache::lonlocal::texthash(
16237:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
16238:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
16239:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
16240:         );
16241:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
16242:                            &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'};
16243:         if ($context eq 'auto') {
16244:             $outcome .= $badclass_msg.$linefeed;
16245:         } else {
16246:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
16247:         }
16248:         foreach my $item (@badclasses) {
16249:             if ($context eq 'auto') {
16250:                 $outcome .= " - $item\n";
16251:             } else {
16252:                 $outcome .= "<li>$item</li>\n";
16253:             }
16254:         }
16255:         if ($context eq 'auto') {
16256:             $outcome .= $linefeed;
16257:         } else {
16258:             $outcome .= "</ul><br /><br /></div>\n";
16259:         }
16260:     }
16261:     if ($args->{'no_end_date'}) {
16262:         $args->{'endaccess'} = 0;
16263:     }
16264:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
16265:     $cenv{'internal.autoend'}=$args->{'enrollend'};
16266:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
16267:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
16268:     if ($args->{'showphotos'}) {
16269:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
16270:     }
16271:     $cenv{'internal.authtype'} = $args->{'authtype'};
16272:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
16273:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
16274:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
16275:             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'); 
16276:             if ($context eq 'auto') {
16277:                 $outcome .= $krb_msg;
16278:             } else {
16279:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
16280:             }
16281:             $outcome .= $linefeed;
16282:         }
16283:     }
16284:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
16285:        if ($args->{'setpolicy'}) {
16286:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16287:        }
16288:        if ($args->{'setcontent'}) {
16289:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16290:        }
16291:        if ($args->{'setcomment'}) {
16292:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16293:        }
16294:     }
16295:     if ($args->{'reshome'}) {
16296: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
16297: 	$cenv{'reshome'}=~s/\/+$/\//;
16298:     }
16299: #
16300: # course has keyed access
16301: #
16302:     if ($args->{'setkeys'}) {
16303:        $cenv{'keyaccess'}='yes';
16304:     }
16305: # if specified, key authority is not course, but user
16306: # only active if keyaccess is yes
16307:     if ($args->{'keyauth'}) {
16308: 	my ($user,$domain) = split(':',$args->{'keyauth'});
16309: 	$user = &LONCAPA::clean_username($user);
16310: 	$domain = &LONCAPA::clean_username($domain);
16311: 	if ($user ne '' && $domain ne '') {
16312: 	    $cenv{'keyauth'}=$user.':'.$domain;
16313: 	}
16314:     }
16315: 
16316: #
16317: #  generate and store uniquecode (available to course requester), if course should have one.
16318: #
16319:     if ($args->{'uniquecode'}) {
16320:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
16321:         if ($code) {
16322:             $cenv{'internal.uniquecode'} = $code;
16323:             my %crsinfo =
16324:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
16325:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
16326:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
16327:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
16328:             }
16329:             if (ref($coderef)) {
16330:                 $$coderef = $code;
16331:             }
16332:         }
16333:     }
16334: 
16335:     if ($args->{'disresdis'}) {
16336:         $cenv{'pch.roles.denied'}='st';
16337:     }
16338:     if ($args->{'disablechat'}) {
16339:         $cenv{'plc.roles.denied'}='st';
16340:     }
16341: 
16342:     # Record we've not yet viewed the Course Initialization Helper for this 
16343:     # course
16344:     $cenv{'course.helper.not.run'} = 1;
16345:     #
16346:     # Use new Randomseed
16347:     #
16348:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
16349:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
16350:     #
16351:     # The encryption code and receipt prefix for this course
16352:     #
16353:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
16354:     $cenv{'internal.encpref'}=100+int(9*rand(99));
16355:     #
16356:     # By default, use standard grading
16357:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
16358: 
16359:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
16360:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
16361: #
16362: # Open all assignments
16363: #
16364:     if ($args->{'openall'}) {
16365:        my $opendate = time;
16366:        if ($args->{'openallfrom'} =~ /^\d+$/) {
16367:            $opendate = $args->{'openallfrom'};
16368:        }
16369:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
16370:        my %storecontent = ($storeunder         => $opendate,
16371:                            $storeunder.'.type' => 'date_start');
16372:        $outcome .= &mt('All assignments open starting [_1]',
16373:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
16374:                    &Apache::lonnet::cput
16375:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
16376:    }
16377: #
16378: # Set first page
16379: #
16380:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
16381: 	    || ($cloneid)) {
16382: 	use LONCAPA::map;
16383: 	$outcome .= &mt('Setting first resource').': ';
16384: 
16385: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
16386:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
16387: 
16388:         $outcome .= ($fatal?$errtext:'read ok').' - ';
16389:         my $title; my $url;
16390:         if ($args->{'firstres'} eq 'syl') {
16391: 	    $title=&mt('Syllabus');
16392:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
16393:         } else {
16394:             $title=&mt('Table of Contents');
16395:             $url='/adm/navmaps';
16396:         }
16397: 
16398:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
16399: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
16400: 
16401: 	if ($errtext) { $fatal=2; }
16402:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
16403:     }
16404: 
16405:     return (1,$outcome,\@clonemsg);
16406: }
16407: 
16408: sub make_unique_code {
16409:     my ($cdom,$cnum) = @_;
16410:     # get lock on uniquecodes db
16411:     my $lockhash = {
16412:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
16413:                                                   ':'.$env{'user.domain'},
16414:                    };
16415:     my $tries = 0;
16416:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
16417:     my ($code,$error);
16418: 
16419:     while (($gotlock ne 'ok') && ($tries<3)) {
16420:         $tries ++;
16421:         sleep 1;
16422:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
16423:     }
16424:     if ($gotlock eq 'ok') {
16425:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
16426:         my $gotcode;
16427:         my $attempts = 0;
16428:         while ((!$gotcode) && ($attempts < 100)) {
16429:             $code = &generate_code();
16430:             if (!exists($currcodes{$code})) {
16431:                 $gotcode = 1;
16432:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
16433:                     $error = 'nostore';
16434:                 }
16435:             }
16436:             $attempts ++;
16437:         }
16438:         my @del_lock = ($cnum."\0".'uniquecodes');
16439:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
16440:     } else {
16441:         $error = 'nolock';
16442:     }
16443:     return ($code,$error);
16444: }
16445: 
16446: sub generate_code {
16447:     my $code;
16448:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
16449:     for (my $i=0; $i<6; $i++) {
16450:         my $lettnum = int (rand 2);
16451:         my $item = '';
16452:         if ($lettnum) {
16453:             $item = $letts[int( rand(18) )];
16454:         } else {
16455:             $item = 1+int( rand(8) );
16456:         }
16457:         $code .= $item;
16458:     }
16459:     return $code;
16460: }
16461: 
16462: ############################################################
16463: ############################################################
16464: 
16465: #SD
16466: # only Community and Course, or anything else?
16467: sub course_type {
16468:     my ($cid) = @_;
16469:     if (!defined($cid)) {
16470:         $cid = $env{'request.course.id'};
16471:     }
16472:     if (defined($env{'course.'.$cid.'.type'})) {
16473:         return $env{'course.'.$cid.'.type'};
16474:     } else {
16475:         return 'Course';
16476:     }
16477: }
16478: 
16479: sub group_term {
16480:     my $crstype = &course_type();
16481:     my %names = (
16482:                   'Course' => 'group',
16483:                   'Community' => 'group',
16484:                 );
16485:     return $names{$crstype};
16486: }
16487: 
16488: sub course_types {
16489:     my @types = ('official','unofficial','community','textbook');
16490:     my %typename = (
16491:                          official   => 'Official course',
16492:                          unofficial => 'Unofficial course',
16493:                          community  => 'Community',
16494:                          textbook   => 'Textbook course',
16495:                    );
16496:     return (\@types,\%typename);
16497: }
16498: 
16499: sub icon {
16500:     my ($file)=@_;
16501:     my $curfext = lc((split(/\./,$file))[-1]);
16502:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
16503:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
16504:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
16505: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
16506: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
16507: 	            $curfext.".gif") {
16508: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
16509: 		$curfext.".gif";
16510: 	}
16511:     }
16512:     return &lonhttpdurl($iconname);
16513: } 
16514: 
16515: sub lonhttpdurl {
16516: #
16517: # Had been used for "small fry" static images on separate port 8080.
16518: # Modify here if lightweight http functionality desired again.
16519: # Currently eliminated due to increasing firewall issues.
16520: #
16521:     my ($url)=@_;
16522:     return $url;
16523: }
16524: 
16525: sub connection_aborted {
16526:     my ($r)=@_;
16527:     $r->print(" ");$r->rflush();
16528:     my $c = $r->connection;
16529:     return $c->aborted();
16530: }
16531: 
16532: #    Escapes strings that may have embedded 's that will be put into
16533: #    strings as 'strings'.
16534: sub escape_single {
16535:     my ($input) = @_;
16536:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
16537:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
16538:     return $input;
16539: }
16540: 
16541: #  Same as escape_single, but escape's "'s  This 
16542: #  can be used for  "strings"
16543: sub escape_double {
16544:     my ($input) = @_;
16545:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
16546:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
16547:     return $input;
16548: }
16549:  
16550: #   Escapes the last element of a full URL.
16551: sub escape_url {
16552:     my ($url)   = @_;
16553:     my @urlslices = split(/\//, $url,-1);
16554:     my $lastitem = &escape(pop(@urlslices));
16555:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
16556: }
16557: 
16558: sub compare_arrays {
16559:     my ($arrayref1,$arrayref2) = @_;
16560:     my (@difference,%count);
16561:     @difference = ();
16562:     %count = ();
16563:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
16564:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
16565:         foreach my $element (keys(%count)) {
16566:             if ($count{$element} == 1) {
16567:                 push(@difference,$element);
16568:             }
16569:         }
16570:     }
16571:     return @difference;
16572: }
16573: 
16574: sub lon_status_items {
16575:     my %defaults = (
16576:                      E         => 100,
16577:                      W         => 4,
16578:                      N         => 1,
16579:                      U         => 5,
16580:                      threshold => 200,
16581:                      sysmail   => 2500,
16582:                    );
16583:     my %names = (
16584:                    E => 'Errors',
16585:                    W => 'Warnings',
16586:                    N => 'Notices',
16587:                    U => 'Unsent',
16588:                 );
16589:     return (\%defaults,\%names);
16590: }
16591: 
16592: # -------------------------------------------------------- Initialize user login
16593: sub init_user_environment {
16594:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
16595:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
16596: 
16597:     my $public=($username eq 'public' && $domain eq 'public');
16598: 
16599: # See if old ID present, if so, remove
16600: 
16601:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
16602:     my $now=time;
16603: 
16604:     if ($public) {
16605: 	my $max_public=100;
16606: 	my $oldest;
16607: 	my $oldest_time=0;
16608: 	for(my $next=1;$next<=$max_public;$next++) {
16609: 	    if (-e $lonids."/publicuser_$next.id") {
16610: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
16611: 		if ($mtime<$oldest_time || !$oldest_time) {
16612: 		    $oldest_time=$mtime;
16613: 		    $oldest=$next;
16614: 		}
16615: 	    } else {
16616: 		$cookie="publicuser_$next";
16617: 		last;
16618: 	    }
16619: 	}
16620: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
16621:     } else {
16622: 	# if this isn't a robot, kill any existing non-robot sessions
16623: 	if (!$args->{'robot'}) {
16624: 	    opendir(DIR,$lonids);
16625: 	    while ($filename=readdir(DIR)) {
16626: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
16627:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
16628:                             &GDBM_READER(),0640)) {
16629:                         my $linkedfile;
16630:                         if (exists($oldenv{'user.linkedenv'})) {
16631:                             $linkedfile = $oldenv{'user.linkedenv'};
16632:                         }
16633:                         untie(%oldenv);
16634:                         if (unlink("$lonids/$filename")) {
16635:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
16636:                                 if (-l "$lonids/$linkedfile.id") {
16637:                                     unlink("$lonids/$linkedfile.id");
16638:                                 }
16639:                             }
16640:                         }
16641:                     } else {
16642:                         unlink($lonids.'/'.$filename);
16643:                     }
16644: 		}
16645: 	    }
16646: 	    closedir(DIR);
16647: # If there is a undeleted lockfile for the user's paste buffer remove it.
16648:             my $namespace = 'nohist_courseeditor';
16649:             my $lockingkey = 'paste'."\0".'locked_num';
16650:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
16651:                                                 $domain,$username);
16652:             if (exists($lockhash{$lockingkey})) {
16653:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
16654:                 unless ($delresult eq 'ok') {
16655:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
16656:                 }
16657:             }
16658: 	}
16659: # Give them a new cookie
16660: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
16661: 		                   : $now.$$.int(rand(10000)));
16662: 	$cookie="$username\_$id\_$domain\_$authhost";
16663:     
16664: # Initialize roles
16665: 
16666: 	($userroles,$firstaccenv,$timerintenv) = 
16667:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
16668:     }
16669: # ------------------------------------ Check browser type and MathML capability
16670: 
16671:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
16672:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
16673: 
16674: # ------------------------------------------------------------- Get environment
16675: 
16676:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
16677:     my ($tmp) = keys(%userenv);
16678:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
16679:     } else {
16680: 	undef(%userenv);
16681:     }
16682:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
16683: 	$form->{'interface'}=$userenv{'interface'};
16684:     }
16685:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
16686: 
16687: # --------------- Do not trust query string to be put directly into environment
16688:     foreach my $option ('interface','localpath','localres') {
16689:         $form->{$option}=~s/[\n\r\=]//gs;
16690:     }
16691: # --------------------------------------------------------- Write first profile
16692: 
16693:     {
16694:         my $ip = &Apache::lonnet::get_requestor_ip();
16695: 	my %initial_env = 
16696: 	    ("user.name"          => $username,
16697: 	     "user.domain"        => $domain,
16698: 	     "user.home"          => $authhost,
16699: 	     "browser.type"       => $clientbrowser,
16700: 	     "browser.version"    => $clientversion,
16701: 	     "browser.mathml"     => $clientmathml,
16702: 	     "browser.unicode"    => $clientunicode,
16703: 	     "browser.os"         => $clientos,
16704:              "browser.mobile"     => $clientmobile,
16705:              "browser.info"       => $clientinfo,
16706:              "browser.osversion"  => $clientosversion,
16707: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
16708: 	     "request.course.fn"  => '',
16709: 	     "request.course.uri" => '',
16710: 	     "request.course.sec" => '',
16711: 	     "request.role"       => 'cm',
16712: 	     "request.role.adv"   => $env{'user.adv'},
16713: 	     "request.host"       => $ip,);
16714: 
16715:         if ($form->{'localpath'}) {
16716: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
16717: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
16718:         }
16719: 	
16720: 	if ($form->{'interface'}) {
16721: 	    $form->{'interface'}=~s/\W//gs;
16722: 	    $initial_env{"browser.interface"} = $form->{'interface'};
16723: 	    $env{'browser.interface'}=$form->{'interface'};
16724: 	}
16725: 
16726:         if ($form->{'iptoken'}) {
16727:             my $lonhost = $r->dir_config('lonHostID');
16728:             $initial_env{"user.noloadbalance"} = $lonhost;
16729:             $env{'user.noloadbalance'} = $lonhost;
16730:         }
16731: 
16732:         if ($form->{'noloadbalance'}) {
16733:             my @hosts = &Apache::lonnet::current_machine_ids();
16734:             my $hosthere = $form->{'noloadbalance'};
16735:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
16736:                 $initial_env{"user.noloadbalance"} = $hosthere;
16737:                 $env{'user.noloadbalance'} = $hosthere;
16738:             }
16739:         }
16740: 
16741:         unless ($domain eq 'public') {
16742:             my %is_adv = ( is_adv => $env{'user.adv'} );
16743:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
16744: 
16745:             foreach my $tool ('aboutme','blog','webdav','portfolio','timezone') {
16746:                 $userenv{'availabletools.'.$tool} = 
16747:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
16748:                                                       undef,\%userenv,\%domdef,\%is_adv);
16749:             }
16750: 
16751:             foreach my $crstype ('official','unofficial','community','textbook') {
16752:                 $userenv{'canrequest.'.$crstype} =
16753:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
16754:                                                       'reload','requestcourses',
16755:                                                       \%userenv,\%domdef,\%is_adv);
16756:             }
16757: 
16758:             $userenv{'canrequest.author'} =
16759:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
16760:                                                   'reload','requestauthor',
16761:                                                   \%userenv,\%domdef,\%is_adv);
16762:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
16763:                                                  $domain,$username);
16764:             my $reqstatus = $reqauthor{'author_status'};
16765:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
16766:                 if (ref($reqauthor{'author'}) eq 'HASH') {
16767:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
16768:                                                       $reqauthor{'author'}{'timestamp'};
16769:                 }
16770:             }
16771:         }
16772: 
16773: 	$env{'user.environment'} = "$lonids/$cookie.id";
16774: 
16775: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
16776: 		 &GDBM_WRCREAT(),0640)) {
16777: 	    &_add_to_env(\%disk_env,\%initial_env);
16778: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
16779: 	    &_add_to_env(\%disk_env,$userroles);
16780:             if (ref($firstaccenv) eq 'HASH') {
16781:                 &_add_to_env(\%disk_env,$firstaccenv);
16782:             }
16783:             if (ref($timerintenv) eq 'HASH') {
16784:                 &_add_to_env(\%disk_env,$timerintenv);
16785:             }
16786: 	    if (ref($args->{'extra_env'})) {
16787: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
16788: 	    }
16789: 	    untie(%disk_env);
16790: 	} else {
16791: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
16792: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
16793: 	    return 'error: '.$!;
16794: 	}
16795:     }
16796:     $env{'request.role'}='cm';
16797:     $env{'request.role.adv'}=$env{'user.adv'};
16798:     $env{'browser.type'}=$clientbrowser;
16799: 
16800:     return $cookie;
16801: 
16802: }
16803: 
16804: sub _add_to_env {
16805:     my ($idf,$env_data,$prefix) = @_;
16806:     if (ref($env_data) eq 'HASH') {
16807:         while (my ($key,$value) = each(%$env_data)) {
16808: 	    $idf->{$prefix.$key} = $value;
16809: 	    $env{$prefix.$key}   = $value;
16810:         }
16811:     }
16812: }
16813: 
16814: # --- Get the symbolic name of a problem and the url
16815: sub get_symb {
16816:     my ($request,$silent) = @_;
16817:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
16818:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
16819:     if ($symb eq '') {
16820:         if (!$silent) {
16821:             if (ref($request)) { 
16822:                 $request->print("Unable to handle ambiguous references:$url:.");
16823:             }
16824:             return ();
16825:         }
16826:     }
16827:     &Apache::lonenc::check_decrypt(\$symb);
16828:     return ($symb);
16829: }
16830: 
16831: # --------------------------------------------------------------Get annotation
16832: 
16833: sub get_annotation {
16834:     my ($symb,$enc) = @_;
16835: 
16836:     my $key = $symb;
16837:     if (!$enc) {
16838:         $key =
16839:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
16840:     }
16841:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
16842:     return $annotation{$key};
16843: }
16844: 
16845: sub clean_symb {
16846:     my ($symb,$delete_enc) = @_;
16847: 
16848:     &Apache::lonenc::check_decrypt(\$symb);
16849:     my $enc = $env{'request.enc'};
16850:     if ($delete_enc) {
16851:         delete($env{'request.enc'});
16852:     }
16853: 
16854:     return ($symb,$enc);
16855: }
16856: 
16857: ############################################################
16858: ############################################################
16859: 
16860: =pod
16861: 
16862: =head1 Routines for building display used to search for courses
16863: 
16864: 
16865: =over 4
16866: 
16867: =item * &build_filters()
16868: 
16869: Create markup for a table used to set filters to use when selecting
16870: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
16871: and quotacheck.pl
16872: 
16873: 
16874: Inputs:
16875: 
16876: filterlist - anonymous array of fields to include as potential filters
16877: 
16878: crstype - course type
16879: 
16880: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
16881:               to pop-open a course selector (will contain "extra element").
16882: 
16883: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
16884: 
16885: filter - anonymous hash of criteria and their values
16886: 
16887: action - form action
16888: 
16889: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
16890: 
16891: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
16892: 
16893: cloneruname - username of owner of new course who wants to clone
16894: 
16895: clonerudom - domain of owner of new course who wants to clone
16896: 
16897: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
16898: 
16899: codetitlesref - reference to array of titles of components in institutional codes (official courses)
16900: 
16901: codedom - domain
16902: 
16903: formname - value of form element named "form".
16904: 
16905: fixeddom - domain, if fixed.
16906: 
16907: prevphase - value to assign to form element named "phase" when going back to the previous screen
16908: 
16909: cnameelement - name of form element in form on opener page which will receive title of selected course
16910: 
16911: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
16912: 
16913: cdomelement - name of form element in form on opener page which will receive domain of selected course
16914: 
16915: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
16916: 
16917: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
16918: 
16919: clonewarning - warning message about missing information for intended course owner when DC creates a course
16920: 
16921: 
16922: Returns: $output - HTML for display of search criteria, and hidden form elements.
16923: 
16924: 
16925: Side Effects: None
16926: 
16927: =cut
16928: 
16929: # ---------------------------------------------- search for courses based on last activity etc.
16930: 
16931: sub build_filters {
16932:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
16933:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
16934:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
16935:         $cnameelement,$cnumelement,$cdomelement,$setroles,
16936:         $clonetext,$clonewarning) = @_;
16937:     my ($list,$jscript);
16938:     my $onchange = 'javascript:updateFilters(this)';
16939:     my ($domainselectform,$sincefilterform,$createdfilterform,
16940:         $ownerdomselectform,$persondomselectform,$instcodeform,
16941:         $typeselectform,$instcodetitle);
16942:     if ($formname eq '') {
16943:         $formname = $caller;
16944:     }
16945:     foreach my $item (@{$filterlist}) {
16946:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
16947:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
16948:             if ($item eq 'domainfilter') {
16949:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
16950:             } elsif ($item eq 'coursefilter') {
16951:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
16952:             } elsif ($item eq 'ownerfilter') {
16953:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
16954:             } elsif ($item eq 'ownerdomfilter') {
16955:                 $filter->{'ownerdomfilter'} =
16956:                     &LONCAPA::clean_domain($filter->{$item});
16957:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
16958:                                                        'ownerdomfilter',1);
16959:             } elsif ($item eq 'personfilter') {
16960:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
16961:             } elsif ($item eq 'persondomfilter') {
16962:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
16963:                                                         'persondomfilter',1);
16964:             } else {
16965:                 $filter->{$item} =~ s/\W//g;
16966:             }
16967:             if (!$filter->{$item}) {
16968:                 $filter->{$item} = '';
16969:             }
16970:         }
16971:         if ($item eq 'domainfilter') {
16972:             my $allow_blank = 1;
16973:             if ($formname eq 'portform') {
16974:                 $allow_blank=0;
16975:             } elsif ($formname eq 'studentform') {
16976:                 $allow_blank=0;
16977:             }
16978:             if ($fixeddom) {
16979:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
16980:                                     ' value="'.$codedom.'" />'.
16981:                                     &Apache::lonnet::domain($codedom,'description');
16982:             } else {
16983:                 $domainselectform = &select_dom_form($filter->{$item},
16984:                                                      'domainfilter',
16985:                                                       $allow_blank,'',$onchange);
16986:             }
16987:         } else {
16988:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
16989:         }
16990:     }
16991: 
16992:     # last course activity filter and selection
16993:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
16994: 
16995:     # course created filter and selection
16996:     if (exists($filter->{'createdfilter'})) {
16997:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
16998:     }
16999: 
17000:     my %lt = &Apache::lonlocal::texthash(
17001:                 'cac' => "$crstype Activity",
17002:                 'ccr' => "$crstype Created",
17003:                 'cde' => "$crstype Title",
17004:                 'cdo' => "$crstype Domain",
17005:                 'ins' => 'Institutional Code',
17006:                 'inc' => 'Institutional Categorization',
17007:                 'cow' => "$crstype Owner/Co-owner",
17008:                 'cop' => "$crstype Personnel Includes",
17009:                 'cog' => 'Type',
17010:              );
17011: 
17012:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
17013:         my $typeval = 'Course';
17014:         if ($crstype eq 'Community') {
17015:             $typeval = 'Community';
17016:         }
17017:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
17018:     } else {
17019:         $typeselectform =  '<select name="type" size="1"';
17020:         if ($onchange) {
17021:             $typeselectform .= ' onchange="'.$onchange.'"';
17022:         }
17023:         $typeselectform .= '>'."\n";
17024:         foreach my $posstype ('Course','Community') {
17025:             $typeselectform.='<option value="'.$posstype.'"'.
17026:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
17027:         }
17028:         $typeselectform.="</select>";
17029:     }
17030: 
17031:     my ($cloneableonlyform,$cloneabletitle);
17032:     if (exists($filter->{'cloneableonly'})) {
17033:         my $cloneableon = '';
17034:         my $cloneableoff = ' checked="checked"';
17035:         if ($filter->{'cloneableonly'}) {
17036:             $cloneableon = $cloneableoff;
17037:             $cloneableoff = '';
17038:         }
17039:         $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>';
17040:         if ($formname eq 'ccrs') {
17041:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
17042:         } else {
17043:             $cloneabletitle = &mt('Cloneable by you');
17044:         }
17045:     }
17046:     my $officialjs;
17047:     if ($crstype eq 'Course') {
17048:         if (exists($filter->{'instcodefilter'})) {
17049: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
17050: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
17051:             if ($codedom) {
17052:                 $officialjs = 1;
17053:                 ($instcodeform,$jscript,$$numtitlesref) =
17054:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
17055:                                                                   $officialjs,$codetitlesref);
17056:                 if ($jscript) {
17057:                     $jscript = '<script type="text/javascript">'."\n".
17058:                                '// <![CDATA['."\n".
17059:                                $jscript."\n".
17060:                                '// ]]>'."\n".
17061:                                '</script>'."\n";
17062:                 }
17063:             }
17064:             if ($instcodeform eq '') {
17065:                 $instcodeform =
17066:                     '<input type="text" name="instcodefilter" size="10" value="'.
17067:                     $list->{'instcodefilter'}.'" />';
17068:                 $instcodetitle = $lt{'ins'};
17069:             } else {
17070:                 $instcodetitle = $lt{'inc'};
17071:             }
17072:             if ($fixeddom) {
17073:                 $instcodetitle .= '<br />('.$codedom.')';
17074:             }
17075:         }
17076:     }
17077:     my $output = qq|
17078: <form method="post" name="filterpicker" action="$action">
17079: <input type="hidden" name="form" value="$formname" />
17080: |;
17081:     if ($formname eq 'modifycourse') {
17082:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
17083:                    '<input type="hidden" name="prevphase" value="'.
17084:                    $prevphase.'" />'."\n";
17085:     } elsif ($formname eq 'quotacheck') {
17086:         $output .= qq|
17087: <input type="hidden" name="sortby" value="" />
17088: <input type="hidden" name="sortorder" value="" />
17089: |;
17090:     } else {
17091:         my $name_input;
17092:         if ($cnameelement ne '') {
17093:             $name_input = '<input type="hidden" name="cnameelement" value="'.
17094:                           $cnameelement.'" />';
17095:         }
17096:         $output .= qq|
17097: <input type="hidden" name="cnumelement" value="$cnumelement" />
17098: <input type="hidden" name="cdomelement" value="$cdomelement" />
17099: $name_input
17100: $roleelement
17101: $multelement
17102: $typeelement
17103: |;
17104:         if ($formname eq 'portform') {
17105:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
17106:         }
17107:     }
17108:     if ($fixeddom) {
17109:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
17110:     }
17111:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
17112:     if ($sincefilterform) {
17113:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
17114:                   .$sincefilterform
17115:                   .&Apache::lonhtmlcommon::row_closure();
17116:     }
17117:     if ($createdfilterform) {
17118:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
17119:                   .$createdfilterform
17120:                   .&Apache::lonhtmlcommon::row_closure();
17121:     }
17122:     if ($domainselectform) {
17123:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
17124:                   .$domainselectform
17125:                   .&Apache::lonhtmlcommon::row_closure();
17126:     }
17127:     if ($typeselectform) {
17128:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
17129:             $output .= $typeselectform;
17130:         } else {
17131:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
17132:                       .$typeselectform
17133:                       .&Apache::lonhtmlcommon::row_closure();
17134:         }
17135:     }
17136:     if ($instcodeform) {
17137:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
17138:                   .$instcodeform
17139:                   .&Apache::lonhtmlcommon::row_closure();
17140:     }
17141:     if (exists($filter->{'ownerfilter'})) {
17142:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
17143:                    '<table><tr><td>'.&mt('Username').'<br />'.
17144:                    '<input type="text" name="ownerfilter" size="20" value="'.
17145:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
17146:                    $ownerdomselectform.'</td></tr></table>'.
17147:                    &Apache::lonhtmlcommon::row_closure();
17148:     }
17149:     if (exists($filter->{'personfilter'})) {
17150:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
17151:                    '<table><tr><td>'.&mt('Username').'<br />'.
17152:                    '<input type="text" name="personfilter" size="20" value="'.
17153:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
17154:                    $persondomselectform.'</td></tr></table>'.
17155:                    &Apache::lonhtmlcommon::row_closure();
17156:     }
17157:     if (exists($filter->{'coursefilter'})) {
17158:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
17159:                   .'<input type="text" name="coursefilter" size="25" value="'
17160:                   .$list->{'coursefilter'}.'" />'
17161:                   .&Apache::lonhtmlcommon::row_closure();
17162:     }
17163:     if ($cloneableonlyform) {
17164:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
17165:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
17166:     }
17167:     if (exists($filter->{'descriptfilter'})) {
17168:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
17169:                   .'<input type="text" name="descriptfilter" size="40" value="'
17170:                   .$list->{'descriptfilter'}.'" />'
17171:                   .&Apache::lonhtmlcommon::row_closure(1);
17172:     }
17173:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
17174:                '<input type="hidden" name="updater" value="" />'."\n".
17175:                '<input type="submit" name="gosearch" value="'.
17176:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
17177:     return $jscript.$clonewarning.$output;
17178: }
17179: 
17180: =pod
17181: 
17182: =item * &timebased_select_form()
17183: 
17184: Create markup for a dropdown list used to select a time-based
17185: filter e.g., Course Activity, Course Created, when searching for courses
17186: or communities
17187: 
17188: Inputs:
17189: 
17190: item - name of form element (sincefilter or createdfilter)
17191: 
17192: filter - anonymous hash of criteria and their values
17193: 
17194: Returns: HTML for a select box contained a blank, then six time selections,
17195:          with value set in incoming form variables currently selected.
17196: 
17197: Side Effects: None
17198: 
17199: =cut
17200: 
17201: sub timebased_select_form {
17202:     my ($item,$filter) = @_;
17203:     if (ref($filter) eq 'HASH') {
17204:         $filter->{$item} =~ s/[^\d-]//g;
17205:         if (!$filter->{$item}) { $filter->{$item}=-1; }
17206:         return &select_form(
17207:                             $filter->{$item},
17208:                             $item,
17209:                             {      '-1' => '',
17210:                                 '86400' => &mt('today'),
17211:                                '604800' => &mt('last week'),
17212:                               '2592000' => &mt('last month'),
17213:                               '7776000' => &mt('last three months'),
17214:                              '15552000' => &mt('last six months'),
17215:                              '31104000' => &mt('last year'),
17216:                     'select_form_order' =>
17217:                            ['-1','86400','604800','2592000','7776000',
17218:                             '15552000','31104000']});
17219:     }
17220: }
17221: 
17222: =pod
17223: 
17224: =item * &js_changer()
17225: 
17226: Create script tag containing Javascript used to submit course search form
17227: when course type or domain is changed, and also to hide 'Searching ...' on
17228: page load completion for page showing search result.
17229: 
17230: Inputs: None
17231: 
17232: Returns: markup containing updateFilters() and hideSearching() javascript functions.
17233: 
17234: Side Effects: None
17235: 
17236: =cut
17237: 
17238: sub js_changer {
17239:     return <<ENDJS;
17240: <script type="text/javascript">
17241: // <![CDATA[
17242: function updateFilters(caller) {
17243:     if (typeof(caller) != "undefined") {
17244:         document.filterpicker.updater.value = caller.name;
17245:     }
17246:     document.filterpicker.submit();
17247: }
17248: 
17249: function hideSearching() {
17250:     if (document.getElementById('searching')) {
17251:         document.getElementById('searching').style.display = 'none';
17252:     }
17253:     return;
17254: }
17255: 
17256: // ]]>
17257: </script>
17258: 
17259: ENDJS
17260: }
17261: 
17262: =pod
17263: 
17264: =item * &search_courses()
17265: 
17266: Process selected filters form course search form and pass to lonnet::courseiddump
17267: to retrieve a hash for which keys are courseIDs which match the selected filters.
17268: 
17269: Inputs:
17270: 
17271: dom - domain being searched
17272: 
17273: type - course type ('Course' or 'Community' or '.' if any).
17274: 
17275: filter - anonymous hash of criteria and their values
17276: 
17277: numtitles - for institutional codes - number of categories
17278: 
17279: cloneruname - optional username of new course owner
17280: 
17281: clonerudom - optional domain of new course owner
17282: 
17283: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
17284:             (used when DC is using course creation form)
17285: 
17286: codetitles - reference to array of titles of components in institutional codes (official courses).
17287: 
17288: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
17289:            (and so can clone automatically)
17290: 
17291: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
17292: 
17293: reqinstcode - institutional code of new course, where search_courses is used to identify potential
17294:               courses to clone
17295: 
17296: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
17297: 
17298: 
17299: Side Effects: None
17300: 
17301: =cut
17302: 
17303: 
17304: sub search_courses {
17305:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
17306:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
17307:     my (%courses,%showcourses,$cloner);
17308:     if (($filter->{'ownerfilter'} ne '') ||
17309:         ($filter->{'ownerdomfilter'} ne '')) {
17310:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
17311:                                        $filter->{'ownerdomfilter'};
17312:     }
17313:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
17314:         if (!$filter->{$item}) {
17315:             $filter->{$item}='.';
17316:         }
17317:     }
17318:     my $now = time;
17319:     my $timefilter =
17320:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
17321:     my ($createdbefore,$createdafter);
17322:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
17323:         $createdbefore = $now;
17324:         $createdafter = $now-$filter->{'createdfilter'};
17325:     }
17326:     my ($instcodefilter,$regexpok);
17327:     if ($numtitles) {
17328:         if ($env{'form.official'} eq 'on') {
17329:             $instcodefilter =
17330:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
17331:             $regexpok = 1;
17332:         } elsif ($env{'form.official'} eq 'off') {
17333:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
17334:             unless ($instcodefilter eq '') {
17335:                 $regexpok = -1;
17336:             }
17337:         }
17338:     } else {
17339:         $instcodefilter = $filter->{'instcodefilter'};
17340:     }
17341:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
17342:     if ($type eq '') { $type = '.'; }
17343: 
17344:     if (($clonerudom ne '') && ($cloneruname ne '')) {
17345:         $cloner = $cloneruname.':'.$clonerudom;
17346:     }
17347:     %courses = &Apache::lonnet::courseiddump($dom,
17348:                                              $filter->{'descriptfilter'},
17349:                                              $timefilter,
17350:                                              $instcodefilter,
17351:                                              $filter->{'combownerfilter'},
17352:                                              $filter->{'coursefilter'},
17353:                                              undef,undef,$type,$regexpok,undef,undef,
17354:                                              undef,undef,$cloner,$cc_clone,
17355:                                              $filter->{'cloneableonly'},
17356:                                              $createdbefore,$createdafter,undef,
17357:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
17358:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
17359:         my $ccrole;
17360:         if ($type eq 'Community') {
17361:             $ccrole = 'co';
17362:         } else {
17363:             $ccrole = 'cc';
17364:         }
17365:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
17366:                                                      $filter->{'persondomfilter'},
17367:                                                      'userroles',undef,
17368:                                                      [$ccrole,'in','ad','ep','ta','cr'],
17369:                                                      $dom);
17370:         foreach my $role (keys(%rolehash)) {
17371:             my ($cnum,$cdom,$courserole) = split(':',$role);
17372:             my $cid = $cdom.'_'.$cnum;
17373:             if (exists($courses{$cid})) {
17374:                 if (ref($courses{$cid}) eq 'HASH') {
17375:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
17376:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
17377:                             push(@{$courses{$cid}{roles}},$courserole);
17378:                         }
17379:                     } else {
17380:                         $courses{$cid}{roles} = [$courserole];
17381:                     }
17382:                     $showcourses{$cid} = $courses{$cid};
17383:                 }
17384:             }
17385:         }
17386:         %courses = %showcourses;
17387:     }
17388:     return %courses;
17389: }
17390: 
17391: =pod
17392: 
17393: =back
17394: 
17395: =head1 Routines for version requirements for current course.
17396: 
17397: =over 4
17398: 
17399: =item * &check_release_required()
17400: 
17401: Compares required LON-CAPA version with version on server, and
17402: if required version is newer looks for a server with the required version.
17403: 
17404: Looks first at servers in user's owen domain; if none suitable, looks at
17405: servers in course's domain are permitted to host sessions for user's domain.
17406: 
17407: Inputs:
17408: 
17409: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
17410: 
17411: $courseid - Course ID of current course
17412: 
17413: $rolecode - User's current role in course (for switchserver query string).
17414: 
17415: $required - LON-CAPA version needed by course (format: Major.Minor).
17416: 
17417: 
17418: Returns:
17419: 
17420: $switchserver - query string tp append to /adm/switchserver call (if
17421:                 current server's LON-CAPA version is too old.
17422: 
17423: $warning - Message is displayed if no suitable server could be found.
17424: 
17425: =cut
17426: 
17427: sub check_release_required {
17428:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
17429:     my ($switchserver,$warning);
17430:     if ($required ne '') {
17431:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
17432:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
17433:         if ($reqdmajor ne '' && $reqdminor ne '') {
17434:             my $otherserver;
17435:             if (($major eq '' && $minor eq '') ||
17436:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
17437:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
17438:                 my $switchlcrev =
17439:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
17440:                                                            $userdomserver);
17441:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
17442:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
17443:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
17444:                     my $cdom = $env{'course.'.$courseid.'.domain'};
17445:                     if ($cdom ne $env{'user.domain'}) {
17446:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
17447:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
17448:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
17449:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
17450:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
17451:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
17452:                         my $canhost =
17453:                             &Apache::lonnet::can_host_session($env{'user.domain'},
17454:                                                               $coursedomserver,
17455:                                                               $remoterev,
17456:                                                               $udomdefaults{'remotesessions'},
17457:                                                               $defdomdefaults{'hostedsessions'});
17458: 
17459:                         if ($canhost) {
17460:                             $otherserver = $coursedomserver;
17461:                         } else {
17462:                             $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.");
17463:                         }
17464:                     } else {
17465:                         $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).");
17466:                     }
17467:                 } else {
17468:                     $otherserver = $userdomserver;
17469:                 }
17470:             }
17471:             if ($otherserver ne '') {
17472:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
17473:             }
17474:         }
17475:     }
17476:     return ($switchserver,$warning);
17477: }
17478: 
17479: =pod
17480: 
17481: =item * &check_release_result()
17482: 
17483: Inputs:
17484: 
17485: $switchwarning - Warning message if no suitable server found to host session.
17486: 
17487: $switchserver - query string to append to /adm/switchserver containing lonHostID
17488:                 and current role.
17489: 
17490: Returns: HTML to display with information about requirement to switch server.
17491:          Either displaying warning with link to Roles/Courses screen or
17492:          display link to switchserver.
17493: 
17494: =cut
17495: 
17496: sub check_release_result {
17497:     my ($switchwarning,$switchserver) = @_;
17498:     my $output = &start_page('Selected course unavailable on this server').
17499:                  '<p class="LC_warning">';
17500:     if ($switchwarning) {
17501:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
17502:         if (&show_course()) {
17503:             $output .= &mt('Display courses');
17504:         } else {
17505:             $output .= &mt('Display roles');
17506:         }
17507:         $output .= '</a>';
17508:     } elsif ($switchserver) {
17509:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
17510:                    '<br />'.
17511:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
17512:                    &mt('Switch Server').
17513:                    '</a>';
17514:     }
17515:     $output .= '</p>'.&end_page();
17516:     return $output;
17517: }
17518: 
17519: =pod
17520: 
17521: =item * &needs_coursereinit()
17522: 
17523: Determine if course contents stored for user's session needs to be
17524: refreshed, because content has changed since "Big Hash" last tied.
17525: 
17526: Check for change is made if time last checked is more than 10 minutes ago
17527: (by default).
17528: 
17529: Inputs:
17530: 
17531: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
17532: 
17533: $interval (optional) - Time which may elapse (in s) between last check for content
17534:                        change in current course. (default: 600 s).
17535: 
17536: Returns: an array; first element is:
17537: 
17538: =over 4
17539: 
17540: 'switch' - if content updates mean user's session
17541:            needs to be switched to a server running a newer LON-CAPA version
17542: 
17543: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
17544:            on current server hosting user's session
17545: 
17546: ''       - if no action required.
17547: 
17548: =back
17549: 
17550: If first item element is 'switch':
17551: 
17552: second item is $switchwarning - Warning message if no suitable server found to host session.
17553: 
17554: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
17555:                               and current role.
17556: 
17557: otherwise: no other elements returned.
17558: 
17559: =back
17560: 
17561: =cut
17562: 
17563: sub needs_coursereinit {
17564:     my ($loncaparev,$interval) = @_;
17565:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
17566:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
17567:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
17568:     my $now = time;
17569:     if ($interval eq '') {
17570:         $interval = 600;
17571:     }
17572:     if (($now-$env{'request.course.timechecked'})>$interval) {
17573:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
17574:         my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
17575:         if ($blocked) {
17576:             return ();
17577:         }
17578:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
17579:         if ($lastchange > $env{'request.course.tied'}) {
17580:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
17581:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
17582:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
17583:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
17584:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
17585:                                              $curr_reqd_hash{'internal.releaserequired'}});
17586:                     my ($switchserver,$switchwarning) =
17587:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
17588:                                                 $curr_reqd_hash{'internal.releaserequired'});
17589:                     if ($switchwarning ne '' || $switchserver ne '') {
17590:                         return ('switch',$switchwarning,$switchserver);
17591:                     }
17592:                 }
17593:             }
17594:             return ('update');
17595:         }
17596:     }
17597:     return ();
17598: }
17599: 
17600: sub update_content_constraints {
17601:     my ($cdom,$cnum,$chome,$cid) = @_;
17602:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
17603:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
17604:     my %checkresponsetypes;
17605:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
17606:         my ($item,$name,$value) = split(/:/,$key);
17607:         if ($item eq 'resourcetag') {
17608:             if ($name eq 'responsetype') {
17609:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
17610:             }
17611:         }
17612:     }
17613:     my $navmap = Apache::lonnavmaps::navmap->new();
17614:     if (defined($navmap)) {
17615:         my %allresponses;
17616:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
17617:             my %responses = $res->responseTypes();
17618:             foreach my $key (keys(%responses)) {
17619:                 next unless(exists($checkresponsetypes{$key}));
17620:                 $allresponses{$key} += $responses{$key};
17621:             }
17622:         }
17623:         foreach my $key (keys(%allresponses)) {
17624:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
17625:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
17626:                 ($reqdmajor,$reqdminor) = ($major,$minor);
17627:             }
17628:         }
17629:         undef($navmap);
17630:     }
17631:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
17632:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
17633:     }
17634:     return;
17635: }
17636: 
17637: sub allmaps_incourse {
17638:     my ($cdom,$cnum,$chome,$cid) = @_;
17639:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
17640:         $cid = $env{'request.course.id'};
17641:         $cdom = $env{'course.'.$cid.'.domain'};
17642:         $cnum = $env{'course.'.$cid.'.num'};
17643:         $chome = $env{'course.'.$cid.'.home'};
17644:     }
17645:     my %allmaps = ();
17646:     my $lastchange =
17647:         &Apache::lonnet::get_coursechange($cdom,$cnum);
17648:     if ($lastchange > $env{'request.course.tied'}) {
17649:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
17650:         unless ($ferr) {
17651:             &update_content_constraints($cdom,$cnum,$chome,$cid);
17652:         }
17653:     }
17654:     my $navmap = Apache::lonnavmaps::navmap->new();
17655:     if (defined($navmap)) {
17656:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
17657:             $allmaps{$res->src()} = 1;
17658:         }
17659:     }
17660:     return \%allmaps;
17661: }
17662: 
17663: sub parse_supplemental_title {
17664:     my ($title) = @_;
17665: 
17666:     my ($foldertitle,$renametitle);
17667:     if ($title =~ /&amp;&amp;&amp;/) {
17668:         $title = &HTML::Entites::decode($title);
17669:     }
17670:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
17671:         $renametitle=$4;
17672:         my ($time,$uname,$udom) = ($1,$2,$3);
17673:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
17674:         my $name =  &plainname($uname,$udom);
17675:         $name = &HTML::Entities::encode($name,'"<>&\'');
17676:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
17677:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
17678:             $name.': <br />'.$foldertitle;
17679:     }
17680:     if (wantarray) {
17681:         return ($title,$foldertitle,$renametitle);
17682:     }
17683:     return $title;
17684: }
17685: 
17686: sub recurse_supplemental {
17687:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
17688:     if ($suppmap) {
17689:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
17690:         if ($fatal) {
17691:             $errors ++;
17692:         } else {
17693:             if ($#LONCAPA::map::resources > 0) {
17694:                 foreach my $res (@LONCAPA::map::resources) {
17695:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
17696:                     if (($src ne '') && ($status eq 'res')) {
17697:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
17698:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
17699:                         } else {
17700:                             $numfiles ++;
17701:                         }
17702:                     }
17703:                 }
17704:             }
17705:         }
17706:     }
17707:     return ($numfiles,$errors);
17708: }
17709: 
17710: sub symb_to_docspath {
17711:     my ($symb,$navmapref) = @_;
17712:     return unless ($symb && ref($navmapref));
17713:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
17714:     if ($resurl=~/\.(sequence|page)$/) {
17715:         $mapurl=$resurl;
17716:     } elsif ($resurl eq 'adm/navmaps') {
17717:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
17718:     }
17719:     my $mapresobj;
17720:     unless (ref($$navmapref)) {
17721:         $$navmapref = Apache::lonnavmaps::navmap->new();
17722:     }
17723:     if (ref($$navmapref)) {
17724:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
17725:     }
17726:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
17727:     my $type=$2;
17728:     my $path;
17729:     if (ref($mapresobj)) {
17730:         my $pcslist = $mapresobj->map_hierarchy();
17731:         if ($pcslist ne '') {
17732:             foreach my $pc (split(/,/,$pcslist)) {
17733:                 next if ($pc <= 1);
17734:                 my $res = $$navmapref->getByMapPc($pc);
17735:                 if (ref($res)) {
17736:                     my $thisurl = $res->src();
17737:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
17738:                     my $thistitle = $res->title();
17739:                     $path .= '&'.
17740:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
17741:                              &escape($thistitle).
17742:                              ':'.$res->randompick().
17743:                              ':'.$res->randomout().
17744:                              ':'.$res->encrypted().
17745:                              ':'.$res->randomorder().
17746:                              ':'.$res->is_page();
17747:                 }
17748:             }
17749:         }
17750:         $path =~ s/^\&//;
17751:         my $maptitle = $mapresobj->title();
17752:         if ($mapurl eq 'default') {
17753:             $maptitle = 'Main Content';
17754:         }
17755:         $path .= (($path ne '')? '&' : '').
17756:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
17757:                  &escape($maptitle).
17758:                  ':'.$mapresobj->randompick().
17759:                  ':'.$mapresobj->randomout().
17760:                  ':'.$mapresobj->encrypted().
17761:                  ':'.$mapresobj->randomorder().
17762:                  ':'.$mapresobj->is_page();
17763:     } else {
17764:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
17765:         my $ispage = (($type eq 'page')? 1 : '');
17766:         if ($mapurl eq 'default') {
17767:             $maptitle = 'Main Content';
17768:         }
17769:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
17770:                 &escape($maptitle).':::::'.$ispage;
17771:     }
17772:     unless ($mapurl eq 'default') {
17773:         $path = 'default&'.
17774:                 &escape('Main Content').
17775:                 ':::::&'.$path;
17776:     }
17777:     return $path;
17778: }
17779: 
17780: sub captcha_display {
17781:     my ($context,$lonhost,$defdom) = @_;
17782:     my ($output,$error);
17783:     my ($captcha,$pubkey,$privkey,$version) =
17784:         &get_captcha_config($context,$lonhost,$defdom);
17785:     if ($captcha eq 'original') {
17786:         $output = &create_captcha();
17787:         unless ($output) {
17788:             $error = 'captcha';
17789:         }
17790:     } elsif ($captcha eq 'recaptcha') {
17791:         $output = &create_recaptcha($pubkey,$version);
17792:         unless ($output) {
17793:             $error = 'recaptcha';
17794:         }
17795:     }
17796:     return ($output,$error,$captcha,$version);
17797: }
17798: 
17799: sub captcha_response {
17800:     my ($context,$lonhost,$defdom) = @_;
17801:     my ($captcha_chk,$captcha_error);
17802:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
17803:     if ($captcha eq 'original') {
17804:         ($captcha_chk,$captcha_error) = &check_captcha();
17805:     } elsif ($captcha eq 'recaptcha') {
17806:         $captcha_chk = &check_recaptcha($privkey,$version);
17807:     } else {
17808:         $captcha_chk = 1;
17809:     }
17810:     return ($captcha_chk,$captcha_error);
17811: }
17812: 
17813: sub get_captcha_config {
17814:     my ($context,$lonhost,$dom_in_effect) = @_;
17815:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
17816:     my $hostname = &Apache::lonnet::hostname($lonhost);
17817:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
17818:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
17819:     if ($context eq 'usercreation') {
17820:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
17821:         if (ref($domconfig{$context}) eq 'HASH') {
17822:             $hashtocheck = $domconfig{$context}{'cancreate'};
17823:             if (ref($hashtocheck) eq 'HASH') {
17824:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
17825:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
17826:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
17827:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
17828:                     }
17829:                     if ($privkey && $pubkey) {
17830:                         $captcha = 'recaptcha';
17831:                         $version = $hashtocheck->{'recaptchaversion'};
17832:                         if ($version ne '2') {
17833:                             $version = 1;
17834:                         }
17835:                     } else {
17836:                         $captcha = 'original';
17837:                     }
17838:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
17839:                     $captcha = 'original';
17840:                 }
17841:             }
17842:         } else {
17843:             $captcha = 'captcha';
17844:         }
17845:     } elsif ($context eq 'login') {
17846:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
17847:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
17848:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
17849:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
17850:             if ($privkey && $pubkey) {
17851:                 $captcha = 'recaptcha';
17852:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
17853:                 if ($version ne '2') {
17854:                     $version = 1;
17855:                 }
17856:             } else {
17857:                 $captcha = 'original';
17858:             }
17859:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
17860:             $captcha = 'original';
17861:         }
17862:     } elsif ($context eq 'passwords') {
17863:         if ($dom_in_effect) {
17864:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
17865:             if ($passwdconf{'captcha'} eq 'recaptcha') {
17866:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
17867:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
17868:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
17869:                 }
17870:                 if ($privkey && $pubkey) {
17871:                     $captcha = 'recaptcha';
17872:                     $version = $passwdconf{'recaptchaversion'};
17873:                     if ($version ne '2') {
17874:                         $version = 1;
17875:                     }
17876:                 } else {
17877:                     $captcha = 'original';
17878:                 }
17879:             } elsif ($passwdconf{'captcha'} ne 'notused') {
17880:                 $captcha = 'original';
17881:             }
17882:         }
17883:     }
17884:     return ($captcha,$pubkey,$privkey,$version);
17885: }
17886: 
17887: sub create_captcha {
17888:     my %captcha_params = &captcha_settings();
17889:     my ($output,$maxtries,$tries) = ('',10,0);
17890:     while ($tries < $maxtries) {
17891:         $tries ++;
17892:         my $captcha = Authen::Captcha->new (
17893:                                            output_folder => $captcha_params{'output_dir'},
17894:                                            data_folder   => $captcha_params{'db_dir'},
17895:                                           );
17896:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
17897: 
17898:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
17899:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
17900:                       '<span class="LC_nobreak">'.
17901:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
17902:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
17903:                       '</span><br />'.
17904:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
17905:             last;
17906:         }
17907:     }
17908:     if ($output eq '') {
17909:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
17910:     }
17911:     return $output;
17912: }
17913: 
17914: sub captcha_settings {
17915:     my %captcha_params = (
17916:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
17917:                            www_output_dir => "/captchaspool",
17918:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
17919:                            numchars       => '5',
17920:                          );
17921:     return %captcha_params;
17922: }
17923: 
17924: sub check_captcha {
17925:     my ($captcha_chk,$captcha_error);
17926:     my $code = $env{'form.code'};
17927:     my $md5sum = $env{'form.crypt'};
17928:     my %captcha_params = &captcha_settings();
17929:     my $captcha = Authen::Captcha->new(
17930:                       output_folder => $captcha_params{'output_dir'},
17931:                       data_folder   => $captcha_params{'db_dir'},
17932:                   );
17933:     $captcha_chk = $captcha->check_code($code,$md5sum);
17934:     my %captcha_hash = (
17935:                         0       => 'Code not checked (file error)',
17936:                        -1      => 'Failed: code expired',
17937:                        -2      => 'Failed: invalid code (not in database)',
17938:                        -3      => 'Failed: invalid code (code does not match crypt)',
17939:     );
17940:     if ($captcha_chk != 1) {
17941:         $captcha_error = $captcha_hash{$captcha_chk}
17942:     }
17943:     return ($captcha_chk,$captcha_error);
17944: }
17945: 
17946: sub create_recaptcha {
17947:     my ($pubkey,$version) = @_;
17948:     if ($version >= 2) {
17949:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
17950:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
17951:     } else {
17952:         my $use_ssl;
17953:         if ($ENV{'SERVER_PORT'} == 443) {
17954:             $use_ssl = 1;
17955:         }
17956:         my $captcha = Captcha::reCAPTCHA->new;
17957:         return $captcha->get_options_setter({theme => 'white'})."\n".
17958:                $captcha->get_html($pubkey,undef,$use_ssl).
17959:                &mt('If the text is hard to read, [_1] will replace them.',
17960:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
17961:                '<br /><br />';
17962:      }
17963: }
17964: 
17965: sub check_recaptcha {
17966:     my ($privkey,$version) = @_;
17967:     my $captcha_chk;
17968:     my $ip = &Apache::lonnet::get_requestor_ip(); 
17969:     if ($version >= 2) {
17970:         my $ua = LWP::UserAgent->new;
17971:         $ua->timeout(10);
17972:         my %info = (
17973:                      secret   => $privkey,
17974:                      response => $env{'form.g-recaptcha-response'},
17975:                      remoteip => $ip,
17976:                    );
17977:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
17978:         if ($response->is_success)  {
17979:             my $data = JSON::DWIW->from_json($response->decoded_content);
17980:             if (ref($data) eq 'HASH') {
17981:                 if ($data->{'success'}) {
17982:                     $captcha_chk = 1;
17983:                 }
17984:             }
17985:         }
17986:     } else {
17987:         my $captcha = Captcha::reCAPTCHA->new;
17988:         my $captcha_result =
17989:             $captcha->check_answer(
17990:                                     $privkey,
17991:                                     $ip,
17992:                                     $env{'form.recaptcha_challenge_field'},
17993:                                     $env{'form.recaptcha_response_field'},
17994:                                   );
17995:         if ($captcha_result->{is_valid}) {
17996:             $captcha_chk = 1;
17997:         }
17998:     }
17999:     return $captcha_chk;
18000: }
18001: 
18002: sub emailusername_info {
18003:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
18004:     my %titles = &Apache::lonlocal::texthash (
18005:                      lastname      => 'Last Name',
18006:                      firstname     => 'First Name',
18007:                      institution   => 'School/college/university',
18008:                      location      => "School's city, state/province, country",
18009:                      web           => "School's web address",
18010:                      officialemail => 'E-mail address at institution (if different)',
18011:                      id            => 'Student/Employee ID',
18012:                  );
18013:     return (\@fields,\%titles);
18014: }
18015: 
18016: sub cleanup_html {
18017:     my ($incoming) = @_;
18018:     my $outgoing;
18019:     if ($incoming ne '') {
18020:         $outgoing = $incoming;
18021:         $outgoing =~ s/;/&#059;/g;
18022:         $outgoing =~ s/\#/&#035;/g;
18023:         $outgoing =~ s/\&/&#038;/g;
18024:         $outgoing =~ s/</&#060;/g;
18025:         $outgoing =~ s/>/&#062;/g;
18026:         $outgoing =~ s/\(/&#040/g;
18027:         $outgoing =~ s/\)/&#041;/g;
18028:         $outgoing =~ s/"/&#034;/g;
18029:         $outgoing =~ s/'/&#039;/g;
18030:         $outgoing =~ s/\$/&#036;/g;
18031:         $outgoing =~ s{/}{&#047;}g;
18032:         $outgoing =~ s/=/&#061;/g;
18033:         $outgoing =~ s/\\/&#092;/g
18034:     }
18035:     return $outgoing;
18036: }
18037: 
18038: # Checks for critical messages and returns a redirect url if one exists.
18039: # $interval indicates how often to check for messages.
18040: # $context is the calling context -- roles, grades, contents, menu or flip.
18041: sub critical_redirect {
18042:     my ($interval,$context) = @_;
18043:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
18044:         return ();
18045:     }
18046:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
18047:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
18048:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
18049:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
18050:             my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
18051:             if ($blocked) {
18052:                 my $checkrole = "cm./$cdom/$cnum";
18053:                 if ($env{'request.course.sec'} ne '') {
18054:                     $checkrole .= "/$env{'request.course.sec'}";
18055:                 }
18056:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
18057:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
18058:                     return;
18059:                 }
18060:             }
18061:         }
18062:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
18063:                                         $env{'user.name'});
18064:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
18065:         my $redirecturl;
18066:         if ($what[0]) {
18067:             if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
18068:                 $redirecturl='/adm/email?critical=display';
18069:                 my $url=&Apache::lonnet::absolute_url().$redirecturl;
18070:                 return (1, $url);
18071:             }
18072:         }
18073:     }
18074:     return ();
18075: }
18076: 
18077: # Use:
18078: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
18079: #
18080: ##################################################
18081: #          password associated functions         #
18082: ##################################################
18083: sub des_keys {
18084:     # Make a new key for DES encryption.
18085:     # Each key has two parts which are returned separately.
18086:     # Please note:  Each key must be passed through the &hex function
18087:     # before it is output to the web browser.  The hex versions cannot
18088:     # be used to decrypt.
18089:     my @hexstr=('0','1','2','3','4','5','6','7',
18090:                 '8','9','a','b','c','d','e','f');
18091:     my $lkey='';
18092:     for (0..7) {
18093:         $lkey.=$hexstr[rand(15)];
18094:     }
18095:     my $ukey='';
18096:     for (0..7) {
18097:         $ukey.=$hexstr[rand(15)];
18098:     }
18099:     return ($lkey,$ukey);
18100: }
18101: 
18102: sub des_decrypt {
18103:     my ($key,$cyphertext) = @_;
18104:     my $keybin=pack("H16",$key);
18105:     my $cypher;
18106:     if ($Crypt::DES::VERSION>=2.03) {
18107:         $cypher=new Crypt::DES $keybin;
18108:     } else {
18109:         $cypher=new DES $keybin;
18110:     }
18111:     my $plaintext='';
18112:     my $cypherlength = length($cyphertext);
18113:     my $numchunks = int($cypherlength/32);
18114:     for (my $j=0; $j<$numchunks; $j++) {
18115:         my $start = $j*32;
18116:         my $cypherblock = substr($cyphertext,$start,32);
18117:         my $chunk =
18118:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
18119:         $chunk .=
18120:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
18121:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
18122:         $plaintext .= $chunk;
18123:     }
18124:     return $plaintext;
18125: }
18126: 
18127: sub get_requested_shorturls {
18128:     my ($cdom,$cnum,$navmap) = @_;
18129:     return unless (ref($navmap));
18130:     my ($numnew,$errors);
18131:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
18132:     if (@toshorten) {
18133:         my (%maps,%resources,%titles);
18134:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
18135:                                                                'shorturls',$cdom,$cnum);
18136:         if (keys(%resources)) {
18137:             my %tocreate;
18138:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
18139:                 my $symb = $resources{$item};
18140:                 if ($symb) {
18141:                     $tocreate{$cnum.'&'.$symb} = 1;
18142:                 }
18143:             }
18144:             if (keys(%tocreate)) {
18145:                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
18146:                                                       \%tocreate);
18147:             }
18148:         }
18149:     }
18150:     return ($numnew,$errors);
18151: }
18152: 
18153: sub make_short_symbs {
18154:     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
18155:     my ($numnew,@errors);
18156:     if (ref($tocreateref) eq 'HASH') {
18157:         my %tocreate = %{$tocreateref};
18158:         if (keys(%tocreate)) {
18159:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
18160:             my $su = Short::URL->new(no_vowels => 1);
18161:             my $init = '';
18162:             my (%newunique,%addcourse,%courseonly,%failed);
18163:             # get lock on tiny db
18164:             my $now = time;
18165:             if ($lockuser eq '') {
18166:                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
18167:             }
18168:             my $lockhash = {
18169:                                 "lock\0$now" => $lockuser,
18170:                             };
18171:             my $tries = 0;
18172:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
18173:             my ($code,$error);
18174:             while (($gotlock ne 'ok') && ($tries<3)) {
18175:                 $tries ++;
18176:                 sleep 1;
18177:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
18178:             }
18179:             if ($gotlock eq 'ok') {
18180:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
18181:                                        \%addcourse,\%courseonly,\%failed);
18182:                 if (keys(%failed)) {
18183:                     my $numfailed = scalar(keys(%failed));
18184:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
18185:                 }
18186:                 if (keys(%newunique)) {
18187:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
18188:                     if ($putres eq 'ok') {
18189:                         $numnew = scalar(keys(%newunique));
18190:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
18191:                         unless ($newputres eq 'ok') {
18192:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
18193:                         }
18194:                     } else {
18195:                         push(@errors,&mt('error: could not store unique six character URLs'));
18196:                     }
18197:                 }
18198:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
18199:                 unless ($dellockres eq 'ok') {
18200:                     push(@errors,&mt('error: could not release lockfile'));
18201:                 }
18202:             } else {
18203:                 push(@errors,&mt('error: could not obtain lockfile'));
18204:             }
18205:             if (keys(%courseonly)) {
18206:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
18207:                 if ($result ne 'ok') {
18208:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
18209:                 }
18210:             }
18211:         }
18212:     }
18213:     return ($numnew,\@errors);
18214: }
18215: 
18216: sub shorten_symbs {
18217:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
18218:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
18219:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
18220:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
18221:     my (%possibles,%collisions);
18222:     foreach my $key (keys(%{$tocreate})) {
18223:         my $num = String::CRC32::crc32($key);
18224:         my $tiny = $su->encode($num,$init);
18225:         if ($tiny) {
18226:             $possibles{$tiny} = $key;
18227:         }
18228:     }
18229:     if (!$init) {
18230:         $init = 1;
18231:     } else {
18232:         $init ++;
18233:     }
18234:     if (keys(%possibles)) {
18235:         my @posstiny = keys(%possibles);
18236:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
18237:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
18238:         if (keys(%currtiny)) {
18239:             foreach my $key (keys(%currtiny)) {
18240:                 next if ($currtiny{$key} eq '');
18241:                 if ($currtiny{$key} eq $possibles{$key}) {
18242:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
18243:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
18244:                         $courseonly->{$tsymb} = $key;
18245:                     }
18246:                 } else {
18247:                     $collisions{$possibles{$key}} = 1;
18248:                 }
18249:                 delete($possibles{$key});
18250:             }
18251:         }
18252:         foreach my $key (keys(%possibles)) {
18253:             $newunique->{$key} = $possibles{$key};
18254:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
18255:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
18256:                 $addcourse->{$tsymb} = $key;
18257:             }
18258:         }
18259:     }
18260:     if (keys(%collisions)) {
18261:         if ($init <5) {
18262:             if (!$init) {
18263:                 $init = 1;
18264:             } else {
18265:                 $init ++;
18266:             }
18267:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
18268:                                    $newunique,$addcourse,$courseonly,$failed);
18269:         } else {
18270:             foreach my $key (keys(%collisions)) {
18271:                 $failed->{$key} = 1;
18272:                 $failed->{$key} = 1;
18273:             }
18274:         }
18275:     }
18276:     return $init;
18277: }
18278: 
18279: sub is_nonframeable {
18280:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
18281:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
18282:     return if (($remprotocol eq '') || ($remhost eq ''));
18283: 
18284:     $remprotocol = lc($remprotocol);
18285:     $remhost = lc($remhost);
18286:     my $remport = 80;
18287:     if ($remprotocol eq 'https') {
18288:         $remport = 443;
18289:     }
18290:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
18291:     if ($cached) {
18292:         unless ($nocache) {
18293:             if ($result) {
18294:                 return 1;
18295:             } else {
18296:                 return 0;
18297:             }
18298:         }
18299:     }
18300:     my $uselink;
18301:     my $request = new HTTP::Request('HEAD',$url);
18302:     my $ua = LWP::UserAgent->new;
18303:     $ua->timeout(5);
18304:     my $response=$ua->request($request);
18305:     if ($response->is_success()) {
18306:         my $secpolicy = lc($response->header('content-security-policy'));
18307:         my $xframeop = lc($response->header('x-frame-options'));
18308:         $secpolicy =~ s/^\s+|\s+$//g;
18309:         $xframeop =~ s/^\s+|\s+$//g;
18310:         if (($secpolicy ne '') || ($xframeop ne '')) {
18311:             my $remotehost = $remprotocol.'://'.$remhost;
18312:             my ($origin,$protocol,$port);
18313:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
18314:                 $port = $ENV{'SERVER_PORT'};
18315:             } else {
18316:                 $port = 80;
18317:             }
18318:             if ($absolute eq '') {
18319:                 $protocol = 'http:';
18320:                 if ($port == 443) {
18321:                     $protocol = 'https:';
18322:                 }
18323:                 $origin = $protocol.'//'.lc($hostname);
18324:             } else {
18325:                 $origin = lc($absolute);
18326:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
18327:             }
18328:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
18329:                 my $framepolicy = $1;
18330:                 $framepolicy =~ s/^\s+|\s+$//g;
18331:                 my @policies = split(/\s+/,$framepolicy);
18332:                 if (@policies) {
18333:                     if (grep(/^\Q'none'\E$/,@policies)) {
18334:                         $uselink = 1;
18335:                     } else {
18336:                         $uselink = 1;
18337:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
18338:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
18339:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
18340:                             undef($uselink);
18341:                         }
18342:                         if ($uselink) {
18343:                             if (grep(/^\Q'self'\E$/,@policies)) {
18344:                                 if (($origin ne '') && ($remotehost eq $origin)) {
18345:                                     undef($uselink);
18346:                                 }
18347:                             }
18348:                         }
18349:                         if ($uselink) {
18350:                             my @possok;
18351:                             if ($ip ne '') {
18352:                                 push(@possok,$ip);
18353:                             }
18354:                             my $hoststr = '';
18355:                             foreach my $part (reverse(split(/\./,$hostname))) {
18356:                                 if ($hoststr eq '') {
18357:                                     $hoststr = $part;
18358:                                 } else {
18359:                                     $hoststr = "$part.$hoststr";
18360:                                 }
18361:                                 if ($hoststr eq $hostname) {
18362:                                     push(@possok,$hostname);
18363:                                 } else {
18364:                                     push(@possok,"*.$hoststr");
18365:                                 }
18366:                             }
18367:                             if (@possok) {
18368:                                 foreach my $poss (@possok) {
18369:                                     last if (!$uselink);
18370:                                     foreach my $policy (@policies) {
18371:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
18372:                                             undef($uselink);
18373:                                             last;
18374:                                         }
18375:                                     }
18376:                                 }
18377:                             }
18378:                         }
18379:                     }
18380:                 }
18381:             } elsif ($xframeop ne '') {
18382:                 $uselink = 1;
18383:                 my @policies = split(/\s*,\s*/,$xframeop);
18384:                 if (@policies) {
18385:                     unless (grep(/^deny$/,@policies)) {
18386:                         if ($origin ne '') {
18387:                             if (grep(/^sameorigin$/,@policies)) {
18388:                                 if ($remotehost eq $origin) {
18389:                                     undef($uselink);
18390:                                 }
18391:                             }
18392:                             if ($uselink) {
18393:                                 foreach my $policy (@policies) {
18394:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
18395:                                         my $allowfrom = $1;
18396:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
18397:                                             undef($uselink);
18398:                                             last;
18399:                                         }
18400:                                     }
18401:                                 }
18402:                             }
18403:                         }
18404:                     }
18405:                 }
18406:             }
18407:         }
18408:     }
18409:     if ($nocache) {
18410:         if ($cached) {
18411:             my $devalidate;
18412:             if ($uselink && !$result) {
18413:                 $devalidate = 1;
18414:             } elsif (!$uselink && $result) {
18415:                 $devalidate = 1;
18416:             }
18417:             if ($devalidate) {
18418:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
18419:             }
18420:         }
18421:     } else {
18422:         if ($uselink) {
18423:             $result = 1;
18424:         } else {
18425:             $result = 0;
18426:         }
18427:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
18428:     }
18429:     return $uselink;
18430: }
18431: 
18432: sub page_menu {
18433:     my ($menucolls,$menunum) = @_;
18434:     my %menu;
18435:     foreach my $item (split(/;/,$menucolls)) {
18436:         my ($num,$value) = split(/\%/,$item);
18437:         if ($num eq $menunum) {
18438:             my @entries = split(/\&/,$value);
18439:             foreach my $entry (@entries) {
18440:                 my ($name,$fields) = split(/=/,$entry);
18441:                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
18442:                     $menu{$name} = $fields;
18443:                 } else {
18444:                     my @shown;
18445:                     if ($fields =~ /,/) {
18446:                         @shown = split(/,/,$fields);
18447:                     } else {
18448:                         @shown = ($fields);
18449:                     }
18450:                     if (@shown) {
18451:                         foreach my $field (@shown) {
18452:                             next if ($field eq '');
18453:                             $menu{$field} = 1;
18454:                         }
18455:                     }
18456:                 }
18457:             }
18458:         }
18459:     }
18460:     return %menu;
18461: }
18462: 
18463: 1;
18464: __END__;
18465: 

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